StatProfilerHTML.jl report
Generated on Mon, 01 Apr 2024 21:01:18
File source code
Line Exclusive Inclusive Code
1 # This file is a part of Julia. License is MIT: https://julialang.org/license
2
3 import Core: CodeInfo, SimpleVector, donotdelete, compilerbarrier, arrayref
4
5 const Callable = Union{Function,Type}
6
7 const Bottom = Union{}
8
9 # Define minimal array interface here to help code used in macros:
10 length(a::Array) = arraylen(a)
11
12 # This is more complicated than it needs to be in order to get Win64 through bootstrap
13 eval(:(getindex(A::Array, i1::Int) = arrayref($(Expr(:boundscheck)), A, i1)))
14 eval(:(getindex(A::Array, i1::Int, i2::Int, I::Int...) = (@inline; arrayref($(Expr(:boundscheck)), A, i1, i2, I...))))
15
16 ==(a::GlobalRef, b::GlobalRef) = a.mod === b.mod && a.name === b.name
17
18 """
19 AbstractSet{T}
20
21 Supertype for set-like types whose elements are of type `T`.
22 [`Set`](@ref), [`BitSet`](@ref) and other types are subtypes of this.
23 """
24 abstract type AbstractSet{T} end
25
26 """
27 AbstractDict{K, V}
28
29 Supertype for dictionary-like types with keys of type `K` and values of type `V`.
30 [`Dict`](@ref), [`IdDict`](@ref) and other types are subtypes of this.
31 An `AbstractDict{K, V}` should be an iterator of `Pair{K, V}`.
32 """
33 abstract type AbstractDict{K,V} end
34
35 ## optional pretty printer:
36 #const NamedTuplePair{N, V, names, T<:NTuple{N, Any}} = Pairs{Symbol, V, NTuple{N, Symbol}, NamedTuple{names, T}}
37 #export NamedTuplePair
38
39 macro _gc_preserve_begin(arg1)
40 Expr(:gc_preserve_begin, esc(arg1))
41 end
42
43 macro _gc_preserve_end(token)
44 Expr(:gc_preserve_end, esc(token))
45 end
46
47 """
48 @nospecialize
49
50 Applied to a function argument name, hints to the compiler that the method
51 implementation should not be specialized for different types of that argument,
52 but instead use the declared type for that argument.
53 It can be applied to an argument within a formal argument list,
54 or in the function body.
55 When applied to an argument, the macro must wrap the entire argument expression, e.g.,
56 `@nospecialize(x::Real)` or `@nospecialize(i::Integer...)` rather than wrapping just the argument name.
57 When used in a function body, the macro must occur in statement position and
58 before any code.
59
60 When used without arguments, it applies to all arguments of the parent scope.
61 In local scope, this means all arguments of the containing function.
62 In global (top-level) scope, this means all methods subsequently defined in the current module.
63
64 Specialization can reset back to the default by using [`@specialize`](@ref).
65
66 ```julia
67 function example_function(@nospecialize x)
68 ...
69 end
70
71 function example_function(x, @nospecialize(y = 1))
72 ...
73 end
74
75 function example_function(x, y, z)
76 @nospecialize x y
77 ...
78 end
79
80 @nospecialize
81 f(y) = [x for x in y]
82 @specialize
83 ```
84
85 !!! note
86 `@nospecialize` affects code generation but not inference: it limits the diversity
87 of the resulting native code, but it does not impose any limitations (beyond the
88 standard ones) on type-inference. Use [`Base.@nospecializeinfer`](@ref) together with
89 `@nospecialize` to additionally suppress inference.
90
91 # Example
92
93 ```julia
94 julia> f(A::AbstractArray) = g(A)
95 f (generic function with 1 method)
96
97 julia> @noinline g(@nospecialize(A::AbstractArray)) = A[1]
98 g (generic function with 1 method)
99
100 julia> @code_typed f([1.0])
101 CodeInfo(
102 1 ─ %1 = invoke Main.g(_2::AbstractArray)::Float64
103 └── return %1
104 ) => Float64
105 ```
106
107 Here, the `@nospecialize` annotation results in the equivalent of
108
109 ```julia
110 f(A::AbstractArray) = invoke(g, Tuple{AbstractArray}, A)
111 ```
112
113 ensuring that only one version of native code will be generated for `g`,
114 one that is generic for any `AbstractArray`.
115 However, the specific return type is still inferred for both `g` and `f`,
116 and this is still used in optimizing the callers of `f` and `g`.
117 """
118 macro nospecialize(vars...)
119 if nfields(vars) === 1
120 # in argument position, need to fix `@nospecialize x=v` to `@nospecialize (kw x v)`
121 var = getfield(vars, 1)
122 if isa(var, Expr) && var.head === :(=)
123 var.head = :kw
124 end
125 end
126 return Expr(:meta, :nospecialize, vars...)
127 end
128
129 """
130 @specialize
131
132 Reset the specialization hint for an argument back to the default.
133 For details, see [`@nospecialize`](@ref).
134 """
135 macro specialize(vars...)
136 if nfields(vars) === 1
137 # in argument position, need to fix `@specialize x=v` to `@specialize (kw x v)`
138 var = getfield(vars, 1)
139 if isa(var, Expr) && var.head === :(=)
140 var.head = :kw
141 end
142 end
143 return Expr(:meta, :specialize, vars...)
144 end
145
146 """
147 @isdefined s -> Bool
148
149 Tests whether variable `s` is defined in the current scope.
150
151 See also [`isdefined`](@ref) for field properties and [`isassigned`](@ref) for
152 array indexes or [`haskey`](@ref) for other mappings.
153
154 # Examples
155 ```jldoctest
156 julia> @isdefined newvar
157 false
158
159 julia> newvar = 1
160 1
161
162 julia> @isdefined newvar
163 true
164
165 julia> function f()
166 println(@isdefined x)
167 x = 3
168 println(@isdefined x)
169 end
170 f (generic function with 1 method)
171
172 julia> f()
173 false
174 true
175 ```
176 """
177 macro isdefined(s::Symbol)
178 return Expr(:escape, Expr(:isdefined, s))
179 end
180
181 """
182 nameof(m::Module) -> Symbol
183
184 Get the name of a `Module` as a [`Symbol`](@ref).
185
186 # Examples
187 ```jldoctest
188 julia> nameof(Base.Broadcast)
189 :Broadcast
190 ```
191 """
192 nameof(m::Module) = ccall(:jl_module_name, Ref{Symbol}, (Any,), m)
193
194 function _is_internal(__module__)
195 if ccall(:jl_base_relative_to, Any, (Any,), __module__)::Module === Core.Compiler ||
196 nameof(__module__) === :Base
197 return true
198 end
199 return false
200 end
201
202 # can be used in place of `@assume_effects :total` (supposed to be used for bootstrapping)
203 macro _total_meta()
204 return _is_internal(__module__) && Expr(:meta, Expr(:purity,
205 #=:consistent=#true,
206 #=:effect_free=#true,
207 #=:nothrow=#true,
208 #=:terminates_globally=#true,
209 #=:terminates_locally=#false,
210 #=:notaskstate=#true,
211 #=:inaccessiblememonly=#true))
212 end
213 # can be used in place of `@assume_effects :foldable` (supposed to be used for bootstrapping)
214 macro _foldable_meta()
215 return _is_internal(__module__) && Expr(:meta, Expr(:purity,
216 #=:consistent=#true,
217 #=:effect_free=#true,
218 #=:nothrow=#false,
219 #=:terminates_globally=#true,
220 #=:terminates_locally=#false,
221 #=:notaskstate=#false,
222 #=:inaccessiblememonly=#true))
223 end
224 # can be used in place of `@assume_effects :nothrow` (supposed to be used for bootstrapping)
225 macro _nothrow_meta()
226 return _is_internal(__module__) && Expr(:meta, Expr(:purity,
227 #=:consistent=#false,
228 #=:effect_free=#false,
229 #=:nothrow=#true,
230 #=:terminates_globally=#false,
231 #=:terminates_locally=#false,
232 #=:notaskstate=#false,
233 #=:inaccessiblememonly=#false))
234 end
235 # can be used in place of `@assume_effects :terminates_locally` (supposed to be used for bootstrapping)
236 macro _terminates_locally_meta()
237 return _is_internal(__module__) && Expr(:meta, Expr(:purity,
238 #=:consistent=#false,
239 #=:effect_free=#false,
240 #=:nothrow=#false,
241 #=:terminates_globally=#false,
242 #=:terminates_locally=#true,
243 #=:notaskstate=#false,
244 #=:inaccessiblememonly=#false))
245 end
246 # can be used in place of `@assume_effects :effect_free :terminates_locally` (supposed to be used for bootstrapping)
247 macro _effect_free_terminates_locally_meta()
248 return _is_internal(__module__) && Expr(:meta, Expr(:purity,
249 #=:consistent=#false,
250 #=:effect_free=#true,
251 #=:nothrow=#false,
252 #=:terminates_globally=#false,
253 #=:terminates_locally=#true,
254 #=:notaskstate=#false,
255 #=:inaccessiblememonly=#false))
256 end
257
258 # another version of inlining that propagates an inbounds context
259 macro _propagate_inbounds_meta()
260 return Expr(:meta, :inline, :propagate_inbounds)
261 end
262
263 function iterate end
264
265 """
266 convert(T, x)
267
268 Convert `x` to a value of type `T`.
269
270 If `T` is an [`Integer`](@ref) type, an [`InexactError`](@ref) will be raised if `x`
271 is not representable by `T`, for example if `x` is not integer-valued, or is outside the
272 range supported by `T`.
273
274 # Examples
275 ```jldoctest
276 julia> convert(Int, 3.0)
277 3
278
279 julia> convert(Int, 3.5)
280 ERROR: InexactError: Int64(3.5)
281 Stacktrace:
282 [...]
283 ```
284
285 If `T` is a [`AbstractFloat`](@ref) type,
286 then it will return the closest value to `x` representable by `T`.
287
288 ```jldoctest
289 julia> x = 1/3
290 0.3333333333333333
291
292 julia> convert(Float32, x)
293 0.33333334f0
294
295 julia> convert(BigFloat, x)
296 0.333333333333333314829616256247390992939472198486328125
297 ```
298
299 If `T` is a collection type and `x` a collection, the result of
300 `convert(T, x)` may alias all or part of `x`.
301 ```jldoctest
302 julia> x = Int[1, 2, 3];
303
304 julia> y = convert(Vector{Int}, x);
305
306 julia> y === x
307 true
308 ```
309
310 See also: [`round`](@ref), [`trunc`](@ref), [`oftype`](@ref), [`reinterpret`](@ref).
311 """
312 function convert end
313
314 # ensure this is never ambiguous, and therefore fast for lookup
315 convert(T::Type{Union{}}, x...) = throw(ArgumentError("cannot convert a value to Union{} for assignment"))
316
317 convert(::Type{Type}, x::Type) = x # the ssair optimizer is strongly dependent on this method existing to avoid over-specialization
318 # in the absence of inlining-enabled
319 # (due to fields typed as `Type`, which is generally a bad idea)
320 # These end up being called during bootstrap and then would be invalidated if not for the following:
321 convert(::Type{String}, x::String) = x
322
323 """
324 @eval [mod,] ex
325
326 Evaluate an expression with values interpolated into it using `eval`.
327 If two arguments are provided, the first is the module to evaluate in.
328 """
329 macro eval(ex)
330 return Expr(:escape, Expr(:call, GlobalRef(Core, :eval), __module__, Expr(:quote, ex)))
331 end
332 macro eval(mod, ex)
333 return Expr(:escape, Expr(:call, GlobalRef(Core, :eval), mod, Expr(:quote, ex)))
334 end
335
336 # use `@eval` here to directly form `:new` expressions avoid implicit `convert`s
337 # in order to achieve better effects inference
338 @eval struct Pairs{K, V, I, A} <: AbstractDict{K, V}
339 data::A
340 itr::I
341 Pairs{K, V, I, A}(data, itr) where {K, V, I, A} = $(Expr(:new, :(Pairs{K, V, I, A}), :(data isa A ? data : convert(A, data)), :(itr isa I ? itr : convert(I, itr))))
342 Pairs{K, V}(data::A, itr::I) where {K, V, I, A} = $(Expr(:new, :(Pairs{K, V, I, A}), :data, :itr))
343 Pairs{K}(data::A, itr::I) where {K, I, A} = $(Expr(:new, :(Pairs{K, eltype(A), I, A}), :data, :itr))
344 Pairs(data::A, itr::I) where {I, A} = $(Expr(:new, :(Pairs{eltype(I), eltype(A), I, A}), :data, :itr))
345 end
346 pairs(::Type{NamedTuple}) = Pairs{Symbol, V, NTuple{N, Symbol}, NamedTuple{names, T}} where {V, N, names, T<:NTuple{N, Any}}
347
348 """
349 Iterators.Pairs(values, keys) <: AbstractDict{eltype(keys), eltype(values)}
350
351 Transforms an indexable container into a Dictionary-view of the same data.
352 Modifying the key-space of the underlying data may invalidate this object.
353 """
354 Pairs
355
356 argtail(x, rest...) = rest
357
358 """
359 tail(x::Tuple)::Tuple
360
361 Return a `Tuple` consisting of all but the first component of `x`.
362
363 See also: [`front`](@ref Base.front), [`rest`](@ref Base.rest), [`first`](@ref), [`Iterators.peel`](@ref).
364
365 # Examples
366 ```jldoctest
367 julia> Base.tail((1,2,3))
368 (2, 3)
369
370 julia> Base.tail(())
371 ERROR: ArgumentError: Cannot call tail on an empty tuple.
372 ```
373 """
374 tail(x::Tuple) = argtail(x...)
375 tail(::Tuple{}) = throw(ArgumentError("Cannot call tail on an empty tuple."))
376
377 function unwrap_unionall(@nospecialize(a))
378 while isa(a,UnionAll)
379 a = a.body
380 end
381 return a
382 end
383
384 function rewrap_unionall(@nospecialize(t), @nospecialize(u))
385 if !isa(u, UnionAll)
386 return t
387 end
388 return UnionAll(u.var, rewrap_unionall(t, u.body))
389 end
390
391 function rewrap_unionall(t::Core.TypeofVararg, @nospecialize(u))
392 isdefined(t, :T) || return t
393 if !isa(u, UnionAll)
394 return t
395 end
396 T = rewrap_unionall(t.T, u)
397 if !isdefined(t, :N) || t.N === u.var
398 return Vararg{T}
399 end
400 return Vararg{T, t.N}
401 end
402
403 # replace TypeVars in all enclosing UnionAlls with fresh TypeVars
404 function rename_unionall(@nospecialize(u))
405 if !isa(u, UnionAll)
406 return u
407 end
408 var = u.var::TypeVar
409 body = UnionAll(var, rename_unionall(u.body))
410 nv = TypeVar(var.name, var.lb, var.ub)
411 return UnionAll(nv, body{nv})
412 end
413
414 # remove concrete constraint on diagonal TypeVar if it comes from troot
415 function widen_diagonal(@nospecialize(t), troot::UnionAll)
416 body = ccall(:jl_widen_diagonal, Any, (Any, Any), t, troot)
417 end
418
419 function isvarargtype(@nospecialize(t))
420 return isa(t, Core.TypeofVararg)
421 end
422
423 function isvatuple(@nospecialize(t))
424 t = unwrap_unionall(t)
425 if isa(t, DataType)
426 n = length(t.parameters)
427 return n > 0 && isvarargtype(t.parameters[n])
428 end
429 return false
430 end
431
432 function unwrapva(@nospecialize(t))
433 isa(t, Core.TypeofVararg) || return t
434 return isdefined(t, :T) ? t.T : Any
435 end
436
437 function unconstrain_vararg_length(va::Core.TypeofVararg)
438 # construct a new Vararg type where its length is unconstrained,
439 # but its element type still captures any dependencies the input
440 # element type may have had on the input length
441 return Vararg{unwrapva(va)}
442 end
443
444 typename(a) = error("typename does not apply to this type")
445 typename(a::DataType) = a.name
446 function typename(a::Union)
447 ta = typename(a.a)
448 tb = typename(a.b)
449 ta === tb || error("typename does not apply to unions whose components have different typenames")
450 return tb
451 end
452 typename(union::UnionAll) = typename(union.body)
453
454 _tuple_error(T::Type, x) = (@noinline; throw(MethodError(convert, (T, x))))
455
456 convert(::Type{T}, x::T) where {T<:Tuple} = x
457 function convert(::Type{T}, x::NTuple{N,Any}) where {N, T<:Tuple}
458 # First see if there could be any conversion of the input type that'd be a subtype of the output.
459 # If not, we'll throw an explicit MethodError (otherwise, it might throw a typeassert).
460 if typeintersect(NTuple{N,Any}, T) === Union{}
461 _tuple_error(T, x)
462 end
463 function cvt1(n)
464 @inline
465 Tn = fieldtype(T, n)
466 xn = getfield(x, n, #=boundscheck=#false)
467 xn isa Tn && return xn
468 return convert(Tn, xn)
469 end
470 return ntuple(cvt1, Val(N))::NTuple{N,Any}
471 end
472
473 # optimizations?
474 # converting to tuple types of fixed length
475 #convert(::Type{T}, x::T) where {N, T<:NTuple{N,Any}} = x
476 #convert(::Type{T}, x::NTuple{N,Any}) where {N, T<:NTuple{N,Any}} =
477 # ntuple(n -> convert(fieldtype(T, n), x[n]), Val(N))
478 #convert(::Type{T}, x::Tuple{Vararg{Any}}) where {N, T<:NTuple{N,Any}} =
479 # throw(MethodError(convert, (T, x)))
480 # converting to tuple types of indefinite length
481 #convert(::Type{Tuple{Vararg{V}}}, x::Tuple{Vararg{V}}) where {V} = x
482 #convert(::Type{NTuple{N, V}}, x::NTuple{N, V}) where {N, V} = x
483 #function convert(T::Type{Tuple{Vararg{V}}}, x::Tuple) where {V}
484 # @isdefined(V) || (V = fieldtype(T, 1))
485 # return map(t -> convert(V, t), x)
486 #end
487 #function convert(T::Type{NTuple{N, V}}, x::NTuple{N, Any}) where {N, V}
488 # @isdefined(V) || (V = fieldtype(T, 1))
489 # return map(t -> convert(V, t), x)
490 #end
491 # short tuples
492 #convert(::Type{Tuple{}}, ::Tuple{}) = ()
493 #convert(::Type{Tuple{S}}, x::Tuple{S}) where {S} = x
494 #convert(::Type{Tuple{S, T}}, x::Tuple{S, T}) where {S, T} = x
495 #convert(::Type{Tuple{S, T, U}}, x::Tuple{S, T, U}) where {S, T, U} = x
496 #convert(::Type{Tuple{S}}, x::Tuple{Any}) where {S} = (convert(S, x[1]),)
497 #convert(::Type{Tuple{S, T}}, x::Tuple{Any, Any}) where {S, T} = (convert(S, x[1]), convert(T, x[2]),)
498 #convert(::Type{Tuple{S, T, U}}, x::Tuple{Any, Any, Any}) where {S, T, U} = (convert(S, x[1]), convert(T, x[2]), convert(U, x[3]))
499 #convert(::Type{Tuple{}}, x::Tuple) = _tuple_error(Tuple{}, x)
500 #convert(::Type{Tuple{S}}, x::Tuple) = _tuple_error(Tuple{S}, x)
501 #convert(::Type{Tuple{S, T}}, x::Tuple{Any, Any}) where {S, T} =_tuple_error(Tuple{S, T}, x)
502 #convert(::Type{Tuple{S, T, U}}, x::Tuple{Any, Any, Any}) where {S, T, U} = _tuple_error(Tuple{S, T, U}, x)
503
504 """
505 oftype(x, y)
506
507 Convert `y` to the type of `x` i.e. `convert(typeof(x), y)`.
508
509 # Examples
510 ```jldoctest
511 julia> x = 4;
512
513 julia> y = 3.;
514
515 julia> oftype(x, y)
516 3
517
518 julia> oftype(y, x)
519 4.0
520 ```
521 """
522 oftype(x, y) = y isa typeof(x) ? y : convert(typeof(x), y)::typeof(x)
523
524 unsigned(x::Int) = reinterpret(UInt, x)
525 signed(x::UInt) = reinterpret(Int, x)
526
527 """
528 cconvert(T,x)
529
530 Convert `x` to a value to be passed to C code as type `T`, typically by calling `convert(T, x)`.
531
532 In cases where `x` cannot be safely converted to `T`, unlike [`convert`](@ref), `cconvert` may
533 return an object of a type different from `T`, which however is suitable for
534 [`unsafe_convert`](@ref) to handle. The result of this function should be kept valid (for the GC)
535 until the result of [`unsafe_convert`](@ref) is not needed anymore.
536 This can be used to allocate memory that will be accessed by the `ccall`.
537 If multiple objects need to be allocated, a tuple of the objects can be used as return value.
538
539 Neither `convert` nor `cconvert` should take a Julia object and turn it into a `Ptr`.
540 """
541 function cconvert end
542
543 cconvert(T::Type, x) = x isa T ? x : convert(T, x) # do the conversion eagerly in most cases
544 cconvert(::Type{Union{}}, x...) = convert(Union{}, x...)
545 cconvert(::Type{<:Ptr}, x) = x # but defer the conversion to Ptr to unsafe_convert
546 unsafe_convert(::Type{T}, x::T) where {T} = x # unsafe_convert (like convert) defaults to assuming the convert occurred
547 unsafe_convert(::Type{T}, x::T) where {T<:Ptr} = x # to resolve ambiguity with the next method
548 unsafe_convert(::Type{P}, x::Ptr) where {P<:Ptr} = convert(P, x)
549
550 """
551 reinterpret(::Type{Out}, x::In)
552
553 Change the type-interpretation of the binary data in the isbits value `x`
554 to that of the isbits type `Out`.
555 The size (ignoring padding) of `Out` has to be the same as that of the type of `x`.
556 For example, `reinterpret(Float32, UInt32(7))` interprets the 4 bytes corresponding to `UInt32(7)` as a
557 [`Float32`](@ref).
558
559 ```jldoctest
560 julia> reinterpret(Float32, UInt32(7))
561 1.0f-44
562
563 julia> reinterpret(NTuple{2, UInt8}, 0x1234)
564 (0x34, 0x12)
565
566 julia> reinterpret(UInt16, (0x34, 0x12))
567 0x1234
568
569 julia> reinterpret(Tuple{UInt16, UInt8}, (0x01, 0x0203))
570 (0x0301, 0x02)
571 ```
572
573 !!! warning
574
575 Use caution if some combinations of bits in `Out` are not considered valid and would
576 otherwise be prevented by the type's constructors and methods. Unexpected behavior
577 may result without additional validation.
578 """
579 function reinterpret(::Type{Out}, x) where {Out}
580 if isprimitivetype(Out) && isprimitivetype(typeof(x))
581 1 (2 %) 1 (2 %)
1 (2 %) samples spent in reinterpret
1 (100 %) (ex.), 1 (100 %) (incl.) when called from exp_impl line 229
return bitcast(Out, x)
582 end
583 # only available when Base is fully loaded.
584 return _reinterpret(Out, x)
585 end
586
587 """
588 sizeof(T::DataType)
589 sizeof(obj)
590
591 Size, in bytes, of the canonical binary representation of the given `DataType` `T`, if any.
592 Or the size, in bytes, of object `obj` if it is not a `DataType`.
593
594 See also [`Base.summarysize`](@ref).
595
596 # Examples
597 ```jldoctest
598 julia> sizeof(Float32)
599 4
600
601 julia> sizeof(ComplexF64)
602 16
603
604 julia> sizeof(1.0)
605 8
606
607 julia> sizeof(collect(1.0:10.0))
608 80
609
610 julia> struct StructWithPadding
611 x::Int64
612 flag::Bool
613 end
614
615 julia> sizeof(StructWithPadding) # not the sum of `sizeof` of fields due to padding
616 16
617
618 julia> sizeof(Int64) + sizeof(Bool) # different from above
619 9
620 ```
621
622 If `DataType` `T` does not have a specific size, an error is thrown.
623
624 ```jldoctest
625 julia> sizeof(AbstractArray)
626 ERROR: Abstract type AbstractArray does not have a definite size.
627 Stacktrace:
628 [...]
629 ```
630 """
631 sizeof(x) = Core.sizeof(x)
632
633 """
634 ifelse(condition::Bool, x, y)
635
636 Return `x` if `condition` is `true`, otherwise return `y`. This differs from `?` or `if` in
637 that it is an ordinary function, so all the arguments are evaluated first. In some cases,
638 using `ifelse` instead of an `if` statement can eliminate the branch in generated code and
639 provide higher performance in tight loops.
640
641 # Examples
642 ```jldoctest
643 julia> ifelse(1 > 2, 1, 2)
644 2
645 ```
646 """
647 ifelse(condition::Bool, x, y) = Core.ifelse(condition, x, y)
648
649 # simple Array{Any} operations needed for bootstrap
650 @eval setindex!(A::Array{Any}, @nospecialize(x), i::Int) = arrayset($(Expr(:boundscheck)), A, x, i)
651
652 """
653 esc(e)
654
655 Only valid in the context of an [`Expr`](@ref) returned from a macro. Prevents the macro hygiene
656 pass from turning embedded variables into gensym variables. See the [Macros](@ref man-macros)
657 section of the Metaprogramming chapter of the manual for more details and examples.
658 """
659 esc(@nospecialize(e)) = Expr(:escape, e)
660
661 """
662 @boundscheck(blk)
663
664 Annotates the expression `blk` as a bounds checking block, allowing it to be elided by [`@inbounds`](@ref).
665
666 !!! note
667 The function in which `@boundscheck` is written must be inlined into
668 its caller in order for `@inbounds` to have effect.
669
670 # Examples
671 ```jldoctest; filter = r"Stacktrace:(\\n \\[[0-9]+\\].*)*"
672 julia> @inline function g(A, i)
673 @boundscheck checkbounds(A, i)
674 return "accessing (\$A)[\$i]"
675 end;
676
677 julia> f1() = return g(1:2, -1);
678
679 julia> f2() = @inbounds return g(1:2, -1);
680
681 julia> f1()
682 ERROR: BoundsError: attempt to access 2-element UnitRange{Int64} at index [-1]
683 Stacktrace:
684 [1] throw_boundserror(::UnitRange{Int64}, ::Tuple{Int64}) at ./abstractarray.jl:455
685 [2] checkbounds at ./abstractarray.jl:420 [inlined]
686 [3] g at ./none:2 [inlined]
687 [4] f1() at ./none:1
688 [5] top-level scope
689
690 julia> f2()
691 "accessing (1:2)[-1]"
692 ```
693
694 !!! warning
695
696 The `@boundscheck` annotation allows you, as a library writer, to opt-in to
697 allowing *other code* to remove your bounds checks with [`@inbounds`](@ref).
698 As noted there, the caller must verify—using information they can access—that
699 their accesses are valid before using `@inbounds`. For indexing into your
700 [`AbstractArray`](@ref) subclasses, for example, this involves checking the
701 indices against its [`axes`](@ref). Therefore, `@boundscheck` annotations
702 should only be added to a [`getindex`](@ref) or [`setindex!`](@ref)
703 implementation after you are certain its behavior is correct.
704 """
705 macro boundscheck(blk)
706 return Expr(:if, Expr(:boundscheck), esc(blk))
707 end
708
709 """
710 @inbounds(blk)
711
712 Eliminates array bounds checking within expressions.
713
714 In the example below the in-range check for referencing
715 element `i` of array `A` is skipped to improve performance.
716
717 ```julia
718 function sum(A::AbstractArray)
719 r = zero(eltype(A))
720 for i in eachindex(A)
721 @inbounds r += A[i]
722 end
723 return r
724 end
725 ```
726
727 !!! warning
728
729 Using `@inbounds` may return incorrect results/crashes/corruption
730 for out-of-bounds indices. The user is responsible for checking it manually.
731 Only use `@inbounds` when it is certain from the information locally available
732 that all accesses are in bounds. In particular, using `1:length(A)` instead of
733 `eachindex(A)` in a function like the one above is _not_ safely inbounds because
734 the first index of `A` may not be `1` for all user defined types that subtype
735 `AbstractArray`.
736 """
737 macro inbounds(blk)
738 return Expr(:block,
739 Expr(:inbounds, true),
740 Expr(:local, Expr(:(=), :val, esc(blk))),
741 Expr(:inbounds, :pop),
742 :val)
743 end
744
745 """
746 @label name
747
748 Labels a statement with the symbolic label `name`. The label marks the end-point
749 of an unconditional jump with [`@goto name`](@ref).
750 """
751 macro label(name::Symbol)
752 return esc(Expr(:symboliclabel, name))
753 end
754
755 """
756 @goto name
757
758 `@goto name` unconditionally jumps to the statement at the location [`@label name`](@ref).
759
760 `@label` and `@goto` cannot create jumps to different top-level statements. Attempts cause an
761 error. To still use `@goto`, enclose the `@label` and `@goto` in a block.
762 """
763 macro goto(name::Symbol)
764 return esc(Expr(:symbolicgoto, name))
765 end
766
767 # SimpleVector
768
769 getindex(v::SimpleVector, i::Int) = (@_foldable_meta; Core._svec_ref(v, i))
770 function length(v::SimpleVector)
771 @_total_meta
772 t = @_gc_preserve_begin v
773 len = unsafe_load(Ptr{Int}(pointer_from_objref(v)))
774 @_gc_preserve_end t
775 return len
776 end
777 firstindex(v::SimpleVector) = 1
778 lastindex(v::SimpleVector) = length(v)
779 iterate(v::SimpleVector, i=1) = (length(v) < i ? nothing : (v[i], i + 1))
780 eltype(::Type{SimpleVector}) = Any
781 keys(v::SimpleVector) = OneTo(length(v))
782 isempty(v::SimpleVector) = (length(v) == 0)
783 axes(v::SimpleVector) = (OneTo(length(v)),)
784 axes(v::SimpleVector, d::Integer) = d <= 1 ? axes(v)[d] : OneTo(1)
785
786 function ==(v1::SimpleVector, v2::SimpleVector)
787 length(v1)==length(v2) || return false
788 for i = 1:length(v1)
789 v1[i] == v2[i] || return false
790 end
791 return true
792 end
793
794 map(f, v::SimpleVector) = Any[ f(v[i]) for i = 1:length(v) ]
795
796 getindex(v::SimpleVector, I::AbstractArray) = Core.svec(Any[ v[i] for i in I ]...)
797
798 unsafe_convert(::Type{Ptr{Any}}, sv::SimpleVector) = convert(Ptr{Any},pointer_from_objref(sv)) + sizeof(Ptr)
799
800 """
801 isassigned(array, i) -> Bool
802
803 Test whether the given array has a value associated with index `i`. Return `false`
804 if the index is out of bounds, or has an undefined reference.
805
806 # Examples
807 ```jldoctest
808 julia> isassigned(rand(3, 3), 5)
809 true
810
811 julia> isassigned(rand(3, 3), 3 * 3 + 1)
812 false
813
814 julia> mutable struct Foo end
815
816 julia> v = similar(rand(3), Foo)
817 3-element Vector{Foo}:
818 #undef
819 #undef
820 #undef
821
822 julia> isassigned(v, 1)
823 false
824 ```
825 """
826 function isassigned end
827
828 function isassigned(v::SimpleVector, i::Int)
829 @boundscheck 1 <= i <= length(v) || return false
830 return true
831 end
832
833
834 """
835 Colon()
836
837 Colons (:) are used to signify indexing entire objects or dimensions at once.
838
839 Very few operations are defined on Colons directly; instead they are converted
840 by [`to_indices`](@ref) to an internal vector type (`Base.Slice`) to represent the
841 collection of indices they span before being used.
842
843 The singleton instance of `Colon` is also a function used to construct ranges;
844 see [`:`](@ref).
845 """
846 struct Colon <: Function
847 end
848 const (:) = Colon()
849
850
851 """
852 Val(c)
853
854 Return `Val{c}()`, which contains no run-time data. Types like this can be used to
855 pass the information between functions through the value `c`, which must be an `isbits`
856 value or a `Symbol`. The intent of this construct is to be able to dispatch on constants
857 directly (at compile time) without having to test the value of the constant at run time.
858
859 # Examples
860 ```jldoctest
861 julia> f(::Val{true}) = "Good"
862 f (generic function with 1 method)
863
864 julia> f(::Val{false}) = "Bad"
865 f (generic function with 2 methods)
866
867 julia> f(Val(true))
868 "Good"
869 ```
870 """
871 struct Val{x}
872 end
873
874 Val(x) = Val{x}()
875
876 """
877 invokelatest(f, args...; kwargs...)
878
879 Calls `f(args...; kwargs...)`, but guarantees that the most recent method of `f`
880 will be executed. This is useful in specialized circumstances,
881 e.g. long-running event loops or callback functions that may
882 call obsolete versions of a function `f`.
883 (The drawback is that `invokelatest` is somewhat slower than calling
884 `f` directly, and the type of the result cannot be inferred by the compiler.)
885
886 !!! compat "Julia 1.9"
887 Prior to Julia 1.9, this function was not exported, and was called as `Base.invokelatest`.
888 """
889 58 (100 %)
58 (100 %) samples spent in invokelatest
58 (100 %) (incl.) when called from run_main_repl line 416
58 (100 %) samples spent calling #invokelatest#2
function invokelatest(@nospecialize(f), @nospecialize args...; kwargs...)
890 kwargs = merge(NamedTuple(), kwargs)
891 if isempty(kwargs)
892 58 (100 %)
58 (100 %) samples spent in #invokelatest#2
58 (100 %) (incl.) when called from invokelatest line 889
58 (100 %) samples spent calling #1013
return Core._call_latest(f, args...)
893 end
894 return Core._call_latest(Core.kwcall, kwargs, f, args...)
895 end
896
897 """
898 invoke_in_world(world, f, args...; kwargs...)
899
900 Call `f(args...; kwargs...)` in a fixed world age, `world`.
901
902 This is useful for infrastructure running in the user's Julia session which is
903 not part of the user's program. For example, things related to the REPL, editor
904 support libraries, etc. In these cases it can be useful to prevent unwanted
905 method invalidation and recompilation latency, and to prevent the user from
906 breaking supporting infrastructure by mistake.
907
908 The current world age can be queried using [`Base.get_world_counter()`](@ref)
909 and stored for later use within the lifetime of the current Julia session, or
910 when serializing and reloading the system image.
911
912 Technically, `invoke_in_world` will prevent any function called by `f` from
913 being extended by the user during their Julia session. That is, generic
914 function method tables seen by `f` (and any functions it calls) will be frozen
915 as they existed at the given `world` age. In a sense, this is like the opposite
916 of [`invokelatest`](@ref).
917
918 !!! note
919 It is not valid to store world ages obtained in precompilation for later use.
920 This is because precompilation generates a "parallel universe" where the
921 world age refers to system state unrelated to the main Julia session.
922 """
923 function invoke_in_world(world::UInt, @nospecialize(f), @nospecialize args...; kwargs...)
924 kwargs = Base.merge(NamedTuple(), kwargs)
925 if isempty(kwargs)
926 return Core._call_in_world(world, f, args...)
927 end
928 return Core._call_in_world(world, Core.kwcall, kwargs, f, args...)
929 end
930
931 inferencebarrier(@nospecialize(x)) = compilerbarrier(:type, x)
932
933 """
934 isempty(collection) -> Bool
935
936 Determine whether a collection is empty (has no elements).
937
938 !!! warning
939
940 `isempty(itr)` may consume the next element of a stateful iterator `itr`
941 unless an appropriate `Base.isdone(itr)` or `isempty` method is defined.
942 Use of `isempty` should therefore be avoided when writing generic
943 code which should support any iterator type.
944
945 # Examples
946 ```jldoctest
947 julia> isempty([])
948 true
949
950 julia> isempty([1 2 3])
951 false
952 ```
953 """
954 function isempty(itr)
955 d = isdone(itr)
956 d !== missing && return d
957 iterate(itr) === nothing
958 end
959
960 """
961 values(iterator)
962
963 For an iterator or collection that has keys and values, return an iterator
964 over the values.
965 This function simply returns its argument by default, since the elements
966 of a general iterator are normally considered its "values".
967
968 # Examples
969 ```jldoctest
970 julia> d = Dict("a"=>1, "b"=>2);
971
972 julia> values(d)
973 ValueIterator for a Dict{String, Int64} with 2 entries. Values:
974 2
975 1
976
977 julia> values([2])
978 1-element Vector{Int64}:
979 2
980 ```
981 """
982 values(itr) = itr
983
984 """
985 Missing
986
987 A type with no fields whose singleton instance [`missing`](@ref) is used
988 to represent missing values.
989
990 See also: [`skipmissing`](@ref), [`nonmissingtype`](@ref), [`Nothing`](@ref).
991 """
992 struct Missing end
993
994 """
995 missing
996
997 The singleton instance of type [`Missing`](@ref) representing a missing value.
998
999 See also: [`NaN`](@ref), [`skipmissing`](@ref), [`nonmissingtype`](@ref).
1000 """
1001 const missing = Missing()
1002
1003 """
1004 ismissing(x)
1005
1006 Indicate whether `x` is [`missing`](@ref).
1007
1008 See also: [`skipmissing`](@ref), [`isnothing`](@ref), [`isnan`](@ref).
1009 """
1010 ismissing(x) = x === missing
1011
1012 function popfirst! end
1013
1014 """
1015 peek(stream[, T=UInt8])
1016
1017 Read and return a value of type `T` from a stream without advancing the current position
1018 in the stream. See also [`startswith(stream, char_or_string)`](@ref).
1019
1020 # Examples
1021
1022 ```jldoctest
1023 julia> b = IOBuffer("julia");
1024
1025 julia> peek(b)
1026 0x6a
1027
1028 julia> position(b)
1029 0
1030
1031 julia> peek(b, Char)
1032 'j': ASCII/Unicode U+006A (category Ll: Letter, lowercase)
1033 ```
1034
1035 !!! compat "Julia 1.5"
1036 The method which accepts a type requires Julia 1.5 or later.
1037 """
1038 function peek end
1039
1040 """
1041 @__LINE__ -> Int
1042
1043 Expand to the line number of the location of the macrocall.
1044 Return `0` if the line number could not be determined.
1045 """
1046 macro __LINE__()
1047 return __source__.line
1048 end
1049
1050 # Iteration
1051 """
1052 isdone(itr, state...) -> Union{Bool, Missing}
1053
1054 This function provides a fast-path hint for iterator completion.
1055 This is useful for mutable iterators that want to avoid having elements
1056 consumed, if they are not going to be exposed to the user (e.g. to check
1057 for done-ness in `isempty` or `zip`). Mutable iterators that want to
1058 opt into this feature should define an isdone method that returns
1059 true/false depending on whether the iterator is done or not. Stateless
1060 iterators need not implement this function. If the result is `missing`,
1061 callers may go ahead and compute `iterate(x, state...) === nothing` to
1062 compute a definite answer.
1063 """
1064 isdone(itr, state...) = missing
1065
1066 """
1067 iterate(iter [, state]) -> Union{Nothing, Tuple{Any, Any}}
1068
1069 Advance the iterator to obtain the next element. If no elements
1070 remain, `nothing` should be returned. Otherwise, a 2-tuple of the
1071 next element and the new iteration state should be returned.
1072 """
1073 function iterate end
1074
1075 """
1076 isiterable(T) -> Bool
1077
1078 Test if type `T` is an iterable collection type or not,
1079 that is whether it has an `iterate` method or not.
1080 """
1081 function isiterable(T)::Bool
1082 return hasmethod(iterate, Tuple{T})
1083 end