Skip to content

Commit

Permalink
Add a convenience utility for locating the origin of methods
Browse files Browse the repository at this point in the history
This can be handy when trying to figure out where some `var"#31#32"`
function was defined.
  • Loading branch information
timholy committed Jan 4, 2021
1 parent c2c9fe7 commit d1a2813
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
15 changes: 15 additions & 0 deletions src/Observables.jl
Original file line number Diff line number Diff line change
Expand Up @@ -439,4 +439,19 @@ include("flatten.jl")
include("time.jl")
include("macros.jl")

# Look up the source location of `do` block Observable MethodInstances
function methodlist(@nospecialize(ft::Type))
if ft <: OnUpdate
ft = Base.unwrap_unionall(Base.unwrap_unionall(ft).parameters[1])
if ft <: MapUpdater
ft = Base.unwrap_unionall(Base.unwrap_unionall(ft).parameters[1])
end
end
return Base.MethodList(ft.name.mt)
end

methodlist(mi::Core.MethodInstance) = methodlist(Base.unwrap_unionall(mi.specTypes).parameters[1])
methodlist(obsf::ObserverFunction) = methodlist(obsf.f)
methodlist(@nospecialize(f::Function)) = methodlist(typeof(f))

end # module
28 changes: 28 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -336,3 +336,31 @@ end
obs[] = 1
@test obs_copy[] == 1
end

@testset "methodlist" begin
_only(list) = (@assert length(list) == 1; return list[1]) # `only` is avail in Julia 1.4+
obs = Observable(1)
obsf = on(obs) do x
x + 1
end
line1 = -2 + @__LINE__
obs2 = map(obs) do x
x + 1
end
line2 = -2 + @__LINE__
obsflist = onany(obs, 5) do x, y
x + y
end
line3 = -2 + @__LINE__
obsf2 = _only(obsflist)
m = _only(Observables.methodlist(obsf).ms)
@test occursin("runtests.jl:$line1", string(m))
m = _only(Observables.methodlist(obsf.f).ms)
@test occursin("runtests.jl:$line1", string(m))
m = _only(Observables.methodlist(obs.listeners[2]).ms)
@test occursin("runtests.jl:$line2", string(m))
m = _only(Observables.methodlist(obsf2).ms)
@test occursin("runtests.jl:$line3", string(m))
obsf3 = on(sqrt, obs)
@test Observables.methodlist(obsf3).mt.name === :sqrt
end

0 comments on commit d1a2813

Please sign in to comment.