Extract AST from Ruby Block

Is it possible to grab an AST block from Ruby itself?

I looked at both ParseTree and ruby_parser, but they both seem to have fragmentary support (from what I read) for Ruby 1.9.2. I need something that works well with 1.9.2.

+7
source share
1 answer

Ripper is included in the 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 code by passing AST, so you can get the AST for a given method / block. In 1.9, this is not so; the code is parsed first, then converted to YARV bytecode, and then executed. Not the original, but the AST is stored after the translation stage, and the latter is not reversible; therefore you cannot get an AST for a block in 1.9.

+7
source

All Articles