Repository navigation
Expand file tree
/
Copy pathmain.cpp
More file actions
93 lines (63 loc) · 1.99 KB
/
Copy pathmain.cpp
File metadata and controls
93 lines (63 loc) · 1.99 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
#include"lexer.cpp"
int main(int argc, char const *argv[]){
//reading arguments from terminal.
std::string sourcecode="";
if(argc!=2){
std::cerr<<"Error: Invalid number of arguments."<<std::endl;
std::cerr<<"Usage: ./lexer <filename>"<<std::endl;
return 1;
}
std::string filename=argv[1];
//checking the extension of the file .
if(filename.find(".hshi")==std::string::npos){
std::cerr<<"Error: Invalid file extension. Please use .hshi extension."<<std::endl;
return 1;
}
//opening the file
std::fstream file;
file.open(filename,std::ios::in);
if(!file){
std::cerr<<"Error: File not found."<<std::endl;
return 1;
}
//reading the file
std::string line;
while(getline(file,line)){
sourcecode+=line;
}
// std::cout<<sourcecode<<std::endl;
//closing the file
file.close();
//now its time to tokenize the source code.
std::vector<lexer> tokens;
tokens =tokenize(sourcecode);
Parser parser(tokens);
std::vector<std::shared_ptr<ASTNode>> ast = parser.parse();
std::string executableCode = codeGeneration(ast);
// std::cout<<executableCode<<std::endl;
// Write the generated code to a file
std::ofstream outFile("generated_code.cpp");
if (outFile.is_open()) {
outFile << executableCode;
outFile.close();
} else {
std::cerr << "Unable to open file for writing.\n";
return 1;
}
// Compile the generated code
if (system("g++ -o generated_code generated_code.cpp") != 0) {
std::cerr << "Compilation failed.\n";
return 1;
}
// Run the compiled code
if (system("./generated_code") != 0) {
std::cerr << "Execution failed.\n";
return 1;
}
// Delete the generated code file
if (remove("generated_code.cpp") != 0) {
std::cerr << "Failed to delete generated code file.\n";
return 1;
}
return 0;
}