diff options
author | Tom Willemse | 2020-10-21 23:42:40 -0700 |
---|---|---|
committer | Tom Willemse | 2020-10-21 23:42:40 -0700 |
commit | a50265860470ab53ee137536d738cdc57ff47e72 (patch) | |
tree | 001eeb17da2990cb4a524cf85c6186fe79639382 /src/com/craftinginterpreters/lox/Lox.java | |
parent | 38a6ee0725ddc4eb57357a2398bc82dc8b264c7e (diff) | |
download | crafting-interpreters-a50265860470ab53ee137536d738cdc57ff47e72.tar.gz crafting-interpreters-a50265860470ab53ee137536d738cdc57ff47e72.zip |
Add Scanner for Lox
Diffstat (limited to 'src/com/craftinginterpreters/lox/Lox.java')
-rw-r--r-- | src/com/craftinginterpreters/lox/Lox.java | 64 |
1 files changed, 64 insertions, 0 deletions
diff --git a/src/com/craftinginterpreters/lox/Lox.java b/src/com/craftinginterpreters/lox/Lox.java new file mode 100644 index 0000000..51d72c7 --- /dev/null +++ b/src/com/craftinginterpreters/lox/Lox.java @@ -0,0 +1,64 @@ +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 { + private static boolean hadError = 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())); + + // Indicate an error in the exit code. + if (hadError) System.exit(65); + } + + 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); + hadError = false; + } + } + + private static void run(String source) { + Scanner scanner = new Scanner(source); + List<Token> tokens = scanner.scanTokens(); + + // For now, just print the tokens. + for (Token token : tokens) { + System.out.println(token); + } + } + + 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; + } +} |