• 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

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

3
# name and module reflection
4

5
"""
6
    parentmodule(m::Module) -> Module
7

8
Get a module's enclosing `Module`. `Main` is its own parent.
9

10
See also: [`names`](@ref), [`nameof`](@ref), [`fullname`](@ref), [`@__MODULE__`](@ref).
11

12
# Examples
13
```jldoctest
14
julia> parentmodule(Main)
15
Main
16

17
julia> parentmodule(Base.Broadcast)
18
Base
19
```
20
"""
21
parentmodule(m::Module) = ccall(:jl_module_parent, Ref{Module}, (Any,), m)
543,609✔
22

23
"""
24
    moduleroot(m::Module) -> Module
25

26
Find the root module of a given module. This is the first module in the chain of
27
parent modules of `m` which is either a registered root module or which is its
28
own parent module.
29
"""
30
function moduleroot(m::Module)
46,344✔
31
    while true
51,986✔
32
        is_root_module(m) && return m
51,986✔
33
        p = parentmodule(m)
5,642✔
34
        p === m && return m
5,642✔
35
        m = p
×
36
    end
5,642✔
37
end
38

39
"""
40
    @__MODULE__ -> Module
41

42
Get the `Module` of the toplevel eval,
43
which is the `Module` code is currently being read from.
44
"""
45
macro __MODULE__()
816✔
46
    return __module__
816✔
47
end
48

49
"""
50
    fullname(m::Module)
51

52
Get the fully-qualified name of a module as a tuple of symbols. For example,
53

54
# Examples
55
```jldoctest
56
julia> fullname(Base.Iterators)
57
(:Base, :Iterators)
58

59
julia> fullname(Main)
60
(:Main,)
61
```
62
"""
63
function fullname(m::Module)
125✔
64
    mn = nameof(m)
402✔
65
    if m === Main || m === Base || m === Core
569✔
66
        return (mn,)
237✔
67
    end
68
    mp = parentmodule(m)
165✔
69
    if mp === m
165✔
70
        return (mn,)
60✔
71
    end
72
    return (fullname(mp)..., mn)
105✔
73
end
74

75
"""
76
    names(x::Module; all::Bool = false, imported::Bool = false)
77

78
Get an array of the names exported by a `Module`, excluding deprecated names.
79
If `all` is true, then the list also includes non-exported names defined in the module,
80
deprecated names, and compiler-generated names.
81
If `imported` is true, then names explicitly imported from other modules
82
are also included.
83

84
As a special case, all names defined in `Main` are considered \"exported\",
85
since it is not idiomatic to explicitly export names from `Main`.
86

87
See also: [`@locals`](@ref Base.@locals), [`@__MODULE__`](@ref).
88
"""
89
names(m::Module; all::Bool = false, imported::Bool = false) =
9,384✔
90
    sort!(unsorted_names(m; all, imported))
91
unsorted_names(m::Module; all::Bool = false, imported::Bool = false) =
53,936✔
92
    ccall(:jl_module_names, Array{Symbol,1}, (Any, Cint, Cint), m, all, imported)
93

94
isexported(m::Module, s::Symbol) = ccall(:jl_module_exports_p, Cint, (Any, Any), m, s) != 0
124✔
95
isdeprecated(m::Module, s::Symbol) = ccall(:jl_is_binding_deprecated, Cint, (Any, Any), m, s) != 0
12,488,855✔
96
isbindingresolved(m::Module, var::Symbol) = ccall(:jl_binding_resolved_p, Cint, (Any, Any), m, var) != 0
47,859✔
97

98
function binding_module(m::Module, s::Symbol)
574✔
99
    p = ccall(:jl_get_module_of_binding, Ptr{Cvoid}, (Any, Any), m, s)
1,039✔
100
    p == C_NULL && return m
1,039✔
101
    return unsafe_pointer_to_objref(p)::Module
1,036✔
102
end
103

104
const _NAMEDTUPLE_NAME = NamedTuple.body.body.name
105

106
function _fieldnames(@nospecialize t)
111✔
107
    if t.name === _NAMEDTUPLE_NAME
810✔
108
        if t.parameters[1] isa Tuple
34✔
109
            return t.parameters[1]
33✔
110
        else
111
            throw(ArgumentError("type does not have definite field names"))
1✔
112
        end
113
    end
114
    return t.name.names
776✔
115
end
116

117
"""
118
    fieldname(x::DataType, i::Integer)
119

120
Get the name of field `i` of a `DataType`.
121

122
# Examples
123
```jldoctest
124
julia> fieldname(Rational, 1)
125
:num
126

127
julia> fieldname(Rational, 2)
128
:den
129
```
130
"""
131
function fieldname(t::DataType, i::Integer)
553✔
132
    throw_not_def_field() = throw(ArgumentError("type does not have definite field names"))
553✔
133
    function throw_field_access(t, i, n_fields)
555✔
134
        field_label = n_fields == 1 ? "field" : "fields"
2✔
135
        throw(ArgumentError("Cannot access field $i since type $t only has $n_fields $field_label."))
2✔
136
    end
137
    throw_need_pos_int(i) = throw(ArgumentError("Field numbers must be positive integers. $i is invalid."))
554✔
138

139
    isabstracttype(t) && throw_not_def_field()
553✔
140
    names = _fieldnames(t)
553✔
141
    n_fields = length(names)::Int
553✔
142
    i > n_fields && throw_field_access(t, i, n_fields)
553✔
143
    i < 1 && throw_need_pos_int(i)
551✔
144
    return @inbounds names[i]::Symbol
550✔
145
end
146

147
fieldname(t::UnionAll, i::Integer) = fieldname(unwrap_unionall(t), i)
3✔
148
fieldname(t::Type{<:Tuple}, i::Integer) =
5✔
149
    i < 1 || i > fieldcount(t) ? throw(BoundsError(t, i)) : Int(i)
150

151
"""
152
    fieldnames(x::DataType)
153

154
Get a tuple with the names of the fields of a `DataType`.
155

156
See also [`propertynames`](@ref), [`hasfield`](@ref).
157

158
# Examples
159
```jldoctest
160
julia> fieldnames(Rational)
161
(:num, :den)
162

163
julia> fieldnames(typeof(1+im))
164
(:re, :im)
165
```
166
"""
167
fieldnames(t::DataType) = (fieldcount(t); # error check to make sure type is specific enough
260✔
168
                           (_fieldnames(t)...,))::Tuple{Vararg{Symbol}}
257✔
169
fieldnames(t::UnionAll) = fieldnames(unwrap_unionall(t))
156✔
170
fieldnames(::Core.TypeofBottom) =
1✔
171
    throw(ArgumentError("The empty type does not have field names since it does not have instances."))
172
fieldnames(t::Type{<:Tuple}) = ntuple(identity, fieldcount(t))
3✔
173

174
"""
175
    hasfield(T::Type, name::Symbol)
176

177
Return a boolean indicating whether `T` has `name` as one of its own fields.
178

179
See also [`fieldnames`](@ref), [`fieldcount`](@ref), [`hasproperty`](@ref).
180

181
!!! compat "Julia 1.2"
182
     This function requires at least Julia 1.2.
183

184
# Examples
185
```jldoctest
186
julia> struct Foo
187
            bar::Int
188
       end
189

190
julia> hasfield(Foo, :bar)
191
true
192

193
julia> hasfield(Foo, :x)
194
false
195
```
196
"""
197
hasfield(T::Type, name::Symbol) = fieldindex(T, name, false) > 0
4✔
198

199
"""
200
    nameof(t::DataType) -> Symbol
201

202
Get the name of a (potentially `UnionAll`-wrapped) `DataType` (without its parent module)
203
as a symbol.
204

205
# Examples
206
```jldoctest
207
julia> module Foo
208
           struct S{T}
209
           end
210
       end
211
Foo
212

213
julia> nameof(Foo.S{T} where T)
214
:S
215
```
216
"""
217
nameof(t::DataType) = t.name.name
413,823✔
218
nameof(t::UnionAll) = nameof(unwrap_unionall(t))::Symbol
6,030✔
219

220
"""
221
    parentmodule(t::DataType) -> Module
222

223
Determine the module containing the definition of a (potentially `UnionAll`-wrapped) `DataType`.
224

225
# Examples
226
```jldoctest
227
julia> module Foo
228
           struct Int end
229
       end
230
Foo
231

232
julia> parentmodule(Int)
233
Core
234

235
julia> parentmodule(Foo.Int)
236
Foo
237
```
238
"""
239
parentmodule(t::DataType) = t.name.module
452,678✔
240
parentmodule(t::UnionAll) = parentmodule(unwrap_unionall(t))
6,030✔
241

242
"""
243
    isconst(m::Module, s::Symbol) -> Bool
244

245
Determine whether a global is declared `const` in a given module `m`.
246
"""
247
isconst(m::Module, s::Symbol) =
47,614,849✔
248
    ccall(:jl_is_const, Cint, (Any, Any), m, s) != 0
249

250
function isconst(g::GlobalRef)
×
251
    return ccall(:jl_globalref_is_const, Cint, (Any,), g) != 0
697,224,388✔
252
end
253

254
"""
255
    isconst(t::DataType, s::Union{Int,Symbol}) -> Bool
256

257
Determine whether a field `s` is declared `const` in a given type `t`.
258
"""
259
function isconst(@nospecialize(t::Type), s::Symbol)
×
260
    t = unwrap_unionall(t)
×
261
    isa(t, DataType) || return false
×
262
    return isconst(t, fieldindex(t, s, false))
×
263
end
264
function isconst(@nospecialize(t::Type), s::Int)
703,062✔
265
    t = unwrap_unionall(t)
703,062✔
266
    # TODO: what to do for `Union`?
267
    isa(t, DataType) || return false # uncertain
703,062✔
268
    ismutabletype(t) || return true # immutable structs are always const
1,226,805✔
269
    1 <= s <= length(t.name.names) || return true # OOB reads are "const" since they always throw
179,319✔
270
    constfields = t.name.constfields
179,319✔
271
    constfields === C_NULL && return false
179,319✔
272
    s -= 1
22,574✔
273
    return unsafe_load(Ptr{UInt32}(constfields), 1 + s÷32) & (1 << (s%32)) != 0
22,574✔
274
end
275

276
"""
277
    isfieldatomic(t::DataType, s::Union{Int,Symbol}) -> Bool
278

279
Determine whether a field `s` is declared `@atomic` in a given type `t`.
280
"""
281
function isfieldatomic(@nospecialize(t::Type), s::Symbol)
×
282
    t = unwrap_unionall(t)
×
283
    isa(t, DataType) || return false
×
284
    return isfieldatomic(t, fieldindex(t, s, false))
×
285
end
286
function isfieldatomic(@nospecialize(t::Type), s::Int)
8,489,523✔
287
    t = unwrap_unionall(t)
8,489,523✔
288
    # TODO: what to do for `Union`?
289
    isa(t, DataType) || return false # uncertain
8,489,523✔
290
    ismutabletype(t) || return false # immutable structs are never atomic
16,756,670✔
291
    1 <= s <= length(t.name.names) || return false # OOB reads are not atomic (they always throw)
222,376✔
292
    atomicfields = t.name.atomicfields
222,376✔
293
    atomicfields === C_NULL && return false
222,376✔
294
    s -= 1
61,659✔
295
    return unsafe_load(Ptr{UInt32}(atomicfields), 1 + s÷32) & (1 << (s%32)) != 0
61,659✔
296
end
297

298
"""
299
    @locals()
300

301
Construct a dictionary of the names (as symbols) and values of all local
302
variables defined as of the call site.
303

304
!!! compat "Julia 1.1"
305
    This macro requires at least Julia 1.1.
306

307
# Examples
308
```jldoctest
309
julia> let x = 1, y = 2
310
           Base.@locals
311
       end
312
Dict{Symbol, Any} with 2 entries:
313
  :y => 2
314
  :x => 1
315

316
julia> function f(x)
317
           local y
318
           show(Base.@locals); println()
319
           for i = 1:1
320
               show(Base.@locals); println()
321
           end
322
           y = 2
323
           show(Base.@locals); println()
324
           nothing
325
       end;
326

327
julia> f(42)
328
Dict{Symbol, Any}(:x => 42)
329
Dict{Symbol, Any}(:i => 1, :x => 42)
330
Dict{Symbol, Any}(:y => 2, :x => 42)
331
```
332
"""
333
macro locals()
9✔
334
    return Expr(:locals)
9✔
335
end
336

337
# concrete datatype predicates
338

339
datatype_fieldtypes(x::DataType) = ccall(:jl_get_fieldtypes, Core.SimpleVector, (Any,), x)
3,698,028✔
340

341
struct DataTypeLayout
342
    size::UInt32
343
    nfields::UInt32
344
    npointers::UInt32
345
    firstptr::Int32
346
    alignment::UInt16
347
    flags::UInt16
348
    # haspadding : 1;
349
    # fielddesc_type : 2;
350
end
351

352
"""
353
    Base.datatype_alignment(dt::DataType) -> Int
354

355
Memory allocation minimum alignment for instances of this type.
356
Can be called on any `isconcretetype`.
357
"""
358
function datatype_alignment(dt::DataType)
930✔
359
    @_foldable_meta
×
360
    dt.layout == C_NULL && throw(UndefRefError())
15,848✔
361
    alignment = unsafe_load(convert(Ptr{DataTypeLayout}, dt.layout)).alignment
15,848✔
362
    return Int(alignment)
15,848✔
363
end
364

365
function uniontype_layout(@nospecialize T::Type)
345✔
366
    sz = RefValue{Csize_t}(0)
345✔
367
    algn = RefValue{Csize_t}(0)
345✔
368
    isinline = ccall(:jl_islayout_inline, Cint, (Any, Ptr{Csize_t}, Ptr{Csize_t}), T, sz, algn) != 0
345✔
369
    (isinline, Int(sz[]), Int(algn[]))
345✔
370
end
371

372
LLT_ALIGN(x, sz) = (x + sz - 1) & -sz
14,028✔
373

374
# amount of total space taken by T when stored in a container
375
function aligned_sizeof(@nospecialize T::Type)
19,266✔
376
    @_foldable_meta
×
377
    if isbitsunion(T)
37,376✔
378
        _, sz, al = uniontype_layout(T)
341✔
379
        return LLT_ALIGN(sz, al)
341✔
380
    elseif allocatedinline(T)
18,925✔
381
        al = datatype_alignment(T)
13,092✔
382
        return LLT_ALIGN(Core.sizeof(T), al)
13,092✔
383
    else
384
        return Core.sizeof(Ptr{Cvoid})
5,833✔
385
    end
386
end
387

388
gc_alignment(sz::Integer) = Int(ccall(:jl_alignment, Cint, (Csize_t,), sz))
×
389
gc_alignment(T::Type) = gc_alignment(Core.sizeof(T))
×
390

391
"""
392
    Base.datatype_haspadding(dt::DataType) -> Bool
393

394
Return whether the fields of instances of this type are packed in memory,
395
with no intervening padding bytes.
396
Can be called on any `isconcretetype`.
397
"""
398
function datatype_haspadding(dt::DataType)
9✔
399
    @_foldable_meta
9✔
400
    dt.layout == C_NULL && throw(UndefRefError())
9✔
401
    flags = unsafe_load(convert(Ptr{DataTypeLayout}, dt.layout)).flags
9✔
402
    return flags & 1 == 1
9✔
403
end
404

405
"""
406
    Base.datatype_nfields(dt::DataType) -> Bool
407

408
Return the number of fields known to this datatype's layout.
409
Can be called on any `isconcretetype`.
410
"""
411
function datatype_nfields(dt::DataType)
×
412
    @_foldable_meta
×
413
    dt.layout == C_NULL && throw(UndefRefError())
6,313✔
414
    return unsafe_load(convert(Ptr{DataTypeLayout}, dt.layout)).nfields
6,313✔
415
end
416

417
"""
418
    Base.datatype_pointerfree(dt::DataType) -> Bool
419

420
Return whether instances of this type can contain references to gc-managed memory.
421
Can be called on any `isconcretetype`.
422
"""
423
function datatype_pointerfree(dt::DataType)
314✔
424
    @_foldable_meta
×
425
    dt.layout == C_NULL && throw(UndefRefError())
140,703✔
426
    npointers = unsafe_load(convert(Ptr{DataTypeLayout}, dt.layout)).npointers
140,703✔
427
    return npointers == 0
140,703✔
428
end
429

430
"""
431
    Base.datatype_fielddesc_type(dt::DataType) -> Int
432

433
Return the size in bytes of each field-description entry in the layout array,
434
located at `(dt.layout + sizeof(DataTypeLayout))`.
435
Can be called on any `isconcretetype`.
436

437
See also [`fieldoffset`](@ref).
438
"""
439
function datatype_fielddesc_type(dt::DataType)
×
440
    @_foldable_meta
×
441
    dt.layout == C_NULL && throw(UndefRefError())
×
442
    flags = unsafe_load(convert(Ptr{DataTypeLayout}, dt.layout)).flags
×
443
    return (flags >> 1) & 3
×
444
end
445

446
# For type stability, we only expose a single struct that describes everything
447
struct FieldDesc
448
    isforeign::Bool
×
449
    isptr::Bool
450
    size::UInt32
451
    offset::UInt32
452
end
453

454
struct FieldDescStorage{T}
455
    ptrsize::T
456
    offset::T
457
end
458
FieldDesc(fd::FieldDescStorage{T}) where {T} =
496,306✔
459
    FieldDesc(false, fd.ptrsize & 1 != 0,
460
              fd.ptrsize >> 1, fd.offset)
461

462
struct DataTypeFieldDesc
463
    dt::DataType
464
    function DataTypeFieldDesc(dt::DataType)
×
465
        dt.layout == C_NULL && throw(UndefRefError())
184,684✔
466
        new(dt)
184,684✔
467
    end
468
end
469

470
function getindex(dtfd::DataTypeFieldDesc, i::Int)
×
471
    layout_ptr = convert(Ptr{DataTypeLayout}, dtfd.dt.layout)
496,306✔
472
    fd_ptr = layout_ptr + sizeof(DataTypeLayout)
496,306✔
473
    layout = unsafe_load(layout_ptr)
496,306✔
474
    fielddesc_type = (layout.flags >> 1) & 3
496,306✔
475
    nfields = layout.nfields
496,306✔
476
    @boundscheck ((1 <= i <= nfields) || throw(BoundsError(dtfd, i)))
496,306✔
477
    if fielddesc_type == 0
496,306✔
478
        return FieldDesc(unsafe_load(Ptr{FieldDescStorage{UInt8}}(fd_ptr), i))
496,230✔
479
    elseif fielddesc_type == 1
76✔
480
        return FieldDesc(unsafe_load(Ptr{FieldDescStorage{UInt16}}(fd_ptr), i))
76✔
481
    elseif fielddesc_type == 2
×
482
        return FieldDesc(unsafe_load(Ptr{FieldDescStorage{UInt32}}(fd_ptr), i))
×
483
    else
484
        # fielddesc_type == 3
485
        return FieldDesc(true, true, 0, 0)
×
486
    end
487
end
488

489
"""
490
    ismutable(v) -> Bool
491

492
Return `true` if and only if value `v` is mutable.  See [Mutable Composite Types](@ref)
493
for a discussion of immutability. Note that this function works on values, so if you
494
give it a `DataType`, it will tell you that a value of the type is mutable.
495

496
!!! note
497
    For technical reasons, `ismutable` returns `true` for values of certain special types
498
    (for example `String` and `Symbol`) even though they cannot be mutated in a permissible way.
499

500
See also [`isbits`](@ref), [`isstructtype`](@ref).
501

502
# Examples
503
```jldoctest
504
julia> ismutable(1)
505
false
506

507
julia> ismutable([1,2])
508
true
509
```
510

511
!!! compat "Julia 1.5"
512
    This function requires at least Julia 1.5.
513
"""
514
ismutable(@nospecialize(x)) = (@_total_meta; typeof(x).name.flags & 0x2 == 0x2)
15,029,100✔
515

516
"""
517
    ismutabletype(T) -> Bool
518

519
Determine whether type `T` was declared as a mutable type
520
(i.e. using `mutable struct` keyword).
521

522
!!! compat "Julia 1.7"
523
    This function requires at least Julia 1.7.
524
"""
525
function ismutabletype(@nospecialize t)
75,310✔
526
    @_total_meta
3✔
527
    t = unwrap_unionall(t)
11,649,925✔
528
    # TODO: what to do for `Union`?
529
    return isa(t, DataType) && t.name.flags & 0x2 == 0x2
47,229,884✔
530
end
531

532
"""
533
    isstructtype(T) -> Bool
534

535
Determine whether type `T` was declared as a struct type
536
(i.e. using the `struct` or `mutable struct` keyword).
537
"""
538
function isstructtype(@nospecialize t)
7✔
539
    @_total_meta
7✔
540
    t = unwrap_unionall(t)
7✔
541
    # TODO: what to do for `Union`?
542
    isa(t, DataType) || return false
9✔
543
    return !isprimitivetype(t) && !isabstracttype(t)
5✔
544
end
545

546
"""
547
    isprimitivetype(T) -> Bool
548

549
Determine whether type `T` was declared as a primitive type
550
(i.e. using the `primitive type` syntax).
551
"""
552
function isprimitivetype(@nospecialize t)
460✔
553
    @_total_meta
×
554
    t = unwrap_unionall(t)
3,419,304✔
555
    # TODO: what to do for `Union`?
556
    isa(t, DataType) || return false
3,419,194✔
557
    return (t.flags & 0x0080) == 0x0080
3,543,380✔
558
end
559

560
"""
561
    isbitstype(T)
562

563
Return `true` if type `T` is a "plain data" type,
564
meaning it is immutable and contains no references to other values,
565
only `primitive` types and other `isbitstype` types.
566
Typical examples are numeric types such as [`UInt8`](@ref),
567
[`Float64`](@ref), and [`Complex{Float64}`](@ref).
568
This category of types is significant since they are valid as type parameters,
569
may not track [`isdefined`](@ref) / [`isassigned`](@ref) status,
570
and have a defined layout that is compatible with C.
571

572
See also [`isbits`](@ref), [`isprimitivetype`](@ref), [`ismutable`](@ref).
573

574
# Examples
575
```jldoctest
576
julia> isbitstype(Complex{Float64})
577
true
578

579
julia> isbitstype(Complex)
580
false
581
```
582
"""
583
isbitstype(@nospecialize t) = (@_total_meta; isa(t, DataType) && (t.flags & 0x0008) == 0x0008)
9,326,286✔
584

585
"""
586
    isbits(x)
587

588
Return `true` if `x` is an instance of an [`isbitstype`](@ref) type.
589
"""
590
isbits(@nospecialize x) = isbitstype(typeof(x))
12,981,882✔
591

592
"""
593
    objectid(x) -> UInt
594

595
Get a hash value for `x` based on object identity.
596

597
If `x === y` then `objectid(x) == objectid(y)`, and usually when `x !== y`, `objectid(x) != objectid(y)`.
598

599
See also [`hash`](@ref), [`IdDict`](@ref).
600
"""
601
function objectid(x)
2,599,722✔
602
    # objectid is foldable iff it isn't a pointer.
603
    if isidentityfree(typeof(x))
2,789,849✔
604
        return _foldable_objectid(x)
5,675,639✔
605
    end
606
    return _objectid(x)
312,601✔
607
end
608
function _foldable_objectid(@nospecialize(x))
2,498,885✔
609
    @_foldable_meta
2,498,861✔
610
    _objectid(x)
5,675,633✔
611
end
612
_objectid(@nospecialize(x)) = ccall(:jl_object_id, UInt, (Any,), x)
5,988,242✔
613

