Can I detect if code is being run from a generated function?

Is there any way to detect if some code is being run inside a generated function? Something like:

function foo()
    if being_called_from_a_generated_function()
        # do something
    else
        # do it slightly differently
    end
end

@generated function bar()
    foo() # should take the "do something" branch
end

@generated function baz()
    quote
        foo() # should take the "do it slightly differently" branch
    end
end

Basically I have a foo with an efficient implementation but which is illegal inside generated functions, but foo can still work from inside generated functions as long as I do things slightly less efficiently to stay within the rules of what is allowed there, and I’d like to be able to have foo work in either case.

if u r using generated, function you can control which version gets called right?

Not sure why calling foo_inside_generated is not a solution instead of detection?

I can’t, this is up to the users of this function, and I don’t want to force them having to think about this.

Ahh, found it, its jl_is_in_pure_context:

julia> foo() = ccall(:jl_is_in_pure_context, Cint, ()) == 1 ? "generated" : "not generated";

julia> @generated bar() = foo();

julia> @generated baz() = :(foo());

julia> bar()
"generated"

julia> baz()
"not generated"
3 Likes