-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlox.java
97 lines (82 loc) · 2.74 KB
/
lox.java
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
package SLox;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
public class lox {
private static final Interpreter interpreter = new Interpreter();
static boolean hadError = false;
static boolean hadRuntimeError = false;
public static void main(String[] args) throws IOException {
if (args.length > 1) {
System.out.println("Usage: jlox [script]");
System.exit(64);
} else if (args.length == 1) {
runFile(args[0]);
} else {
runPrompt();
}
}
private static void runFile(String path) throws IOException {
byte[] bytes = Files.readAllBytes(Paths.get(path));
run(new String(bytes, Charset.defaultCharset()),false);
if (hadError) System.exit(65);
if (hadRuntimeError) System.exit(70);
}
private static void runPrompt() throws IOException {
InputStreamReader input = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(input);
for (;;) {
System.out.print("> ");
String line = reader.readLine();
if (line == null) break;
run(line, true);
hadError = false;
}
// Indicate an error in the exit code.
}
private static void run(String source, boolean isR) {
Scanner scanner = new Scanner(source);
List<Token> tokens = scanner.scanTokens();
Parser parser = new Parser(tokens);
List<Stmt> statements = parser.parse();
// Stop if there was a syntax error.
if (hadError) return;
Resolver resolver = new Resolver(interpreter);
resolver.resolve(statements);
checkVisitedVariables(resolver);
// Stop if there was a resolution error.
if (hadError) return;
interpreter.interpret(statements,isR);
//System.out.println(new AstPrinter().print(expressions));
}
private static void checkVisitedVariables(Resolver resolver){
if(!resolver.visited.isEmpty())
lox.error(resolver.visited.get(0),
"Variable is defined but never used.");
}
private static void report(int line, String where,
String message) {
System.err.println(
"[line " + line + "] Error" + where + ": " + message);
hadError = true;
}
static void error(int line, String message) {
report(line, "", message);
}
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);
}
}
static void runtimeError(RuntimeError error) {
System.err.println(error.getMessage() +
"\n[line " + error.token.line + "]");
hadRuntimeError = true;
}
}