614
"""
615
    isdispatchtuple(T)
616

617
Determine whether type `T` is a tuple "leaf type",
618
meaning it could appear as a type signature in dispatch
619
and has no subtypes (or supertypes) which could appear in a call.
620
"""
621
isdispatchtuple(@nospecialize(t)) = (@_total_meta; isa(t, DataType) && (t.flags & 0x0004) == 0x0004)
2,433,384✔
622

623
datatype_ismutationfree(dt::DataType) = (@_total_meta; (dt.flags & 0x0100) == 0x0100)
54,089,088✔
624

625
"""
626
    ismutationfree(T)
627

628
Determine whether type `T` is mutation free in the sense that no mutable memory
629
is reachable from this type (either in the type itself) or through any fields.
630
Note that the type itself need not be immutable. For example, an empty mutable
631
type is `ismutabletype`, but also `ismutationfree`.
632
"""
633
function ismutationfree(@nospecialize(t))
61,857✔
634
    t = unwrap_unionall(t)
13,026,981✔
635
    if isa(t, DataType)
12,762,158✔
636
        return datatype_ismutationfree(t)
54,089,088✔
637
    elseif isa(t, Union)
35,105✔
638
        return ismutationfree(t.a) && ismutationfree(t.b)
35,105✔
639
    end
640
    # TypeVar, etc.
641
    return false
×
642
end
643

644
datatype_isidentityfree(dt::DataType) = (@_total_meta; (dt.flags & 0x0200) == 0x0200)
303,492✔
645

646
"""
647
    isidentityfree(T)
648

649
Determine whether type `T` is identity free in the sense that this type or any
650
reachable through its fields has non-content-based identity.
651
"""
652
function isidentityfree(@nospecialize(t))
2,599,263✔
653
    t = unwrap_unionall(t)
2,717,374✔
654
    if isa(t, DataType)
2,711,163✔
655
        return datatype_isidentityfree(t)
2,901,783✔
656
    elseif isa(t, Union)
46✔
657
        return isidentityfree(t.a) && isidentityfree(t.b)
46✔
658
    end
659
    # TypeVar, etc.
660
    return false
×
661
end
662

663
iskindtype(@nospecialize t) = (t === DataType || t === UnionAll || t === Union || t === typeof(Bottom))
37,864,603✔
664
isconcretedispatch(@nospecialize t) = isconcretetype(t) && !iskindtype(t)
11,797,952✔
665
has_free_typevars(@nospecialize(t)) = ccall(:jl_has_free_typevars, Cint, (Any,), t) != 0
85,734,253✔
666

667
# equivalent to isa(v, Type) && isdispatchtuple(Tuple{v}) || v === Union{}
668
# and is thus perhaps most similar to the old (pre-1.0) `isleaftype` query
669
function isdispatchelem(@nospecialize v)
309✔
670
    return (v === Bottom) || (v === typeof(Bottom)) || isconcretedispatch(v) ||
11,855,987✔
671
        (isType(v) && !has_free_typevars(v))
672
end
673

674
const _TYPE_NAME = Type.body.name
675
isType(@nospecialize t) = isa(t, DataType) && t.name === _TYPE_NAME
122,506,035✔
676

677
"""
678
    isconcretetype(T)
679

680
Determine whether type `T` is a concrete type, meaning it could have direct instances
681
(values `x` such that `typeof(x) === T`).
682

683
See also: [`isbits`](@ref), [`isabstracttype`](@ref), [`issingletontype`](@ref).
684

685
# Examples
686
```jldoctest
687
julia> isconcretetype(Complex)
688
false
689

690
julia> isconcretetype(Complex{Float32})
691
true
692

693
julia> isconcretetype(Vector{Complex})
694
true
695

696
julia> isconcretetype(Vector{Complex{Float32}})
697
true
698

699
julia> isconcretetype(Union{})
700
false
701

702
julia> isconcretetype(Union{Int,String})
703
false
704
```
705
"""
706
isconcretetype(@nospecialize(t)) = (@_total_meta; isa(t, DataType) && (t.flags & 0x0002) == 0x0002)
47,337,791✔
707

708
"""
709
    isabstracttype(T)
710

711
Determine whether type `T` was declared as an abstract type
712
(i.e. using the `abstract type` syntax).
713

714
# Examples
715
```jldoctest
716
julia> isabstracttype(AbstractArray)
717
true
718

719
julia> isabstracttype(Vector)
720
false
721
```
722
"""
723
function isabstracttype(@nospecialize(t))
2,623,549✔
724
    @_total_meta
12✔
725
    t = unwrap_unionall(t)
9,163,539✔
726
    # TODO: what to do for `Union`?
727
    return isa(t, DataType) && (t.name.flags & 0x1) == 0x1
56,304,035✔
728
end
729

730
"""
731
    Base.issingletontype(T)
732

733
Determine whether type `T` has exactly one possible instance; for example, a
734
struct type with no fields.
735
"""
736
issingletontype(@nospecialize(t)) = (@_total_meta; isa(t, DataType) && isdefined(t, :instance))
149,874,084✔
737

738
"""
739
    typeintersect(T::Type, S::Type)
740

741
Compute a type that contains the intersection of `T` and `S`. Usually this will be the
742
smallest such type or one close to it.
743
"""
744
typeintersect(@nospecialize(a), @nospecialize(b)) = (@_total_meta; ccall(:jl_type_intersection, Any, (Any, Any), a::Type, b::Type))
37,132,352✔
745

746
morespecific(@nospecialize(a), @nospecialize(b)) = (@_total_meta; ccall(:jl_type_morespecific, Cint, (Any, Any), a::Type, b::Type) != 0)
14,895✔
747

748
"""
749
    fieldoffset(type, i)
750

751
The byte offset of field `i` of a type relative to the data start. For example, we could
752
use it in the following manner to summarize information about a struct:
753

754
```jldoctest
755
julia> structinfo(T) = [(fieldoffset(T,i), fieldname(T,i), fieldtype(T,i)) for i = 1:fieldcount(T)];
756

757
julia> structinfo(Base.Filesystem.StatStruct)
758
13-element Vector{Tuple{UInt64, Symbol, Type}}:
759
 (0x0000000000000000, :desc, Union{RawFD, String})
760
 (0x0000000000000008, :device, UInt64)
761
 (0x0000000000000010, :inode, UInt64)
762
 (0x0000000000000018, :mode, UInt64)
763
 (0x0000000000000020, :nlink, Int64)
764
 (0x0000000000000028, :uid, UInt64)
765
 (0x0000000000000030, :gid, UInt64)
766
 (0x0000000000000038, :rdev, UInt64)
767
 (0x0000000000000040, :size, Int64)
768
 (0x0000000000000048, :blksize, Int64)
769
 (0x0000000000000050, :blocks, Int64)
770
 (0x0000000000000058, :mtime, Float64)
771
 (0x0000000000000060, :ctime, Float64)
772
```
773
"""
774
fieldoffset(x::DataType, idx::Integer) = (@_foldable_meta; ccall(:jl_get_field_offset, Csize_t, (Any, Cint), x, idx))
961✔
775

776
"""
777
    fieldtype(T, name::Symbol | index::Int)
778

779
Determine the declared type of a field (specified by name or index) in a composite DataType `T`.
780

781
# Examples
782
```jldoctest
783
julia> struct Foo
784
           x::Int64
785
           y::String
786
       end
787

788
julia> fieldtype(Foo, :x)
789
Int64
790

791
julia> fieldtype(Foo, 2)
792
String
793
```
794
"""
795
fieldtype
796

797
"""
798
    Base.fieldindex(T, name::Symbol, err:Bool=true)
799

800
Get the index of a named field, throwing an error if the field does not exist (when err==true)
801
or returning 0 (when err==false).
802

803
# Examples
804
```jldoctest
805
julia> struct Foo
806
           x::Int64
807
           y::String
808
       end
809

810
julia> Base.fieldindex(Foo, :z)
811
ERROR: type Foo has no field z
812
Stacktrace:
813
[...]
814

815
julia> Base.fieldindex(Foo, :z, false)
816
0
817
```
818
"""
819
function fieldindex(T::DataType, name::Symbol, err::Bool=true)
22,469,218✔
820
    @_foldable_meta
×
821
    @noinline
×
822
    return Int(ccall(:jl_field_index, Cint, (Any, Any, Cint), T, name, err)+1)
22,469,218✔
823
end
824

825
function fieldindex(t::UnionAll, name::Symbol, err::Bool=true)
2✔
826
    t = argument_datatype(t)
2✔
827
    if t === nothing
2✔
828
        err && throw(ArgumentError("type does not have definite fields"))
×
829
        return 0
×
830
    end
831
    return fieldindex(t, name, err)
2✔
832
end
833

834
function argument_datatype(@nospecialize t)
23✔
835
    @_total_meta
13✔
836
    @noinline
13✔
837
    return ccall(:jl_argument_datatype, Any, (Any,), t)::Union{Nothing,DataType}
23✔
838
end
839

840
function datatype_fieldcount(t::DataType)
1,766,446✔
841
    if t.name === _NAMEDTUPLE_NAME
1,766,446✔
842
        names, types = t.parameters[1], t.parameters[2]
26,277✔
843
        if names isa Tuple
26,277✔
844
            return length(names)
26,268✔
845
        end
846
        if types isa DataType && types <: Tuple
9✔
847
            return fieldcount(types)
6✔
848
        end
849
        return nothing
3✔
850
    elseif isabstracttype(t) || (t.name === Tuple.name && isvatuple(t))
3,480,351✔
851
        return nothing
5✔
852
    end
853
    if isdefined(t, :types)
1,740,164✔
854
        return length(t.types)
1,711,088✔
855
    end
856
    return length(t.name.names)
29,076✔
857
end
858

859
"""
860
    fieldcount(t::Type)
861

862
Get the number of fields that an instance of the given type would have.
863
An error is thrown if the type is too abstract to determine this.
864
"""
865
function fieldcount(@nospecialize t)
2,039✔
866
    @_foldable_meta
×
867
    if t isa UnionAll || t isa Union
4,069✔
868
        t = argument_datatype(t)
20✔
869
        if t === nothing
11✔
870
            throw(ArgumentError("type does not have a definite number of fields"))
1✔
871
        end
872
    elseif t === Union{}
2,028✔
873
        throw(ArgumentError("The empty type does not have a well-defined number of fields since it does not have instances."))
1✔
874
    end
875
    if !(t isa DataType)
2,037✔
876
        throw(TypeError(:fieldcount, DataType, t))
×
877
    end
878
    fcount = datatype_fieldcount(t)
622,204✔
879
    if fcount === nothing
622,204✔
880
        throw(ArgumentError("type does not have a definite number of fields"))
8✔
881
    end
882
    return fcount
622,196✔
883
end
884

885
"""
886
    fieldtypes(T::Type)
887

888
The declared types of all fields in a composite DataType `T` as a tuple.
889

890
!!! compat "Julia 1.1"
891
    This function requires at least Julia 1.1.
892

893
# Examples
894
```jldoctest
895
julia> struct Foo
896
           x::Int64
897
           y::String
898
       end
899

900
julia> fieldtypes(Foo)
901
(Int64, String)
902
```
903
"""
904
fieldtypes(T::Type) = (@_foldable_meta; ntupleany(i -> fieldtype(T, i), fieldcount(T)))
187✔
905

906
# return all instances, for types that can be enumerated
907

908
"""
909
    instances(T::Type)
910

911
Return a collection of all instances of the given type, if applicable. Mostly used for
912
enumerated types (see `@enum`).
913

914
# Example
915
```jldoctest
916
julia> @enum Color red blue green
917

918
julia> instances(Color)
919
(red, blue, green)
920
```
921
"""
922
function instances end
923

924
function to_tuple_type(@nospecialize(t))
224,076✔
925
    if isa(t, Tuple) || isa(t, AbstractArray) || isa(t, SimpleVector)
446,334✔
926
        t = Tuple{t...}
1,814✔
927
    end
928
    if isa(t, Type) && t <: Tuple
224,076✔
929
        for p in (unwrap_unionall(t)::DataType).parameters
447,417✔
930
            if isa(p, Core.TypeofVararg)
442,193✔
931
                p = unwrapva(p)
