What's a good way to add method to `Base.MainInclude.eval`?

My module provides utilities to generate optimized code based on user input.
For instance, a generate function returns values of type Expr, that the user is responsible to evaluate whenever they need:

code, data = generate(input)
use_generated_code(eval(code), data)

My problem is that the generated code has many LineNumberNodes inserted, which makes the generated code difficult to inspect for end users. Still, I’m willing to keep these nodes to ease debugging. So I have chosen to wrap it into some opaque newtype:

struct GeneratedCode
    code::Expr
end
function Base.show(io::IO, c::GeneratedCode)
    print(io, "GeneratedCode{")
    print(io, Base.remove_linenums!(deepcopy(c.code)))
    print(io, "}")
end
# But I can't get the following overload right:
eval(c::GeneratedCode) = eval(c.code)

How to correctly overload eval then? I have tried with Core.eval and Base.MainInclude.eval instead, with no luck, because it seems that a new eval function is created within every module, right? Is there no way I can achieve something like the above?

Add

Core.eval(m::Module, c::GeneratedCode) = Core.eval(m, c.code)

should work. The new eval function created within every module is actually just something like eval(x) = Core.eval(@__MODULE__, x).

1 Like