Andrew Grimm
Andrew Grimm

Reputation: 81520

Is the information displayed in ruby --dump available at runtime?

In 10 Things You Didn't Know Ruby Could Do, slide 30, James Edward Gray II mentions

ruby -e 'puts { is_this_a_block }' --dump parsetree

which produces

###########################################################
## Do NOT use this node dump for any purpose other than  ##
## debug and research.  Compatibility is not guaranteed. ##
###########################################################

# @ NODE_SCOPE (line: 1)
# +- nd_tbl: (empty)
# +- nd_args:
# |   (null node)
# +- nd_body:
#     @ NODE_ITER (line: 1)
#     +- nd_iter:
#     |   @ NODE_FCALL (line: 1)
#     |   +- nd_mid: :puts
#     |   +- nd_args:
#     |       (null node)
#     +- nd_body:
#         @ NODE_SCOPE (line: 1)
#         +- nd_tbl: (empty)
#         +- nd_args:
#         |   (null node)
#         +- nd_body:
#             @ NODE_VCALL (line: 1)
#             +- nd_mid: :is_this_a_block

Is the information outputted here available at runtime? If so, does the information represent merely what code has been written down, or does it also have the results of any metaprogramming that has been done?

Upvotes: 4

Views: 258

Answers (1)

Ilya O.
Ilya O.

Reputation: 1500

Yep. You can use the Ripper gem (which is included out-of-the-box with MRI 1.9) to generate an AST (abstract syntax tree) for a given string of code (via Ripper.sexp). However, because of architectural changes in MRI 1.9, once your code is parsed and translated into YARV bytecode both the original source and the AST is dropped and you will no longer be able to get this information. However, if you throw in any code that you would have generated via metaprogramming into Ripper.sexp you can get the AST of the result. You can use also some of the other tricks shown in JEG2's talk to parse in the source file and generate an AST for it (although any metaprogrammed code will not be parsed as it does not exist yet).

Upvotes: 3

Related Questions