Ruby代码编译:从AST到YARV指令的深入解析
1. YARV指令优化
在编译过程中,Ruby会对YARV(Yet Another Ruby Virtual Machine)指令进行优化。例如,对于 puts 2+2
这样的代码,最初生成的YARV指令如下:
NODE_SCOPE
putself
putobject
putobject
send
send
NODE_FCALL
2
2
<callinfo!mid:+, argc:1, ...
<callinfo!mid:puts, argc:1, ...
YARV instructions
table: [ none ]
args: [ none ]
method id:
puts
在优化步骤中,Ruby会用专门的指令替换一些YARV指令。像 send <callinfo!mid:+...
会被 opt_plus
替换,第二个 send
会被 opt_send_simple
替换,优化后的指令如下:
NODE_SCOPE
putself
putobject
putobject
opt_plus
opt_send_simple
NODE_FCALL
2
2
<callinfo!mid:puts,
argc:1...
YARV instructions
table: [ none ]
ar