/* Copyright (C) 2019-2023 Hangzhou HSH Co. Ltd. * All right reserved.*/ 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.Path; import java.util.List; /** * @author simon * @date 2023-06-04 15:21 * @desc */ public class Lox { private static final Interpreter interpreter = new Interpreter(); private static boolean hadError = false; private 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(); } } /** * start jlox from the command line and give it a path to a file, it reads the file and executes * it * * @param path 文件路径 */ private static void runFile(String path) throws IOException { byte[] bytes = Files.readAllBytes(Path.of(path)); run(new String(bytes, Charset.defaultCharset())); // Indicate an error in the exit code. 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); // reset this flag in the interactive loop. If the user makes a mistake, // it shouldn’t kill their entire session. // hadError = true; } } private static void run(String source) { Scanner scanner = new Scanner(source); List tokens = scanner.scanTokens(); // for (Token token : tokens) { // System.out.println(token); // } Parser parser = new Parser(tokens); List statements = parser.parse(); // Stop if there was a syntax error. if (hadError) return; // System.out.println(" ...AST: " + new AstPrinter().print(statements)); interpreter.interpret(statements); } /** * 错误处理 * * @param line 行号 * @param message 消息 */ 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; } 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); } } public static void runtimeError(RuntimeError error) { System.err.println(error.getMessage() + "\n[line " + error.token.line + "]"); hadRuntimeError = true; } }