Files
trivial_c_plus/main.cpp
2026-05-06 23:47:46 -04:00

75 lines
1.7 KiB
C++

#include "include/tokenizer.h"
#include "include/parser.h"
#include "include/evaluator.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <unordered_map>
// ---------------- read entire file ----------------
static std::string read_file(const std::string& path) {
std::ifstream file(path);
if (!file.is_open()) {
throw std::runtime_error("Could not open file: " + path);
}
std::stringstream buffer;
buffer << file.rdbuf();
return buffer.str();
}
// ---------------- execute code ----------------
static void execute(const std::string& source, Env& env) {
auto tokens = tokenize(source);
auto ast = parse(tokens);
evaluate(ast, env);
}
// ---------------- REPL ----------------
static void repl() {
Env env;
std::string line;
while (true) {
std::cout << ">> ";
if (!std::getline(std::cin, line))
break;
if (line == "exit" || line == "quit")
break;
try {
execute(line, env);
} catch (const std::exception& e) {
std::cout << "Error: " << e.what() << "\n";
}
}
}
// ---------------- main ----------------
int main(int argc, char** argv) {
Env env;
try {
// ---------------- FILE MODE ----------------
if (argc > 1) {
std::string file_path = argv[1];
std::string source = read_file(file_path);
execute(source, env);
return 0;
}
// ---------------- REPL MODE ----------------
repl();
} catch (const std::exception& e) {
std::cout << "Fatal Error: " << e.what() << "\n";
return 1;
}
return 0;
}