-
Notifications
You must be signed in to change notification settings - Fork 0
/
Compiler.cs
52 lines (44 loc) · 1.36 KB
/
Compiler.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
using Microsoft.CodeAnalysis.CSharp.Scripting;
using Microsoft.CodeAnalysis.Scripting;
namespace Luminor;
public class Compiler
{
private readonly string sourceCode;
public Compiler(string sourceCode)
{
this.sourceCode = sourceCode;
}
public async Task Compile()
{
var lexer = new Lexer(sourceCode);
var tokens = lexer.Tokenize();
var parser = new Parser(tokens);
var ast = parser.Parse();
var executable = GenerateCode(ast);
await ExecuteCodeAsync(executable);
}
private string GenerateCode(Node node)
{
return node.Type switch
{
NodeType.Program => string.Join("\n", node.Body.Select(GenerateCode)),
NodeType.Assignment => $"var {node.Name} = {node.Value};",
NodeType.Print => $"Console.WriteLine({node.Value});",
_ => throw new NotImplementedException()
};
}
private async Task ExecuteCodeAsync(string code)
{
try
{
var options = ScriptOptions.Default
.WithReferences(AppDomain.CurrentDomain.GetAssemblies())
.WithImports("System", "System.Console");
await CSharpScript.EvaluateAsync(code, options);
}
catch (Exception ex)
{
Console.WriteLine("Execution Error: " + ex.Message);
}
}
}