-
Notifications
You must be signed in to change notification settings - Fork 0
/
MultiFileMethods.cs
68 lines (62 loc) · 2.82 KB
/
MultiFileMethods.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
using System.Linq.Expressions;
using RCaron.LibrarySourceGenerator;
namespace RCaron.Jit;
[Module("JIT Multi-File overrides", ImplementModuleRun = false)]
public partial class MultiFileMethods
{
[Method("Open-File")]
public void OpenFile(CompiledContext compiledContext, string path, object[]? functions = null, object[]? classes = null,
bool noRun = false)
{
OpenFromString(compiledContext, File.ReadAllText(path), Path.GetFullPath(path), functions, classes, noRun);
}
[Method("Open-FromString")]
public void OpenFromString(CompiledContext compiledContext, string code, string? fileName = null, object[]? functions = null, object[]? classes = null,
bool noRun = false)
{
var p = RCaronRunner.Parse(code);
p.FileScope.FileName = fileName;
var compiled = Compiler.Compile(p);
if (!noRun)
{
var lambda = Expression.Lambda(compiled.blockExpression);
lambda.Compile().DynamicInvoke();
}
if (functions == null && classes == null)
{
compiledContext.FileScope.ImportedFileScopes ??= new();
compiledContext.FileScope.ImportedFileScopes.Add(p.FileScope);
compiledContext.ImportedContexts ??= new();
compiledContext.ImportedContexts.Add(compiled.compiledContext);
}
if (functions != null)
{
compiledContext.FileScope.ImportedFunctions ??= new(StringComparer.InvariantCultureIgnoreCase);
compiledContext.ImportedFunctions ??= new(StringComparer.InvariantCultureIgnoreCase);
foreach (var function in functions)
{
var functionName = function.ToString()!;
if(!(p.FileScope.Functions?.TryGetValue(functionName, out var f) ?? false))
throw RCaronException.FunctionToImportNotFound(functionName);
compiledContext.FileScope.ImportedFunctions.Add(functionName, f);
compiledContext.ImportedFunctions.Add(functionName, compiled.compiledContext.Functions[functionName]);
}
}
if (classes != null)
{
compiledContext.FileScope.ImportedClassDefinitions ??= new();
compiledContext.ImportedClasses ??= new();
foreach (var @class in classes)
{
var className = @class.ToString()!;
if (Motor.TryGetClassDefinition(p.FileScope.ClassDefinitions, className, out var classDef))
{
compiledContext.FileScope.ImportedClassDefinitions.Add(classDef);
compiledContext.ImportedClasses.Add(compiled.compiledContext.GetClass(classDef)!);
}
else
throw RCaronException.ClassToImportNotFound(className);
}
}
}
}