10,366✔
932
            end
933
            if !(isa(p, Type) || isa(p, TypeVar))
442,194✔
934
                error("argument tuple type must contain only types")
1✔
935
            end
936
        end
661,040✔
937
    else
938
        error("expected tuple type")
1✔
939
    end
940
    t
224,074✔
941
end
942

943
function signature_type(@nospecialize(f), @nospecialize(argtypes))
223,104✔
944
    argtypes = to_tuple_type(argtypes)
223,105✔
945
    ft = Core.Typeof(f)
445,152✔
946
    u = unwrap_unionall(argtypes)::DataType
223,105✔
947
    return rewrap_unionall(Tuple{ft, u.parameters...}, argtypes)
223,103✔
948
end
949

950
"""
951
    code_lowered(f, types; generated=true, debuginfo=:default)
952

953
Return an array of the lowered forms (IR) for the methods matching the given generic function
954
and type signature.
955

956
If `generated` is `false`, the returned `CodeInfo` instances will correspond to fallback
957
implementations. An error is thrown if no fallback implementation exists.
958
If `generated` is `true`, these `CodeInfo` instances will correspond to the method bodies
959
yielded by expanding the generators.
960

961
The keyword `debuginfo` controls the amount of code metadata present in the output.
962

963
Note that an error will be thrown if `types` are not leaf types when `generated` is
964
`true` and any of the corresponding methods are an `@generated` method.
965
"""
966
function code_lowered(@nospecialize(f), @nospecialize(t=Tuple); generated::Bool=true, debuginfo::Symbol=:default)
101✔
967
    if @isdefined(IRShow)
49✔
968
        debuginfo = IRShow.debuginfo(debuginfo)
49✔
969
    elseif debuginfo === :default
×
970
        debuginfo = :source
×
971
    end
972
    if debuginfo !== :source && debuginfo !== :none
49✔
973
        throw(ArgumentError("'debuginfo' must be either :source or :none"))
×
974
    end
975
    world = get_world_counter()
49✔
976
    return map(method_instances(f, t, world)) do m
49✔
977
        if generated && hasgenerator(m)
48✔
978
            if may_invoke_generator(m)
5✔
979
                return ccall(:jl_code_for_staged, Any, (Any, UInt), m, world)::CodeInfo
5✔
980
            else
981
                error("Could not expand generator for `@generated` method ", m, ". ",
×
982
                      "This can happen if the provided argument types (", t, ") are ",
983
                      "not leaf types, but the `generated` argument is `true`.")
984
            end
985
        end
986
        code = uncompressed_ir(m.def::Method)
43✔
987
        debuginfo === :none && remove_linenums!(code)
42✔
988
        return code
42✔
989
    end
990
end
991

992
hasgenerator(m::Method) = isdefined(m, :generator)
46✔
993
hasgenerator(m::Core.MethodInstance) = hasgenerator(m.def::Method)
46✔
994

995
# low-level method lookup functions used by the compiler
996

997
unionlen(x::Union) = unionlen(x.a) + unionlen(x.b)
1,964,260✔
998
unionlen(@nospecialize(x)) = 1
×
999

1000
_uniontypes(x::Union, ts) = (_uniontypes(x.a,ts); _uniontypes(x.b,ts); ts)
2,381,284✔
1001
_uniontypes(@nospecialize(x), ts) = (push!(ts, x); ts)
2,084,752✔
1002
uniontypes(@nospecialize(x)) = _uniontypes(x, Any[])
210,910✔
1003

1004
function _methods(@nospecialize(f), @nospecialize(t), lim::Int, world::UInt)
211,099✔
1005
    tt = signature_type(f, t)
221,069✔
1006
    return _methods_by_ftype(tt, lim, world)
221,069✔
1007
end
1008

1009
function _methods_by_ftype(@nospecialize(t), lim::Int, world::UInt)
212,006✔
1010
    return _methods_by_ftype(t, nothing, lim, world)
228,747✔
1011
end
1012
function _methods_by_ftype(@nospecialize(t), mt::Union{Core.MethodTable, Nothing}, lim::Int, world::UInt)
212,006✔
1013
    return _methods_by_ftype(t, mt, lim, world, false, RefValue{UInt}(typemin(UInt)), RefValue{UInt}(typemax(UInt)), Ptr{Int32}(C_NULL))
228,750✔
1014
end
1015
function _methods_by_ftype(@nospecialize(t), mt::Union{Core.MethodTable, Nothing}, lim::Int, world::UInt, ambig::Bool, min::Ref{UInt}, max::Ref{UInt}, has_ambig::Ref{Int32})
18,850,262✔
1016
    return ccall(:jl_matching_methods, Any, (Any, Any, Cint, Cint, UInt, Ptr{UInt}, Ptr{UInt}, Ptr{Int32}), t, mt, lim, ambig, world, min, max, has_ambig)::Union{Vector{Any},Nothing}
18,850,262✔
1017
end
1018

1019
# high-level, more convenient method lookup functions
1020

1021
# type for reflecting and pretty-printing a subset of methods
1022
mutable struct MethodList <: AbstractArray{Method,1}
1023
    ms::Array{Method,1}
10,417✔
1024
    mt::Core.MethodTable
1025
end
1026

1027
size(m::MethodList) = size(m.ms)
319,963✔
1028
getindex(m::MethodList, i::Integer) = m.ms[i]
945,765✔
1029

1030
function MethodList(mt::Core.MethodTable)
307,472✔
1031
    ms = Method[]
307,472✔
1032
    visit(mt) do m
307,472✔
1033
        push!(ms, m)
881,427✔
1034
    end
1035
    return MethodList(ms, mt)
370✔
1036
end
1037

1038
"""
1039
    methods(f, [types], [module])
1040

1041
Return the method table for `f`.
1042

1043
If `types` is specified, return an array of methods whose types match.
1044
If `module` is specified, return an array of methods defined in that module.
1045
A list of modules can also be specified as an array.
1046

1047
!!! compat "Julia 1.4"
1048
    At least Julia 1.4 is required for specifying a module.
1049

1050
See also: [`which`](@ref) and `@which`.
1051
"""
1052
function methods(@nospecialize(f), @nospecialize(t),
10,402✔
1053
                 mod::Union{Tuple{Module},AbstractArray{Module},Nothing}=nothing)
1054
    world = get_world_counter()
10,402✔
1055
    # Lack of specialization => a comprehension triggers too many invalidations via _collect, so collect the methods manually
1056
    ms = Method[]
9,978✔
1057
    for m in _methods(f, t, -1, world)::Vector
10,681✔
1058
        m = m::Core.MethodMatch
65,808✔
1059
        (mod === nothing || parentmodule(m.method) ∈ mod) && push!(ms, m.method)
65,815✔
1060
    end
75,083✔
1061
    MethodList(ms, typeof(f).name.mt)
9,978✔
1062
end
1063
methods(@nospecialize(f), @nospecialize(t), mod::Module) = methods(f, t, (mod,))
5✔
1064

1065
function methods_including_ambiguous(@nospecialize(f), @nospecialize(t))
68✔
1066
    tt = signature_type(f, t)
68✔
1067
    world = get_world_counter()
68✔
1068
    (ccall(:jl_is_in_pure_context, Bool, ()) || world == typemax(UInt)) &&
68✔
1069
        error("code reflection cannot be used from generated functions")
1070
    min = RefValue{UInt}(typemin(UInt))
68✔
1071
    max = RefValue{UInt}(typemax(UInt))
68✔
1072
    ms = _methods_by_ftype(tt, nothing, -1, world, true, min, max, Ptr{Int32}(C_NULL))::Vector
68✔
1073
    return MethodList(Method[(m::Core.MethodMatch).method for m in ms], typeof(f).name.mt)
68✔
1074
end
1075

1076
function methods(@nospecialize(f),
10,374✔
1077
                 mod::Union{Module,AbstractArray{Module},Nothing}=nothing)
1078
    # return all matches
1079
    return methods(f, Tuple{Vararg{Any}}, mod)
19,096✔
1080
end
1081

1082
function visit(f, mt::Core.MethodTable)
307,475✔
1083
    mt.defs !== nothing && visit(f, mt.defs)
307,475✔
1084
    nothing
307,475✔
1085
end
1086
function visit(f, mc::Core.TypeMapLevel)
22,819✔
1087
    function avisit(f, e::Array{Any,1})
114,095✔
1088
        for i in 2:2:length(e)
126,908✔
1089
            isassigned(e, i) || continue
652,360✔
1090
            ei = e[i]
236,684✔
1091
            if ei isa Vector{Any}
236,684✔
1092
                for j in 2:2:length(ei)
1,460✔
1093
                    isassigned(ei, j) || continue
10,160✔
1094
                    visit(f, ei[j])
7,213✔
1095
                end
19,590✔
1096
            else
1097
                visit(f, ei)
235,954✔
1098
            end
1099
        end
652,360✔
1100
    end
1101
    if mc.targ !== nothing
22,819✔
1102
        avisit(f, mc.targ::Vector{Any})
22,819✔
1103
    end
1104
    if mc.arg1 !== nothing
22,819✔
1105
        avisit(f, mc.arg1::Vector{Any})
22,819✔
1106
    end
1107
    if mc.tname !== nothing
22,819✔
1108
        avisit(f, mc.tname::Vector{Any})
22,819✔
1109
    end
1110
    if mc.name1 !== nothing
22,819✔
1111
        avisit(f, mc.name1::Vector{Any})
22,819✔
1112
    end
1113
    mc.list !== nothing && visit(f, mc.list)
22,819✔
1114
    mc.any !== nothing && visit(f, mc.any)
22,819✔
1115
    nothing
22,819✔
1116
end
1117
function visit(f, d::Core.TypeMapEntry)
544,732✔
1118
    while d !== nothing
544,732✔
1119
        f(d.func)
881,429✔
1120
        d = d.next
881,429✔
1121
    end
881,429✔
1122
    nothing
544,732✔
1123
end
1124
struct MethodSpecializations
1125
    specializations::Union{Nothing, Core.MethodInstance, Core.SimpleVector}
34✔
1126
end
1127
"""
1128
    specializations(m::Method) → itr
1129

1130
Return an iterator `itr` of all compiler-generated specializations of `m`.
1131
"""
1132
specializations(m::Method) = MethodSpecializations(isdefined(m, :specializations) ? m.specializations : nothing)
34✔
1133
function iterate(specs::MethodSpecializations)
33✔
1134
    s = specs.specializations
34✔
1135
    s === nothing && return nothing
34✔
1136
    isa(s, Core.MethodInstance) && return (s, nothing)
34✔
1137
    return iterate(specs, 0)
18✔
1138
end
1139
iterate(specs::MethodSpecializations, ::Nothing) = nothing
2✔
1140
function iterate(specs::MethodSpecializations, i::Int)
287✔
1141
    s = specs.specializations::Core.SimpleVector
288✔
1142
    n = length(s)
288✔
1143
    i >= n && return nothing
288✔
1144
    item = nothing
284✔
1145
    while i < n && item === nothing
577✔
1146
        item = s[i+=1]
292✔
1147
    end
292✔
1148
    item === nothing && return nothing
285✔
1149
    return (item, i)
283✔
1150
end
1151
length(specs::MethodSpecializations) = count(Returns(true), specs)
1✔
1152

1153
function length(mt::Core.MethodTable)
3✔
1154
    n = 0
3✔
1155
    visit(mt) do m
3✔
1156
        n += 1
2✔
1157
    end
1158
    return n::Int
3✔
1159
end
1160
isempty(mt::Core.MethodTable) = (mt.defs === nothing)
×
1161

1162
uncompressed_ir(m::Method) = isdefined(m, :source) ? _uncompressed_ir(m, m.source) :
54✔
1163
                             isdefined(m, :generator) ? error("Method is @generated; try `code_lowered` instead.") :
1164
                             error("Code for this Method is not available.")
