-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
70 lines (60 loc) · 1.56 KB
/
main.cpp
File metadata and controls
70 lines (60 loc) · 1.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include "analyzer.hpp"
#include "ast.hpp"
#include "interpreter.hpp"
#include "lexer.hpp"
#include "parser.hpp"
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
static std::string readFileOrDie(const std::string &path) {
std::ifstream in(path, std::ios::in | std::ios::binary);
if (!in) {
throw std::runtime_error("failed to open file: " + path);
}
std::ostringstream ss;
ss << in.rdbuf();
return ss.str();
}
int main(int argc, char **argv) {
if (argc != 2) {
std::cerr << "Usage: " << argv[0] << " <program_file>\n";
return 2;
}
try {
// 1) read source
std::string src = readFileOrDie(argv[1]);
// 2) lex
Lexer lx(std::move(src));
auto toks = lx.tokenize();
// 3) print tokens
std::cout << "=== TOKENS ===\n";
for (const auto &t : toks) {
std::cout << t.line << ":" << t.col << " " << kindName(t.kind) << " '"
<< t.lexeme << "'\n";
}
// 4) parse + print AST
std::cout << "\n=== AST ===\n";
Parser ps(std::move(toks));
auto prog = ps.parseProgram();
for (auto &st : prog) {
st->dump(std::cout, 0);
}
// 5) semantic analysis
std::cout << "\n=== ANALYSIS ===\n";
Analyzer az;
az.analyze(prog);
if (az.hasErrors()) {
std::cerr << "Execution aborted due to semantic errors\n";
return 1;
}
std::cout << "\n=== EXECUTION ===\n";
Interpreter it;
it.execute(prog);
return 0;
} catch (const std::exception &e) {
std::cerr << "Error: " << e.what() << "\n";
return 1;
}
}