#include "interpreter.hh" #include "error_handler.hh" #include "tokenizer.hh" #include "parser.hh" #include #include #include #include #include #define PROMPT "> " extern ErrorHandler error_handler; void run_file(const char *path); void run_prompt(); void run(const std::string &code); void run_interpreter(int argc, char *argv[]) { if (argc == 2) { run_file(argv[1]); } else { run_prompt(); } } void run_file(const char *path) { if (std::ifstream source_code{path, std::ios::ate}) { uint64_t size = source_code.tellg(); std::string code(size, '\0'); source_code.seekg(0); source_code.read(&code[0], size); run(code); if (error_handler.had_error) { exit(EX_DATAERR); } } } void run_prompt() { std::string line{}; std::cout << PROMPT; while (std::getline(std::cin, line)) { run(line); std::cout << PROMPT; error_handler.had_error = false; } } void run(const std::string &code) { Scanner scanner{code}; std::vector tokens = scanner.scan_tokens(); Parser parser{tokens}; std::optional expression = parser.parse(); if (expression) { AstPrinter printer{}; std::cout << printer.print(*expression) << '\n'; } }