1165
_uncompressed_ir(m::Method, s::CodeInfo) = copy(s)
16✔
1166
_uncompressed_ir(m::Method, s::Array{UInt8,1}) = ccall(:jl_uncompress_ir, Any, (Any, Ptr{Cvoid}, Any), m, C_NULL, s)::CodeInfo
409✔
1167
_uncompressed_ir(ci::Core.CodeInstance, s::Array{UInt8,1}) = ccall(:jl_uncompress_ir, Any, (Any, Any, Any), ci.def.def::Method, ci, s)::CodeInfo
×
1168
# for backwards compat
1169
const uncompressed_ast = uncompressed_ir
1170
const _uncompressed_ast = _uncompressed_ir
1171

1172
function method_instances(@nospecialize(f), @nospecialize(t), world::UInt)
49✔
1173
    tt = signature_type(f, t)
49✔
1174
    results = Core.MethodInstance[]
49✔
1175
    # this make a better error message than the typeassert that follows
1176
    world == typemax(UInt) && error("code reflection cannot be used from generated functions")
49✔
1177
    for match in _methods_by_ftype(tt, -1, world)::Vector
48✔
1178
        instance = Core.Compiler.specialize_method(match)
48✔
1179
        push!(results, instance)
48✔
1180
    end
94✔
1181
    return results
47✔
1182
end
1183

1184
default_debug_info_kind() = unsafe_load(cglobal(:jl_default_debug_info_kind, Cint))
38✔
1185

1186
# this type mirrors jl_cgparams_t (documented in julia.h)
1187
struct CodegenParams
1188
    track_allocations::Cint
1189
    code_coverage::Cint
1190
    prefer_specsig::Cint
1191
    gnu_pubnames::Cint
1192
    debug_info_kind::Cint
1193
    safepoint_on_entry::Cint
1194

1195
    lookup::Ptr{Cvoid}
1196

1197
    generic_context::Any
1198

1199
    function CodegenParams(; track_allocations::Bool=true, code_coverage::Bool=true,
246✔
1200
                   prefer_specsig::Bool=false,
1201
                   gnu_pubnames=true, debug_info_kind::Cint = default_debug_info_kind(),
1202
                   safepoint_on_entry::Bool=true,
1203
                   lookup::Ptr{Cvoid}=cglobal(:jl_rettype_inferred),
1204
                   generic_context = nothing)
1205
        return new(
123✔
1206
            Cint(track_allocations), Cint(code_coverage),
1207
            Cint(prefer_specsig),
1208
            Cint(gnu_pubnames), debug_info_kind,
1209
            Cint(safepoint_on_entry),
1210
            lookup, generic_context)
1211
    end
1212
end
1213

1214
const SLOT_USED = 0x8
1215
ast_slotflag(@nospecialize(code), i) = ccall(:jl_ir_slotflag, UInt8, (Any, Csize_t), code, i - 1)
850✔
1216

1217
"""
1218
    may_invoke_generator(method, atype, sparams) -> Bool
1219

1220
Computes whether or not we may invoke the generator for the given `method` on
1221
the given `atype` and `sparams`. For correctness, all generated function are
1222
required to return monotonic answers. However, since we don't expect users to
1223
be able to successfully implement this criterion, we only call generated
1224
functions on concrete types. The one exception to this is that we allow calling
1225
generators with abstract types if the generator does not use said abstract type
1226
(and thus cannot incorrectly use it to break monotonicity). This function
1227
computes whether we are in either of these cases.
1228

1229
Unlike normal functions, the compilation heuristics still can't generate good dispatch
1230
in some cases, but this may still allow inference not to fall over in some limited cases.
1231
"""
1232
function may_invoke_generator(mi::MethodInstance)
5✔
1233
    return may_invoke_generator(mi.def::Method, mi.specTypes, mi.sparam_vals)
9,150✔
1234
end
1235
function may_invoke_generator(method::Method, @nospecialize(atype), sparams::SimpleVector)
9,290✔
1236
    # If we have complete information, we may always call the generator
1237
    isdispatchtuple(atype) && return true
9,418✔
1238

1239
    # We don't have complete information, but it is possible that the generator
1240
    # syntactically doesn't make use of the information we don't have. Check
1241
    # for that.
1242

1243
    # For now, only handle the (common, generated by the frontend case) that the
1244
    # generator only has one method
1245
    generator = method.generator
1,209✔
1246
    isa(generator, Core.GeneratedFunctionStub) || return false
1,290✔
1247
    gen_mthds = _methods_by_ftype(Tuple{typeof(generator.gen), Vararg{Any}}, 1, method.primary_world)
1,128✔
1248
    (gen_mthds isa Vector && length(gen_mthds) == 1) || return false
1,128✔
1249

1250
    generator_method = first(gen_mthds).method
2,256✔
1251
    nsparams = length(sparams)
1,128✔
1252
    isdefined(generator_method, :source) || return false
1,128✔
1253
    code = generator_method.source
1,128✔
1254
    nslots = ccall(:jl_ir_nslots, Int, (Any,), code)
1,128✔
1255
    at = unwrap_unionall(atype)
1,261✔
1256
    at isa DataType || return false
1,128✔
1257
    (nslots >= 1 + length(sparams) + length(at.parameters)) || return false
1,482✔
1258

1259
    firstarg = 1
×
1260
    for i = 1:nsparams
1,537✔
1261
        if isa(sparams[i], TypeVar)
1,205✔
1262
            if (ast_slotflag(code, firstarg + i) & SLOT_USED) != 0
384✔
1263
                return false
328✔
1264
            end
1265
        end
1266
    end
1,319✔
1267
    nargs = Int(method.nargs)
446✔
1268
    non_va_args = method.isva ? nargs - 1 : nargs
446✔
1269
    for i = 1:non_va_args
892✔
1270
        if !isdispatchelem(at.parameters[i])
2,080✔
1271
            if (ast_slotflag(code, firstarg + i + nsparams) & SLOT_USED) != 0
455✔
1272
                return false
360✔
1273
            end
1274
        end
1275
    end
1,274✔
1276
    if method.isva
86✔
1277
        # If the va argument is used, we need to ensure that all arguments that
1278
        # contribute to the va tuple are dispatchelemes
1279
        if (ast_slotflag(code, firstarg + nargs + nsparams) & SLOT_USED) != 0
11✔
1280
            for i = (non_va_args+1):length(at.parameters)
22✔
1281
                if !isdispatchelem(at.parameters[i])
28✔
1282
                    return false
9✔
1283
                end
1284
            end
8✔
1285
        end
1286
    end
1287
    return true
77✔
1288
end
1289

1290
# give a decent error message if we try to instantiate a staged function on non-leaf types
1291
function func_for_method_checked(m::Method, @nospecialize(types), sparams::SimpleVector)
212,405✔
1292
    if isdefined(m, :generator) && !may_invoke_generator(m, types, sparams)
212,405✔
1293
        error("cannot call @generated function `", m, "` ",
×
1294
              "with abstract argument types: ", types)
1295
    end
1296
    return m
212,405✔
1297
end
1298

1299
"""
1300
    code_typed(f, types; kw...)
1301

1302
Returns an array of type-inferred lowered form (IR) for the methods matching the given
1303
generic function and type signature.
1304

1305
# Keyword Arguments
1306

1307
- `optimize=true`: controls whether additional optimizations, such as inlining, are also applied.
1308
- `debuginfo=:default`: controls the amount of code metadata present in the output,
1309
possible options are `:source` or `:none`.
1310

1311
# Internal Keyword Arguments
1312

1313
This section should be considered internal, and is only for who understands Julia compiler
1314
internals.
1315

1316
- `world=Base.get_world_counter()`: optional, controls the world age to use when looking up methods,
1317
use current world age if not specified.
1318
- `interp=Core.Compiler.NativeInterpreter(world)`: optional, controls the interpreter to use,
1319
use the native interpreter Julia uses if not specified.
1320

1321
# Example
1322

1323
One can put the argument types in a tuple to get the corresponding `code_typed`.
1324

1325
```julia
1326
julia> code_typed(+, (Float64, Float64))
1327
1-element Vector{Any}:
1328
 CodeInfo(
1329
1 ─ %1 = Base.add_float(x, y)::Float64
1330
└──      return %1
1331
) => Float64
1332
```
1333
"""
1334
function code_typed(@nospecialize(f), @nospecialize(types=default_tt(f));
1,561✔
1335
                    optimize=true,
1336
                    debuginfo::Symbol=:default,
1337
                    world = get_world_counter(),
1338
                    interp = Core.Compiler.NativeInterpreter(world))
1339
    if isa(f, Core.OpaqueClosure)
633✔
1340
        return code_typed_opaque_closure(f; optimize, debuginfo, interp)
2✔
1341
    end
1342
    tt = signature_type(f, types)
631✔
1343
    return code_typed_by_type(tt; optimize, debuginfo, world, interp)
631✔
1344
end
1345

1346
# returns argument tuple type which is supposed to be used for `code_typed` and its family;
1347
# if there is a single method this functions returns the method argument signature,
1348
# otherwise returns `Tuple` that doesn't match with any signature
1349
function default_tt(@nospecialize(f))
541✔
1350
    ms = methods(f)
541✔
1351
    if length(ms) == 1
541✔
1352
        return tuple_type_tail(only(ms).sig)
517✔
1353
    else
1354
        return Tuple
24✔
1355
    end
1356
end
1357

1358
"""
1359
    code_typed_by_type(types::Type{<:Tuple}; ...)
1360

1361
Similar to [`code_typed`](@ref), except the argument is a tuple type describing
1362
a full signature to query.
1363
"""
1364
function code_typed_by_type(@nospecialize(tt::Type);
1,642✔
1365
                            optimize=true,
1366
                            debuginfo::Symbol=:default,
1367
                            world = get_world_counter(),
1368
                            interp = Core.Compiler.NativeInterpreter(world))
1369
    (ccall(:jl_is_in_pure_context, Bool, ()) || world == typemax(UInt)) &&
821✔
1370
        error("code reflection cannot be used from generated functions")
1371
    if @isdefined(IRShow)
819✔
1372
        debuginfo = IRShow.debuginfo(debuginfo)
824✔
1373
    elseif debuginfo === :default
×
1374
        debuginfo = :source
×
1375
    end
1376
    if debuginfo !== :source && debuginfo !== :none
819✔
1377
        throw(ArgumentError("'debuginfo' must be either :source or :none"))
×
1378
    end
1379
    tt = to_tuple_type(tt)
819✔
1380
    matches = _methods_by_ftype(tt, -1, world)::Vector
819✔
1381
    asts = []
819✔
1382
    for match in matches
821✔
1383
        match = match::Core.MethodMatch
823✔
1384
        meth = func_for_method_checked(match.method, tt, match.sparams)
823✔
1385
        (code, ty) = Core.Compiler.typeinf_code(interp, meth, match.spec_types, match.sparams, optimize)
824✔
1386
        if code === nothing
823✔
1387
            push!(asts, meth => Any)
1✔
1388
        else
1389
            debuginfo === :none && remove_linenums!(code)
822✔
1390
            push!(asts, code => ty)
822✔
1391
        end
1392
    end
1,640✔
1393
    return asts
819✔
1394
end
1395

1396
function code_typed_opaque_closure(@nospecialize(oc::Core.OpaqueClosure);
6✔
1397
    debuginfo::Symbol=:default, __...)
1398
    ccall(:jl_is_in_pure_context, Bool, ()) && error("code reflection cannot be used from generated functions")
3✔
1399
    m = oc.source
3✔
1400
    if isa(m, Method)
3✔
1401
        code = _uncompressed_ir(m, m.source)
6✔
1402
        debuginfo === :none && remove_linenums!(code)
3✔
1403
        # intersect the declared return type and the inferred return type (if available)
1404
        rt = typeintersect(code.rettype, typeof(oc).parameters[2])
3✔
1405
        return Any[code => rt]
3✔
1406
    else
1407
        error("encountered invalid Core.OpaqueClosure object")
×
1408
    end
1409
end
1410

