-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
53 lines (47 loc) · 1.12 KB
/
Copy pathmain.cpp
File metadata and controls
53 lines (47 loc) · 1.12 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
/**
* main.cpp
* author: Bao Le
*/
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <stdexcept>
#include "ast.hpp"
#include "lexer.hpp"
#include "parser.hpp"
#include "semantic.hpp"
#include "codegen.hpp"
std::string read_file(const std::string& path) {
std::ifstream file(path);
if (!file.is_open()) {
throw std::runtime_error("Failed to open file: " + path);
}
// read the file into a string
std::stringstream ss;
ss << file.rdbuf();
return ss.str();
}
int main(int argc, char* argv[]) {
std::string source;
if (argc > 1) {
source = read_file(argv[1]);
}
else {
std::ostringstream ss;
ss << std::cin.rdbuf();
source = ss.str();
}
// Lexer
Lexer lexer(source);
auto tokens = lexer.tokenize();
// Parser
Parser parser(std::move(tokens));
auto ast = parser.parse_program();
// Semantic Analysis
SemanticAnalyzer analyzer(ast.get());
analyzer.analyze();
// Code generation
CodeGenerator codegen(ast.get());
codegen.generate("output.s"); // writes assembly to a file
}