-
Notifications
You must be signed in to change notification settings - Fork 0
/
Lox.cpp
135 lines (123 loc) · 2.78 KB
/
Lox.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
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
126
127
128
129
130
131
132
133
134
135
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <iterator>
#include "Lox.h"
#include "Scanner.h"
#include "AstPrinter.h"
#include "Parser.h"
#include "Interpreter.h"
#include "Resolver.h"
bool Lox::hadError = false;
bool Lox::hadRuntimeError = false;
void Lox::runFile(char *filename)
{
std::ifstream infile(filename, std::ios::in | std::ios::binary);
if (!infile.bad() && infile.is_open())
{
std::ostringstream content;
content << infile.rdbuf();
infile.close();
run(content.str(), false);
if (hadError)
{
exit(65);
}
if (hadRuntimeError)
{
exit(70);
}
}
else
{
std::cerr << "Could not open file " << filename << std::endl;
}
}
void Lox::runPipe()
{
std::cin >> std::noskipws;
std::istream_iterator<char> begin(std::cin);
std::istream_iterator<char> end;
std::string input(begin, end);
run(input, false);
if (hadError)
{
exit(65);
}
if (hadRuntimeError)
{
exit(70);
}
}
void Lox::runPrompt()
{
for (;;)
{
std::string line;
std::cout << "> ";
if (std::getline(std::cin, line))
{
run(line, true);
hadError = false;
}
else
{
break;
}
}
}
void Lox::run(std::string source, bool repl)
{
Scanner scanner(source);
std::vector<Token> tokens = scanner.scanTokens();
Parser parser(tokens);
std::vector<Stmt *> statements = parser.parse();
if (!hadError)
{
Interpreter interpreter(repl);
Resolver resolver(&interpreter);
resolver.resolve(statements);
if (!hadError)
{
interpreter.interpret(statements);
}
}
if (!repl)
{
for (auto &statement : statements)
{
if (statement->type != StmtType_Function) // HACK: Must keep original function statement alive in REPL mode...
{
delete statement;
}
}
}
}
void Lox::error(int line, std::string message)
{
report(line, "", message);
}
void Lox::error(Token token, std::string message)
{
if (token.type == EOF_TOKEN)
{
report(token.line, " at end", message);
}
else
{
std::stringstream ss;
ss << " at '" << token.lexeme << "'";
report(token.line, ss.str(), message);
}
}
void Lox::runtimeError(Token token, std::string message)
{
std::cerr << message << std::endl << "[line " << token.line << "]" << std::endl;
hadRuntimeError = true;
}
void Lox::report(int line, std::string where, std::string message)
{
std::cerr << "[line " << line << "] Error" << where << ": " << message << std::endl;
hadError = true;
}