1411
"""
1412
    code_ircode(f, [types])
1413

1414
Return an array of pairs of `IRCode` and inferred return type if type inference succeeds.
1415
The `Method` is included instead of `IRCode` otherwise.
1416

1417
See also: [`code_typed`](@ref)
1418

1419
# Internal Keyword Arguments
1420

1421
This section should be considered internal, and is only for who understands Julia compiler
1422
internals.
1423

1424
- `world=Base.get_world_counter()`: optional, controls the world age to use when looking up
1425
  methods, use current world age if not specified.
1426
- `interp=Core.Compiler.NativeInterpreter(world)`: optional, controls the interpreter to
1427
  use, use the native interpreter Julia uses if not specified.
1428
- `optimize_until`: optional, controls the optimization passes to run.  If it is a string,
1429
  it specifies the name of the pass up to which the optimizer is run.  If it is an integer,
1430
  it specifies the number of passes to run.  If it is `nothing` (default), all passes are
1431
  run.
1432

1433
# Example
1434

1435
One can put the argument types in a tuple to get the corresponding `code_ircode`.
1436

1437
```julia
1438
julia> Base.code_ircode(+, (Float64, Int64))
1439
1-element Vector{Any}:
1440
 388 1 ─ %1 = Base.sitofp(Float64, _3)::Float64
1441
    │   %2 = Base.add_float(_2, %1)::Float64
1442
    └──      return %2
1443
     => Float64
1444

1445
julia> Base.code_ircode(+, (Float64, Int64); optimize_until = "compact 1")
1446
1-element Vector{Any}:
1447
 388 1 ─ %1 = Base.promote(_2, _3)::Tuple{Float64, Float64}
1448
    │   %2 = Core._apply_iterate(Base.iterate, Base.:+, %1)::Float64
1449
    └──      return %2
1450
     => Float64
1451
```
1452
"""
1453
function code_ircode(
70✔
1454
    @nospecialize(f),
1455
    @nospecialize(types = default_tt(f));
1456
    world = get_world_counter(),
1457
    interp = Core.Compiler.NativeInterpreter(world),
1458
    optimize_until::Union{Integer,AbstractString,Nothing} = nothing,
1459
)
1460
    if isa(f, Core.OpaqueClosure)
33✔
1461
        error("OpaqueClosure not supported")
×
1462
    end
1463
    tt = signature_type(f, types)
33✔
1464
    return code_ircode_by_type(tt; world, interp, optimize_until)
33✔
1465
end
1466

1467
"""
1468
    code_ircode_by_type(types::Type{<:Tuple}; ...)
1469

1470
Similar to [`code_ircode`](@ref), except the argument is a tuple type describing
1471
a full signature to query.
1472
"""
1473
function code_ircode_by_type(
66✔
1474
    @nospecialize(tt::Type);
1475
    world = get_world_counter(),
1476
    interp = Core.Compiler.NativeInterpreter(world),
1477
    optimize_until::Union{Integer,AbstractString,Nothing} = nothing,
1478
)
1479
    (ccall(:jl_is_in_pure_context, Bool, ()) || world == typemax(UInt)) &&
33✔
1480
        error("code reflection cannot be used from generated functions")
1481
    tt = to_tuple_type(tt)
33✔
1482
    matches = _methods_by_ftype(tt, -1, world)::Vector
33✔
1483
    asts = []
33✔
1484
    for match in matches
33✔
1485
        match = match::Core.MethodMatch
33✔
1486
        meth = func_for_method_checked(match.method, tt, match.sparams)
33✔
1487
        (code, ty) = Core.Compiler.typeinf_ircode(
33✔
1488
            interp,
1489
            meth,
1490
            match.spec_types,
1491
            match.sparams,
1492
            optimize_until,
1493
        )
1494
        if code === nothing
33✔
1495
            push!(asts, meth => Any)
×
1496
        else
1497
            push!(asts, code => ty)
33✔
1498
        end
1499
    end
66✔
1500
    return asts
33✔
1501
end
1502

1503
function return_types(@nospecialize(f), @nospecialize(types=default_tt(f));
422,216✔
1504
                      world = get_world_counter(),
1505
                      interp = Core.Compiler.NativeInterpreter(world))
1506
    (ccall(:jl_is_in_pure_context, Bool, ()) || world == typemax(UInt)) &&
211,091✔
1507
        error("code reflection cannot be used from generated functions")
1508
    if isa(f, Core.OpaqueClosure)
211,091✔
1509
        _, rt = only(code_typed_opaque_closure(f))
2✔
1510
        return Any[rt]
1✔
1511
    end
1512

1513
    if isa(f, Core.Builtin)
211,090✔
1514
        argtypes = Any[to_tuple_type(types).parameters...]
1✔
1515
        rt = Core.Compiler.builtin_tfunction(interp, f, argtypes, nothing)
1✔
1516
        return Any[Core.Compiler.widenconst(rt)]
1✔
1517
    end
1518
    rts = []
211,089✔
1519
    for match in _methods(f, types, -1, world)::Vector
211,089✔
1520
        match = match::Core.MethodMatch
211,548✔
1521
        meth = func_for_method_checked(match.method, types, match.sparams)
211,548✔
1522
        ty = Core.Compiler.typeinf_type(interp, meth, match.spec_types, match.sparams)
211,548✔
1523
        push!(rts, something(ty, Any))
423,096✔
1524
    end
422,637✔
1525
    return rts
211,089✔
1526
end
1527

1528
function infer_effects(@nospecialize(f), @nospecialize(types=default_tt(f));
1,817✔
1529
                       world = get_world_counter(),
1530
                       interp = Core.Compiler.NativeInterpreter(world))
1531
    (ccall(:jl_is_in_pure_context, Bool, ()) || world == typemax(UInt)) &&
826✔
1532
        error("code reflection cannot be used from generated functions")
1533
    if isa(f, Core.Builtin)
826✔
1534
        types = to_tuple_type(types)
12✔
1535
        argtypes = Any[Core.Compiler.Const(f), types.parameters...]
12✔
1536
        rt = Core.Compiler.builtin_tfunction(interp, f, argtypes[2:end], nothing)
12✔
1537
        return Core.Compiler.builtin_effects(Core.Compiler.typeinf_lattice(interp), f,
12✔
1538
            Core.Compiler.ArgInfo(nothing, argtypes), rt)
1539
    end
1540
    tt = signature_type(f, types)
814✔
1541
    result = Core.Compiler.findall(tt, Core.Compiler.method_table(interp))
814✔
1542
    if result === missing
814✔
1543
        # unanalyzable call, return the unknown effects
1544
        return Core.Compiler.Effects()
×
1545
    end
1546
    (; matches) = result
1,628✔
1547
    effects = Core.Compiler.EFFECTS_TOTAL
814✔
1548
    if matches.ambig || !any(match::Core.MethodMatch->match.fully_covers, matches.matches)
2,434✔
1549
        # account for the fact that we may encounter a MethodError with a non-covered or ambiguous signature.
1550
        effects = Core.Compiler.Effects(effects; nothrow=false)
8✔
1551
    end
1552
    for match in matches.matches
817✔
1553
        match = match::Core.MethodMatch
