-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathi_compile.py
101 lines (87 loc) · 2.71 KB
/
i_compile.py
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
import re
import sys
from u_compile import OP_CODES, INS_OP_NUMS
from i_config import REG_FL
symbols = {}
instructions = []
def isNum(s):
try:
int(s)
return True
except ValueError:
return False
with open("test.s", encoding="utf-8") as f:
line_id = 0
bin_ad = 0
for line in f.readlines():
# print(line, "bin=", bin_ad)
line_id += 1
valid = line.strip().split(";")[0]
if len(valid) == 0:
continue
tokens = re.split(",\s*|\s+", valid)
if len(tokens) == 1:
token = tokens[0]
if token[0] == ".":
symbols[token] = bin_ad
continue
elif isNum(token):
instructions.append({
'type': "raw",
'line': line_id,
'bin': bin_ad,
'content': "{:016b}".format(int(token))
})
bin_ad += 1
continue
imme = 0
for token in tokens:
if token[0] == '.' or isNum(token):
if imme:
print("ERROR on line {}: Cannot give more than 1 immediate.".format(line_id), file=sys.stderr)
exit(1)
imme = 1
instructions.append({
'type': "instruction",
'line': line_id,
'bin': bin_ad,
'tokens': tokens
})
bin_ad += 1 + imme
with open("test.mif", "w") as f:
f.write("""WIDTH=16;
DEPTH=256;
ADDRESS_RADIX=UNS;
DATA_RADIX=BIN;
CONTENT BEGIN
""")
for instruction in instructions:
print(instruction)
if instruction['type'] == "raw":
f.write(" {} : {};\n".format(instruction['bin'], instruction['content']))
elif instruction['type'] == "instruction":
tmp = ""
imm = 0
opname = instruction['tokens'][0]
opcode = OP_CODES[opname]
opand = INS_OP_NUMS[opname]
tmp += "{:07b}".format(opcode)
for i in range(1, 4):
if i > opand:
tmp += "000"
continue
token = instruction['tokens'][i]
if isNum(token):
imm = (int(token) + 2**16) % 2**16
tmp += "111"
elif token[0] == '.':
imm = symbols[token]
tmp += "111"
else:
tmp += REG_FL[token]
f.write(" {} : {};\n".format(instruction['bin'], tmp))
if imm:
f.write(" {} : {:016b};\n".format(instruction['bin'] + 1, imm))
f.write("END;")
print(symbols)
print("Compile RAM Completed.")