-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchoc_as.py
117 lines (79 loc) · 2.02 KB
/
choc_as.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
# The assembler
import re
BIT = {'nop':0b00, 'and':0b01, 'or':0b10, 'not':0b11} # bit ops
ATH = {'add':0b00, 'sub':0b01, 'sl':0b10, 'sr':0b11} # arithmetic ops
LOS = {'SPECIAL':0b00, 'st':0b01, 'ld':0b10, 'li':0b11} # load/store ops
BRC = {'bz':0b00, 'bnz':0b01, 'jz':0b10, 'jnz':0b11} # branch ops
SPC = {'ln':0b00, 'mov':0b01, 'pop':0b10, 'push':0b11} # special ops
r0 = 0
r1 = 1
r2 = 2
r3 = 3
res = 3
opcodes = []
def plus(val):
opcodes.append(val)
# compile code
def qcompile(file_name):
f = open(file_name, 'wb')
byte_array = bytearray(opcodes)
f.write(byte_array)
# general ops
def arith(instr, a, b):
return 0b01 << 6 | a << 4 | b << 2 | ATH[instr]
def bitw(instr, a, b):
return 0b00 << 6 | a << 4 | b << 2 | BIT[instr]
def load_store(instr, a, b):
if(instr == 'li'):
temp = {0: 0b00, 1: 0b01, -1: 0b11}
return 0b10 << 6 | a << 4 | temp[b] << 4 | LOS[instr]
return 0b10 << 6 | a << 4 | b << 2 | LOS[as_t.instr]
def branch(instr, a, b):
return 0b11 << 6 | a << 4 | b << 2 | BRC[instr]
def special(instr, a):
return 0b10 << 6 | a << 4 | SPC[instr] << 2 | 0b00
# bit ops
def nop():
plus(0)
def qand(a, b):
plus(bitw('and', a, b))
def qor(a, b):
plus(bitw('or', a, b))
def qnot(a, b):
plus(bitw('not', a, b))
# arithmetic ops
def add(a, b):
plus(arith('add', a, b))
def sub(a, b):
plus(arith('sub', a, b))
def sl(a, b):
plus(arith('s;', a, b))
def sr(a, b):
plus(arith('sr', a, b))
# load/store ops
def st(a, b):
plus(load_store('st', a, b))
def ld(a, b):
plus(load_store('ld', a, b))
def li(a, b):
plus(load_store('li', a, b))
def word(addr):
plus(addr)
# special ops
def ln(a):
plus(special('ln', a))
def mov(a):
plus(special('mov', a))
def pop(a):
plus(special('pop', a))
def push(a):
plus(special('push', a))
# branch ops
def bz(s, t):
plus(branch('bz', s, t))
def bnz(s, t):
plus(branch('bnz', s, t))
def jz(s, t):
plus(branch('jz', s, t))
def jnz(s, t):
plus(branch('jnz', s, t))