816✔
1554
        frame = Core.Compiler.typeinf_frame(interp,
816✔
1555
            match.method, match.spec_types, match.sparams, #=run_optimizer=#false)
1556
        frame === nothing && return Core.Compiler.Effects()
816✔
1557
        effects = Core.Compiler.merge_effects(effects, frame.ipo_effects)
1,632✔
1558
    end
1,627✔
1559
    return effects
814✔
1560
end
1561

1562
"""
1563
    print_statement_costs(io::IO, f, types)
1564

1565
Print type-inferred and optimized code for `f` given argument types `types`,
1566
prepending each line with its cost as estimated by the compiler's inlining engine.
1567
"""
1568
function print_statement_costs(io::IO, @nospecialize(f), @nospecialize(t); kwargs...)
2✔
1569
    tt = signature_type(f, t)
1✔
1570
    print_statement_costs(io, tt; kwargs...)
1✔
1571
end
1572

1573
function print_statement_costs(io::IO, @nospecialize(tt::Type);
2✔
1574
                               world = get_world_counter(),
1575
                               interp = Core.Compiler.NativeInterpreter(world))
1576
    matches = _methods_by_ftype(tt, -1, world)::Vector
1✔
1577
    params = Core.Compiler.OptimizationParams(interp)
1✔
1578
    cst = Int[]
1✔
1579
    for match in matches
1✔
1580
        match = match::Core.MethodMatch
1✔
1581
        meth = func_for_method_checked(match.method, tt, match.sparams)
1✔
1582
        println(io, meth)
1✔
1583
        (code, ty) = Core.Compiler.typeinf_code(interp, meth, match.spec_types, match.sparams, true)
1✔
1584
        if code === nothing
1✔
1585
            println(io, "  inference not successful")
×
1586
        else
1587
            empty!(cst)
1✔
1588
            resize!(cst, length(code.code))
1✔
1589
            sptypes = Core.Compiler.VarState[Core.Compiler.VarState(sp, false) for sp in match.sparams]
1✔
1590
            maxcost = Core.Compiler.statement_costs!(cst, code.code, code, sptypes, false, params)
20✔
1591
            nd = ndigits(maxcost)
1✔
1592
            irshow_config = IRShow.IRShowConfig() do io, linestart, idx
1✔
1593
                print(io, idx > 0 ? lpad(cst[idx], nd+1) : " "^(nd+1), " ")
22✔
1594
                return ""
21✔
1595
            end
1596
            IRShow.show_ir(io, code, irshow_config)
1✔
1597
        end
1598
        println(io)
1✔
1599
    end
1✔
1600
end
1601

1602
print_statement_costs(args...; kwargs...) = print_statement_costs(stdout, args...; kwargs...)
×
1603

1604
function _which(@nospecialize(tt::Type);
745✔
1605
    method_table::Union{Nothing,Core.MethodTable,Core.Compiler.MethodTableView}=nothing,
1606
    world::UInt=get_world_counter(),
1607
    raise::Bool=true)
1608
    world == typemax(UInt) && error("code reflection cannot be used from generated functions")
371✔
1609
    if method_table === nothing
×
1610
        table = Core.Compiler.InternalMethodTable(world)
×
1611
    elseif method_table isa Core.MethodTable
×
1612
        table = Core.Compiler.OverlayMethodTable(world, method_table)
×
1613
    else
1614
        table = method_table
×
1615
    end
1616
    match, = Core.Compiler.findsup(tt, table)
371✔
1617
    if match === nothing
371✔
1618
        raise && error("no unique matching method found for the specified argument types")
3✔
1619
        return nothing
×
1620
    end
1621
    return match
368✔
1622
end
1623

1624
"""
1625
    which(f, types)
1626

1627
Returns the method of `f` (a `Method` object) that would be called for arguments of the given `types`.
1628

1629
If `types` is an abstract type, then the method that would be called by `invoke` is returned.
1630

1631
See also: [`parentmodule`](@ref), and `@which` and `@edit` in [`InteractiveUtils`](@ref man-interactive-utils).
1632
"""
1633
function which(@nospecialize(f), @nospecialize(t))
113✔
1634
    tt = signature_type(f, t)
113✔
1635
    return which(tt)
118✔
1636
end
1637

1638
"""
1639
    which(types::Type{<:Tuple})
1640

1641
Returns the method that would be called by the given type signature (as a tuple type).
1642
"""
1643
function which(@nospecialize(tt#=::Type=#))
114✔
1644
    return _which(tt).method
119✔
1645
end
1646

1647
"""
1648
    which(module, symbol)
1649

1650
Return the module in which the binding for the variable referenced by `symbol` in `module` was created.
1651
"""
1652
function which(m::Module, s::Symbol)
12✔
1653
    if !isdefined(m, s)
12✔
1654
        error("\"$s\" is not defined in module $m")
4✔
1655
    end
1656
    return binding_module(m, s)
9✔
1657
end
1658

1659
# function reflection
1660

1661
"""
1662
    nameof(f::Function) -> Symbol
1663

1664
Get the name of a generic `Function` as a symbol. For anonymous functions,
1665
this is a compiler-generated name. For explicitly-declared subtypes of
1666
`Function`, it is the name of the function's type.
1667
"""
1668
function nameof(f::Function)
4✔
1669
    t = typeof(f)
4✔
1670
    mt = t.name.mt
4✔
1671
    if mt === Symbol.name.mt
4✔
1672
        # uses shared method table, so name is not unique to this function type
1673
        return nameof(t)
1✔
1674
    end
1675
    return mt.name
3✔
1676
end
1677

1678
function nameof(f::Core.IntrinsicFunction)
5✔
1679
    name = ccall(:jl_intrinsic_name, Ptr{UInt8}, (Core.IntrinsicFunction,), f)
7✔
1680
    return ccall(:jl_symbol, Ref{Symbol}, (Ptr{UInt8},), name)
7✔
1681
end
1682

1683
"""
1684
    parentmodule(f::Function) -> Module
1685

1686
Determine the module containing the (first) definition of a generic
1687
function.
1688
"""
1689
parentmodule(f::Function) = parentmodule(typeof(f))
3✔
1690

1691
"""
1692
    parentmodule(f::Function, types) -> Module
1693

1694
Determine the module containing the first method of a generic function `f` matching
1695
the specified `types`.
1696
"""
1697
function parentmodule(@nospecialize(f), @nospecialize(types))
2✔
1698
    m = methods(f, types)
2✔
1699
    if isempty(m)
2✔
1700
        error("no matching methods")
×
1701
    end
1702
    return parentmodule(first(m))
2✔
1703
end
1704

1705
"""
1706
    parentmodule(m::Method) -> Module
1707

1708
Return the module in which the given method `m` is defined.
1709

1710
!!! compat "Julia 1.9"
1711
    Passing a `Method` as an argument requires Julia 1.9 or later.
1712
"""
1713
parentmodule(m::Method) = m.module
880,529✔
1714

1715
"""
1716
    hasmethod(f, t::Type{<:Tuple}[, kwnames]; world=get_world_counter()) -> Bool
1717

1718
Determine whether the given generic function has a method matching the given
1719
`Tuple` of argument types with the upper bound of world age given by `world`.
1720

1721
If a tuple of keyword argument names `kwnames` is provided, this also checks
1722
whether the method of `f` matching `t` has the given keyword argument names.
1723
If the matching method accepts a variable number of keyword arguments, e.g.
1724
with `kwargs...`, any names given in `kwnames` are considered valid. Otherwise
1725
the provided names must be a subset of the method's keyword arguments.
1726

1727
See also [`applicable`](@ref).
1728

1729
!!! compat "Julia 1.2"
1730
    Providing keyword argument names requires Julia 1.2 or later.
1731

1732
# Examples
1733
```jldoctest
1734
julia> hasmethod(length, Tuple{Array})
1735
true
1736

1737
julia> f(; oranges=0) = oranges;
1738

1739
julia> hasmethod(f, Tuple{}, (:oranges,))
1740
true
1741

1742
julia> hasmethod(f, Tuple{}, (:apples, :bananas))
1743
false
1744

1745
julia> g(; xs...) = 4;
1746

1747
julia> hasmethod(g, Tuple{}, (:a, :b, :c, :d))  # g accepts arbitrary kwargs
1748
true
1749
```
1750
"""
1751
function hasmethod(@nospecialize(f), @nospecialize(t))
34,501✔
1752
    return Core._hasmethod(f, t isa Type ? t : to_tuple_type(t))
34,501✔
1753
end
1754

1755
function Core.kwcall(kwargs::NamedTuple, ::typeof(hasmethod), @nospecialize(f), @nospecialize(t))
4✔
1756
    world = kwargs.world::UInt # make sure this is the only local, to avoid confusing kwarg_decl()
3✔
1757
    return ccall(:jl_gf_invoke_lookup, Any, (Any, Any, UInt), signature_type(f, t), nothing, world) !== nothing
5✔
1758
end
1759

1760
function hasmethod(f, t, kwnames::Tuple{Vararg{Symbol}}; world::UInt=get_world_counter())
28✔
1761
    @nospecialize
14✔
1762
    isempty(kwnames) && return hasmethod(f, t; world)
25✔
1763
    t = to_tuple_type(t)
11✔
1764
    ft = Core.Typeof(f)
22✔
1765
    u = unwrap_unionall(t)::DataType
11✔
1766
    tt = rewrap_unionall(Tuple{typeof(Core.kwcall), NamedTuple, ft, u.parameters...}, t)
11✔
1767
    match = ccall(:jl_gf_invoke_lookup, Any, (Any, Any, UInt), tt, nothing, world)
11✔
1768
    match === nothing && return false
11✔
1769
    kws = ccall(:jl_uncompress_argnames, Array{Symbol,1}, (Any,), (match::Method).slot_syms)
10✔
1770
    isempty(kws) && return true # some kwfuncs simply forward everything directly
10✔
1771
    for kw in kws
10✔
1772
        endswith(String(kw), "...") && return true
56✔
1773
    end
58✔
1774
    kwnames = Symbol[kwnames[i] for i in 1:length(kwnames)]
12✔
1775
    return issubset(kwnames, kws)
6✔
1776
end
1777

1778
"""
1779
    fbody = bodyfunction(basemethod::Method)
1780

1781
Find the keyword "body function" (the function that contains the body of the method
1782
as written, called after all missing keyword-arguments have been assigned default values).
1783
`basemethod` is the method you obtain via [`which`](@ref) or [`methods`](@ref).
1784
"""
1785
function bodyfunction(basemethod::Method)
2✔
1786
    fmod = parentmodule(basemethod)
2✔
1787
    # The lowered code for `basemethod` should look like
1788
    #   %1 = mkw(kwvalues..., #self#, args...)
1789
    #        return %1
1790
    # where `mkw` is the name of the "active" keyword body-function.
1791
    ast = uncompressed_ast(basemethod)
2✔
1792
    if isa(ast, Core.CodeInfo) && length(ast.code) >= 2
2✔
1793
        callexpr = ast.code[end-1]
2✔
1794
        if isa(callexpr, Expr) && callexpr.head === :call
2✔
1795
            fsym = callexpr.args[1]
2✔
1796
            while true
3✔
1797
                if isa(fsym, Symbol)
3✔
1798
                    return getfield(fmod, fsym)
×
1799
                elseif isa(fsym, GlobalRef)
3✔
1800
                    if fsym.mod === Core && fsym.name === :_apply
3✔
1801
                        fsym = callexpr.args[2]
×
1802
                    elseif fsym.mod === Core && fsym.name === :_apply_iterate
3✔
1803
                        fsym = callexpr.args[3]
1✔
1804
                    end
1805
                    if isa(fsym, Symbol)
3✔
1806
                        return getfield(fmod, fsym)::Function
×
1807
                    elseif isa(fsym, GlobalRef)
3✔
1808
                        return getfield(fsym.mod, fsym.name)::Function
2✔
1809
                    elseif isa(fsym, Core.SSAValue)
1✔
1810
                        fsym = ast.code[fsym.id]
1✔
1811
                    else
1812
                        return nothing
×
1813
                    end
1814
                else
1815
                    return nothing
×
1816
                end
1817
            end
1✔
1818
        end
1819
    end
1820
    return nothing
×
1821
end
1822

1823
"""
1824
    Base.isambiguous(m1, m2; ambiguous_bottom=false) -> Bool
1825

1826
Determine whether two methods `m1` and `m2` may be ambiguous for some call
1827
signature. This test is performed in the context of other methods of the same
1828
function; in isolation, `m1` and `m2` might be ambiguous, but if a third method
1829
resolving the ambiguity has been defined, this returns `false`.
1830
Alternatively, in isolation `m1` and `m2` might be ordered, but if a third
1831
method cannot be sorted with them, they may cause an ambiguity together.
1832

1833
For parametric types, the `ambiguous_bottom` keyword argument controls whether
1834
`Union{}` counts as an ambiguous intersection of type parameters – when `true`,
1835
it is considered ambiguous, when `false` it is not.
1836

1837
# Examples
1838
```jldoctest
1839
julia> foo(x::Complex{<:Integer}) = 1
1840
foo (generic function with 1 method)
1841

1842
julia> foo(x::Complex{<:Rational}) = 2
1843
foo (generic function with 2 methods)
1844

1845
julia> m1, m2 = collect(methods(foo));
1846

1847
julia> typeintersect(m1.sig, m2.sig)
1848
Tuple{typeof(foo), Complex{Union{}}}
1849

1850
julia> Base.isambiguous(m1, m2, ambiguous_bottom=true)
1851
true
1852

1853
julia> Base.isambiguous(m1, m2, ambiguous_bottom=false)
1854
false
1855
```
1856
"""
1857
function isambiguous(m1::Method, m2::Method; ambiguous_bottom::Bool=false)
12,946✔
1858
    m1 === m2 && return false
6,473✔
1859
    ti = typeintersect(m1.sig, m2.sig)
6,473✔
1860
    ti === Bottom && return false
6,473✔
1861
    function inner(ti)
12,642✔
1862
        ti === Bottom && return false
6,169✔
1863
        if !ambiguous_bottom
6,169✔
1864
            has_bottom_parameter(ti) && return false
5,506✔
1865
        end
1866
        world = get_world_counter()
2,150✔
1867
        min = Ref{UInt}(typemin(UInt))
2,150✔
1868
        max = Ref{UInt}(typemax(UInt))
2,150✔
1869
        has_ambig = Ref{Int32}(0)
2,150✔
1870
        ms = _methods_by_ftype(ti, nothing, -1, world, true, min, max, has_ambig)::Vector
2,150✔
1871
        has_ambig[] == 0 && return false
2,150✔
1872
        if !ambiguous_bottom
373✔
1873
            filter!(ms) do m::Core.MethodMatch
258✔
1874
                return !has_bottom_parameter(m.spec_types)
1,952✔
1875
            end
1876
        end
1877
        # if ml-matches reported the existence of an ambiguity over their
1878
        # intersection, see if both m1 and m2 seem to be involved in it
1879
        # (if one was fully dominated by a different method, we want to will
1880
        # report the other ambiguous pair)
1881
        have_m1 = have_m2 = false
373✔
1882
        for match in ms
373✔
1883
            match = match::Core.MethodMatch
2,730✔
1884
            m = match.method
2,730✔
1885
            m === m1 && (have_m1 = true)
2,730✔
1886
            m === m2 && (have_m2 = true)
2,730✔
1887
        end
3,103✔
1888
        if !have_m1 || !have_m2
431✔
1889
            # ml-matches did not need both methods to expose the reported ambiguity
1890
            return false
315✔
1891
        end
1892
        if !ambiguous_bottom
58✔
1893
            # since we're intentionally ignoring certain ambiguities (via the
1894
            # filter call above), see if we can now declare the intersection fully
1895
            # covered even though it is partially ambiguous over Union{} as a type
1896
            # parameter somewhere
1897
            minmax = nothing
23✔
1898
            for match in ms
23✔
1899
                m = match.method
74✔
1900
                match.fully_covers || continue
74✔
1901
                if minmax === nothing || morespecific(m.sig, minmax.sig)
109✔
1902
                    minmax = m
23✔
1903
                end
1904
            end
97✔
1905
            if minmax === nothing || minmax == m1 || minmax == m2
59✔
1906
                return true
19✔
1907
            end
1908
            for match in ms
4✔
1909
                m = match.method
12✔
1910
                m === minmax && continue
12✔
1911
                if !morespecific(minmax.sig, m.sig)
8✔
1912
                    if match.fully_covers || !morespecific(m.sig, minmax.sig)
4✔
1913
                        return true
4✔
1914
                    end
1915
                end
1916
            end
8✔
1917
            return false
×
1918
        end
1919
        return true
35✔
1920
    end
1921
    if !(ti <: m1.sig && ti <: m2.sig)
6,473✔
1922
        # When type-intersection fails, it's often also not commutative. Thus
1923
        # checking the reverse may allow detecting ambiguity solutions
1924
        # correctly in more cases (and faster).
1925
        ti2 = typeintersect(m2.sig, m1.sig)
337✔
1926
        if ti2 <: m1.sig && ti2 <: m2.sig
337✔
1927
            ti = ti2
33✔
1928
        elseif ti != ti2
304✔
1929
            # TODO: this would be the more correct way to handle this case, but
1930
            #       people complained so we don't do it
1931
            #inner(ti2) || return false # report that the type system failed to decide if it was ambiguous by saying they definitely are
1932
            return false # report that the type system failed to decide if it was ambiguous by saying they definitely are not
282✔
1933
        else
1934
            return false # report that the type system failed to decide if it was ambiguous by saying they definitely are not
22✔
1935
        end
1936
    end
1937
    inner(ti) || return false
12,280✔
1938
    # otherwise type-intersection reported an ambiguity we couldn't solve
1939
    return true
58✔
1940
end
1941

1942
"""
1943
    delete_method(m::Method)
1944

1945
Make method `m` uncallable and force recompilation of any methods that use(d) it.
1946
"""
1947
function delete_method(m::Method)
18✔
1948
    ccall(:jl_method_table_disable, Cvoid, (Any, Any), get_methodtable(m), m)
18✔
1949
end
1950

1951
function get_methodtable(m::Method)
×
1952
    return ccall(:jl_method_get_table, Any, (Any,), m)::Core.MethodTable
18✔
1953
end
1954

1955
"""
1956
    has_bottom_parameter(t) -> Bool
1957

1958
Determine whether `t` is a Type for which one or more of its parameters is `Union{}`.
1959
"""
1960
function has_bottom_parameter(t::DataType)
54,221✔
1961
    for p in t.parameters
78,652✔
1962
        has_bottom_parameter(p) && return true
51,711✔
1963
    end
70,586✔
1964
    return false
45,816✔
1965
end
1966
has_bottom_parameter(t::typeof(Bottom)) = true
4,274✔
1967
has_bottom_parameter(t::UnionAll) = has_bottom_parameter(unwrap_unionall(t))
8,620✔
1968
has_bottom_parameter(t::Union) = has_bottom_parameter(t.a) & has_bottom_parameter(t.b)
4,567✔
1969
has_bottom_parameter(t::TypeVar) = has_bottom_parameter(t.ub)
18,564✔
1970
has_bottom_parameter(::Any) = false
5,242✔
1971

1972
min_world(m::Core.CodeInstance) = m.min_world
18,842,170✔
1973
max_world(m::Core.CodeInstance) = m.max_world
18,842,170✔
1974
min_world(m::Core.CodeInfo) = m.min_world
×
1975
max_world(m::Core.CodeInfo) = m.max_world
×
1976
get_world_counter() = ccall(:jl_get_world_counter, UInt, ())
17,097,032✔
1977

1978
"""
1979
    propertynames(x, private=false)
1980

1981
Get a tuple or a vector of the properties (`x.property`) of an object `x`.
1982
This is typically the same as [`fieldnames(typeof(x))`](@ref), but types
1983
that overload [`getproperty`](@ref) should generally overload `propertynames`
1984
as well to get the properties of an instance of the type.
1985

1986
`propertynames(x)` may return only "public" property names that are part
1987
of the documented interface of `x`.   If you want it to also return "private"
1988
property names intended for internal use, pass `true` for the optional second argument.
1989
REPL tab completion on `x.` shows only the `private=false` properties.
1990

1991
See also: [`hasproperty`](@ref), [`hasfield`](@ref).
1992
"""
1993
propertynames(x) = fieldnames(typeof(x))
5✔
1994
propertynames(m::Module) = names(m)
×
1995
propertynames(x, private::Bool) = propertynames(x) # ignore private flag by default
×
1996

1997
"""
1998
    hasproperty(x, s::Symbol)
1999

2000
Return a boolean indicating whether the object `x` has `s` as one of its own properties.
2001

2002
!!! compat "Julia 1.2"
2003
     This function requires at least Julia 1.2.
2004

2005
See also: [`propertynames`](@ref), [`hasfield`](@ref).
2006
"""
2007
hasproperty(x, s::Symbol) = s in propertynames(x)
2✔
2008

2009
"""
2010
    @invoke f(arg::T, ...; kwargs...)
2011

2012
Provides a convenient way to call [`invoke`](@ref) by expanding
2013
`@invoke f(arg1::T1, arg2::T2; kwargs...)` to `invoke(f, Tuple{T1,T2}, arg1, arg2; kwargs...)`.
2014
When an argument's type annotation is omitted, it's replaced with `Core.Typeof` that argument.
2015
To invoke a method where an argument is untyped or explicitly typed as `Any`, annotate the
2016
argument with `::Any`.
2017

2018
It also supports the following syntax:
2019
- `@invoke (x::X).f` expands to `invoke(getproperty, Tuple{X,Symbol}, x, :f)`
2020
- `@invoke (x::X).f = v::V` expands to `invoke(setproperty!, Tuple{X,Symbol,V}, x, :f, v)`
2021
- `@invoke (xs::Xs)[i::I]` expands to `invoke(getindex, Tuple{Xs,I}, xs, i)`
2022
- `@invoke (xs::Xs)[i::I] = v::V` expands to `invoke(setindex!, Tuple{Xs,V,I}, xs, v, i)`
2023

2024
# Examples
2025

2026
```jldoctest
2027
julia> @macroexpand @invoke f(x::T, y)
2028
:(Core.invoke(f, Tuple{T, Core.Typeof(y)}, x, y))
2029

2030
julia> @invoke 420::Integer % Unsigned
2031
0x00000000000001a4
2032

2033
julia> @macroexpand @invoke (x::X).f
2034
:(Core.invoke(Base.getproperty, Tuple{X, Core.Typeof(:f)}, x, :f))
2035

2036
julia> @macroexpand @invoke (x::X).f = v::V
2037
:(Core.invoke(Base.setproperty!, Tuple{X, Core.Typeof(:f), V}, x, :f, v))
2038

2039
julia> @macroexpand @invoke (xs::Xs)[i::I]
2040
:(Core.invoke(Base.getindex, Tuple{Xs, I}, xs, i))
2041

2042
julia> @macroexpand @invoke (xs::Xs)[i::I] = v::V
2043
:(Core.invoke(Base.setindex!, Tuple{Xs, V, I}, xs, v, i))
2044
```
2045

2046
!!! compat "Julia 1.7"
2047
    This macro requires Julia 1.7 or later.
2048

2049
!!! compat "Julia 1.9"
2050
    This macro is exported as of Julia 1.9.
2051

2052
!!! compat "Julia 1.10"
2053
    The additional syntax is supported as of Julia 1.10.
2054
"""
2055
macro invoke(ex)
20✔
2056
    topmod = Core.Compiler._topmod(__module__) # well, except, do not get it via CC but define it locally
20✔
2057
    f, args, kwargs = destructure_callex(topmod, ex)
20✔
2058
    types = Expr(:curly, :Tuple)
20✔
2059
    out = Expr(:call, GlobalRef(Core, :invoke))
20✔
2060
    isempty(kwargs) || push!(out.args, Expr(:parameters, kwargs...))
20✔
2061
    push!(out.args, f)
20✔
2062
    push!(out.args, types)
20✔
2063
    for arg in args
20✔
2064
        if isexpr(arg, :(::))
39✔
2065
            push!(out.args, arg.args[1])
37✔
2066
            push!(types.args, arg.args[2])
37✔
2067
        else
2068
            push!(out.args, arg)
2✔
2069
            push!(types.args, Expr(:call, GlobalRef(Core, :Typeof), arg))
2✔
2070
        end
2071
    end
39✔
2072
    return esc(out)
20✔
2073
end
2074

2075
"""
2076
    @invokelatest f(args...; kwargs...)
2077

2078
Provides a convenient way to call [`Base.invokelatest`](@ref).
2079
`@invokelatest f(args...; kwargs...)` will simply be expanded into
2080
`Base.invokelatest(f, args...; kwargs...)`.
2081

2082
It also supports the following syntax:
2083
- `@invokelatest x.f` expands to `Base.invokelatest(getproperty, x, :f)`
2084
- `@invokelatest x.f = v` expands to `Base.invokelatest(setproperty!, x, :f, v)`
2085
- `@invokelatest xs[i]` expands to `invoke(getindex, xs, i)`
2086
- `@invokelatest xs[i] = v` expands to `invoke(setindex!, xs, v, i)`
2087

2088
```jldoctest
2089
julia> @macroexpand @invokelatest f(x; kw=kwv)
2090
:(Base.invokelatest(f, x; kw = kwv))
2091

2092
julia> @macroexpand @invokelatest x.f
2093
:(Base.invokelatest(Base.getproperty, x, :f))
2094

2095
julia> @macroexpand @invokelatest x.f = v
2096
:(Base.invokelatest(Base.setproperty!, x, :f, v))
2097

2098
julia> @macroexpand @invokelatest xs[i]
2099
:(Base.invokelatest(Base.getindex, xs, i))
2100

2101
julia> @macroexpand @invokelatest xs[i] = v
2102
:(Base.invokelatest(Base.setindex!, xs, v, i))
2103
```
2104

2105
!!! compat "Julia 1.7"
2106
    This macro requires Julia 1.7 or later.
2107

2108
!!! compat "Julia 1.10"
2109
    The additional syntax is supported as of Julia 1.10.
2110
"""
2111
macro invokelatest(ex)
226✔
2112
    topmod = Core.Compiler._topmod(__module__) # well, except, do not get it via CC but define it locally
226✔
2113
    f, args, kwargs = destructure_callex(topmod, ex)
226✔
2114
    out = Expr(:call, GlobalRef(Base, :invokelatest))
226✔
2115
    isempty(kwargs) || push!(out.args, Expr(:parameters, kwargs...))
226✔
2116
    push!(out.args, f)
226✔
2117
    append!(out.args, args)
226✔
2118
    return esc(out)
226✔
2119
end
2120

2121
function destructure_callex(topmod::Module, @nospecialize(ex))
226✔
2122
    function flatten(xs)
226✔
2123
        out = Any[]
×
2124
        for x in xs
×
2125
            if isexpr(x, :tuple)
×
2126
                append!(out, x.args)
×
2127
            else
2128
                push!(out, x)
×
2129
            end
2130
        end
×
2131
        return out
×
2132
    end
2133

2134
    kwargs = Any[]
226✔
2135
    if isexpr(ex, :call) # `f(args...)`
226✔
2136
        f = first(ex.args)
226✔
2137
        args = Any[]
226✔
2138
        for x in ex.args[2:end]
226✔
2139
            if isexpr(x, :parameters)
3,718✔
2140
                append!(kwargs, x.args)
×
2141
            elseif isexpr(x, :kw)
3,718✔
2142
                push!(kwargs, x)
×
2143
            else
2144
                push!(args, x)
1,878✔
2145
            end
2146
        end
2,104✔
2147
    elseif isexpr(ex, :.)   # `x.f`
×
2148
        f = GlobalRef(topmod, :getproperty)
×
2149
        args = flatten(ex.args)
×
2150
    elseif isexpr(ex, :ref) # `x[i]`
×
2151
        f = GlobalRef(topmod, :getindex)
×
2152
        args = flatten(ex.args)
×
2153
    elseif isexpr(ex, :(=)) # `x.f = v` or `x[i] = v`
×
2154
        lhs, rhs = ex.args
×
2155
        if isexpr(lhs, :.)
×
2156
            f = GlobalRef(topmod, :setproperty!)
×
2157
            args = flatten(Any[lhs.args..., rhs])
×
2158
        elseif isexpr(lhs, :ref)
×
2159
            f = GlobalRef(topmod, :setindex!)
×
2160
            args = flatten(Any[lhs.args[1], rhs, lhs.args[2]])
×
2161
        else
2162
            throw(ArgumentError("expected a `setproperty!` expression `x.f = v` or `setindex!` expression `x[i] = v`"))
×
2163
        end
2164
    else
2165
        throw(ArgumentError("expected a `:call` expression `f(args...; kwargs...)`"))
×
2166
    end
2167
    return f, args, kwargs
226✔
2168
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