-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompiler.py
More file actions
101 lines (94 loc) · 3.17 KB
/
Copy pathcompiler.py
File metadata and controls
101 lines (94 loc) · 3.17 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
import binascii
import sys
import struct
dict_opcode = {"AND":0,
"ORR":1,
"EOR":2,
"ADD":3,
"ADC":4,
"CMP":5,
"SUB":6,
"SBC":7,
"MOV":8,
"LSH":9,
"RSH":10}
dict_register = {"r0":0,
"r1":1,
"r2":2,
"r3":3,
"r4":4,
"r5":5,
"r6":6,
"r7":7,
"r8":8,
"r9":9,
"r10":10,
"r11":11,
"r12":12,
"r13":13,
"r14":14,
"r15":15}
dict_branch = {"B":8,
"BEQ":9,
"BNE":10,
"BLE":11,
"BGE":12,
"BL":13,
"BG":14,}
def instr_handler_op(iv,dest_r,s_op,f_op,op,ivf):
binary = 0
if iv > 255:
return("Error Immediate Value too high")
binary = iv << 0 | dest_r << 8 | s_op << 12 | f_op << 16 | op << 20 | ivf << 24
print(bin(binary))
print(binary)
return struct.pack('>I',binary)
def instr_handler_branch(offset,bcc):
if offset >= 0 :
signe = 0
elif offset < 0:
offset = abs(offset)
signe = 1
if abs(offset) > 134217727:
return("Error Offset too high for branch")
binary = offset << 0 | signe << 27 | bcc << 28
print(bin(binary))
print(binary)
return struct.pack('>I',binary)
def main(filename):
file = open(filename,"r")
tab = file.readlines()
file.close()
for i in range(len(tab)):
tab[i] = tab[i].rstrip("\n")
binary_file = open("binary","wb")
for i in range(len(tab)):
s = tab[i].replace(",","").split()
if s and (s[0].upper() in dict_opcode):
print(s)
op = dict_opcode[s[0].upper()]
if op == 0 or op == 1 or op == 2 or op ==3 or op ==4 or op ==6 or op ==7 or op ==9 or op ==10:
if not(s[3].isnumeric()):
instr = instr_handler_op(0,dict_register[s[1]],dict_register[s[3]],dict_register[s[2]],op,0)
else:
instr = instr_handler_op(int(s[3]),dict_register[s[1]],0,dict_register[s[2]],op,1)
elif op == 5:
if not(s[2].isnumeric()):
instr = instr_handler_op(0,0,dict_register[s[2]],dict_register[s[1]],op,0)
else:
instr = instr_handler_op(int(s[2]),0,0,dict_register[s[1]],op,1)
elif op == 8:
if not(s[2].isnumeric()):
instr = instr_handler_op(0,dict_register[s[1]],dict_register[s[2]],0,op,0)
else:
instr = instr_handler_op(int(s[2]),dict_register[s[1]],0,0,op,1)
binary_file.write(instr)
elif s and (s[0].upper() in dict_branch):
print(s)
print(int(s[1]))
instr = instr_handler_branch(int(s[1]), dict_branch[s[0]])
binary_file.write(instr)
if isinstance(instr, str):
return(print(instr))
binary_file.close()
main(sys.argv[1])