57 lines
1.1 KiB
C++
57 lines
1.1 KiB
C++
#include "interpreter.hh"
|
|
#include "error_handler.hh"
|
|
#include "scanner.hh"
|
|
#include <cstdint>
|
|
#include <fstream>
|
|
#include <iostream>
|
|
#include <sysexits.h>
|
|
|
|
#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<Token> tokens = scanner.scan_tokens();
|
|
|
|
for (const auto &token : tokens) {
|
|
std::cout << token << '\n';
|
|
}
|
|
}
|