-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
125 lines (109 loc) · 3.36 KB
/
Program.cs
File metadata and controls
125 lines (109 loc) · 3.36 KB
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
using System.Text;
namespace Lox
{
internal class Program
{
private static readonly Interpreter _interpreter = new Interpreter();
static bool hadError = false;
static bool hadRuntimeError = false;
static void Main(string[] args)
{
if (args.Length > 1)
{
Console.WriteLine("Usage: C#lox [script]");
Environment.Exit(64);
}
else if (args.Length == 1)
{
runFile(args[0]);
}
else
{
runPrompt();
}
}
private static void runFile(string path)
{
try
{
//byte[] fileBytes = File.ReadAllBytes(path);
//string fileContent = Encoding.UTF8.GetString(fileBytes);
string fileContent =File.ReadAllText(path);
//Console.WriteLine($"{path} {fileContent}");
run(fileContent);
if (hadError)
{
Environment.Exit(64);
}
if (hadRuntimeError)
{
Environment.Exit(70);
}
}
catch (IOException e)
{
Console.WriteLine("An IO exception has been thrown!");
Console.WriteLine(e.ToString());
}
}
private static void runPrompt()
{
Console.InputEncoding = Encoding.UTF8;
Console.OutputEncoding = Encoding.UTF8;
for (; ; )
{
Console.Write("> ");
var line = Console.ReadLine();
if (line == null)
{
break;
}
run(line);
hadError = false;
}
}
private static void run(string source)
{
var scanner = new Scanner(source);
var tokens = scanner.scanTokens();
var parser = new Parser(tokens);
List<Stmt> statements = parser.parse();
if (hadError)
{
return;
}
Resolver resolver = new Resolver(_interpreter);
resolver.resolve(statements);
if (hadError)
{
return;
}
_interpreter.interpret(statements);
//Console.WriteLine(new AstPrinter().print(expression));
}
internal static void error(int line, string message)
{
report(line, "", message);
}
internal static void report(int line, string where, string message) {
Console.Error.WriteLine(" [line " + line + "] Error " + where + ": " + message );
hadError = true;
}
internal 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);
}
}
internal static void runtimeError(RuntimeError error)
{
Console.Error.WriteLine(error.Message + Environment.NewLine + " [line " + error.Token.line + "]");
hadRuntimeError = true;
}
}
}