crafting-interpreters/src/com/craftinginterpreters/lox/Lox.java

94 lines
2.7 KiB
Java
Raw Normal View History

2020-10-21 23:42:40 -07:00
package com.craftinginterpreters.lox;
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 {
2020-11-11 21:33:02 -08:00
private static final Interpreter interpreter = new Interpreter();
public static boolean hadError = false;
public static boolean hadRuntimeError = false;
2020-10-21 23:42:40 -07:00
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()));
// Indicate an error in the exit code.
2020-11-11 21:07:49 -08:00
if (hadError)
System.exit(65);
2020-11-11 21:33:02 -08:00
if (hadRuntimeError)
System.exit(70);
2020-10-21 23:42:40 -07:00
}
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();
2020-11-11 21:07:49 -08:00
if (line == null)
break;
2020-10-21 23:42:40 -07:00
run(line);
hadError = false;
}
}
private static void run(String source) {
Scanner scanner = new Scanner(source);
List<Token> tokens = scanner.scanTokens();
2020-11-11 21:07:49 -08:00
Parser parser = new Parser(tokens);
List<Stmt> statements = parser.parse();
2020-10-21 23:42:40 -07:00
2020-11-11 21:07:49 -08:00
// Stop if there was a syntax error
2020-11-11 21:33:02 -08:00
if (hadError)
return;
2020-11-11 21:07:49 -08:00
2021-03-03 22:44:52 -08:00
Resolver resolver = new Resolver(interpreter);
resolver.resolve(statements);
// Stop if there was a resolution error
if (hadError)
return;
interpreter.interpret(statements);
2020-10-21 23:42:40 -07:00
}
public static void error(int line, String message) {
report(line, "", message);
}
private static void report(int line, String where, String message) {
System.err.println("[line " + line + "] Error" + where + ": " + message);
hadError = true;
}
2020-11-11 21:07:49 -08:00
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);
}
}
2020-11-11 21:33:02 -08:00
public static void runtimeError(RuntimeError error) {
System.err.println(error.getMessage() + "\n[line " + error.token.line + "]");
hadRuntimeError = true;
}
2020-10-21 23:42:40 -07:00
}