"code reflection cannot be used from generated functions"


I just got to love code_typed as it can compile-infer whether a function will fail because of MethodNotFound Error

However my usecase requires this as part of a generated function… which is why I run into the following error

code reflection cannot be used from generated functions

Looking into the code of code_typed I find the following hard-coded check

function code_typed(@nospecialize(f), @nospecialize(types=Tuple);
                    optimize=true, debuginfo::Symbol=:default,
                    world = ccall(:jl_get_world_counter, UInt, ()),
                    params = Core.Compiler.Params(world))
    ccall(:jl_is_in_pure_context, Bool, ()) && error("code reflection cannot be used from generated functions")

So there is indeed a hard-coded check whether this function is called in a generated context or not.

Why is this is not supported? It feels enormously like it should be possible to work, as only Type information and module information is needed.
Does someone know a workaround? I really really need generated functions here and would like to use code_typed for its inference support.



Just found a solution.

I only needed the inferred returntype, whether it is Union{} or not.
This can also be done with Core.Compiler.return_type which successfully runs in generated functions!



You can just use that at runtime, then when you fix the code, Revise.jl can pickup the correction and you don’t need to restart Julia.

RT = Base.promote_op(f, argT...) # preferred name for calling to `Core.Compiler.return_type`
RT === Union{} && @warn "call to F is statically known to fail"