-
-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
reflection.jl
2267 lines (1921 loc) · 73.1 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
"""
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!(unsorted_names(m; all, imported))
unsorted_names(m::Module; all::Bool = false, imported::Bool = false) =
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
const _NAMEDTUPLE_NAME = NamedTuple.body.body.name
function _fieldnames(@nospecialize t)
if t.name === _NAMEDTUPLE_NAME
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.
See also [`fieldnames`](@ref), [`fieldcount`](@ref), [`hasproperty`](@ref).
!!! compat "Julia 1.2"
This function requires at least Julia 1.2.
# Examples
```jldoctest
julia> struct Foo
bar::Int
end
julia> hasfield(Foo, :bar)
true
julia> hasfield(Foo, :x)
false
```
"""
hasfield(T::Type, name::Symbol) = fieldindex(T, name, false) > 0
"""
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 `m`.
"""
isconst(m::Module, s::Symbol) =
ccall(:jl_is_const, Cint, (Any, Any), m, s) != 0
function isconst(g::GlobalRef)
return ccall(:jl_globalref_is_const, Cint, (Any,), g) != 0
end
"""
isconst(t::DataType, s::Union{Int,Symbol}) -> Bool
Determine whether a field `s` is declared `const` in a given type `t`.
"""
function isconst(@nospecialize(t::Type), s::Symbol)
t = unwrap_unionall(t)
isa(t, DataType) || return false
return isconst(t, fieldindex(t, s, false))
end
function isconst(@nospecialize(t::Type), s::Int)
t = unwrap_unionall(t)
# TODO: what to do for `Union`?
isa(t, DataType) || return false # uncertain
ismutabletype(t) || return true # immutable structs are always const
1 <= s <= length(t.name.names) || return true # OOB reads are "const" since they always throw
constfields = t.name.constfields
constfields === C_NULL && return false
s -= 1
return unsafe_load(Ptr{UInt32}(constfields), 1 + s÷32) & (1 << (s%32)) != 0
end
"""
isfieldatomic(t::DataType, s::Union{Int,Symbol}) -> Bool
Determine whether a field `s` is declared `@atomic` in a given type `t`.
"""
function isfieldatomic(@nospecialize(t::Type), s::Symbol)
t = unwrap_unionall(t)
isa(t, DataType) || return false
return isfieldatomic(t, fieldindex(t, s, false))
end
function isfieldatomic(@nospecialize(t::Type), s::Int)
t = unwrap_unionall(t)
# TODO: what to do for `Union`?
isa(t, DataType) || return false # uncertain
ismutabletype(t) || return false # immutable structs are never atomic
1 <= s <= length(t.name.names) || return false # OOB reads are not atomic (they always throw)
atomicfields = t.name.atomicfields
atomicfields === C_NULL && return false
s -= 1
return unsafe_load(Ptr{UInt32}(atomicfields), 1 + s÷32) & (1 << (s%32)) != 0
end
"""
@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
# concrete datatype predicates
datatype_fieldtypes(x::DataType) = ccall(:jl_get_fieldtypes, Core.SimpleVector, (Any,), x)
struct DataTypeLayout
size::UInt32
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)
@_foldable_meta
dt.layout == C_NULL && throw(UndefRefError())
alignment = unsafe_load(convert(Ptr{DataTypeLayout}, dt.layout)).alignment
return Int(alignment)
end
function uniontype_layout(@nospecialize 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, Int(sz[]), Int(algn[]))
end
LLT_ALIGN(x, sz) = (x + sz - 1) & -sz
# amount of total space taken by T when stored in a container
function aligned_sizeof(@nospecialize T::Type)
@_foldable_meta
if isa(T, Union)
if allocatedinline(T)
# NOTE this check is equivalent to `isbitsunion(T)`, we can improve type
# inference in the second branch with the outer `isa(T, Union)` check
_, sz, al = uniontype_layout(T)
return LLT_ALIGN(sz, al)
end
elseif allocatedinline(T)
al = datatype_alignment(T)
return LLT_ALIGN(Core.sizeof(T), al)
end
return Core.sizeof(Ptr{Cvoid})
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)
@_foldable_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)
@_foldable_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)
@_foldable_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)
@_foldable_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 `DataType`, it will tell you that a value of the type is mutable.
!!! note
For technical reasons, `ismutable` returns `true` for values of certain special types
(for example `String` and `Symbol`) even though they cannot be mutated in a permissible way.
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)) = (@_total_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).
If `T` is not a type, then return `false`.
!!! compat "Julia 1.7"
This function requires at least Julia 1.7.
"""
function ismutabletype(@nospecialize t)
@_total_meta
t = unwrap_unionall(t)
# TODO: what to do for `Union`?
return isa(t, DataType) && ismutabletypename(t.name)
end
ismutabletypename(tn::Core.TypeName) = tn.flags & 0x2 == 0x2
"""
isstructtype(T) -> Bool
Determine whether type `T` was declared as a struct type
(i.e. using the `struct` or `mutable struct` keyword).
If `T` is not a type, then return `false`.
"""
function isstructtype(@nospecialize t)
@_total_meta
t = unwrap_unionall(t)
# TODO: what to do for `Union`?
isa(t, DataType) || return false
return !isprimitivetype(t) && !isabstracttype(t)
end
"""
isprimitivetype(T) -> Bool
Determine whether type `T` was declared as a primitive type
(i.e. using the `primitive type` syntax).
If `T` is not a type, then return `false`.
"""
function isprimitivetype(@nospecialize t)
@_total_meta
t = unwrap_unionall(t)
# TODO: what to do for `Union`?
isa(t, DataType) || return false
return (t.flags & 0x0080) == 0x0080
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.
If `T` is not a type, then return `false`.
See also [`isbits`](@ref), [`isprimitivetype`](@ref), [`ismutable`](@ref).
# Examples
```jldoctest
julia> isbitstype(Complex{Float64})
true
julia> isbitstype(Complex)
false
```
"""
isbitstype(@nospecialize t) = (@_total_meta; isa(t, DataType) && (t.flags & 0x0008) == 0x0008)
"""
isbits(x)
Return `true` if `x` is an instance of an [`isbitstype`](@ref) type.
"""
isbits(@nospecialize x) = isbitstype(typeof(x))
"""
objectid(x) -> UInt
Get a hash value for `x` based on object identity.
If `x === y` then `objectid(x) == objectid(y)`, and usually when `x !== y`, `objectid(x) != objectid(y)`.
See also [`hash`](@ref), [`IdDict`](@ref).
"""
function objectid(x)
# objectid is foldable iff it isn't a pointer.
if isidentityfree(typeof(x))
return _foldable_objectid(x)
end
return _objectid(x)
end
function _foldable_objectid(@nospecialize(x))
@_foldable_meta
_objectid(x)
end
_objectid(@nospecialize(x)) = ccall(:jl_object_id, UInt, (Any,), x)
"""
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.
If `T` is not a type, then return `false`.
"""
isdispatchtuple(@nospecialize(t)) = (@_total_meta; isa(t, DataType) && (t.flags & 0x0004) == 0x0004)
datatype_ismutationfree(dt::DataType) = (@_total_meta; (dt.flags & 0x0100) == 0x0100)
"""
Base.ismutationfree(T)
Determine whether type `T` is mutation free in the sense that no mutable memory
is reachable from this type (either in the type itself) or through any fields.
Note that the type itself need not be immutable. For example, an empty mutable
type is `ismutabletype`, but also `ismutationfree`.
If `T` is not a type, then return `false`.
"""
function ismutationfree(@nospecialize(t))
t = unwrap_unionall(t)
if isa(t, DataType)
return datatype_ismutationfree(t)
elseif isa(t, Union)
return ismutationfree(t.a) && ismutationfree(t.b)
end
# TypeVar, etc.
return false
end
datatype_isidentityfree(dt::DataType) = (@_total_meta; (dt.flags & 0x0200) == 0x0200)
"""
Base.isidentityfree(T)
Determine whether type `T` is identity free in the sense that this type or any
reachable through its fields has non-content-based identity.
If `T` is not a type, then return `false`.
"""
function isidentityfree(@nospecialize(t))
t = unwrap_unionall(t)
if isa(t, DataType)
return datatype_isidentityfree(t)
elseif isa(t, Union)
return isidentityfree(t.a) && isidentityfree(t.b)
end
# TypeVar, etc.
return false
end
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
function isdispatchelem(@nospecialize v)
return (v === Bottom) || (v === typeof(Bottom)) || isconcretedispatch(v) ||
(isType(v) && !has_free_typevars(v))
end
const _TYPE_NAME = Type.body.name
isType(@nospecialize t) = isa(t, DataType) && t.name === _TYPE_NAME
"""
isconcretetype(T)
Determine whether type `T` is a concrete type, meaning it could have direct instances
(values `x` such that `typeof(x) === T`).
Note that this is not the negation of `isabstracttype(T)`.
If `T` is not a type, then return `false`.
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)) = (@_total_meta; isa(t, DataType) && (t.flags & 0x0002) == 0x0002)
"""
isabstracttype(T)
Determine whether type `T` was declared as an abstract type
(i.e. using the `abstract type` syntax).
Note that this is not the negation of `isconcretetype(T)`.
If `T` is not a type, then return `false`.
# Examples
```jldoctest
julia> isabstracttype(AbstractArray)
true
julia> isabstracttype(Vector)
false
```
"""
function isabstracttype(@nospecialize(t))
@_total_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.
If `T` is not a type, then return `false`.
"""
issingletontype(@nospecialize(t)) = (@_total_meta; isa(t, DataType) && isdefined(t, :instance))
"""
typeintersect(T::Type, S::Type)
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)) = (@_total_meta; ccall(:jl_type_intersection, Any, (Any, Any), a::Type, b::Type))
morespecific(@nospecialize(a), @nospecialize(b)) = (@_total_meta; ccall(:jl_type_morespecific, Cint, (Any, Any), a::Type, b::Type) != 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) = (@_foldable_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 err ? _fieldindex_maythrow(T, name) : _fieldindex_nothrow(T, name)
end
function _fieldindex_maythrow(T::DataType, name::Symbol)
@_foldable_meta
@noinline
return Int(ccall(:jl_field_index, Cint, (Any, Any, Cint), T, name, true)+1)
end
function _fieldindex_nothrow(T::DataType, name::Symbol)
@_total_meta
@noinline
return Int(ccall(:jl_field_index, Cint, (Any, Any, Cint), T, name, false)+1)
end
function fieldindex(t::UnionAll, name::Symbol, err::Bool=true)
t = argument_datatype(t)
if t === nothing
err && throw(ArgumentError("type does not have definite fields"))
return 0
end
return fieldindex(t, name, err)
end
function argument_datatype(@nospecialize t)
@_total_meta
@noinline
return ccall(:jl_argument_datatype, Any, (Any,), t)::Union{Nothing,DataType}
end
function datatype_fieldcount(t::DataType)
if t.name === _NAMEDTUPLE_NAME
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
return nothing
elseif isabstracttype(t) || (t.name === Tuple.name && isvatuple(t))
return nothing
end
if isdefined(t, :types)
return length(t.types)
end
return length(t.name.names)
end
"""
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)
@_foldable_meta
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
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
fcount = datatype_fieldcount(t)
if fcount === nothing
throw(ArgumentError("type does not have a definite number of fields"))
end
return fcount
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) = (@_foldable_meta; 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)::DataType).parameters
if isa(p, Core.TypeofVararg)
p = unwrapva(p)
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(argtypes))
argtypes = to_tuple_type(argtypes)
ft = Core.Typeof(f)
u = unwrap_unionall(argtypes)::DataType
return rewrap_unionall(Tuple{ft, u.parameters...}, argtypes)
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"))