-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinstruction_parser.py
More file actions
97 lines (90 loc) · 2.5 KB
/
instruction_parser.py
File metadata and controls
97 lines (90 loc) · 2.5 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
from symbol_manager import SymbolManager
JUMP2BIN: dict[str, int] = {
'JGT': 0b001,
'JEQ': 0b010,
'JGE': 0b011,
'JLT': 0b100,
'JNE': 0b101,
'JLE': 0b110,
'JMP': 0b111
}
COMP2BIN: dict[str, int] = {
'0': 0b0101010,
'1': 0b0111111,
'-1': 0b0111010,
'D': 0b0001100,
'A': 0b0110000,
'!D': 0b0001101,
'!A': 0b0110001,
'-D': 0b0001111,
'-A': 0b0110011,
'D+1': 0b0011111,
'A+1': 0b0110111,
'D-1': 0b0001110,
'A-1': 0b0110010,
'D+A': 0b0000010,
'D-A': 0b0010011,
'A-D': 0b0000111,
'D&A': 0b0000000,
'D|A': 0b0010101,
'M': 0b1110000,
'!M': 0b1110001,
'-M': 0b1110011,
'M+1': 0b1110111,
'M-1': 0b1110010,
'D+M': 0b1000010,
'D-M': 0b1010011,
'M-D': 0b1000111,
'D&M': 0b1000000,
'D|M': 0b1010101
}
DEST2BIN: dict[str, int] = {
'M': 0b001,
'D': 0b010,
'DM': 0b011,
'A': 0b100,
'AM': 0b101,
'AD': 0b110,
'ADM': 0b111
}
class InstructionParser:
instruction: str
symbol_manager: SymbolManager
address: str
dest: int
comp: int
jump: int
def __init__(self, instruction: str, symbol_manager: SymbolManager):
self.instruction = instruction
self.symbol_manager = symbol_manager
self.address = ''
self.dest = 0
self.comp = 0
self.jump = 0
def is_a_instruction(self) -> bool:
return self.instruction[0] == '@'
def parse(self):
if self.is_a_instruction():
self.address = self.instruction[1:]
if not self.address.isdecimal():
self.symbol_manager.register_symbol(self.address)
else:
semi_split = self.instruction.split(';')
if len(semi_split) >= 2:
self.jump = JUMP2BIN[semi_split[1]]
equal_split = semi_split[0].split('=')
if len(equal_split) >= 2:
self.comp = COMP2BIN[equal_split[1]]
sorted_dest = "".join(sorted(equal_split[0]))
self.dest = DEST2BIN[sorted_dest]
else:
self.comp = COMP2BIN[equal_split[0]]
def to_binary(self) -> str:
if self.is_a_instruction():
if self.address.isdecimal():
int_address = int(self.address)
else:
int_address = self.symbol_manager.get_int_address(self.address)
return f'0{int_address:015b}'
else:
return f'111{self.comp:07b}{self.dest:03b}{self.jump:03b}'