• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

JuliaLang / julia / #37527

pending completion
#37527

push

local

web-flow
make `IRShow.method_name` inferrable (#49607)

18 of 18 new or added lines in 3 files covered. (100.0%)

68710 of 81829 relevant lines covered (83.97%)

33068903.12 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

81.77
/base/stacktraces.jl
1
# This file is a part of Julia. License is MIT: https://julialang.org/license
2

3
"""
4
Tools for collecting and manipulating stack traces. Mainly used for building errors.
5
"""
6
module StackTraces
7

8

9
import Base: hash, ==, show
10
import Core: CodeInfo, MethodInstance
11

12
export StackTrace, StackFrame, stacktrace
13

14
"""
15
    StackFrame
16

17
Stack information representing execution context, with the following fields:
18

19
- `func::Symbol`
20

21
  The name of the function containing the execution context.
22

23
- `linfo::Union{Core.MethodInstance, CodeInfo, Nothing}`
24

25
  The MethodInstance containing the execution context (if it could be found).
26

27
- `file::Symbol`
28

29
  The path to the file containing the execution context.
30

31
- `line::Int`
32

33
  The line number in the file containing the execution context.
34

35
- `from_c::Bool`
36

37
  True if the code is from C.
38

39
- `inlined::Bool`
40

41
  True if the code is from an inlined frame.
42

43
- `pointer::UInt64`
44

45
  Representation of the pointer to the execution context as returned by `backtrace`.
46

47
"""
48
struct StackFrame # this type should be kept platform-agnostic so that profiles can be dumped on one machine and read on another
49
    "the name of the function containing the execution context"
33,514✔
50
    func::Symbol
51
    "the path to the file containing the execution context"
52
    file::Symbol
53
    "the line number in the file containing the execution context"
54
    line::Int
55
    "the MethodInstance or CodeInfo containing the execution context (if it could be found), \
56
     or Module (for macro expansions)"
57
    linfo::Union{MethodInstance, Method, Module, CodeInfo, Nothing}
58
    "true if the code is from C"
59
    from_c::Bool
60
    "true if the code is from an inlined frame"
61
    inlined::Bool
62
    "representation of the pointer to the execution context as returned by `backtrace`"
63
    pointer::UInt64  # Large enough to be read losslessly on 32- and 64-bit machines.
64
end
65

66
StackFrame(func, file, line) = StackFrame(Symbol(func), Symbol(file), line,
×
67
                                          nothing, false, false, 0)
68

69
"""
70
    StackTrace
71

72
An alias for `Vector{StackFrame}` provided for convenience; returned by calls to
73
`stacktrace`.
74
"""
75
const StackTrace = Vector{StackFrame}
76

77
const empty_sym = Symbol("")
78
const UNKNOWN = StackFrame(empty_sym, empty_sym, -1, nothing, true, false, 0) # === lookup(C_NULL)
79

80

81
#=
82
If the StackFrame has function and line information, we consider two of them the same if
83
they share the same function/line information.
84
=#
85
function ==(a::StackFrame, b::StackFrame)
822✔
86
    return a.line == b.line && a.from_c == b.from_c && a.func == b.func && a.file == b.file && a.inlined == b.inlined # excluding linfo and pointer
64,659✔
87
end
88

89
function hash(frame::StackFrame, h::UInt)
1,426,058✔
90
    h += 0xf4fbda67fe20ce88 % UInt
1,426,058✔
91
    h = hash(frame.line, h)
1,426,058✔
92
    h = hash(frame.file, h)
1,426,058✔
93
    h = hash(frame.func, h)
1,426,058✔
94
    h = hash(frame.from_c, h)
1,426,058✔
95
    h = hash(frame.inlined, h)
1,426,058✔
96
    return h
1,426,058✔
97
end
98

99
get_inlinetable(::Any) = nothing
×
100
function get_inlinetable(mi::MethodInstance)
7,332✔
101
    isdefined(mi, :def) && mi.def isa Method && isdefined(mi, :cache) && isdefined(mi.cache, :inferred) &&
12,567✔
102
        mi.cache.inferred !== nothing || return nothing
103
    linetable = ccall(:jl_uncompress_ir, Any, (Any, Any, Any), mi.def, mi.cache, mi.cache.inferred).linetable
2,097✔
104
    return filter!(x -> x.inlined_at > 0, linetable)
1,294,253✔
105
end
106

107
get_method_instance_roots(::Any) = nothing
×
108
function get_method_instance_roots(mi::Union{Method, MethodInstance})
5,235✔
109
    m = mi isa MethodInstance ? mi.def : mi
5,235✔
110
    m isa Method && isdefined(m, :roots) || return nothing
5,235✔
111
    return filter(x -> x isa MethodInstance, m.roots)
608,483✔
112
end
113

114
function lookup_inline_frame_info(func::Symbol, file::Symbol, linenum::Int, inlinetable::Vector{Core.LineInfoNode})
1,728✔
115
    #REPL frames and some base files lack this prefix while others have it; should fix?
116
    filestripped = Symbol(lstrip(string(file), ('.', '\\', '/')))
1,728✔
117
    linfo = nothing
×
118
    #=
119
    Some matching entries contain the MethodInstance directly.
120
    Other matching entries contain only a Method or Symbol (function name); such entries
121
    are located after the entry with the MethodInstance, so backtracking is required.
122
    If backtracking fails, the Method or Module is stored for return, but we continue
123
    the search in case a MethodInstance is found later.
124
    TODO: If a backtrack has failed, do we need to backtrack again later if another Method
125
    or Symbol match is found? Or can a limit on the subsequent backtracks be placed?
126
    =#
127
    for (i, line) in enumerate(inlinetable)
3,456✔
128
        Base.IRShow.method_name(line) === func && line.file ∈ (file, filestripped) && line.line == linenum || continue
872,329✔
129
        if line.method isa MethodInstance
2,749✔
130
            linfo = line.method
1,172✔
131
            break
1,172✔
132
        elseif line.method isa Method || line.method isa Symbol
3,154✔
133
            linfo = line.method isa Method ? line.method : line.module
3,154✔
134
            # backtrack to find the matching MethodInstance, if possible
135
            for j in (i - 1):-1:1
3,150✔
136
                nextline = inlinetable[j]
3,504✔
137
                nextline.inlined_at == line.inlined_at && Base.IRShow.method_name(line) === Base.IRShow.method_name(nextline) && line.file === nextline.file || break
3,518✔
138
                if nextline.method isa MethodInstance
3,490✔
139
                    linfo = nextline.method
1,558✔
140
                    break
1,558✔
141
                end
142
            end
1,932✔
143
        end
144
    end
871,157✔
145
    return linfo
1,728✔
146
end
147

148
function lookup_inline_frame_info(func::Symbol, file::Symbol, miroots::Vector{Any})
7,358✔
149
    # REPL frames and some base files lack this prefix while others have it; should fix?
150
    filestripped = Symbol(lstrip(string(file), ('.', '\\', '/')))
7,358✔
151
    matches = filter(miroots) do x
7,358✔
152
        x.def isa Method || return false
663,563✔
153
        m = x.def::Method
663,563✔
154
        return m.name == func && m.file ∈ (file, filestripped)
663,563✔
155
    end
156
    if length(matches) > 1
7,358✔
157
        # ambiguous, check if method is same and return that instead
158
        all_matched = true
×
159
        for m in matches
4,254✔
160
            all_matched = m.def.line == matches[1].def.line &&
12,622✔
161
                m.def.module == matches[1].def.module
162
            all_matched || break
12,622✔
163
        end
9,450✔
164
        if all_matched
4,254✔
165
            return matches[1].def
541✔
166
        end
167
        # all else fails, return module if they match, or give up
168
        all_matched = true
×
169
        for m in matches
3,713✔
170
            all_matched = m.def.module == matches[1].def.module
25,686✔
171
            all_matched || break
25,686✔
172
        end
29,399✔
173
        return all_matched ? matches[1].def.module : nothing
3,713✔
174
    elseif length(matches) == 1
3,104✔
175
        return matches[1]
2,279✔
176
    end
177
    return nothing
825✔
178
end
179

180
"""
181
    lookup(pointer::Ptr{Cvoid}) -> Vector{StackFrame}
182

183
Given a pointer to an execution context (usually generated by a call to `backtrace`), looks
184
up stack frame context information. Returns an array of frame information for all functions
185
inlined at that point, innermost function first.
186
"""
187
Base.@constprop :none function lookup(pointer::Ptr{Cvoid})
20,105✔
188
    infos = ccall(:jl_lookup_code_address, Any, (Ptr{Cvoid}, Cint), pointer, false)::Core.SimpleVector
20,105✔
189
    pointer = convert(UInt64, pointer)
20,105✔
190
    isempty(infos) && return [StackFrame(empty_sym, empty_sym, -1, nothing, true, false, pointer)] # this is equal to UNKNOWN
20,105✔
191
    parent_linfo = infos[end][4]
20,105✔
192
    inlinetable = get_inlinetable(parent_linfo)
32,878✔
193
    miroots = inlinetable === nothing ? get_method_instance_roots(parent_linfo) : nothing # fallback if linetable missing
20,105✔
194
    res = Vector{StackFrame}(undef, length(infos))
20,105✔
195
    for i in reverse(1:length(infos))
40,210✔
196
        info = infos[i]::Core.SimpleVector
32,333✔
197
        @assert(length(info) == 6)
32,333✔
198
        func = info[1]::Symbol
32,333✔
199
        file = info[2]::Symbol
32,333✔
200
        linenum = info[3]::Int
32,333✔
201
        linfo = info[4]
32,333✔
202
        if i < length(infos)
32,333✔
203
            if inlinetable !== nothing
12,228✔
204
                linfo = lookup_inline_frame_info(func, file, linenum, inlinetable)
1,728✔
205
            elseif miroots !== nothing
10,500✔
206
                linfo = lookup_inline_frame_info(func, file, miroots)
7,358✔
207
            end
208
            linfo = linfo === nothing ? parentmodule(res[i + 1]) : linfo # e.g. `macro expansion`
12,615✔
209
        end
210
        res[i] = StackFrame(func, file, linenum, linfo, info[5]::Bool, info[6]::Bool, pointer)
32,333✔
211
    end
44,561✔
212
    return res
20,105✔
213
end
214

215
const top_level_scope_sym = Symbol("top-level scope")
216

217
function lookup(ip::Union{Base.InterpreterIP,Core.Compiler.InterpreterIP})
194✔
218
    code = ip.code
194✔
219
    if code === nothing
194✔
220
        # interpreted top-level expression with no CodeInfo
221
        return [StackFrame(top_level_scope_sym, empty_sym, 0, nothing, false, false, 0)]
×
222
    end
223
    codeinfo = (code isa MethodInstance ? code.uninferred : code)::CodeInfo
388✔
224
    # prepare approximate code info
225
    if code isa MethodInstance && (meth = code.def; meth isa Method)
194✔
226
        func = meth.name
×
227
        file = meth.file
×
228
        line = meth.line
×
229
    else
230
        func = top_level_scope_sym
×
231
        file = empty_sym
×
232
        line = Int32(0)
×
233
    end
234
    i = max(ip.stmt+1, 1)  # ip.stmt is 0-indexed
194✔
235
    if i > length(codeinfo.codelocs) || codeinfo.codelocs[i] == 0
388✔
236
        return [StackFrame(func, file, line, code, false, false, 0)]
×
237
    end
238
    lineinfo = codeinfo.linetable[codeinfo.codelocs[i]]::Core.LineInfoNode
194✔
239
    scopes = StackFrame[]
194✔
240
    while true
530✔
241
        inlined = lineinfo.inlined_at != 0
530✔
242
        push!(scopes, StackFrame(Base.IRShow.method_name(lineinfo)::Symbol, lineinfo.file, lineinfo.line, inlined ? nothing : code, false, inlined, 0))
724✔
243
        inlined || break
530✔
244
        lineinfo = codeinfo.linetable[lineinfo.inlined_at]::Core.LineInfoNode
336✔
245
    end
336✔
246
    return scopes
194✔
247
end
248

249
"""
250
    stacktrace([trace::Vector{Ptr{Cvoid}},] [c_funcs::Bool=false]) -> StackTrace
251

252
Return a stack trace in the form of a vector of `StackFrame`s. (By default stacktrace
253
doesn't return C functions, but this can be enabled.) When called without specifying a
254
trace, `stacktrace` first calls `backtrace`.
255
"""
256
Base.@constprop :none function stacktrace(trace::Vector{<:Union{Base.InterpreterIP,Core.Compiler.InterpreterIP,Ptr{Cvoid}}}, c_funcs::Bool=false)
45✔
257
    stack = StackTrace()
76✔
258
    for ip in trace
39✔
259
        for frame in lookup(ip)
1,112✔
260
            # Skip frames that come from C calls.
261
            if c_funcs || !frame.from_c
2,965✔
262
                push!(stack, frame)
534✔
263
            end
264
        end
2,661✔
265
    end
1,151✔
266
    return stack
39✔
267
end
268

269
Base.@constprop :none function stacktrace(c_funcs::Bool=false)
×
270
    stack = stacktrace(backtrace(), c_funcs)
×
271
    # Remove frame for this function (and any functions called by this function).
272
    remove_frames!(stack, :stacktrace)
×
273
    # also remove all of the non-Julia functions that led up to this point (if that list is non-empty)
274
    c_funcs && deleteat!(stack, 1:(something(findfirst(frame -> !frame.from_c, stack), 1) - 1))
×
275
    return stack
×
276
end
277

278
"""
279
    remove_frames!(stack::StackTrace, name::Symbol)
280

281
Takes a `StackTrace` (a vector of `StackFrames`) and a function name (a `Symbol`) and
282
removes the `StackFrame` specified by the function name from the `StackTrace` (also removing
283
all frames above the specified function). Primarily used to remove `StackTraces` functions
284
from the `StackTrace` prior to returning it.
285
"""
286
function remove_frames!(stack::StackTrace, name::Symbol)
×
287
    deleteat!(stack, 1:something(findlast(frame -> frame.func == name, stack), 0))
×
288
    return stack
×
289
end
290

291
function remove_frames!(stack::StackTrace, names::Vector{Symbol})
×
292
    deleteat!(stack, 1:something(findlast(frame -> frame.func in names, stack), 0))
×
293
    return stack
×
294
end
295

296
"""
297
    remove_frames!(stack::StackTrace, m::Module)
298

299
Return the `StackTrace` with all `StackFrame`s from the provided `Module` removed.
300
"""
301
function remove_frames!(stack::StackTrace, m::Module)
×
302
    filter!(f -> !from(f, m), stack)
×
303
    return stack
×
304
end
305

306
is_top_level_frame(f::StackFrame) = f.linfo isa CodeInfo || (f.linfo === nothing && f.func === top_level_scope_sym)
8✔
307

308
function show_spec_linfo(io::IO, frame::StackFrame)
2,814✔
309
    linfo = frame.linfo
2,814✔
310
    if linfo === nothing
2,814✔
311
        if frame.func === empty_sym
279✔
312
            print(io, "ip:0x", string(frame.pointer, base=16))
×
313
        elseif frame.func === top_level_scope_sym
279✔
314
            print(io, "top-level scope")
18✔
315
        else
316
            Base.print_within_stacktrace(io, Base.demangle_function_name(string(frame.func)), bold=true)
261✔
317
        end
318
    elseif linfo isa CodeInfo
2,535✔
319
        print(io, "top-level scope")
91✔
320
    elseif linfo isa Module
2,444✔
321
        Base.print_within_stacktrace(io, Base.demangle_function_name(string(frame.func)), bold=true)
776✔
322
    else
323
        def, sig = if linfo isa MethodInstance
1,668✔
324
             linfo.def, linfo.specTypes
1,654✔
325
        else
326
            linfo, linfo.sig
1,682✔
327
        end
328
        if def isa Method
1,668✔
329
            argnames = Base.method_argnames(def)
3,336✔
330
            argnames = replace(argnames, :var"#unused#" => :var"")
1,668✔
331
            if def.nkw > 0
1,668✔
332
                # rearrange call kw_impl(kw_args..., func, pos_args...) to func(pos_args...)
333
                kwarg_types = Any[ fieldtype(sig, i) for i = 2:(1+def.nkw) ]
285✔
334
                uw = Base.unwrap_unionall(sig)::DataType
260✔
335
                pos_sig = Base.rewrap_unionall(Tuple{uw.parameters[(def.nkw+2):end]...}, sig)
263✔
336
                kwnames = argnames[2:(def.nkw+1)]
260✔
337
                for i = 1:length(kwnames)
520✔
338
                    str = string(kwnames[i])::String
285✔
339
                    if endswith(str, "...")
285✔
340
                        kwnames[i] = Symbol(str[1:end-3])
×
341
                    end
342
                end
310✔
343
                Base.show_tuple_as_call(io, def.name, pos_sig;
260✔
344
                                        demangle=true,
345
                                        kwargs=zip(kwnames, kwarg_types),
346
                                        argnames=argnames[def.nkw+2:end])
347
            else
348
                Base.show_tuple_as_call(io, def.name, sig; demangle=true, argnames)
1,408✔
349
            end
350
        else
351
            Base.show_mi(io, linfo, true)
×
352
        end
353
    end
354
end
355

356
function show(io::IO, frame::StackFrame)
169✔
357
    show_spec_linfo(io, frame)
169✔
358
    if frame.file !== empty_sym
169✔
359
        file_info = basename(string(frame.file))
162✔
360
        print(io, " at ")
162✔
361
        print(io, file_info, ":")
162✔
362
        if frame.line >= 0
162✔
363
            print(io, frame.line)
162✔
364
        else
365
            print(io, "?")
×
366
        end
367
    end
368
    if frame.inlined
169✔
369
        print(io, " [inlined]")
54✔
370
    end
371
end
372

373
function Base.parentmodule(frame::StackFrame)
2,257✔
374
    linfo = frame.linfo
8,027✔
375
    if linfo isa MethodInstance
8,027✔
376
        def = linfo.def
2,871✔
377
        if def isa Module
2,871✔
378
            return def
×
379
        else
380
            return (def::Method).module
2,871✔
381
        end
382
    elseif linfo isa Method
5,156✔
383
        return linfo.module
66✔
384
    elseif linfo isa Module
5,090✔
385
        return linfo
1,123✔
386
    else
387
        # The module is not always available (common reasons include
388
        # frames arising from the interpreter)
389
        nothing
3,967✔
390
    end
391
end
392

393
"""
394
    from(frame::StackFrame, filter_mod::Module) -> Bool
395

396
Return whether the `frame` is from the provided `Module`
397
"""
398
function from(frame::StackFrame, m::Module)
×
399
    return parentmodule(frame) === m
×
400
end
401

402
end
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc