-
Notifications
You must be signed in to change notification settings - Fork 0
/
LoxInterpreter.cpp
98 lines (81 loc) · 1.83 KB
/
LoxInterpreter.cpp
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
#include "LoxInterpreter.h"
bool had_error;
void LoxInterpreter::run_file(const string& file)
{
ifstream f1(file, std::ios::binary | std::ios::ate);
if (!f1)
{
cout << "Cannot open file: " << file;
exit(255);
}
int len = f1.tellg();
f1.seekg(ios::beg);
string code(len, 0);
f1.read(&code[0], len);
run_code(code);
f1.close();
}
[[noreturn]] void LoxInterpreter::run_prompt()
{
interpreter i;
resolver r(i);
string code;
while (true)
{
cout << "> ";
getline(cin, code);
if (code.length()== 0)
continue;
//run_code(code);
scanner s(code);
parser p(s.scan_Tokens());
if(code.find(';') == string::npos)
{
auto expr = p.parse_expr();
r.resolve(expr);
i.eval(expr);
} else
{
auto stmts = p.parse_stmt();
r.resolve(stmts);
if(!had_error)
i.interpret(stmts);
}
cout << endl;
}
}
void LoxInterpreter::run_code(string code)
{
scanner s(code);
auto tokens = s.scan_Tokens();
/*cout << "*****************Scanner*****************" << endl;
cout << tokens.size() << " tokens." << endl;
for (const auto& i : tokens)
cout << i->to_string() << endl;
cout << endl;
cout << "*****************Parser*****************" << endl;*/
parser p(move(tokens));
auto stmts = p.parse_stmt();
/*//AST_Printer printer;
//printer.print(stmts);
cout << endl;
cout << "*****************Interpreter*****************" << endl;*/
interpreter i;
resolver r(i);
r.resolve(stmts);
if(!had_error)
i.interpret(stmts);
}
LoxInterpreter::LoxInterpreter(int argc, char** argv)
{
had_error = false;
if (argc > 2)
{
cout << "Usage: lox [script]" << endl;
exit(0);
}
else if (argc == 2)
run_file(argv[1]);
else
run_prompt();
}