#include "token.hh" #include "scanner.hh" #include #include #include #include #include #include #define PROMPT "> " static bool had_error = false; void run_file(const char *path); void run_prompt(); void run(const std::string &code); void error(int line, const std::string &message); void report(int line, const std::string &where, const std::string &message); int main(int argc, char *argv[]) { if (argc > 2) { std::cout << "Usage: cclox [script]\n"; exit(EX_USAGE); } if (argc == 2) { run_file(argv[1]); } else { run_prompt(); } return 0; } 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 (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; had_error = false; } } void run(const std::string &code) { Scanner scanner{code}; std::vector tokens = scanner.scan_tokens(); for (auto token : tokens) { std::cout << token << '\n'; } } void error(int line, const std::string &message) { report(line, "", message); } void report(int line, const std::string &where, const std::string &message) { std::cout << "[line " << line << "] Error" << where << ": " << message << '\n'; had_error = true; }