I am writing an internal DSL in Ruby. Currently, the basic structure in this mini language is a block that must include the method during
, and optionally some other methods. E.g.:
do
something...
during do ... end
something else ...
end
I would like to simplify the language by treating blocks differently if they do not include the during
keyword. In this case I can just treat them like any other Ruby block.
Is it possible to detect if a block includes a specific method without running it? It is ok to assume that the method is not nested within an inner scope, like an if
or while
statement. I assume that if possible, this will involve reflection, which is ok.
Refinement and explanations
I am not trying to solve the halting problem or overcome any trick that a Ruby hacker might think of. The solution may apply only to the most naive case.
In several languages it is possible to get some reflection on the source code at runtime. In Python method objects have fields like bindings and bytecode. In Java, it is possible, although not trivial, to read the bytecode of a method and look for invokevirtual
commands.
I am not very familiar with Ruby. I don't know if Ruby objects that represent control elements, like procs and blocks, have similar fields. If my memory serves, Ruby has some framework for accessing its AST on runtime. However, I don't know if and how this framework can access specific blocks. A solution based on runtime AST parsing that works only for simple cases is perfectly acceptable.