Extract the AST from a Ruby block

 ̄綄美尐妖づ 提交于 2019-12-05 22:44:26

问题


Is it possible to grab the AST of a block from Ruby itself?

I've had a look at both ParseTree and ruby_parser, but they both seem to have sketchy support (from what I've read) for Ruby 1.9.2. I need something that works well with 1.9.2.


回答1:


Ripper is included in MRI 1.9 out of the box.

ruby-1.9.2-p180 :004 > require 'ripper'
 => true
ruby-1.9.2-p180 :005 > Ripper.sexp("def a; end")
 => [:program, [[:def, [:@ident, "a", [1, 4]], [:params, nil, nil, nil, nil, nil], [:bodystmt, [[:void_stmt]], nil, nil, nil]]]] 

In 1.8, Ruby executes the code by traversing the AST, so it is possible to get the AST for a given method/block. In 1.9 it is not so; the code is first parsed, then converted to YARV bytecode, and then executed. Not the source, nor AST is kept after the translating step, and the latter is not reversible; hence you cannot get the AST for a block in 1.9.



来源:https://stackoverflow.com/questions/6894763/extract-the-ast-from-a-ruby-block

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!