Skip to content

Commit 06701c5

Browse files
committed
Swap array variable and index expression when emitting index
In the book the example on page 229 shows "final VM code" as follows: // bar[k] = 19 push local 2 push argument 0 add [snip: code for assignment skipped] And makes reference to section 7.2.6 which on page 138 has code as follows: // bar[2] = 19 push local 0 push constant 2 add [snip: code for assignment skipped] So, naturally we assume that we output the address of the variable, the the index expression and then add them. However, the provided VM tool does these in the opposite order; it emits the index expression, then the address of the variable then adds them. It's not clear why this is in the opposite order, but in order to pass our specs where we compare our output with theirs we just have to follow along. Idle thought: is it more "reverse polish" stuff? or perhaps to isolate the variable reference from anything that the index expression might do that would change what the variable address actually is (e.g. call a function that changes the variable somehow?)
1 parent 30abf13 commit 06701c5

File tree

2 files changed

+2
-3
lines changed

2 files changed

+2
-3
lines changed

lib/expression_parser.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,8 +56,8 @@ def emit_assignment_to(assignment_expression, vm_writer, symbol_table, klass)
5656
end
5757
private
5858
def emit_index(vm_writer, symbol_table, klass)
59-
variable.emit(vm_writer, symbol_table, klass)
6059
index_expression.emit(vm_writer, symbol_table, klass)
60+
variable.emit(vm_writer, symbol_table, klass)
6161
vm_writer.write_arithmetic('add')
6262
end
6363
def emit_dereference(vm_writer)

spec/unit/expression_parser_spec.rb

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -122,16 +122,15 @@ def parse_method
122122
'a[1]'
123123
).to be_parsed_into(
124124
<<-VM
125-
push static 0
126125
push constant 1
126+
push static 0
127127
add
128128
pop pointer 1
129129
push that 0
130130
VM
131131
).when_parsed_as :expression
132132
end
133133

134-
135134
it 'emits VM code for binary expressions' do
136135
expect(
137136
'1 + 1'

0 commit comments

Comments
 (0)