Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would I recompile Ripper's AST back to Ruby code?

Ripper is the the parsing library that ships with Ruby 1.9. It transforms Ruby code into an AST, like so:

pp Ripper.sexp("def foo; yield :a; return 1 end")

#=>

[:program,
 [[:def,
   [:@ident, "foo", [1, 4]],
   [:params, nil, nil, nil, nil, nil],
   [:bodystmt,
    [[:yield,
      [:args_add_block,
       [[:symbol_literal, [:symbol, [:@ident, "a", [1, 16]]]]],
       false]],
     [:return, [:args_add_block, [[:@int, "1", [1, 26]]], false]]],
    nil,
    nil,
    nil]]]]

Is there a library to take this AST and transform it back into Ruby code?

ruby_parser and ruby2ruby used to do this, but I would like to use Ripper as my parser. (Ruby 1.9 may even ship with such a library, but I'm struggling to find documentation even on Ripper itself)

like image 269
Jon Smock Avatar asked Feb 02 '11 18:02

Jon Smock


1 Answers

See "Sorcerer". This works well but I found a bug when parsing methods. If you add src.emit("; ") below the line 301 of the file "lib/sorcerer/resource.rb", this will be fixed. But you may find more if you decide to use this. Good luck.

like image 89
Guilherme Bernal Avatar answered Nov 15 '22 21:11

Guilherme Bernal