-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
89 lines (76 loc) · 1.87 KB
/
Program.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
using System.CommandLine;
using System.CommandLine.NamingConventionBinder;
using SimpleInterpreter.Interpreter;
using SimpleInterpreter.Lexer;
using SimpleInterpreter.Parser;
// ref -> https://stackoverflow.com/a/8946847/15407937
void ClearCurrentConsoleLine()
{
int currentLineCursor = Console.CursorTop;
Console.SetCursorPosition(0, Console.CursorTop);
Console.Write("\r");
Console.SetCursorPosition(0, currentLineCursor);
}
void repl()
{
// ref -> https://stackoverflow.com/a/929717/15407937
Console.CancelKeyPress += (sender, e) =>
{
e.Cancel = true;
// Console.SetCursorPosition(0, Console.CursorTop - 1);
ClearCurrentConsoleLine();
Environment.Exit(0);
};
while (true)
{
try
{
Console.Write("> ");
var src = Console.ReadLine()!;
run(src);
}
catch (System.Exception e)
{
Console.WriteLine(e);
}
}
}
void run(string src)
{
var lexer = new Lexer(src);
var tokens = lexer.scan();
var parser = new Parser(tokens);
var statments = parser.prase();
var interpreter = new Interpreter(statments);
foreach (var result in interpreter.cal())
{
Console.WriteLine(result);
}
}
async Task run_file(string path)
{
var src = await File.ReadAllTextAsync(path);
run(src);
}
async Task main()
{
var rootCommand = new RootCommand();
var fileOption = new Option<string>
(aliases: new string[] { "--file", },
description: "",
getDefaultValue: () => "");
rootCommand.AddOption(fileOption);
rootCommand.Handler = CommandHandler.Create<string>(async file =>
{
if (string.IsNullOrEmpty(file))
{
repl();
}
else
{
await run_file(file);
}
});
await rootCommand.InvokeAsync(args);
}
await main();