Skip to content

Commit 39a58f7

Browse files
committed
Implement code generation for "pop local n"
1 parent e28c620 commit 39a58f7

File tree

1 file changed

+35
-11
lines changed

1 file changed

+35
-11
lines changed

lib/code_writer.rb

Lines changed: 35 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -64,17 +64,41 @@ def write_arithmetic(command)
6464
end
6565

6666
def write_push_pop(command, segment, index)
67-
output.puts <<-EOF
68-
// Load index into M[SP]
69-
@#{index}
70-
D=A
71-
@SP
72-
A=M
73-
M=D
74-
// SP++
75-
@SP
76-
M=M+1
77-
EOF
67+
case command
68+
when Parser::C_PUSH
69+
output.puts <<-EOF
70+
// Load index into M[SP]
71+
@#{index}
72+
D=A
73+
@SP
74+
A=M
75+
M=D
76+
// SP++
77+
@SP
78+
M=M+1
79+
EOF
80+
when Parser::C_POP
81+
output.puts <<-EOF
82+
// Get base address of the local segment
83+
@LCL // A=1
84+
D=M // D=RAM[1]=300
85+
// Add the index offset to the base address
86+
@#{index} // A=2
87+
D=A+D // D=302
88+
// Store the destination in R13
89+
@R13 // A=13
90+
M=D // RAM[13]=302
91+
// SP--
92+
@SP // A=0
93+
AM=M-1 // A,RAM[0]=RAM[0]-1=257
94+
// D = RAM[A] = the value to pop from the stack
95+
D=M // D=RAM[257]=23
96+
// RAM[302] = 23
97+
@R13 // A=13
98+
A=M // A=RAM[13]=302
99+
M=D // RAM[302]=23
100+
EOF
101+
end
78102
end
79103

80104
private

0 commit comments

Comments
 (0)