From a78fe97f60c2ad39d3d6335c1d058bd8ee4921bb Mon Sep 17 00:00:00 2001 From: Tom Willemse Date: Wed, 11 Nov 2020 21:07:49 -0800 Subject: Add the Parser --- src/com/craftinginterpreters/lox/Lox.java | 24 ++++++++++++++++++------ 1 file changed, 18 insertions(+), 6 deletions(-) (limited to 'src/com/craftinginterpreters/lox/Lox.java') diff --git a/src/com/craftinginterpreters/lox/Lox.java b/src/com/craftinginterpreters/lox/Lox.java index 51d72c7..586442d 100644 --- a/src/com/craftinginterpreters/lox/Lox.java +++ b/src/com/craftinginterpreters/lox/Lox.java @@ -27,7 +27,8 @@ public class Lox { run(new String(bytes, Charset.defaultCharset())); // Indicate an error in the exit code. - if (hadError) System.exit(65); + if (hadError) + System.exit(65); } private static void runPrompt() throws IOException { @@ -37,7 +38,8 @@ public class Lox { for (;;) { System.out.print("> "); String line = reader.readLine(); - if (line == null) break; + if (line == null) + break; run(line); hadError = false; } @@ -46,11 +48,13 @@ public class Lox { private static void run(String source) { Scanner scanner = new Scanner(source); List tokens = scanner.scanTokens(); + Parser parser = new Parser(tokens); + Expr expression = parser.parse(); - // For now, just print the tokens. - for (Token token : tokens) { - System.out.println(token); - } + // Stop if there was a syntax error + if (hadError) return; + + System.out.println(new AstPrinter().print(expression)); } public static void error(int line, String message) { @@ -61,4 +65,12 @@ public class Lox { System.err.println("[line " + line + "] Error" + where + ": " + message); hadError = true; } + + 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); + } + } } -- cgit v1.2.3-54-g00ecf