Modifying the AST of a running Ruby script in-place

J

John Feminella

Is there a way to not merely _construct_ the AST of a Ruby script, but
also to _modify_ it in-memory, thus producing a different script? (I
realize that there's no Ruby spec and thus, every Ruby implementation
is going to have a different parse tree and thus a different answer.
My question is confined mostly to MRI.)

As a simple example, suppose that I would like to write a method
called "subtractify(m)". The subtractify method accepts another method
`m` as input, and then changes all uses of the `+` operator to `-`.
The result is a new, unbound method that can either replace the
original method or be attached somewhere else. If I were to bind this
new method to the original object and replace the original one
(similar to overwriting it with a new `def`), the result should be
equivalent to running the "subtractified" variant of the method with
the original object as the receiver.

Is that (or a similar situation) possible? If so, are there
limitations to what can and can't be modified?

~ jf
 
P

Peter Zotov

Is there a way to not merely _construct_ the AST of a Ruby script, but
also to _modify_ it in-memory, thus producing a different script? (I
realize that there's no Ruby spec and thus, every Ruby implementation
is going to have a different parse tree and thus a different answer.
My question is confined mostly to MRI.)

The problem is, there is no more AST in runtime in MRI 1.9. This was the
biggest 1.9 change: in 1.8 Ruby has traversed and executed the AST
directly, and that was painfully slow. 1.9 now uses bytecode instead;
you can take a look at RubyVM::InstructionSequence.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,067
Latest member
HunterTere

Latest Threads

Top