@tim.holy neat! There’s one problem with instance
(as I figured running your approach on a bunch of instances): it’s not defined for constructors. E.g.
julia> h() = 1
julia> (@which h()).sig.parameters[1].instance
h (generic function with 1 method)
julia> struct S end;
julia> (@which S()).sig.parameters[1].instance
ERROR: UndefRefError: access to undefined reference
Stacktrace:
[1] getproperty(::Type{T} where T, ::Symbol) at ./Base.jl:28
[2] top-level scope at REPL[95]:1
(And the error looks a bit bizzare.) So, instead of typeof(f)
we have Type{SomeType}
at this spot.
This is not too hard to work around, though, assuming constructor’s function defined in the same module as the corresponding type. So, currently, I have the following to convert a method instance to a function:
instance_to_function(mi :: MethodInstance) = begin
sig = Base.unwrap_unionall(mi.specTypes).types
if sig[1] <: Function # typeof(func)
sig[1].instance
else # constructor
getfield(
parentmodule(sig[1].parameters[1]),
mi.def.name)
end
end
I’m yet to see how it works on a larger data set (it could reveal some more problems). But already this is good progress, thanks a lot!