我如何将 Ripper 的 AST 重新编译回 Ruby 代码?
Ripper 是 Ruby 1.9 附带的解析库。它将 Ruby 代码转换为 AST,如下所示:
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]]]]
是否有一个库可以获取此 AST 并将其转换回 Ruby 代码?
ruby_parser 和 ruby2ruby 曾经这样做过,但我想使用 Ripper 作为我的解析器。 (Ruby 1.9 甚至可能附带这样一个库,但我什至很难找到有关 Ripper 本身的文档)
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
请参阅“魔法师”。这很有效,但我在解析方法时发现了一个错误。如果您在文件“lib/sorcerer/resource.rb”的第 301 行下方添加 src.emit("; "),此问题将得到修复。但如果您决定使用它,您可能会发现更多。祝你好运。
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.