Skip to content

Instantly share code, notes, and snippets.

@pfitzseb

pfitzseb/tc.jl Secret

Last active March 16, 2022 11:19
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 pfitzseb/ab648d9d643ac018c44a884b367634da to your computer and use it in GitHub Desktop.
Save pfitzseb/ab648d9d643ac018c44a884b367634da to your computer and use it in GitHub Desktop.
VS Code TraceCalls
module TraceCalls
using Cassette, InteractiveUtils, UUIDs
mutable struct Trace
level::Int
cutoff::Int
items::Set{Dict}
end
Trace(level, cutoff) = Trace(level, cutoff, Set{Dict}())
Base.show(io::IO, ::MIME"application/vnd.julia-vscode.diagnostics", t::Trace) = (
source = "TraceCalls",
items = t.items
)
Cassette.@context TraceCtx
function Cassette.prehook(ctx::TraceCtx, args...)
ctx.metadata.level += 1
end
function Cassette.posthook(ctx::TraceCtx, out, f, args...)
ctx.metadata.level -= 1
if ctx.metadata.level < ctx.metadata.cutoff
if !(isa(f, Core.Builtin))
try
m = which(f, typeof(args))
push!(ctx.metadata.items, Dict(
:msg => string(m),
:line => m.line,
:path => fullpath(string(m.file)),
:severity => 2
))
catch err
@warn "Couldn't find a method for $f"
end
end
end
return nothing
end
function trace(f, level)
trace = Trace(0, level)
ctx = TraceCtx(metadata=trace)
Cassette.overdub(ctx, f)
return trace
end
macro trace(ex)
:(trace(() -> $(esc(ex)), 2))
end
macro trace(level, ex)
:(trace(() -> $(esc(ex)), $(esc(level))))
end
function fullpath(path)
return if isuntitled(path)
path
elseif isabspath(path)
maybe_fix_stdlib_path(path)
else
basepath(path)
end |> realpath′
end
isuntitled(path) = occursin(r"Untitled-\d+$", path)
basepath(path) = normpath(joinpath(Sys.BINDIR, Base.DATAROOTDIR, "julia", "base", path))
function realpath′(p)
try
ispath(p) ? realpath(p) : p
catch e
p
end |> normpath
end
# https://github.com/timholy/CodeTracking.jl/blob/2ba66f6f7864c6a3e06887a6832787bb3dc8e9be/src/utils.jl
const BUILDBOT_STDLIB_PATH = dirname(abspath(joinpath(String((@which uuid1()).file), "..", "..", "..")))
replace_buildbot_stdlibpath(str::String) = replace(str, BUILDBOT_STDLIB_PATH => Sys.STDLIB)
function maybe_fix_stdlib_path(p)
if !ispath′(p)
p_fix = replace_buildbot_stdlibpath(p)
ispath′(p_fix) && return p_fix
end
p
end
ispath′(p) = try
ispath(p)
catch err
false
end
end
f(x) = x + sin(x) + cos(x)
TraceCalls.@trace 200 f(3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment