-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathasm.cpp
More file actions
117 lines (109 loc) · 2.82 KB
/
asm.cpp
File metadata and controls
117 lines (109 loc) · 2.82 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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
#include <iostream>
#include <unordered_map>
#include <cstdint>
#include <format>
#include <string>
auto opcodes = std::unordered_map<std::string, uint8_t>{
{"and", 0},
{"or", 1},
{"not", 2},
{"xor", 3},
{"add", 4},
{"sub", 5},
{"neg", 6},
{"mul", 7},
{"div", 8},
{"mov", 9},
{"mov0", 10},
{"imm", 11},
{"shl", 12},
{"shr", 13},
{"condition_nz", 14},
{"condition_z", 15},
{"condition_lz", 16},
{"condition_gz", 17},
{"condition_1", 18},
{"b", 18},
{"set_b_target", 19},
{"set_data_address", 20},
{"ld", 24},
{"st", 25},
{"cl", 26},
{"swap", 27},
{"ld_p", 28},
{"st_p", 29},
{"set_src1_dst1", 31},
};
auto args = std::unordered_map<std::string, uint8_t>{
{"r0", 0},
{"r1", 1},
{"r2", 2},
{"r3", 3},
{"r4", 4},
{"r5", 5},
{"r6", 6},
{"r7", 7},
{"condition_1", 0},
{"b", 1},
};
uint8_t parse_arg(const std::string& str) {
if (args.contains(str)) {
return args[str];
}
else {
return stoi(str);
}
}
int main(int argc, const char* argv[]) {
bool output_hex = false;
bool enable_debug = false;
bool sep_with_line = false;
for (int i = 1; i < argc; i++) {
if (std::string(argv[i]) == "--hex") {
output_hex = true;
}
else if (std::string(argv[i]) == "--debug") {
enable_debug = true;
}
else if (std::string(argv[i]) == "--sep_with_line") {
sep_with_line = true;
}
else if (std::string(argv[i]) == "--help") {
std::cout << "Usage: asm [options]\n"
"Options:\n"
" --hex Output in hexadecimal format\n"
" --debug Enable debug output\n"
" --sep_with_line Separate output with new lines instead of commas\n"
" --help Show this help message\n";
return 0;
}
}
while (true) {
std::string opcode, arg;
std::cin >> opcode >> arg;
if (!std::cin.good()) {
break;
}
if (enable_debug) {
std::cerr << opcode << ',' << arg << std::endl;
}
uint8_t opcode_b = opcodes[opcode];
uint8_t arg_b = parse_arg(arg);
uint8_t code = (opcode_b << 3) | arg_b;
if (enable_debug) {
std::cerr << (int)opcode_b << ',' << (int)arg_b << std::endl;
}
if (output_hex) {
std::cout << std::format("{:02x}", code);
if (sep_with_line) {
std::cout << std::endl;
} else {
std::cout << ',';
}
}
else {
std::cout.write(reinterpret_cast<char*>(&code), sizeof(code));
}
}
return 0;
}