"Fossies" - the Fresh Open Source Software Archive

Member "julia-1.1.1/share/julia/base/reflection.jl" (16 May 2019, 34488 Bytes) of package /linux/misc/julia-1.1.1-linux-i686.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) Julia source code syntax highlighting (style: standard) with prefixed line numbers. Alternatively you can here view or download the uninterpreted source code file.

    1 # This file is a part of Julia. License is MIT: https://julialang.org/license
    2 
    3 # name and module reflection
    4 
    5 """
    6     nameof(m::Module) -> Symbol
    7 
    8 Get the name of a `Module` as a `Symbol`.
    9 
   10 # Examples
   11 ```jldoctest
   12 julia> nameof(Base.Broadcast)
   13 :Broadcast
   14 ```
   15 """
   16 nameof(m::Module) = ccall(:jl_module_name, Ref{Symbol}, (Any,), m)
   17 
   18 """
   19     parentmodule(m::Module) -> Module
   20 
   21 Get a module's enclosing `Module`. `Main` is its own parent.
   22 
   23 # Examples
   24 ```jldoctest
   25 julia> parentmodule(Main)
   26 Main
   27 
   28 julia> parentmodule(Base.Broadcast)
   29 Base
   30 ```
   31 """
   32 parentmodule(m::Module) = ccall(:jl_module_parent, Ref{Module}, (Any,), m)
   33 
   34 """
   35     moduleroot(m::Module) -> Module
   36 
   37 Find the root module of a given module. This is the first module in the chain of
   38 parent modules of `m` which is either a registered root module or which is its
   39 own parent module.
   40 """
   41 function moduleroot(m::Module)
   42     while true
   43         is_root_module(m) && return m
   44         p = parentmodule(m)
   45         p == m && return m
   46         m = p
   47     end
   48 end
   49 
   50 """
   51     @__MODULE__ -> Module
   52 
   53 Get the `Module` of the toplevel eval,
   54 which is the `Module` code is currently being read from.
   55 """
   56 macro __MODULE__()
   57     return __module__
   58 end
   59 
   60 """
   61     fullname(m::Module)
   62 
   63 Get the fully-qualified name of a module as a tuple of symbols. For example,
   64 
   65 # Examples
   66 ```jldoctest
   67 julia> fullname(Base.Iterators)
   68 (:Base, :Iterators)
   69 
   70 julia> fullname(Main)
   71 (:Main,)
   72 ```
   73 """
   74 function fullname(m::Module)
   75     mn = nameof(m)
   76     if m === Main || m === Base || m === Core
   77         return (mn,)
   78     end
   79     mp = parentmodule(m)
   80     if mp === m
   81         return (mn,)
   82     end
   83     return (fullname(mp)..., mn)
   84 end
   85 
   86 """
   87     names(x::Module; all::Bool = false, imported::Bool = false)
   88 
   89 Get an array of the names exported by a `Module`, excluding deprecated names.
   90 If `all` is true, then the list also includes non-exported names defined in the module,
   91 deprecated names, and compiler-generated names.
   92 If `imported` is true, then names explicitly imported from other modules
   93 are also included.
   94 
   95 As a special case, all names defined in `Main` are considered \"exported\",
   96 since it is not idiomatic to explicitly export names from `Main`.
   97 """
   98 names(m::Module; all::Bool = false, imported::Bool = false) =
   99     sort!(ccall(:jl_module_names, Array{Symbol,1}, (Any, Cint, Cint), m, all, imported))
  100 
  101 isexported(m::Module, s::Symbol) = ccall(:jl_module_exports_p, Cint, (Any, Any), m, s) != 0
  102 isdeprecated(m::Module, s::Symbol) = ccall(:jl_is_binding_deprecated, Cint, (Any, Any), m, s) != 0
  103 isbindingresolved(m::Module, var::Symbol) = ccall(:jl_binding_resolved_p, Cint, (Any, Any), m, var) != 0
  104 
  105 function binding_module(m::Module, s::Symbol)
  106     p = ccall(:jl_get_module_of_binding, Ptr{Cvoid}, (Any, Any), m, s)
  107     p == C_NULL && return m
  108     return unsafe_pointer_to_objref(p)::Module
  109 end
  110 
  111 function resolve(g::GlobalRef; force::Bool=false)
  112     if force || isbindingresolved(g.mod, g.name)
  113         return GlobalRef(binding_module(g.mod, g.name), g.name)
  114     end
  115     return g
  116 end
  117 
  118 const NamedTuple_typename = NamedTuple.body.body.name
  119 
  120 function _fieldnames(@nospecialize t)
  121     if t.name === NamedTuple_typename
  122         if t.parameters[1] isa Tuple
  123             return t.parameters[1]
  124         else
  125             throw(ArgumentError("type does not have definite field names"))
  126         end
  127     end
  128     isdefined(t, :names) ? t.names : t.name.names
  129 end
  130 
  131 """
  132     fieldname(x::DataType, i::Integer)
  133 
  134 Get the name of field `i` of a `DataType`.
  135 
  136 # Examples
  137 ```jldoctest
  138 julia> fieldname(Rational, 1)
  139 :num
  140 
  141 julia> fieldname(Rational, 2)
  142 :den
  143 ```
  144 """
  145 function fieldname(t::DataType, i::Integer)
  146     if t.abstract
  147         throw(ArgumentError("type does not have definite field names"))
  148     end
  149     names = _fieldnames(t)
  150     n_fields = length(names)
  151     field_label = n_fields == 1 ? "field" : "fields"
  152     i > n_fields && throw(ArgumentError("Cannot access field $i since type $t only has $n_fields $field_label."))
  153     i < 1 && throw(ArgumentError("Field numbers must be positive integers. $i is invalid."))
  154     return names[i]::Symbol
  155 end
  156 
  157 fieldname(t::UnionAll, i::Integer) = fieldname(unwrap_unionall(t), i)
  158 fieldname(t::Type{<:Tuple}, i::Integer) =
  159     i < 1 || i > fieldcount(t) ? throw(BoundsError(t, i)) : Int(i)
  160 
  161 """
  162     fieldnames(x::DataType)
  163 
  164 Get a tuple with the names of the fields of a `DataType`.
  165 
  166 # Examples
  167 ```jldoctest
  168 julia> fieldnames(Rational)
  169 (:num, :den)
  170 ```
  171 """
  172 fieldnames(t::DataType) = (fieldcount(t); # error check to make sure type is specific enough
  173                            (_fieldnames(t)...,))
  174 fieldnames(t::UnionAll) = fieldnames(unwrap_unionall(t))
  175 fieldnames(::Core.TypeofBottom) =
  176     throw(ArgumentError("The empty type does not have field names since it does not have instances."))
  177 fieldnames(t::Type{<:Tuple}) = ntuple(identity, fieldcount(t))
  178 
  179 """
  180     nameof(t::DataType) -> Symbol
  181 
  182 Get the name of a (potentially `UnionAll`-wrapped) `DataType` (without its parent module)
  183 as a symbol.
  184 
  185 # Examples
  186 ```jldoctest
  187 julia> module Foo
  188            struct S{T}
  189            end
  190        end
  191 Foo
  192 
  193 julia> nameof(Foo.S{T} where T)
  194 :S
  195 ```
  196 """
  197 nameof(t::DataType) = t.name.name
  198 nameof(t::UnionAll) = nameof(unwrap_unionall(t))
  199 
  200 """
  201     parentmodule(t::DataType) -> Module
  202 
  203 Determine the module containing the definition of a (potentially `UnionAll`-wrapped) `DataType`.
  204 
  205 # Examples
  206 ```jldoctest
  207 julia> module Foo
  208            struct Int end
  209        end
  210 Foo
  211 
  212 julia> parentmodule(Int)
  213 Core
  214 
  215 julia> parentmodule(Foo.Int)
  216 Foo
  217 ```
  218 """
  219 parentmodule(t::DataType) = t.name.module
  220 parentmodule(t::UnionAll) = parentmodule(unwrap_unionall(t))
  221 
  222 """
  223     isconst(m::Module, s::Symbol) -> Bool
  224 
  225 Determine whether a global is declared `const` in a given `Module`.
  226 """
  227 isconst(m::Module, s::Symbol) =
  228     ccall(:jl_is_const, Cint, (Any, Any), m, s) != 0
  229 
  230 """
  231     @isdefined s -> Bool
  232 
  233 Tests whether variable `s` is defined in the current scope.
  234 
  235 # Examples
  236 ```jldoctest
  237 julia> function f()
  238            println(@isdefined x)
  239            x = 3
  240            println(@isdefined x)
  241        end
  242 f (generic function with 1 method)
  243 
  244 julia> f()
  245 false
  246 true
  247 ```
  248 """
  249 macro isdefined(s::Symbol)
  250     return Expr(:isdefined, esc(s))
  251 end
  252 
  253 """
  254     @locals()
  255 
  256 Construct a dictionary of the names (as symbols) and values of all local
  257 variables defined as of the call site.
  258 
  259 !!! compat "Julia 1.1"
  260     This macro requires at least Julia 1.1.
  261 
  262 # Examples
  263 ```jldoctest
  264 julia> let x = 1, y = 2
  265            Base.@locals
  266        end
  267 Dict{Symbol,Any} with 2 entries:
  268   :y => 2
  269   :x => 1
  270 
  271 julia> function f(x)
  272            local y
  273            show(Base.@locals); println()
  274            for i = 1:1
  275                show(Base.@locals); println()
  276            end
  277            y = 2
  278            show(Base.@locals); println()
  279            nothing
  280        end;
  281 
  282 julia> f(42)
  283 Dict{Symbol,Any}(:x=>42)
  284 Dict{Symbol,Any}(:i=>1,:x=>42)
  285 Dict{Symbol,Any}(:y=>2,:x=>42)
  286 ```
  287 """
  288 macro locals()
  289     return Expr(:locals)
  290 end
  291 
  292 """
  293     objectid(x)
  294 
  295 Get a hash value for `x` based on object identity. `objectid(x)==objectid(y)` if `x === y`.
  296 """
  297 objectid(@nospecialize(x)) = ccall(:jl_object_id, UInt, (Any,), x)
  298 
  299 # concrete datatype predicates
  300 
  301 struct DataTypeLayout
  302     nfields::UInt32
  303     alignment::UInt32
  304     # alignment : 28;
  305     # haspadding : 1;
  306     # pointerfree : 1;
  307     # fielddesc_type : 2;
  308 end
  309 
  310 """
  311     Base.datatype_alignment(dt::DataType) -> Int
  312 
  313 Memory allocation minimum alignment for instances of this type.
  314 Can be called on any `isconcretetype`.
  315 """
  316 function datatype_alignment(dt::DataType)
  317     @_pure_meta
  318     dt.layout == C_NULL && throw(UndefRefError())
  319     alignment = unsafe_load(convert(Ptr{DataTypeLayout}, dt.layout)).alignment
  320     return Int(alignment & 0x1FF)
  321 end
  322 
  323 """
  324     Base.datatype_haspadding(dt::DataType) -> Bool
  325 
  326 Return whether the fields of instances of this type are packed in memory,
  327 with no intervening padding bytes.
  328 Can be called on any `isconcretetype`.
  329 """
  330 function datatype_haspadding(dt::DataType)
  331     @_pure_meta
  332     dt.layout == C_NULL && throw(UndefRefError())
  333     alignment = unsafe_load(convert(Ptr{DataTypeLayout}, dt.layout)).alignment
  334     return (alignment >> 9) & 1 == 1
  335 end
  336 
  337 """
  338     Base.datatype_pointerfree(dt::DataType) -> Bool
  339 
  340 Return whether instances of this type can contain references to gc-managed memory.
  341 Can be called on any `isconcretetype`.
  342 """
  343 function datatype_pointerfree(dt::DataType)
  344     @_pure_meta
  345     dt.layout == C_NULL && throw(UndefRefError())
  346     alignment = unsafe_load(convert(Ptr{DataTypeLayout}, dt.layout)).alignment
  347     return (alignment >> 10) & 0xFFFFF == 0
  348 end
  349 
  350 """
  351     Base.datatype_fielddesc_type(dt::DataType) -> Int
  352 
  353 Return the size in bytes of each field-description entry in the layout array,
  354 located at `(dt.layout + sizeof(DataTypeLayout))`.
  355 Can be called on any `isconcretetype`.
  356 
  357 See also [`Base.fieldoffset`](@ref).
  358 """
  359 function datatype_fielddesc_type(dt::DataType)
  360     @_pure_meta
  361     dt.layout == C_NULL && throw(UndefRefError())
  362     alignment = unsafe_load(convert(Ptr{DataTypeLayout}, dt.layout)).alignment
  363     return (alignment >> 30) & 3
  364 end
  365 
  366 """
  367     isimmutable(v) -> Bool
  368 
  369 Return `true` iff value `v` is immutable.  See [Mutable Composite Types](@ref)
  370 for a discussion of immutability. Note that this function works on values, so if you give it
  371 a type, it will tell you that a value of `DataType` is mutable.
  372 
  373 # Examples
  374 ```jldoctest
  375 julia> isimmutable(1)
  376 true
  377 
  378 julia> isimmutable([1,2])
  379 false
  380 ```
  381 """
  382 isimmutable(@nospecialize(x)) = (@_pure_meta; !typeof(x).mutable)
  383 
  384 """
  385     Base.isstructtype(T) -> Bool
  386 
  387 Determine whether type `T` was declared as a struct type
  388 (i.e. using the `struct` or `mutable struct` keyword).
  389 """
  390 function isstructtype(@nospecialize(t::Type))
  391     @_pure_meta
  392     t = unwrap_unionall(t)
  393     # TODO: what to do for `Union`?
  394     isa(t, DataType) || return false
  395     return length(t.types) != 0 || (t.size == 0 && !t.abstract)
  396 end
  397 
  398 """
  399     Base.isprimitivetype(T) -> Bool
  400 
  401 Determine whether type `T` was declared as a primitive type
  402 (i.e. using the `primitive` keyword).
  403 """
  404 function isprimitivetype(@nospecialize(t::Type))
  405     @_pure_meta
  406     t = unwrap_unionall(t)
  407     # TODO: what to do for `Union`?
  408     isa(t, DataType) || return false
  409     return length(t.types) == 0 && t.size != 0 && !t.abstract
  410 end
  411 
  412 """
  413     isbitstype(T)
  414 
  415 Return `true` if type `T` is a "plain data" type,
  416 meaning it is immutable and contains no references to other values,
  417 only `primitive` types and other `isbitstype` types.
  418 Typical examples are numeric types such as [`UInt8`](@ref),
  419 [`Float64`](@ref), and [`Complex{Float64}`](@ref).
  420 This category of types is significant since they are valid as type parameters,
  421 may not track [`isdefined`](@ref) / [`isassigned`](@ref) status,
  422 and have a defined layout that is compatible with C.
  423 
  424 # Examples
  425 ```jldoctest
  426 julia> isbitstype(Complex{Float64})
  427 true
  428 
  429 julia> isbitstype(Complex)
  430 false
  431 ```
  432 """
  433 isbitstype(@nospecialize(t::Type)) = (@_pure_meta; isa(t, DataType) && t.isbitstype)
  434 
  435 """
  436     isbits(x)
  437 
  438 Return `true` if `x` is an instance of an `isbitstype` type.
  439 """
  440 isbits(@nospecialize x) = (@_pure_meta; typeof(x).isbitstype)
  441 
  442 """
  443     isdispatchtuple(T)
  444 
  445 Determine whether type `T` is a tuple "leaf type",
  446 meaning it could appear as a type signature in dispatch
  447 and has no subtypes (or supertypes) which could appear in a call.
  448 """
  449 isdispatchtuple(@nospecialize(t)) = (@_pure_meta; isa(t, DataType) && t.isdispatchtuple)
  450 
  451 iskindtype(@nospecialize t) = (t === DataType || t === UnionAll || t === Union || t === typeof(Bottom))
  452 isconcretedispatch(@nospecialize t) = isconcretetype(t) && !iskindtype(t)
  453 has_free_typevars(@nospecialize(t)) = ccall(:jl_has_free_typevars, Cint, (Any,), t) != 0
  454 
  455 # equivalent to isa(v, Type) && isdispatchtuple(Tuple{v}) || v === Union{}
  456 # and is thus perhaps most similar to the old (pre-1.0) `isleaftype` query
  457 const _TYPE_NAME = Type.body.name
  458 function isdispatchelem(@nospecialize v)
  459     return (v === Bottom) || (v === typeof(Bottom)) || isconcretedispatch(v) ||
  460         (isa(v, DataType) && v.name === _TYPE_NAME && !has_free_typevars(v)) # isType(v)
  461 end
  462 
  463 """
  464     isconcretetype(T)
  465 
  466 Determine whether type `T` is a concrete type, meaning it could have direct instances
  467 (values `x` such that `typeof(x) === T`).
  468 
  469 # Examples
  470 ```jldoctest
  471 julia> isconcretetype(Complex)
  472 false
  473 
  474 julia> isconcretetype(Complex{Float32})
  475 true
  476 
  477 julia> isconcretetype(Vector{Complex})
  478 true
  479 
  480 julia> isconcretetype(Vector{Complex{Float32}})
  481 true
  482 
  483 julia> isconcretetype(Union{})
  484 false
  485 
  486 julia> isconcretetype(Union{Int,String})
  487 false
  488 ```
  489 """
  490 isconcretetype(@nospecialize(t)) = (@_pure_meta; isa(t, DataType) && t.isconcretetype)
  491 
  492 """
  493     Base.isabstracttype(T)
  494 
  495 Determine whether type `T` was declared as an abstract type
  496 (i.e. using the `abstract` keyword).
  497 
  498 # Examples
  499 ```jldoctest
  500 julia> Base.isabstracttype(AbstractArray)
  501 true
  502 
  503 julia> Base.isabstracttype(Vector)
  504 false
  505 ```
  506 """
  507 function isabstracttype(@nospecialize(t))
  508     @_pure_meta
  509     t = unwrap_unionall(t)
  510     # TODO: what to do for `Union`?
  511     return isa(t, DataType) && t.abstract
  512 end
  513 
  514 """
  515     Base.parameter_upper_bound(t::UnionAll, idx)
  516 
  517 Determine the upper bound of a type parameter in the underlying datatype.
  518 This method should generally not be relied upon:
  519 code instead should usually use static parameters in dispatch to extract these values.
  520 
  521 # Examples
  522 ```jldoctest
  523 julia> struct Foo{T<:AbstractFloat, N}
  524            x::Tuple{T, N}
  525        end
  526 
  527 julia> Base.parameter_upper_bound(Foo, 1)
  528 AbstractFloat
  529 
  530 julia> Base.parameter_upper_bound(Foo, 2)
  531 Any
  532 ```
  533 """
  534 function parameter_upper_bound(t::UnionAll, idx)
  535     @_pure_meta
  536     return rewrap_unionall((unwrap_unionall(t)::DataType).parameters[idx], t)
  537 end
  538 
  539 """
  540     typeintersect(T, S)
  541 
  542 Compute a type that contains the intersection of `T` and `S`. Usually this will be the
  543 smallest such type or one close to it.
  544 """
  545 typeintersect(@nospecialize(a),@nospecialize(b)) = (@_pure_meta; ccall(:jl_type_intersection, Any, (Any,Any), a, b))
  546 
  547 """
  548     fieldoffset(type, i)
  549 
  550 The byte offset of field `i` of a type relative to the data start. For example, we could
  551 use it in the following manner to summarize information about a struct:
  552 
  553 ```jldoctest
  554 julia> structinfo(T) = [(fieldoffset(T,i), fieldname(T,i), fieldtype(T,i)) for i = 1:fieldcount(T)];
  555 
  556 julia> structinfo(Base.Filesystem.StatStruct)
  557 12-element Array{Tuple{UInt64,Symbol,DataType},1}:
  558  (0x0000000000000000, :device, UInt64)
  559  (0x0000000000000008, :inode, UInt64)
  560  (0x0000000000000010, :mode, UInt64)
  561  (0x0000000000000018, :nlink, Int64)
  562  (0x0000000000000020, :uid, UInt64)
  563  (0x0000000000000028, :gid, UInt64)
  564  (0x0000000000000030, :rdev, UInt64)
  565  (0x0000000000000038, :size, Int64)
  566  (0x0000000000000040, :blksize, Int64)
  567  (0x0000000000000048, :blocks, Int64)
  568  (0x0000000000000050, :mtime, Float64)
  569  (0x0000000000000058, :ctime, Float64)
  570 ```
  571 """
  572 fieldoffset(x::DataType, idx::Integer) = (@_pure_meta; ccall(:jl_get_field_offset, Csize_t, (Any, Cint), x, idx))
  573 
  574 """
  575     fieldtype(T, name::Symbol | index::Int)
  576 
  577 Determine the declared type of a field (specified by name or index) in a composite DataType `T`.
  578 
  579 # Examples
  580 ```jldoctest
  581 julia> struct Foo
  582            x::Int64
  583            y::String
  584        end
  585 
  586 julia> fieldtype(Foo, :x)
  587 Int64
  588 
  589 julia> fieldtype(Foo, 2)
  590 String
  591 ```
  592 """
  593 fieldtype
  594 
  595 """
  596     fieldindex(T, name::Symbol, err:Bool=true)
  597 
  598 Get the index of a named field, throwing an error if the field does not exist (when err==true)
  599 or returning 0 (when err==false).
  600 
  601 # Examples
  602 ```jldoctest
  603 julia> struct Foo
  604            x::Int64
  605            y::String
  606        end
  607 
  608 julia> Base.fieldindex(Foo, :z)
  609 ERROR: type Foo has no field z
  610 Stacktrace:
  611 [...]
  612 
  613 julia> Base.fieldindex(Foo, :z, false)
  614 0
  615 ```
  616 """
  617 function fieldindex(T::DataType, name::Symbol, err::Bool=true)
  618     return Int(ccall(:jl_field_index, Cint, (Any, Any, Cint), T, name, err)+1)
  619 end
  620 
  621 argument_datatype(@nospecialize t) = ccall(:jl_argument_datatype, Any, (Any,), t)
  622 function argument_mt(@nospecialize t)
  623     dt = argument_datatype(t)
  624     (dt === nothing || !isdefined(dt.name, :mt)) && return nothing
  625     dt.name.mt
  626 end
  627 
  628 """
  629     fieldcount(t::Type)
  630 
  631 Get the number of fields that an instance of the given type would have.
  632 An error is thrown if the type is too abstract to determine this.
  633 """
  634 function fieldcount(@nospecialize t)
  635     if t isa UnionAll || t isa Union
  636         t = argument_datatype(t)
  637         if t === nothing
  638             throw(ArgumentError("type does not have a definite number of fields"))
  639         end
  640         t = t::DataType
  641     elseif t == Union{}
  642         throw(ArgumentError("The empty type does not have a well-defined number of fields since it does not have instances."))
  643     end
  644     if !(t isa DataType)
  645         throw(TypeError(:fieldcount, DataType, t))
  646     end
  647     if t.name === NamedTuple_typename
  648         names, types = t.parameters
  649         if names isa Tuple
  650             return length(names)
  651         end
  652         if types isa DataType && types <: Tuple
  653             return fieldcount(types)
  654         end
  655         abstr = true
  656     else
  657         abstr = t.abstract || (t.name === Tuple.name && isvatuple(t))
  658     end
  659     if abstr
  660         throw(ArgumentError("type does not have a definite number of fields"))
  661     end
  662     return length(t.types)
  663 end
  664 
  665 """
  666     fieldtypes(T::Type)
  667 
  668 The declared types of all fields in a composite DataType `T` as a tuple.
  669 
  670 !!! compat "Julia 1.1"
  671     This function requires at least Julia 1.1.
  672 
  673 # Examples
  674 ```jldoctest
  675 julia> struct Foo
  676            x::Int64
  677            y::String
  678        end
  679 
  680 julia> fieldtypes(Foo)
  681 (Int64, String)
  682 ```
  683 """
  684 fieldtypes(T::Type) = ntuple(i -> fieldtype(T, i), fieldcount(T))
  685 
  686 # return all instances, for types that can be enumerated
  687 
  688 """
  689     instances(T::Type)
  690 
  691 Return a collection of all instances of the given type, if applicable. Mostly used for
  692 enumerated types (see `@enum`).
  693 
  694 # Example
  695 ```jldoctest
  696 julia> @enum Color red blue green
  697 
  698 julia> instances(Color)
  699 (red::Color = 0, blue::Color = 1, green::Color = 2)
  700 ```
  701 """
  702 function instances end
  703 
  704 function to_tuple_type(@nospecialize(t))
  705     @_pure_meta
  706     if isa(t,Tuple) || isa(t,AbstractArray) || isa(t,SimpleVector)
  707         t = Tuple{t...}
  708     end
  709     if isa(t,Type) && t<:Tuple
  710         for p in unwrap_unionall(t).parameters
  711             if !(isa(p,Type) || isa(p,TypeVar))
  712                 error("argument tuple type must contain only types")
  713             end
  714         end
  715     else
  716         error("expected tuple type")
  717     end
  718     t
  719 end
  720 
  721 function signature_type(@nospecialize(f), @nospecialize(args))
  722     f_type = isa(f, Type) ? Type{f} : typeof(f)
  723     if isa(args, Type)
  724         u = unwrap_unionall(args)
  725         return rewrap_unionall(Tuple{f_type, u.parameters...}, args)
  726     else
  727         return Tuple{f_type, args...}
  728     end
  729 end
  730 
  731 """
  732     code_lowered(f, types; generated=true, debuginfo=:default)
  733 
  734 Return an array of the lowered forms (IR) for the methods matching the given generic function
  735 and type signature.
  736 
  737 If `generated` is `false`, the returned `CodeInfo` instances will correspond to fallback
  738 implementations. An error is thrown if no fallback implementation exists.
  739 If `generated` is `true`, these `CodeInfo` instances will correspond to the method bodies
  740 yielded by expanding the generators.
  741 
  742 The keyword debuginfo controls the amount of code metadata present in the output.
  743 
  744 Note that an error will be thrown if `types` are not leaf types when `generated` is
  745 `true` and any of the corresponding methods are an `@generated` method.
  746 """
  747 function code_lowered(@nospecialize(f), @nospecialize(t=Tuple); generated::Bool=true, debuginfo::Symbol=:default)
  748     if debuginfo == :default
  749         debuginfo = :source
  750     elseif debuginfo != :source && debuginfo != :none
  751         throw(ArgumentError("'debuginfo' must be either :source or :none"))
  752     end
  753     return map(method_instances(f, t)) do m
  754         if generated && isgenerated(m)
  755             if isa(m, Core.MethodInstance)
  756                 return Core.Compiler.get_staged(m)
  757             else # isa(m, Method)
  758                 error("Could not expand generator for `@generated` method ", m, ". ",
  759                       "This can happen if the provided argument types (", t, ") are ",
  760                       "not leaf types, but the `generated` argument is `true`.")
  761             end
  762         end
  763         code = uncompressed_ast(m)
  764         debuginfo == :none && remove_linenums!(code)
  765         return code
  766     end
  767 end
  768 
  769 isgenerated(m::Method) = isdefined(m, :generator)
  770 isgenerated(m::Core.MethodInstance) = isgenerated(m.def)
  771 
  772 # low-level method lookup functions used by the compiler
  773 
  774 unionlen(x::Union) = unionlen(x.a) + unionlen(x.b)
  775 unionlen(@nospecialize(x)) = 1
  776 
  777 _uniontypes(x::Union, ts) = (_uniontypes(x.a,ts); _uniontypes(x.b,ts); ts)
  778 _uniontypes(@nospecialize(x), ts) = (push!(ts, x); ts)
  779 uniontypes(@nospecialize(x)) = _uniontypes(x, Any[])
  780 
  781 function _methods(@nospecialize(f), @nospecialize(t), lim::Int, world::UInt)
  782     tt = signature_type(f, t)
  783     return _methods_by_ftype(tt, lim, world)
  784 end
  785 
  786 function _methods_by_ftype(@nospecialize(t), lim::Int, world::UInt)
  787     return _methods_by_ftype(t, lim, world, UInt[typemin(UInt)], UInt[typemax(UInt)])
  788 end
  789 function _methods_by_ftype(@nospecialize(t), lim::Int, world::UInt, min::Array{UInt,1}, max::Array{UInt,1})
  790     return ccall(:jl_matching_methods, Any, (Any, Cint, Cint, UInt, Ptr{UInt}, Ptr{UInt}), t, lim, 0, world, min, max)
  791 end
  792 
  793 # high-level, more convenient method lookup functions
  794 
  795 # type for reflecting and pretty-printing a subset of methods
  796 mutable struct MethodList
  797     ms::Array{Method,1}
  798     mt::Core.MethodTable
  799 end
  800 
  801 length(m::MethodList) = length(m.ms)
  802 isempty(m::MethodList) = isempty(m.ms)
  803 iterate(m::MethodList, s...) = iterate(m.ms, s...)
  804 eltype(::Type{MethodList}) = Method
  805 
  806 function MethodList(mt::Core.MethodTable)
  807     ms = Method[]
  808     visit(mt) do m
  809         push!(ms, m)
  810     end
  811     return MethodList(ms, mt)
  812 end
  813 
  814 """
  815     methods(f, [types])
  816 
  817 Returns the method table for `f`.
  818 
  819 If `types` is specified, returns an array of methods whose types match.
  820 """
  821 function methods(@nospecialize(f), @nospecialize(t))
  822     if isa(f, Core.Builtin)
  823         throw(ArgumentError("argument is not a generic function"))
  824     end
  825     t = to_tuple_type(t)
  826     world = typemax(UInt)
  827     return MethodList(Method[m[3] for m in _methods(f, t, -1, world)], typeof(f).name.mt)
  828 end
  829 
  830 methods(f::Core.Builtin) = MethodList(Method[], typeof(f).name.mt)
  831 
  832 function methods_including_ambiguous(@nospecialize(f), @nospecialize(t))
  833     tt = signature_type(f, t)
  834     world = typemax(UInt)
  835     min = UInt[typemin(UInt)]
  836     max = UInt[typemax(UInt)]
  837     ms = ccall(:jl_matching_methods, Any, (Any, Cint, Cint, UInt, Ptr{UInt}, Ptr{UInt}), tt, -1, 1, world, min, max)::Array{Any,1}
  838     return MethodList(Method[m[3] for m in ms], typeof(f).name.mt)
  839 end
  840 function methods(@nospecialize(f))
  841     # return all matches
  842     return methods(f, Tuple{Vararg{Any}})
  843 end
  844 
  845 function visit(f, mt::Core.MethodTable)
  846     mt.defs !== nothing && visit(f, mt.defs)
  847     nothing
  848 end
  849 function visit(f, mc::Core.TypeMapLevel)
  850     if mc.targ !== nothing
  851         e = mc.targ::Vector{Any}
  852         for i in 1:length(e)
  853             isassigned(e, i) && visit(f, e[i])
  854         end
  855     end
  856     if mc.arg1 !== nothing
  857         e = mc.arg1::Vector{Any}
  858         for i in 1:length(e)
  859             isassigned(e, i) && visit(f, e[i])
  860         end
  861     end
  862     mc.list !== nothing && visit(f, mc.list)
  863     mc.any !== nothing && visit(f, mc.any)
  864     nothing
  865 end
  866 function visit(f, d::Core.TypeMapEntry)
  867     while d !== nothing
  868         f(d.func)
  869         d = d.next
  870     end
  871     nothing
  872 end
  873 
  874 function length(mt::Core.MethodTable)
  875     n = 0
  876     visit(mt) do m
  877         n += 1
  878     end
  879     return n::Int
  880 end
  881 isempty(mt::Core.MethodTable) = (mt.defs === nothing)
  882 
  883 uncompressed_ast(m::Method) = isdefined(m, :source) ? uncompressed_ast(m, m.source) :
  884                               isdefined(m, :generator) ? error("Method is @generated; try `code_lowered` instead.") :
  885                               error("Code for this Method is not available.")
  886 uncompressed_ast(m::Method, s::CodeInfo) = copy(s)
  887 uncompressed_ast(m::Method, s::Array{UInt8,1}) = ccall(:jl_uncompress_ast, Any, (Any, Any), m, s)::CodeInfo
  888 uncompressed_ast(m::Core.MethodInstance) = uncompressed_ast(m.def)
  889 
  890 function method_instances(@nospecialize(f), @nospecialize(t), world::UInt = typemax(UInt))
  891     tt = signature_type(f, t)
  892     results = Vector{Union{Method,Core.MethodInstance}}()
  893     for method_data in _methods_by_ftype(tt, -1, world)
  894         mtypes, msp, m = method_data
  895         instance = Core.Compiler.code_for_method(m, mtypes, msp, world, false)
  896         push!(results, ifelse(isa(instance, Core.MethodInstance), instance, m))
  897     end
  898     return results
  899 end
  900 
  901 # this type mirrors jl_cgparams_t (documented in julia.h)
  902 struct CodegenParams
  903     cached::Cint
  904 
  905     track_allocations::Cint
  906     code_coverage::Cint
  907     static_alloc::Cint
  908     prefer_specsig::Cint
  909 
  910     module_setup::Any
  911     module_activation::Any
  912     raise_exception::Any
  913     emit_function::Any
  914     emitted_function::Any
  915 
  916     CodegenParams(;cached::Bool=true,
  917                    track_allocations::Bool=true, code_coverage::Bool=true,
  918                    static_alloc::Bool=true, prefer_specsig::Bool=false,
  919                    module_setup=nothing, module_activation=nothing, raise_exception=nothing,
  920                    emit_function=nothing, emitted_function=nothing) =
  921         new(Cint(cached),
  922             Cint(track_allocations), Cint(code_coverage),
  923             Cint(static_alloc), Cint(prefer_specsig),
  924             module_setup, module_activation, raise_exception,
  925             emit_function, emitted_function)
  926 end
  927 
  928 # give a decent error message if we try to instantiate a staged function on non-leaf types
  929 function func_for_method_checked(m::Method, @nospecialize types)
  930     if isdefined(m, :generator) && !isdispatchtuple(types)
  931         error("cannot call @generated function `", m, "` ",
  932               "with abstract argument types: ", types)
  933     end
  934     return m
  935 end
  936 
  937 """
  938     code_typed(f, types; optimize=true, debuginfo=:default)
  939 
  940 Returns an array of type-inferred lowered form (IR) for the methods matching the given
  941 generic function and type signature. The keyword argument `optimize` controls whether
  942 additional optimizations, such as inlining, are also applied.
  943 The keyword debuginfo controls the amount of code metadata present in the output.
  944 """
  945 function code_typed(@nospecialize(f), @nospecialize(types=Tuple); optimize=true, debuginfo::Symbol=:default)
  946     ccall(:jl_is_in_pure_context, Bool, ()) && error("code reflection cannot be used from generated functions")
  947     if isa(f, Core.Builtin)
  948         throw(ArgumentError("argument is not a generic function"))
  949     end
  950     if debuginfo == :default
  951         debuginfo = :source
  952     elseif debuginfo != :source && debuginfo != :none
  953         throw(ArgumentError("'debuginfo' must be either :source or :none"))
  954     end
  955     types = to_tuple_type(types)
  956     asts = []
  957     world = ccall(:jl_get_world_counter, UInt, ())
  958     params = Core.Compiler.Params(world)
  959     for x in _methods(f, types, -1, world)
  960         meth = func_for_method_checked(x[3], types)
  961         (code, ty) = Core.Compiler.typeinf_code(meth, x[1], x[2], optimize, params)
  962         code === nothing && error("inference not successful") # inference disabled?
  963         debuginfo == :none && remove_linenums!(code)
  964         push!(asts, code => ty)
  965     end
  966     return asts
  967 end
  968 
  969 function return_types(@nospecialize(f), @nospecialize(types=Tuple))
  970     ccall(:jl_is_in_pure_context, Bool, ()) && error("code reflection cannot be used from generated functions")
  971     if isa(f, Core.Builtin)
  972         throw(ArgumentError("argument is not a generic function"))
  973     end
  974     types = to_tuple_type(types)
  975     rt = []
  976     world = ccall(:jl_get_world_counter, UInt, ())
  977     params = Core.Compiler.Params(world)
  978     for x in _methods(f, types, -1, world)
  979         meth = func_for_method_checked(x[3], types)
  980         ty = Core.Compiler.typeinf_type(meth, x[1], x[2], params)
  981         ty === nothing && error("inference not successful") # inference disabled?
  982         push!(rt, ty)
  983     end
  984     return rt
  985 end
  986 
  987 """
  988     which(f, types)
  989 
  990 Returns the method of `f` (a `Method` object) that would be called for arguments of the given `types`.
  991 
  992 If `types` is an abstract type, then the method that would be called by `invoke` is returned.
  993 """
  994 function which(@nospecialize(f), @nospecialize(t))
  995     if isa(f, Core.Builtin)
  996         throw(ArgumentError("argument is not a generic function"))
  997     end
  998     t = to_tuple_type(t)
  999     tt = signature_type(f, t)
 1000     m = ccall(:jl_gf_invoke_lookup, Any, (Any, UInt), tt, typemax(UInt))
 1001     if m === nothing
 1002         error("no unique matching method found for the specified argument types")
 1003     end
 1004     return m.func::Method
 1005 end
 1006 
 1007 """
 1008     which(module, symbol)
 1009 
 1010 Return the module in which the binding for the variable referenced by `symbol` in `module` was created.
 1011 """
 1012 function which(m::Module, s::Symbol)
 1013     if !isdefined(m, s)
 1014         error("\"$s\" is not defined in module $m")
 1015     end
 1016     return binding_module(m, s)
 1017 end
 1018 
 1019 # function reflection
 1020 """
 1021     nameof(f::Function) -> Symbol
 1022 
 1023 Get the name of a generic `Function` as a symbol, or `:anonymous`.
 1024 """
 1025 nameof(f::Function) = typeof(f).name.mt.name
 1026 
 1027 functionloc(m::Core.MethodInstance) = functionloc(m.def)
 1028 
 1029 """
 1030     functionloc(m::Method)
 1031 
 1032 Returns a tuple `(filename,line)` giving the location of a `Method` definition.
 1033 """
 1034 function functionloc(m::Method)
 1035     ln = m.line
 1036     if ln <= 0
 1037         error("could not determine location of method definition")
 1038     end
 1039     return (find_source_file(string(m.file)), ln)
 1040 end
 1041 
 1042 """
 1043     functionloc(f::Function, types)
 1044 
 1045 Returns a tuple `(filename,line)` giving the location of a generic `Function` definition.
 1046 """
 1047 functionloc(@nospecialize(f), @nospecialize(types)) = functionloc(which(f,types))
 1048 
 1049 function functionloc(@nospecialize(f))
 1050     mt = methods(f)
 1051     if isempty(mt)
 1052         if isa(f, Function)
 1053             error("function has no definitions")
 1054         else
 1055             error("object is not callable")
 1056         end
 1057     end
 1058     if length(mt) > 1
 1059         error("function has multiple methods; please specify a type signature")
 1060     end
 1061     return functionloc(first(mt))
 1062 end
 1063 
 1064 """
 1065     parentmodule(f::Function) -> Module
 1066 
 1067 Determine the module containing the (first) definition of a generic
 1068 function.
 1069 """
 1070 parentmodule(f::Function) = parentmodule(typeof(f))
 1071 
 1072 """
 1073     parentmodule(f::Function, types) -> Module
 1074 
 1075 Determine the module containing a given definition of a generic function.
 1076 """
 1077 function parentmodule(@nospecialize(f), @nospecialize(types))
 1078     m = methods(f, types)
 1079     if isempty(m)
 1080         error("no matching methods")
 1081     end
 1082     return first(m).module
 1083 end
 1084 
 1085 """
 1086     hasmethod(f, Tuple type; world = typemax(UInt)) -> Bool
 1087 
 1088 Determine whether the given generic function has a method matching the given
 1089 `Tuple` of argument types with the upper bound of world age given by `world`.
 1090 
 1091 See also [`applicable`](@ref).
 1092 
 1093 # Examples
 1094 ```jldoctest
 1095 julia> hasmethod(length, Tuple{Array})
 1096 true
 1097 ```
 1098 """
 1099 function hasmethod(@nospecialize(f), @nospecialize(t); world = typemax(UInt))
 1100     t = to_tuple_type(t)
 1101     t = signature_type(f, t)
 1102     return ccall(:jl_method_exists, Cint, (Any, Any, UInt), typeof(f).name.mt, t, world) != 0
 1103 end
 1104 
 1105 """
 1106     isambiguous(m1, m2; ambiguous_bottom=false) -> Bool
 1107 
 1108 Determine whether two methods `m1` and `m2` (typically of the same
 1109 function) are ambiguous.  This test is performed in the context of
 1110 other methods of the same function; in isolation, `m1` and `m2` might
 1111 be ambiguous, but if a third method resolving the ambiguity has been
 1112 defined, this returns `false`.
 1113 
 1114 For parametric types, the `ambiguous_bottom` keyword argument controls whether
 1115 `Union{}` counts as an ambiguous intersection of type parameters – when `true`,
 1116 it is considered ambiguous, when `false` it is not.
 1117 
 1118 # Examples
 1119 ```jldoctest
 1120 julia> foo(x::Complex{<:Integer}) = 1
 1121 foo (generic function with 1 method)
 1122 
 1123 julia> foo(x::Complex{<:Rational}) = 2
 1124 foo (generic function with 2 methods)
 1125 
 1126 julia> m1, m2 = collect(methods(foo));
 1127 
 1128 julia> typeintersect(m1.sig, m2.sig)
 1129 Tuple{#foo,Complex{Union{}}}
 1130 
 1131 julia> Base.isambiguous(m1, m2, ambiguous_bottom=true)
 1132 true
 1133 
 1134 julia> Base.isambiguous(m1, m2, ambiguous_bottom=false)
 1135 false
 1136 ```
 1137 """
 1138 function isambiguous(m1::Method, m2::Method; ambiguous_bottom::Bool=false)
 1139     ti = typeintersect(m1.sig, m2.sig)
 1140     ti === Bottom && return false
 1141     if !ambiguous_bottom
 1142         has_bottom_parameter(ti) && return false
 1143     end
 1144     ml = _methods_by_ftype(ti, -1, typemax(UInt))
 1145     isempty(ml) && return true
 1146     for m in ml
 1147         if ti <: m[3].sig
 1148             return false
 1149         end
 1150     end
 1151     return true
 1152 end
 1153 
 1154 """
 1155     delete_method(m::Method)
 1156 
 1157 Make method `m` uncallable and force recompilation of any methods that use(d) it.
 1158 """
 1159 function delete_method(m::Method)
 1160     ccall(:jl_method_table_disable, Cvoid, (Any, Any), get_methodtable(m), m)
 1161 end
 1162 
 1163 function get_methodtable(m::Method)
 1164     ft = ccall(:jl_first_argument_datatype, Any, (Any,), m.sig)
 1165     (ft::DataType).name.mt
 1166 end
 1167 
 1168 """
 1169     has_bottom_parameter(t) -> Bool
 1170 
 1171 Determine whether `t` is a Type for which one or more of its parameters is `Union{}`.
 1172 """
 1173 function has_bottom_parameter(t::Type)
 1174     ret = false
 1175     for p in t.parameters
 1176         ret |= (p == Bottom) || has_bottom_parameter(p)
 1177     end
 1178     ret
 1179 end
 1180 has_bottom_parameter(t::UnionAll) = has_bottom_parameter(unwrap_unionall(t))
 1181 has_bottom_parameter(t::Union) = has_bottom_parameter(t.a) & has_bottom_parameter(t.b)
 1182 has_bottom_parameter(t::TypeVar) = t.ub == Bottom || has_bottom_parameter(t.ub)
 1183 has_bottom_parameter(::Any) = false
 1184 
 1185 min_world(m::Method) = reinterpret(UInt, m.min_world)
 1186 max_world(m::Method) = reinterpret(UInt, m.max_world)
 1187 min_world(m::Core.MethodInstance) = reinterpret(UInt, m.min_world)
 1188 max_world(m::Core.MethodInstance) = reinterpret(UInt, m.max_world)
 1189 
 1190 """
 1191     propertynames(x, private=false)
 1192 
 1193 Get a tuple or a vector of the properties (`x.property`) of an object `x`.
 1194 This is typically the same as [`fieldnames(typeof(x))`](@ref), but types
 1195 that overload [`getproperty`](@ref) should generally overload `propertynames`
 1196 as well to get the properties of an instance of the type.
 1197 
 1198 `propertynames(x)` may return only "public" property names that are part
 1199 of the documented interface of `x`.   If you want it to also return "private"
 1200 fieldnames intended for internal use, pass `true` for the optional second argument.
 1201 REPL tab completion on `x.` shows only the `private=false` properties.
 1202 """
 1203 propertynames(x) = fieldnames(typeof(x))
 1204 propertynames(m::Module) = names(m)
 1205 propertynames(x, private) = propertynames(x) # ignore private flag by default