-
-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
reflection.jl
1743 lines (1471 loc) · 53.9 KB
/
reflection.jl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# This file is a part of Julia. License is MIT: https://julialang.org/license
# name and module reflection
"""
nameof(m::Module) -> Symbol
Get the name of a `Module` as a [`Symbol`](@ref).
# Examples
```jldoctest
julia> nameof(Base.Broadcast)
:Broadcast
```
"""
nameof(m::Module) = ccall(:jl_module_name, Ref{Symbol}, (Any,), m)
"""
parentmodule(m::Module) -> Module
Get a module's enclosing `Module`. `Main` is its own parent.
See also: [`names`](@ref), [`nameof`](@ref), [`fullname`](@ref), [`@__MODULE__`](@ref).
# Examples
```jldoctest
julia> parentmodule(Main)
Main
julia> parentmodule(Base.Broadcast)
Base
```
"""
parentmodule(m::Module) = ccall(:jl_module_parent, Ref{Module}, (Any,), m)
"""
moduleroot(m::Module) -> Module
Find the root module of a given module. This is the first module in the chain of
parent modules of `m` which is either a registered root module or which is its
own parent module.
"""
function moduleroot(m::Module)
while true
is_root_module(m) && return m
p = parentmodule(m)
p === m && return m
m = p
end
end
"""
@__MODULE__ -> Module
Get the `Module` of the toplevel eval,
which is the `Module` code is currently being read from.
"""
macro __MODULE__()
return __module__
end
"""
fullname(m::Module)
Get the fully-qualified name of a module as a tuple of symbols. For example,
# Examples
```jldoctest
julia> fullname(Base.Iterators)
(:Base, :Iterators)
julia> fullname(Main)
(:Main,)
```
"""
function fullname(m::Module)
mn = nameof(m)
if m === Main || m === Base || m === Core
return (mn,)
end
mp = parentmodule(m)
if mp === m
return (mn,)
end
return (fullname(mp)..., mn)
end
"""
names(x::Module; all::Bool = false, imported::Bool = false)
Get an array of the names exported by a `Module`, excluding deprecated names.
If `all` is true, then the list also includes non-exported names defined in the module,
deprecated names, and compiler-generated names.
If `imported` is true, then names explicitly imported from other modules
are also included.
As a special case, all names defined in `Main` are considered \"exported\",
since it is not idiomatic to explicitly export names from `Main`.
See also: [`@locals`](@ref Base.@locals), [`@__MODULE__`](@ref).
"""
names(m::Module; all::Bool = false, imported::Bool = false) =
sort!(ccall(:jl_module_names, Array{Symbol,1}, (Any, Cint, Cint), m, all, imported))
isexported(m::Module, s::Symbol) = ccall(:jl_module_exports_p, Cint, (Any, Any), m, s) != 0
isdeprecated(m::Module, s::Symbol) = ccall(:jl_is_binding_deprecated, Cint, (Any, Any), m, s) != 0
isbindingresolved(m::Module, var::Symbol) = ccall(:jl_binding_resolved_p, Cint, (Any, Any), m, var) != 0
function binding_module(m::Module, s::Symbol)
p = ccall(:jl_get_module_of_binding, Ptr{Cvoid}, (Any, Any), m, s)
p == C_NULL && return m
return unsafe_pointer_to_objref(p)::Module
end
function resolve(g::GlobalRef; force::Bool=false)
if force || isbindingresolved(g.mod, g.name)
return GlobalRef(binding_module(g.mod, g.name), g.name)
end
return g
end
const NamedTuple_typename = NamedTuple.body.body.name
function _fieldnames(@nospecialize t)
if t.name === NamedTuple_typename
if t.parameters[1] isa Tuple
return t.parameters[1]
else
throw(ArgumentError("type does not have definite field names"))
end
end
return t.name.names
end
"""
fieldname(x::DataType, i::Integer)
Get the name of field `i` of a `DataType`.
# Examples
```jldoctest
julia> fieldname(Rational, 1)
:num
julia> fieldname(Rational, 2)
:den
```
"""
function fieldname(t::DataType, i::Integer)
throw_not_def_field() = throw(ArgumentError("type does not have definite field names"))
function throw_field_access(t, i, n_fields)
field_label = n_fields == 1 ? "field" : "fields"
throw(ArgumentError("Cannot access field $i since type $t only has $n_fields $field_label."))
end
throw_need_pos_int(i) = throw(ArgumentError("Field numbers must be positive integers. $i is invalid."))
isabstracttype(t) && throw_not_def_field()
names = _fieldnames(t)
n_fields = length(names)::Int
i > n_fields && throw_field_access(t, i, n_fields)
i < 1 && throw_need_pos_int(i)
return @inbounds names[i]::Symbol
end
fieldname(t::UnionAll, i::Integer) = fieldname(unwrap_unionall(t), i)
fieldname(t::Type{<:Tuple}, i::Integer) =
i < 1 || i > fieldcount(t) ? throw(BoundsError(t, i)) : Int(i)
"""
fieldnames(x::DataType)
Get a tuple with the names of the fields of a `DataType`.
See also [`propertynames`](@ref), [`hasfield`](@ref).
# Examples
```jldoctest
julia> fieldnames(Rational)
(:num, :den)
julia> fieldnames(typeof(1+im))
(:re, :im)
```
"""
fieldnames(t::DataType) = (fieldcount(t); # error check to make sure type is specific enough
(_fieldnames(t)...,))::Tuple{Vararg{Symbol}}
fieldnames(t::UnionAll) = fieldnames(unwrap_unionall(t))
fieldnames(::Core.TypeofBottom) =
throw(ArgumentError("The empty type does not have field names since it does not have instances."))
fieldnames(t::Type{<:Tuple}) = ntuple(identity, fieldcount(t))
"""
hasfield(T::Type, name::Symbol)
Return a boolean indicating whether `T` has `name` as one of its own fields.
!!! compat "Julia 1.2"
This function requires at least Julia 1.2.
"""
function hasfield(T::Type, name::Symbol)
@_pure_meta
return fieldindex(T, name, false) > 0
end
"""
nameof(t::DataType) -> Symbol
Get the name of a (potentially `UnionAll`-wrapped) `DataType` (without its parent module)
as a symbol.
# Examples
```jldoctest
julia> module Foo
struct S{T}
end
end
Foo
julia> nameof(Foo.S{T} where T)
:S
```
"""
nameof(t::DataType) = t.name.name
nameof(t::UnionAll) = nameof(unwrap_unionall(t))::Symbol
"""
parentmodule(t::DataType) -> Module
Determine the module containing the definition of a (potentially `UnionAll`-wrapped) `DataType`.
# Examples
```jldoctest
julia> module Foo
struct Int end
end
Foo
julia> parentmodule(Int)
Core
julia> parentmodule(Foo.Int)
Foo
```
"""
parentmodule(t::DataType) = t.name.module
parentmodule(t::UnionAll) = parentmodule(unwrap_unionall(t))
"""
isconst(m::Module, s::Symbol) -> Bool
Determine whether a global is declared `const` in a given `Module`.
"""
isconst(m::Module, s::Symbol) =
ccall(:jl_is_const, Cint, (Any, Any), m, s) != 0
"""
@locals()
Construct a dictionary of the names (as symbols) and values of all local
variables defined as of the call site.
!!! compat "Julia 1.1"
This macro requires at least Julia 1.1.
# Examples
```jldoctest
julia> let x = 1, y = 2
Base.@locals
end
Dict{Symbol, Any} with 2 entries:
:y => 2
:x => 1
julia> function f(x)
local y
show(Base.@locals); println()
for i = 1:1
show(Base.@locals); println()
end
y = 2
show(Base.@locals); println()
nothing
end;
julia> f(42)
Dict{Symbol, Any}(:x => 42)
Dict{Symbol, Any}(:i => 1, :x => 42)
Dict{Symbol, Any}(:y => 2, :x => 42)
```
"""
macro locals()
return Expr(:locals)
end
"""
objectid(x) -> UInt
Get a hash value for `x` based on object identity. `objectid(x)==objectid(y)` if `x === y`.
See also [`hash`](@ref), [`IdDict`](@ref).
"""
objectid(@nospecialize(x)) = ccall(:jl_object_id, UInt, (Any,), x)
# concrete datatype predicates
datatype_fieldtypes(x::DataType) = ccall(:jl_get_fieldtypes, Core.SimpleVector, (Any,), x)
struct DataTypeLayout
nfields::UInt32
npointers::UInt32
firstptr::Int32
alignment::UInt16
flags::UInt16
# haspadding : 1;
# fielddesc_type : 2;
end
"""
Base.datatype_alignment(dt::DataType) -> Int
Memory allocation minimum alignment for instances of this type.
Can be called on any `isconcretetype`.
"""
function datatype_alignment(dt::DataType)
@_pure_meta
dt.layout == C_NULL && throw(UndefRefError())
alignment = unsafe_load(convert(Ptr{DataTypeLayout}, dt.layout)).alignment
return Int(alignment)
end
function uniontype_layout(T::Type)
sz = RefValue{Csize_t}(0)
algn = RefValue{Csize_t}(0)
isinline = ccall(:jl_islayout_inline, Cint, (Any, Ptr{Csize_t}, Ptr{Csize_t}), T, sz, algn) != 0
(isinline, sz[], algn[])
end
# amount of total space taken by T when stored in a container
function aligned_sizeof(T::Type)
@_pure_meta
if isbitsunion(T)
_, sz, al = uniontype_layout(T)
return (sz + al - 1) & -al
elseif allocatedinline(T)
al = datatype_alignment(T)
return (Core.sizeof(T) + al - 1) & -al
else
return Core.sizeof(Ptr{Cvoid})
end
end
gc_alignment(sz::Integer) = Int(ccall(:jl_alignment, Cint, (Csize_t,), sz))
gc_alignment(T::Type) = gc_alignment(Core.sizeof(T))
"""
Base.datatype_haspadding(dt::DataType) -> Bool
Return whether the fields of instances of this type are packed in memory,
with no intervening padding bytes.
Can be called on any `isconcretetype`.
"""
function datatype_haspadding(dt::DataType)
@_pure_meta
dt.layout == C_NULL && throw(UndefRefError())
flags = unsafe_load(convert(Ptr{DataTypeLayout}, dt.layout)).flags
return flags & 1 == 1
end
"""
Base.datatype_nfields(dt::DataType) -> Bool
Return the number of fields known to this datatype's layout.
Can be called on any `isconcretetype`.
"""
function datatype_nfields(dt::DataType)
@_pure_meta
dt.layout == C_NULL && throw(UndefRefError())
return unsafe_load(convert(Ptr{DataTypeLayout}, dt.layout)).nfields
end
"""
Base.datatype_pointerfree(dt::DataType) -> Bool
Return whether instances of this type can contain references to gc-managed memory.
Can be called on any `isconcretetype`.
"""
function datatype_pointerfree(dt::DataType)
@_pure_meta
dt.layout == C_NULL && throw(UndefRefError())
npointers = unsafe_load(convert(Ptr{DataTypeLayout}, dt.layout)).npointers
return npointers == 0
end
"""
Base.datatype_fielddesc_type(dt::DataType) -> Int
Return the size in bytes of each field-description entry in the layout array,
located at `(dt.layout + sizeof(DataTypeLayout))`.
Can be called on any `isconcretetype`.
See also [`fieldoffset`](@ref).
"""
function datatype_fielddesc_type(dt::DataType)
@_pure_meta
dt.layout == C_NULL && throw(UndefRefError())
flags = unsafe_load(convert(Ptr{DataTypeLayout}, dt.layout)).flags
return (flags >> 1) & 3
end
# For type stability, we only expose a single struct that describes everything
struct FieldDesc
isforeign::Bool
isptr::Bool
size::UInt32
offset::UInt32
end
struct FieldDescStorage{T}
ptrsize::T
offset::T
end
FieldDesc(fd::FieldDescStorage{T}) where {T} =
FieldDesc(false, fd.ptrsize & 1 != 0,
fd.ptrsize >> 1, fd.offset)
struct DataTypeFieldDesc
dt::DataType
function DataTypeFieldDesc(dt::DataType)
dt.layout == C_NULL && throw(UndefRefError())
new(dt)
end
end
function getindex(dtfd::DataTypeFieldDesc, i::Int)
layout_ptr = convert(Ptr{DataTypeLayout}, dtfd.dt.layout)
fd_ptr = layout_ptr + sizeof(DataTypeLayout)
layout = unsafe_load(layout_ptr)
fielddesc_type = (layout.flags >> 1) & 3
nfields = layout.nfields
@boundscheck ((1 <= i <= nfields) || throw(BoundsError(dtfd, i)))
if fielddesc_type == 0
return FieldDesc(unsafe_load(Ptr{FieldDescStorage{UInt8}}(fd_ptr), i))
elseif fielddesc_type == 1
return FieldDesc(unsafe_load(Ptr{FieldDescStorage{UInt16}}(fd_ptr), i))
elseif fielddesc_type == 2
return FieldDesc(unsafe_load(Ptr{FieldDescStorage{UInt32}}(fd_ptr), i))
else
# fielddesc_type == 3
return FieldDesc(true, true, 0, 0)
end
end
"""
ismutable(v) -> Bool
Return `true` if and only if value `v` is mutable. See [Mutable Composite Types](@ref)
for a discussion of immutability. Note that this function works on values, so if you give it
a type, it will tell you that a value of `DataType` is mutable.
See also [`isbits`](@ref), [`isstructtype`](@ref).
# Examples
```jldoctest
julia> ismutable(1)
false
julia> ismutable([1,2])
true
```
!!! compat "Julia 1.5"
This function requires at least Julia 1.5.
"""
ismutable(@nospecialize(x)) = (@_pure_meta; typeof(x).name.flags & 0x2 == 0x2)
"""
ismutabletype(T) -> Bool
Determine whether type `T` was declared as a mutable type
(i.e. using `mutable struct` keyword).
!!! compat "Julia 1.7"
This function requires at least Julia 1.7.
"""
function ismutabletype(@nospecialize t)
t = unwrap_unionall(t)
# TODO: what to do for `Union`?
return isa(t, DataType) && t.name.flags & 0x2 == 0x2
end
"""
isstructtype(T) -> Bool
Determine whether type `T` was declared as a struct type
(i.e. using the `struct` or `mutable struct` keyword).
"""
function isstructtype(@nospecialize t)
@_pure_meta
t = unwrap_unionall(t)
# TODO: what to do for `Union`?
isa(t, DataType) || return false
hasfield = !isdefined(t, :types) || !isempty(t.types)
return hasfield || (t.size == 0 && !isabstracttype(t))
end
"""
isprimitivetype(T) -> Bool
Determine whether type `T` was declared as a primitive type
(i.e. using the `primitive` keyword).
"""
function isprimitivetype(@nospecialize t)
@_pure_meta
t = unwrap_unionall(t)
# TODO: what to do for `Union`?
isa(t, DataType) || return false
hasfield = !isdefined(t, :types) || !isempty(t.types)
return !hasfield && t.size != 0 && !isabstracttype(t)
end
"""
isbitstype(T)
Return `true` if type `T` is a "plain data" type,
meaning it is immutable and contains no references to other values,
only `primitive` types and other `isbitstype` types.
Typical examples are numeric types such as [`UInt8`](@ref),
[`Float64`](@ref), and [`Complex{Float64}`](@ref).
This category of types is significant since they are valid as type parameters,
may not track [`isdefined`](@ref) / [`isassigned`](@ref) status,
and have a defined layout that is compatible with C.
See also [`isbits`](@ref), [`isprimitivetype`](@ref), [`ismutable`](@ref).
# Examples
```jldoctest
julia> isbitstype(Complex{Float64})
true
julia> isbitstype(Complex)
false
```
"""
isbitstype(@nospecialize t) = (@_pure_meta; isa(t, DataType) && (t.flags & 0x8) == 0x8)
"""
isbits(x)
Return `true` if `x` is an instance of an [`isbitstype`](@ref) type.
"""
isbits(@nospecialize x) = (@_pure_meta; typeof(x).flags & 0x8 == 0x8)
"""
isdispatchtuple(T)
Determine whether type `T` is a tuple "leaf type",
meaning it could appear as a type signature in dispatch
and has no subtypes (or supertypes) which could appear in a call.
"""
isdispatchtuple(@nospecialize(t)) = (@_pure_meta; isa(t, DataType) && (t.flags & 0x4) == 0x4)
iskindtype(@nospecialize t) = (t === DataType || t === UnionAll || t === Union || t === typeof(Bottom))
isconcretedispatch(@nospecialize t) = isconcretetype(t) && !iskindtype(t)
has_free_typevars(@nospecialize(t)) = ccall(:jl_has_free_typevars, Cint, (Any,), t) != 0
# equivalent to isa(v, Type) && isdispatchtuple(Tuple{v}) || v === Union{}
# and is thus perhaps most similar to the old (pre-1.0) `isleaftype` query
const _TYPE_NAME = Type.body.name
function isdispatchelem(@nospecialize v)
return (v === Bottom) || (v === typeof(Bottom)) || isconcretedispatch(v) ||
(isa(v, DataType) && v.name === _TYPE_NAME && !has_free_typevars(v)) # isType(v)
end
"""
isconcretetype(T)
Determine whether type `T` is a concrete type, meaning it could have direct instances
(values `x` such that `typeof(x) === T`).
See also: [`isbits`](@ref), [`isabstracttype`](@ref), [`issingletontype`](@ref).
# Examples
```jldoctest
julia> isconcretetype(Complex)
false
julia> isconcretetype(Complex{Float32})
true
julia> isconcretetype(Vector{Complex})
true
julia> isconcretetype(Vector{Complex{Float32}})
true
julia> isconcretetype(Union{})
false
julia> isconcretetype(Union{Int,String})
false
```
"""
isconcretetype(@nospecialize(t)) = (@_pure_meta; isa(t, DataType) && (t.flags & 0x2) == 0x2)
"""
isabstracttype(T)
Determine whether type `T` was declared as an abstract type
(i.e. using the `abstract` keyword).
# Examples
```jldoctest
julia> isabstracttype(AbstractArray)
true
julia> isabstracttype(Vector)
false
```
"""
function isabstracttype(@nospecialize(t))
@_pure_meta
t = unwrap_unionall(t)
# TODO: what to do for `Union`?
return isa(t, DataType) && (t.name.flags & 0x1) == 0x1
end
"""
Base.issingletontype(T)
Determine whether type `T` has exactly one possible instance; for example, a
struct type with no fields.
"""
issingletontype(@nospecialize(t)) = (@_pure_meta; isa(t, DataType) && isdefined(t, :instance))
"""
typeintersect(T, S)
Compute a type that contains the intersection of `T` and `S`. Usually this will be the
smallest such type or one close to it.
"""
typeintersect(@nospecialize(a), @nospecialize(b)) = (@_pure_meta; ccall(:jl_type_intersection, Any, (Any, Any), a, b))
morespecific(@nospecialize(a), @nospecialize(b)) = ccall(:jl_type_morespecific, Cint, (Any, Any), a, b) != 0
"""
fieldoffset(type, i)
The byte offset of field `i` of a type relative to the data start. For example, we could
use it in the following manner to summarize information about a struct:
```jldoctest
julia> structinfo(T) = [(fieldoffset(T,i), fieldname(T,i), fieldtype(T,i)) for i = 1:fieldcount(T)];
julia> structinfo(Base.Filesystem.StatStruct)
13-element Vector{Tuple{UInt64, Symbol, Type}}:
(0x0000000000000000, :desc, Union{RawFD, String})
(0x0000000000000008, :device, UInt64)
(0x0000000000000010, :inode, UInt64)
(0x0000000000000018, :mode, UInt64)
(0x0000000000000020, :nlink, Int64)
(0x0000000000000028, :uid, UInt64)
(0x0000000000000030, :gid, UInt64)
(0x0000000000000038, :rdev, UInt64)
(0x0000000000000040, :size, Int64)
(0x0000000000000048, :blksize, Int64)
(0x0000000000000050, :blocks, Int64)
(0x0000000000000058, :mtime, Float64)
(0x0000000000000060, :ctime, Float64)
```
"""
fieldoffset(x::DataType, idx::Integer) = (@_pure_meta; ccall(:jl_get_field_offset, Csize_t, (Any, Cint), x, idx))
"""
fieldtype(T, name::Symbol | index::Int)
Determine the declared type of a field (specified by name or index) in a composite DataType `T`.
# Examples
```jldoctest
julia> struct Foo
x::Int64
y::String
end
julia> fieldtype(Foo, :x)
Int64
julia> fieldtype(Foo, 2)
String
```
"""
fieldtype
"""
Base.fieldindex(T, name::Symbol, err:Bool=true)
Get the index of a named field, throwing an error if the field does not exist (when err==true)
or returning 0 (when err==false).
# Examples
```jldoctest
julia> struct Foo
x::Int64
y::String
end
julia> Base.fieldindex(Foo, :z)
ERROR: type Foo has no field z
Stacktrace:
[...]
julia> Base.fieldindex(Foo, :z, false)
0
```
"""
function fieldindex(T::DataType, name::Symbol, err::Bool=true)
return Int(ccall(:jl_field_index, Cint, (Any, Any, Cint), T, name, err)+1)
end
function fieldindex(t::UnionAll, name::Symbol, err::Bool=true)
t = argument_datatype(t)
if t === nothing
throw(ArgumentError("type does not have definite fields"))
end
return fieldindex(t, name, err)
end
argument_datatype(@nospecialize t) = ccall(:jl_argument_datatype, Any, (Any,), t)
"""
fieldcount(t::Type)
Get the number of fields that an instance of the given type would have.
An error is thrown if the type is too abstract to determine this.
"""
function fieldcount(@nospecialize t)
if t isa UnionAll || t isa Union
t = argument_datatype(t)
if t === nothing
throw(ArgumentError("type does not have a definite number of fields"))
end
t = t::DataType
elseif t == Union{}
throw(ArgumentError("The empty type does not have a well-defined number of fields since it does not have instances."))
end
if !(t isa DataType)
throw(TypeError(:fieldcount, DataType, t))
end
if t.name === NamedTuple_typename
names, types = t.parameters[1], t.parameters[2]
if names isa Tuple
return length(names)
end
if types isa DataType && types <: Tuple
return fieldcount(types)
end
abstr = true
else
abstr = isabstracttype(t) || (t.name === Tuple.name && isvatuple(t))
end
if abstr
throw(ArgumentError("type does not have a definite number of fields"))
end
if isdefined(t, :types)
return length(t.types)
end
return length(t.name.names)
end
"""
fieldtypes(T::Type)
The declared types of all fields in a composite DataType `T` as a tuple.
!!! compat "Julia 1.1"
This function requires at least Julia 1.1.
# Examples
```jldoctest
julia> struct Foo
x::Int64
y::String
end
julia> fieldtypes(Foo)
(Int64, String)
```
"""
fieldtypes(T::Type) = ntupleany(i -> fieldtype(T, i), fieldcount(T))
# return all instances, for types that can be enumerated
"""
instances(T::Type)
Return a collection of all instances of the given type, if applicable. Mostly used for
enumerated types (see `@enum`).
# Example
```jldoctest
julia> @enum Color red blue green
julia> instances(Color)
(red, blue, green)
```
"""
function instances end
function to_tuple_type(@nospecialize(t))
if isa(t, Tuple) || isa(t, AbstractArray) || isa(t, SimpleVector)
t = Tuple{t...}
end
if isa(t, Type) && t <: Tuple
for p in unwrap_unionall(t).parameters
if isa(p, Core.TypeofVararg)
p = p.T
end
if !(isa(p, Type) || isa(p, TypeVar))
error("argument tuple type must contain only types")
end
end
else
error("expected tuple type")
end
t
end
function signature_type(@nospecialize(f), @nospecialize(args))
f_type = isa(f, Type) ? Type{f} : typeof(f)
if isa(args, Type)
u = unwrap_unionall(args)
return rewrap_unionall(Tuple{f_type, u.parameters...}, args)
else
return Tuple{f_type, args...}
end
end
"""
code_lowered(f, types; generated=true, debuginfo=:default)
Return an array of the lowered forms (IR) for the methods matching the given generic function
and type signature.
If `generated` is `false`, the returned `CodeInfo` instances will correspond to fallback
implementations. An error is thrown if no fallback implementation exists.
If `generated` is `true`, these `CodeInfo` instances will correspond to the method bodies
yielded by expanding the generators.
The keyword `debuginfo` controls the amount of code metadata present in the output.
Note that an error will be thrown if `types` are not leaf types when `generated` is
`true` and any of the corresponding methods are an `@generated` method.
"""
function code_lowered(@nospecialize(f), @nospecialize(t=Tuple); generated::Bool=true, debuginfo::Symbol=:default)
if @isdefined(IRShow)
debuginfo = IRShow.debuginfo(debuginfo)
elseif debuginfo === :default
debuginfo = :source
end
if debuginfo !== :source && debuginfo !== :none
throw(ArgumentError("'debuginfo' must be either :source or :none"))
end
return map(method_instances(f, t)) do m
if generated && hasgenerator(m)
if may_invoke_generator(m)
return ccall(:jl_code_for_staged, Any, (Any,), m)::CodeInfo
else
error("Could not expand generator for `@generated` method ", m, ". ",
"This can happen if the provided argument types (", t, ") are ",
"not leaf types, but the `generated` argument is `true`.")
end
end
code = uncompressed_ir(m.def::Method)
debuginfo === :none && remove_linenums!(code)
return code
end
end
hasgenerator(m::Method) = isdefined(m, :generator)
hasgenerator(m::Core.MethodInstance) = hasgenerator(m.def::Method)
# low-level method lookup functions used by the compiler
unionlen(x::Union) = unionlen(x.a) + unionlen(x.b)
unionlen(@nospecialize(x)) = 1
_uniontypes(x::Union, ts) = (_uniontypes(x.a,ts); _uniontypes(x.b,ts); ts)
_uniontypes(@nospecialize(x), ts) = (push!(ts, x); ts)
uniontypes(@nospecialize(x)) = _uniontypes(x, Any[])
function _methods(@nospecialize(f), @nospecialize(t), lim::Int, world::UInt)
tt = signature_type(f, t)
return _methods_by_ftype(tt, lim, world)
end
function _methods_by_ftype(@nospecialize(t), lim::Int, world::UInt)
return _methods_by_ftype(t, nothing, lim, world)
end
function _methods_by_ftype(@nospecialize(t), mt::Union{Core.MethodTable, Nothing}, lim::Int, world::UInt)
return _methods_by_ftype(t, mt, lim, world, false, RefValue{UInt}(typemin(UInt)), RefValue{UInt}(typemax(UInt)), Ptr{Int32}(C_NULL))
end
function _methods_by_ftype(@nospecialize(t), mt::Union{Core.MethodTable, Nothing}, lim::Int, world::UInt, ambig::Bool, min::Array{UInt,1}, max::Array{UInt,1}, has_ambig::Array{Int32,1})
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{Array{Any,1}, Bool}
end
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})
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{Array{Any,1}, Bool}
end
function _method_by_ftype(args...)
matches = _methods_by_ftype(args...)
if length(matches) != 1
error("no unique matching method found for the specified argument types")
end
return matches[1]
end
# high-level, more convenient method lookup functions
# type for reflecting and pretty-printing a subset of methods
mutable struct MethodList <: AbstractArray{Method,1}
ms::Array{Method,1}
mt::Core.MethodTable
end
size(m::MethodList) = size(m.ms)
getindex(m::MethodList, i::Integer) = m.ms[i]
function MethodList(mt::Core.MethodTable)
ms = Method[]
visit(mt) do m
push!(ms, m)
end
return MethodList(ms, mt)
end
"""
methods(f, [types], [module])
Return the method table for `f`.
If `types` is specified, return an array of methods whose types match.
If `module` is specified, return an array of methods defined in that module.
A list of modules can also be specified as an array.
!!! compat "Julia 1.4"
At least Julia 1.4 is required for specifying a module.
See also: [`which`](@ref) and `@which`.
"""
function methods(@nospecialize(f), @nospecialize(t),
mod::Union{Tuple{Module},AbstractArray{Module},Nothing}=nothing)
if isa(f, Core.Builtin)
throw(ArgumentError("argument is not a generic function"))
end
t = to_tuple_type(t)
world = typemax(UInt)
# Lack of specialization => a comprehension triggers too many invalidations via _collect, so collect the methods manually
ms = Method[]
for m in _methods(f, t, -1, world)::Vector
m = m::Core.MethodMatch
(mod === nothing || m.method.module ∈ mod) && push!(ms, m.method)
end
MethodList(ms, typeof(f).name.mt)
end
methods(@nospecialize(f), @nospecialize(t), mod::Module) = methods(f, t, (mod,))
methods(f::Core.Builtin) = MethodList(Method[], typeof(f).name.mt)
function methods_including_ambiguous(@nospecialize(f), @nospecialize(t))
tt = signature_type(f, t)
world = typemax(UInt)
min = RefValue{UInt}(typemin(UInt))
max = RefValue{UInt}(typemax(UInt))
ms = _methods_by_ftype(tt, nothing, -1, world, true, min, max, Ptr{Int32}(C_NULL))
isa(ms, Bool) && return ms
return MethodList(Method[(m::Core.MethodMatch).method for m in ms], typeof(f).name.mt)
end
function methods(@nospecialize(f),
mod::Union{Module,AbstractArray{Module},Nothing}=nothing)
# return all matches
return methods(f, Tuple{Vararg{Any}}, mod)
end
function visit(f, mt::Core.MethodTable)
mt.defs !== nothing && visit(f, mt.defs)
nothing
end
function visit(f, mc::Core.TypeMapLevel)
if mc.targ !== nothing
e = mc.targ::Vector{Any}
for i in 2:2:length(e)
isassigned(e, i) && visit(f, e[i])
end
end
if mc.arg1 !== nothing
e = mc.arg1::Vector{Any}
for i in 2:2:length(e)