YARV is a stack machine: an instruction takes its inputs from the top of a stack and puts its result back there – no registers. show_yarv compiles the code and runs it one instruction at a time, so you can watch. It is a simulator written in Ruby: it carries out the very instructions you saw in the last lesson with the rules of insns.def, calls the real methods for + and puts, and at the end Ruby runs the same code for real – the last step tells you whether both got the same result. Use ▶ to step, or ⏵:
show_yarv("a = 1 + 2\nputs a * 3\na")The right column is the VM stack the way YARV lays it out in memory, its top at the top. At the bottom of the frame: the local variable a. Above it, three slots that every frame gets (striped): me/cref, specval and flags – the ep, the environment pointer, points at flags, and the locals are found below it: a is ep[-3]. That is why getlocal's operand counts downwards. Above them, the operands: watch opt_plus take two and leave one. A method call adds a frame:
show_yarv("def square(x) = x * x\nsquare(4) + 1")definemethod puts the method's own instruction sequence into Object's method table. Then putself, putobject 4, opt_send_without_block: a new control frame is pushed above the old one, the 4 becomes its local x, the instructions on the left switch to those of the method. leave pops the frame and leaves 16 on the caller's stack. Recursion is just more frames – step through to the deepest point:
show_yarv("def fact(n) = n <= 1 ? 1 : n * fact(n - 1)\nfact(4)")- A frame is pushed in
vm_push_frame:372: the locals, thencref_or_me,specvalandtype– "ep with managing data" – and.ep = sp - 1. - What a control frame holds:
rb_control_frame_t:911(pc, sp, iseq, self, ep …); the three env slots:VM_ENV_DATA_SIZE:1418.
run(program) gets instructions like YARV's – [:putobject, 2], [:opt_mult], [:leave] – and works through them with an Array as its stack. :putobject and :leave are there; add :opt_plus and :opt_mult: pop two values, push the result. The program in the cell is 2 * 3 + 4, compiled as YARV would: 10.def run(program)
stack = []
program.each do |name, operand|
case name
when :putobject then stack.push(operand)
# :opt_plus and :opt_mult: pop two, push the result
when :leave then return stack.pop
end
end
end
run([[:putobject, 2], [:putobject, 3], [:opt_mult], [:putobject, 4], [:opt_plus], [:leave]])