From 1e78c8c7f324df3a5bc1992ac68d4277613c45b0 Mon Sep 17 00:00:00 2001 From: Erik Winter Date: Mon, 22 Jul 2024 14:30:33 +0200 Subject: [PATCH] 4.2 --- jlox.iml | 1 - src/Lox.java | 18 +++++++++++++++++- src/Token.java | 17 +++++++++++++++++ src/TokenType.java | 18 ++++++++++++++++++ 4 files changed, 52 insertions(+), 2 deletions(-) create mode 100644 src/Token.java create mode 100644 src/TokenType.java diff --git a/jlox.iml b/jlox.iml index 57d33ec..c90834f 100644 --- a/jlox.iml +++ b/jlox.iml @@ -4,7 +4,6 @@ - diff --git a/src/Lox.java b/src/Lox.java index f2031d6..b18b585 100644 --- a/src/Lox.java +++ b/src/Lox.java @@ -4,9 +4,12 @@ import java.io.InputStreamReader; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Paths; +import java.util.List; import java.util.Scanner; public class Lox { + static boolean hadError = false; + public static void main(String[] args) throws IOException { if (args.length > 1) { System.out.println("Usage: jlox [script]"); @@ -21,6 +24,9 @@ public class Lox { private static void runFile(String path) throws IOException { byte[] bytes = Files.readAllBytes(Paths.get(path)); run(new String(bytes, Charset.defaultCharset())); + if (hadError) { + System.exit(65); + } } private static void runPrompt() throws IOException { @@ -32,6 +38,7 @@ public class Lox { String line = reader.readLine(); if (line == null) break; run(line); + hadError = false; } } @@ -41,7 +48,16 @@ public class Lox { for (Token token : tokens) { System.out.println(token); - + } } + + static void error(int line, String message) { + report(line, "", message); + } + + private static void report(int line, String where, String message) { + System.err.println("[" + line + "] " + where + ": " + message); + hadError = true; + } } diff --git a/src/Token.java b/src/Token.java new file mode 100644 index 0000000..405ac20 --- /dev/null +++ b/src/Token.java @@ -0,0 +1,17 @@ +class Token { + final TokenType type; + final String lexeme; + final Object literal; + final int line; + + Token(TokenType type, String lexeme, Object literal, int line) { + this.type = type; + this.lexeme = lexeme; + this.literal = literal; + this.line = line; + } + + public String toString() { + return type + " " + lexeme + " " + literal; + } +} diff --git a/src/TokenType.java b/src/TokenType.java new file mode 100644 index 0000000..4d9fc56 --- /dev/null +++ b/src/TokenType.java @@ -0,0 +1,18 @@ +enum TokenType { + // Single-character tokens + LEFT_PAREN, RIGHT_PAREN, LEFT_BRACE, RIGHT_BRACE, + COMMA, DOT, MINUS, PLUS, SEMICOLON, SLASH, STAR, + + // One or two character tokens + BANG, BANG_EQUAL, EQUAL, EQUAL_EQUAL, + GREATER, GREATER_EQUAL, LESS, LESS_EQUAL, + + // Literals + IDENTIFIER, STRING, NUMBER, + + // Keywords + AND, CLASS, ELSE, FALSE, FUN, FOR, IF, NIL, OR, + PRINT, RETURN, SUPER, THIS, TRUE, VAR, WHILE, + + EOF +}