-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLox.cs
80 lines (67 loc) · 2 KB
/
Lox.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
namespace SharpLox;
public static class Lox
{
private static readonly Interpreter Interpreter = new();
private static bool HadError;
private static bool HadRuntimeError;
public static void RunFile(string path)
{
var source = File.ReadAllText(path);
Run(source);
// Indicate an error in the exit code.
if (HadError) Environment.Exit(65);
if (HadRuntimeError) Environment.Exit(70);
}
public static void RunPrompt()
{
while (true)
{
Console.Write("> ");
var line = Console.ReadLine();
if (line == null) break;
Run(line);
HadError = false;
}
}
public static void Error(int line, string message)
{
Report(line, "", message);
}
public static void Error(Token token, String message)
{
if (token.Type == TokenType.EOF)
{
Report(token.Line, " at end", message);
}
else
{
Report(token.Line, $" at '{token.Lexeme}'", message);
}
}
public static void RuntimeError(RuntimeError error)
{
var errMessage = $"{error.Message}\n[line {error.Token.Line}]";
Console.Error.WriteLine(errMessage);
HadRuntimeError = true;
}
private static void Run(string source)
{
var scanner = new Scanner(source);
var tokens = scanner.ScanTokens();
var parser = new Parser(tokens);
var statements = parser.Parse();
// Stop if there was a syntax error.
if (HadError) return;
var resolver = new Resolver(Interpreter);
resolver.Resolve(statements);
// Stop if there was a resolution error.
if (HadError) return;
Interpreter.Interpret(statements);
}
private static void Report(int line, string where, string message)
{
var errMessage = $"[line {line}] Error{where}: {message}";
Console.Error.WriteLine(errMessage);
HadError = true;
}
}