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 9, 2021
1 parent d360993 commit 96f4c2e
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 @@ -546,4 +546,19 @@ include("macros.jl")

@deprecate notify! notify

# 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 @@ -379,6 +379,34 @@ end
@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

@testset "deprecations" begin
a = Observable(1)
b = @test_deprecated map(sqrt, a; init=13.0)
Expand Down

0 comments on commit 96f4c2e

Please sign in to comment.