-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompiler.cpp
More file actions
102 lines (87 loc) · 2.79 KB
/
compiler.cpp
File metadata and controls
102 lines (87 loc) · 2.79 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
97
98
99
100
101
102
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
#include <unordered_map>
#include "instructionset.h"
using namespace std;
using namespace ISA;
int main(int argc, char* argv[]) {
if (argc < 2) {
cout << "Usage: " << argv[0] << " <input.asm>\n";
return 1;
}
ifstream infile(argv[1]);
if (!infile) {
cout << "Cannot open file: " << argv[1] << "\n";
return 1;
}
vector<uint8_t> program;
string line;
unordered_map<string, uint8_t> opcodeMap = {
{"NOP", NOP},
{"LOAD_R0", LOAD_R0},
{"LOAD_R1", LOAD_R1},
{"MOV_R0_R1", MOV_R0_TO_R1},
{"MOV_R1_R0", MOV_R1_TO_R0},
{"ADD_R0_IMM", ADD_R0_IMM},
{"ADD_R0_R1", ADD_R0_R1},
{"SUB_R0_IMM", SUB_R0_IMM},
{"SUB_R0_R1", SUB_R0_R1},
{"LOADM_R0", LOADM_R0},
{"STORE_R0", STORE_R0},
{"LOADM_R1", LOADM_R1},
{"STORE_R1", STORE_R1},
{"LOADIND_R0_R1", LOADIND_R0_R1},
{"STOREIND_R0_R1", STOREIND_R0_R1},
{"JMP", JMP},
{"JZ", JZ},
{"JNZ", JNZ},
{"JGE_R0_R1", JGE_R0_R1},
{"HALT", HALT}
};
while (getline(infile, line)) {
auto commentPos = line.find(';');
if (commentPos != string::npos)
line = line.substr(0, commentPos);
stringstream ss(line);
string instr;
ss >> instr;
if (instr.empty()) continue;
auto it = opcodeMap.find(instr);
if (it == opcodeMap.end()) {
cout << "Unknown instruction: " << instr << "\n";
return 1;
}
program.push_back(it->second);
if (it->second != NOP && it->second != MOV_R0_TO_R1 &&
it->second != MOV_R1_TO_R0 && it->second != ADD_R0_R1 &&
it->second != SUB_R0_R1 && it->second != LOADIND_R0_R1 &&
it->second != STOREIND_R0_R1 && it->second != HALT) {
int operand;
if (!(ss >> operand)) {
cout << "Missing operand for instruction: " << instr << "\n";
return 1;
}
if (operand < 0 || operand > 255) {
cout << "Operand out of range (0-255): " << operand << "\n";
return 1;
}
program.push_back(static_cast<uint8_t>(operand));
} else {
program.push_back(0);
}
}
ofstream outfile("program.bin", ios::binary);
if (!outfile) {
cout << "Error: cannot open program.bin for writing\n";
return 1;
}
outfile.write(reinterpret_cast<const char*>(program.data()), program.size());
if (!outfile) {
cout << "Error: failed to write program.bin\n";
return 1;
}
cout << "Program assembled successfully! Bytes: " << program.size() << "\n";
}