-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsam.cpp
More file actions
96 lines (72 loc) · 2.77 KB
/
Copy pathsam.cpp
File metadata and controls
96 lines (72 loc) · 2.77 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include "lexer.hpp"
#include "parser.hpp"
#include "generator.hpp"
int main(int argc, char ** argv){
if(argc < 2){
std::cout<<"Please supply the source file"<<std::endl;
exit(1);
}
std::cout<<"Reading from file: "<<argv[1]<<std::endl;
std::ifstream sourceFileStream(argv[1]);
if(!sourceFileStream.is_open()) {
std::cout<<"Error: Could not open file "<<argv[1]<<std::endl;
exit(1);
}
std::stringstream buffer;
char temp;
while(sourceFileStream.get(temp)){
buffer << temp;
}
std::string sourceCode = buffer.str();
std::cout<<"Source code: \n"<<sourceCode<<std::endl;
try {
Lexer lexer(sourceCode);
std::vector<Token *> tokens = lexer.tokenize();
if (tokens.empty() || tokens.back()->TYPE != TOKEN_EOF){
Token * EOFNode = new Token();
EOFNode->TYPE = TOKEN_EOF;
tokens.push_back(EOFNode);
}
std::cout<<"Tokens generated:"<<std::endl;
for(auto x: tokens){
std::cout<<x->TYPE<<" : "<<x->VALUE<<" at "<<x->line<<":"<<x->column<<std::endl;
}
Parser parser(tokens);
AST_NODE* root = parser.parse();
std::cout<<"Parsed successfully! Number of statements = "<<root->SUB_STATEMENTS.size()<<std::endl;
Generator generator(root, argv[1]);
generator.generate();
std::string filename = argv[1];
// removes the extension
filename.pop_back();
filename.pop_back();
filename.pop_back();
filename.pop_back();
std::cout<<"Generated assembly file: "<<filename<<".asm"<<std::endl;
std::stringstream assemblerInstruction;
assemblerInstruction<<"nasm -f elf64 "<<filename<<".asm";
std::cout<<"Running: "<<assemblerInstruction.str()<<std::endl;
int result = system(assemblerInstruction.str().c_str());
if(result != 0) {
std::cout<<"Error: NASM assembly failed"<<std::endl;
exit(1);
}
std::stringstream linkerInstruction;
linkerInstruction<<"ld -o "<<filename<<" "<<filename<<".o";
std::cout<<"Running: "<<linkerInstruction.str()<<std::endl;
result = system(linkerInstruction.str().c_str());
if(result != 0) {
std::cout<<"Error: Linking failed"<<std::endl;
exit(1);
}
std::cout<<"Compilation successful! Executable: "<<filename<<std::endl;
} catch(const std::exception& e) {
std::cout<<"Compilation error: "<<e.what()<<std::endl;
exit(1);
}
return 0;
}