Using ruby2ruby for translating ruby code
Once upon a time, I wanted to be able to generate RPN-style code from a more common Ruby-based syntax (and DSL). Fast-forward, I have been playing today with ParseTree and ruby2ruby (Thanks Ol for the hints!); The latter provides a to_sexp method on all Proc objects (which was lacking from the former). Given that a sexp is an abstract representation of a code portion, I can then use this structure to generate a new representation (in RPN, obviously) using my own “compiler”.
A real simple example (extracted from my test suite), with just an arithmetic operation:
assert_equal "kmh,8,*", evaluate_rpn_block {
kmh * 8
}
The evaluate_rpn_block method calls ruby2ruby’s to_sexp and then goes through the result tree. A more complete example of what can be done:
assert_equal "kmh,100,GT,0,kmh,IF", evaluate_rpn_block {
if kmh > 100 then
0
else
kmh
end
}
From there, what is lacking would be plugging the internal available functions (and operators) and matching the names used with existing definitions.