Skip to content

Instantly share code, notes, and snippets.

@bicycle1885
Created February 13, 2019 02:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bicycle1885/a07e95be251c1447a4bc9ff35c3e3e9a to your computer and use it in GitHub Desktop.
Save bicycle1885/a07e95be251c1447a4bc9ff35c3e3e9a to your computer and use it in GitHub Desktop.
A macro to show the callstack inside a function call.
module CallStack
export @callstack
using Cassette
mutable struct CallState
depth::Int
end
Cassette.@context CallContext
function Cassette.prehook(ctx::CallContext, f, args...)
state = ctx.metadata
if !(f isa Core.Builtin)
print(" "^state.depth)
display(first(methods(f, typeof.(args))))
end
state.depth += 1
end
function Cassette.posthook(ctx::CallContext, f, args...)
state = ctx.metadata
state.depth -= 1
end
macro callstack(ex)
quote
state = CallState(0)
Cassette.overdub(CallContext(metadata=state), () -> $(esc(ex)))
end
end
end
# Example
# -------
foo() = 1
bar() = foo()
baz() = bar()
# julia> using .CallStack
#
# julia> @callstack baz();
# baz() in Main at /Users/kenta/workspace/julia/callstack.jl:41
# bar() in Main at /Users/kenta/workspace/julia/callstack.jl:40
# foo() in Main at /Users/kenta/workspace/julia/callstack.jl:39
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment