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

JuliaLang / julia / #37572

pending completion
#37572

push

local

web-flow
Improve effects for Base.fieldindex (#50199)

Split out the error path into a function with separate effects assumptions,
so that constant propagation on `err` can conclude that the `err=false` case
does not throw. Fixes #50198.

7 of 7 new or added lines in 1 file covered. (100.0%)

73199 of 84194 relevant lines covered (86.94%)

33380304.55 hits per line

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

82.83
/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,580✔
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)
775✔
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
42,567✔
87
end
88

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

99
get_inlinetable(::Any) = nothing
×
100
function get_inlinetable(mi::MethodInstance)
7,704✔
101
    isdefined(mi, :def) && mi.def isa Method && isdefined(mi, :cache) && isdefined(mi.cache, :inferred) &&
14,071✔
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
1,337✔
104
    return filter!(x -> x.inlined_at > 0, linetable)
68,871✔
105
end
106

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

114
function lookup_inline_frame_info(func::Symbol, file::Symbol, linenum::Int, inlinetable::Vector{Core.LineInfoNode})
453✔
115
    #REPL frames and some base files lack this prefix while others have it; should fix?
116
    filestripped = Symbol(lstrip(string(file), ('.', '\\', '/')))
453✔
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)
906✔
128
        Base.IRShow.method_name(line) === func && line.file ∈ (file, filestripped) && line.line == linenum || continue
54,637✔
129
        if line.method isa MethodInstance
539✔
130
            linfo = line.method
348✔
131
            break
348✔
132
        elseif line.method isa Method || line.method isa Symbol
382✔
133
            linfo = line.method isa Method ? line.method : line.module
382✔
134
            # backtrack to find the matching MethodInstance, if possible
135
            for j in (i - 1):-1:1
382✔
136
                nextline = inlinetable[j]
489✔
137
                nextline.inlined_at == line.inlined_at && Base.IRShow.method_name(line) === Base.IRShow.method_name(nextline) && line.file === nextline.file || break
493✔
138
                if nextline.method isa MethodInstance
485✔
139
                    linfo = nextline.method
186✔
140
                    break
186✔
141
                end
142
            end
299✔
143
        end
144
    end
54,289✔
145
    return linfo
453✔
146
end
147

148
function lookup_inline_frame_info(func::Symbol, file::Symbol, miroots::Vector{Any})
8,564✔
149
    # REPL frames and some base files lack this prefix while others have it; should fix?
150
    filestripped = Symbol(lstrip(string(file), ('.', '\\', '/')))
8,564✔
151
    matches = filter(miroots) do x
8,564✔
152
        x.def isa Method || return false
978,022✔
153
        m = x.def::Method
978,022✔
154
        return m.name == func && m.file ∈ (file, filestripped)
978,022✔
155
    end
156
    if length(matches) > 1
8,564✔
157
        # ambiguous, check if method is same and return that instead
158
        all_matched = true
×
159
        for m in matches
5,464✔
160
            all_matched = m.def.line == matches[1].def.line &&
15,651✔
161
                m.def.module == matches[1].def.module
162
            all_matched || break
15,651✔
163
        end
11,969✔
164
        if all_matched
5,464✔
165
            return matches[1].def
891✔
166
        end
167
        # all else fails, return module if they match, or give up
168
        all_matched = true
×
169
        for m in matches
4,573✔
170
            all_matched = m.def.module == matches[1].def.module
32,265✔
171
            all_matched || break
32,265✔
172
        end
36,838✔
173
        return all_matched ? matches[1].def.module : nothing
4,573✔
174
    elseif length(matches) == 1
3,100✔
175
        return matches[1]
2,441✔
176
    end
177
    return nothing
659✔
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})
19,756✔
188
    infos = ccall(:jl_lookup_code_address, Any, (Ptr{Cvoid}, Cint), pointer, false)::Core.SimpleVector
19,756✔
189
    pointer = convert(UInt64, pointer)
19,756✔
190
    isempty(infos) && return [StackFrame(empty_sym, empty_sym, -1, nothing, true, false, pointer)] # this is equal to UNKNOWN
19,756✔
191
    parent_linfo = infos[end][4]
19,756✔
192
    inlinetable = get_inlinetable(parent_linfo)
31,808✔
193
    miroots = inlinetable === nothing ? get_method_instance_roots(parent_linfo) : nothing # fallback if linetable missing
19,756✔
194
    res = Vector{StackFrame}(undef, length(infos))
19,756✔
195
    for i in reverse(1:length(infos))
39,512✔
196
        info = infos[i]::Core.SimpleVector
32,034✔
197
        @assert(length(info) == 6)
32,034✔
198
        func = info[1]::Symbol
32,034✔
199
        file = info[2]::Symbol
32,034✔
200
        linenum = info[3]::Int
32,034✔
201
        linfo = info[4]
32,034✔
202
        if i < length(infos)
32,034✔
203
            if inlinetable !== nothing
12,278✔
204
                linfo = lookup_inline_frame_info(func, file, linenum, inlinetable)
453✔
205
            elseif miroots !== nothing
11,825✔
206
                linfo = lookup_inline_frame_info(func, file, miroots)
8,564✔
207
            end
208
            linfo = linfo === nothing ? parentmodule(res[i + 1]) : linfo # e.g. `macro expansion`
12,510✔
209
        end
210
        res[i] = StackFrame(func, file, linenum, linfo, info[5]::Bool, info[6]::Bool, pointer)
32,034✔
211
    end
44,312✔
212
    return res
19,756✔
213
end
214

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

217
function lookup(ip::Union{Base.InterpreterIP,Core.Compiler.InterpreterIP})
187✔
218
    code = ip.code
187✔
219
    if code === nothing
187✔
220
        # interpreted top-level expression with no CodeInfo
221
        return [StackFrame(top_level_scope_sym, empty_sym, 0, nothing, false, false, 0)]
1✔
222
    end
223
    codeinfo = (code isa MethodInstance ? code.uninferred : code)::CodeInfo
372✔
224
    # prepare approximate code info
225
    if code isa MethodInstance && (meth = code.def; meth isa Method)
186✔
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
186✔
235
    if i > length(codeinfo.codelocs) || codeinfo.codelocs[i] == 0
372✔
236
        return [StackFrame(func, file, line, code, false, false, 0)]
×
237
    end
238
    lineinfo = codeinfo.linetable[codeinfo.codelocs[i]]::Core.LineInfoNode
186✔
239
    scopes = StackFrame[]
186✔
240
    while true
535✔
241
        inlined = lineinfo.inlined_at != 0
535✔
242
        push!(scopes, StackFrame(Base.IRShow.method_name(lineinfo)::Symbol, lineinfo.file, lineinfo.line, inlined ? nothing : code, false, inlined, 0))
721✔
243
        inlined || break
535✔
244
        lineinfo = codeinfo.linetable[lineinfo.inlined_at]::Core.LineInfoNode
349✔
245
    end
349✔
246
    return scopes
186✔
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)
49✔
257
    stack = StackTrace()
82✔
258
    for ip in trace
43✔
259
        for frame in lookup(ip)
1,157✔
260
            # Skip frames that come from C calls.
261
            if c_funcs || !frame.from_c
3,111✔
262
                push!(stack, frame)
561✔
263
            end
264
        end
2,778✔
265
    end
1,198✔
266
    return stack
42✔
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)
10✔
307

308
function show_spec_linfo(io::IO, frame::StackFrame)
2,683✔
309
    linfo = frame.linfo
2,683✔
310
    if linfo === nothing
2,683✔
311
        if frame.func === empty_sym
281✔
312
            print(io, "ip:0x", string(frame.pointer, base=16))
×
313
        elseif frame.func === top_level_scope_sym
281✔
314
            print(io, "top-level scope")
17✔
315
        else
316
            Base.print_within_stacktrace(io, Base.demangle_function_name(string(frame.func)), bold=true)
264✔
317
        end
318
    elseif linfo isa CodeInfo
2,402✔
319
        print(io, "top-level scope")
85✔
320
    elseif linfo isa Module
2,317✔
321
        Base.print_within_stacktrace(io, Base.demangle_function_name(string(frame.func)), bold=true)
667✔
322
    elseif linfo isa MethodInstance
1,650✔
323
        def = linfo.def
1,635✔
324
        if def isa Module
1,635✔
325
            Base.show_mi(io, linfo, #=from_stackframe=#true)
×
326
        else
327
            show_spec_sig(io, def, linfo.specTypes)
1,635✔
328
        end
329
    else
330
        m = linfo::Method
15✔
331
        show_spec_sig(io, m, m.sig)
15✔
332
    end
333
end
334

335
function show_spec_sig(io::IO, m::Method, @nospecialize(sig::Type))
1,650✔
336
    if get(io, :limit, :false)::Bool
1,890✔
337
        if !haskey(io, :displaysize)
501✔
338
            io = IOContext(io, :displaysize => displaysize(io))
77✔
339
        end
340
    end
341
    argnames = Base.method_argnames(m)
3,300✔
342
    argnames = replace(argnames, :var"#unused#" => :var"")
1,650✔
343
    if m.nkw > 0
1,650✔
344
        # rearrange call kw_impl(kw_args..., func, pos_args...) to func(pos_args...; kw_args)
345
        kwarg_types = Any[ fieldtype(sig, i) for i = 2:(1+m.nkw) ]
304✔
346
        uw = Base.unwrap_unionall(sig)::DataType
280✔
347
        pos_sig = Base.rewrap_unionall(Tuple{uw.parameters[(m.nkw+2):end]...}, sig)
282✔
348
        kwnames = argnames[2:(m.nkw+1)]
280✔
349
        for i = 1:length(kwnames)
560✔
350
            str = string(kwnames[i])::String
304✔
351
            if endswith(str, "...")
304✔
352
                kwnames[i] = Symbol(str[1:end-3])
×
353
            end
354
        end
328✔
355
        Base.show_tuple_as_call(io, m.name, pos_sig;
280✔
356
                                demangle=true,
357
                                kwargs=zip(kwnames, kwarg_types),
358
                                argnames=argnames[m.nkw+2:end])
359
    else
360
        Base.show_tuple_as_call(io, m.name, sig; demangle=true, argnames)
1,370✔
361
    end
362
end
363

364
function show(io::IO, frame::StackFrame)
193✔
365
    show_spec_linfo(io, frame)
193✔
366
    if frame.file !== empty_sym
193✔
367
        file_info = basename(string(frame.file))
186✔
368
        print(io, " at ")
186✔
369
        print(io, file_info, ":")
186✔
370
        if frame.line >= 0
186✔
371
            print(io, frame.line)
186✔
372
        else
373
            print(io, "?")
×
374
        end
375
    end
376
    if frame.inlined
193✔
377
        print(io, " [inlined]")
84✔
378
    end
379
end
380

381
function Base.parentmodule(frame::StackFrame)
2,055✔
382
    linfo = frame.linfo
8,077✔
383
    if linfo isa MethodInstance
8,077✔
384
        def = linfo.def
3,007✔
385
        if def isa Module
3,007✔
386
            return def
×
387
        else
388
            return (def::Method).module
3,007✔
389
        end
390
    elseif linfo isa Method
5,070✔
391
        return linfo.module
69✔
392
    elseif linfo isa Module
5,001✔
393
        return linfo
923✔
394
    else
395
        # The module is not always available (common reasons include
396
        # frames arising from the interpreter)
397
        nothing
4,078✔
398
    end
399
end
400

401
"""
402
    from(frame::StackFrame, filter_mod::Module) -> Bool
403

404
Return whether the `frame` is from the provided `Module`
405
"""
406
function from(frame::StackFrame, m::Module)
×
407
    return parentmodule(frame) === m
×
408
end
409

410
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

© 2026 Coveralls, Inc