-
Notifications
You must be signed in to change notification settings - Fork 0
/
mem_access.py
69 lines (57 loc) · 1.87 KB
/
mem_access.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
from typing import Tuple
def _find_addr(segment: str, index: str, state: dict) -> str:
latt_common = (
'D=M // D = segmentPointer' '\n'
f'@{index}' '\n'
f'A=A+D // addr = segmentPointer + {index}'
)
address = {
'constant': f'@{index}',
'temp' : f'@{5 + int(index)} // addr = 5 + {index}',
'pointer' : f"@{'THIS' if index == '0' else 'THAT'}",
'static' : f"@{state['class']}.{index}",
'local' : f'@LCL\n{latt_common}',
'argument': f'@ARG\n{latt_common}',
'this' : f'@THIS\n{latt_common}',
'that' : f'@THAT\n{latt_common}',
}
return address[segment]
def write_push(segment: str, index: str, state: dict) -> Tuple[Tuple[str, ...], dict]:
addr = _find_addr(segment, index, state)
if segment == 'constant':
D = f'D=A // D = {index}'
else:
D = 'D=M // D = *addr'
asm_block = (
addr,
D,
'@SP',
'A=M',
'M=D // *SP = D',
'@SP',
'M=M+1 // SP++',
)
return asm_block, state
def write_pop(segment: str, index: str, state: dict) -> Tuple[Tuple[str, ...], dict]:
addr = _find_addr(segment, index, state)
if segment == 'pointer':
asm_block = (
'@SP',
'AM=M-1 // SP--',
'D=M // D = *SP',
addr,
f"M=D // {'THIS' if index == '0' else 'THAT'} = *SP",
)
else:
asm_block = (
addr,
'D=A // D = addr',
'@SP',
'AM=M-1 // SP--',
'// now M = *SP, D = addr, we have to make A = addr, D = *SP',
'D=D-M // addr - *SP',
'A=M+D // *SP + (addr - *SP) = addr!',
'D=A-D // addr - (addr - *SP) = *SP!',
'M=D // *addr = *SP!!!',
)
return asm_block, state