Getting AST at Runtime

Hi Guys,

I wonder if there is a way to get an AST of a method? Also, it’d be
really cool if that AST after some transformations could be compiled
back to replace that original method (or at least could compiled back
into a string).

There are some ruby gems allowing to do it (for instance,
https://github.com/quix/live_ast) but all of them are buggy. It’d be
really cool if JRuby provided some kind of API (even if it’s an
internal Java API) to do it.

Thanks,
Victor S.

On 11/14/2011 01:39 AM, Victor S. wrote:

internal Java API) to do it.

I use the pair of ruby_parser[1] and ruby2ruby[2] for this purpose.

ast = RubyParser.new.parse(some_string_of_code)
ast = find_method_ast(ast, method_name)
ast = apply_transformation(ast)
string_of_code = Ruby2Ruby.new.process(ast)
eval(string_of_code)

This does not work for dynamically defined methods, but it works for any
Ruby interpreter (well, MRI, JRuby, Rubinius).

[1] https://github.com/seattlerb/ruby_parser
[2] https://github.com/seattlerb/ruby2ruby

best regards,

Ivo W.

Thanks you for your response. Last time I tried ruby_parser I had some
issues with 1.9 syntax. But maybe the situation has become better so
I’ll give it a shot.

Thanks,
Victor

Ruby 1.9 support is really important for me.

I hoped that there is an API that jruby itself uses, so it will be
really bulletproof (not as hacky as ruby_parser). But it looks like
there is nothing like that.

Thanks,
Victor

On 11/15/2011 03:38 AM, Victor S. wrote:

Thanks you for your response. Last time I tried ruby_parser I had some
issues with 1.9 syntax. But maybe the situation has become better so
I’ll give it a shot.

Good point, which I tend to forget, because I’m still at 1.8.7. The
support of ruby_parser for 1.9 constructs is still incomplete AFAIK.

best regards,

Ivo W.

Thank for your response. It looks like what I was looking for. I’ll
give it a try.

Thanks,
Victor

We do have a project which you can use to get an AST:

https://github.com/jruby/jruby-parser

This will not give you a live AST representation of a method, but if
you know where the method is in source. In theory it has a
round-tripping AST so you should be able to modify the AST and have it
regenerate source but I am unsure anyone has used the feature in a
long time so it might not work well.

-Tom

On Tue, Nov 15, 2011 at 7:34 PM, Victor S. [email protected]
wrote:

On Tue, Nov 15, 2011 at 1:27 AM, Ivo W. [email protected] wrote:

Ivo W.
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email


blog: http://blog.enebo.com twitter: tom_enebo
mail: [email protected]

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs