从Ruby块中提取AST [英] Extract the AST from a Ruby block

查看:217
本文介绍了从Ruby块中提取AST的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以从Ruby本身获取块的AST?

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

我看过ParseTree和ruby_parser,但它们似乎都具有对Ruby 1.9.2的粗略支持(根据我的阅读)。我需要与1.9.2兼容的东西。

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.

推荐答案

开膛手包含在MRI 1.9中。

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]]]] 

在1.8中,Ruby通过遍历AST执行代码,因此可以获取给定方法/块的AST。在1.9中并非如此;该代码首先被解析,然后转换为YARV字节码,然后执行。在翻译步骤之后,不会保留源,也不会保留AST,并且后者不可逆;因此您无法在1.9版中获得AST。

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.

这篇关于从Ruby块中提取AST的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