Ruby does not run the tree. The compiler turns it into an instruction sequence for YARV (Yet Another Ruby VM, Ruby's virtual machine since 1.9). You can ask for it – RubyVM::InstructionSequence is the same compiler ▶ uses:
puts RubyVM::InstructionSequence.compile("a = 1 + 2\nputs a * 3").disasmHow to read it: the number on the left is the position in the sequence (an operand takes a place too, so it jumps by 2), then the instruction and its operands; (1) is the source line. The local table names the variables: a@0.
putobject_INT2FIX_1_pushes the number 1. 0 and 1 are so common that they have instructions of their own, without an operand to read.opt_plusis+as one instruction: for two Integers it adds right away, without calling a method.opt_mult,opt_lt,opt_aref([]) and some thirty more are such shortcuts.setlocal_WC_0stores into a local variable;WC_0means "in this frame", level 0.putselfandopt_send_without_blockareputs: send the message toself, with one argument.leavereturns.
Why is 2 * 3 + 4 not simply compiled to 10? Compare:
names = ->(code) { RubyVM::InstructionSequence.compile(code).to_a.last.grep(Array).map(&:first) }
names.("2 * 3 + 4")Ruby computes it at run time, every time: someone could redefine Integer#* before the line runs, and then 10 would be wrong. That is also why opt_plus checks first: its fast path runs only while Integer#+ is still the original (BASIC_OP_UNREDEFINED_P in the source below); otherwise it calls the method like any other. The compiler does tidy up, though – a peephole optimizer goes over the instructions. Look at the end of this one:
puts RubyVM::InstructionSequence.compile("x = 7\nx > 5 ? :big : :small").disasmTwo leaves. A compiler would naturally write "after the first branch, jump to the end, where leave is" – the optimizer saw that the jump leads straight to leave and put the leave in its place. branchunless jumps when the condition is false. Every method has an instruction sequence of its own, too:
def double(n) = n * 2
puts RubyVM::InstructionSequence.of(method(:double)).disasm- Every instruction is defined in
insns.def, e.g.opt_plus:1299andleave:1156. - The fast path of
+:vm_opt_plus:6711– Fixnum, Flonum, Float, String, Array, each only while not redefined. - The peephole optimizer (the
leaveinstead of a jump):iseq_peephole_optimize:3358.
to_a.last is the body of an instruction sequence: line numbers (Integers), events (Symbols such as :RUBY_EVENT_LINE) and the instructions, each an Array [name, operands...]. Write insn_names(code): the names of the instructions, in order. For "a = 1 + 2" that is [:putobject_INT2FIX_1_, :putobject, :opt_plus, :dup, :setlocal_WC_0, :leave] – the dup is there because the assignment is also the value of the program.def insn_names(code)
body = RubyVM::InstructionSequence.compile(code).to_a.last
# keep the Arrays, give back their first element
body
end
insn_names("a = 1 + 2")