diff --git a/Makefile b/Makefile index 7c4a3faae43f9..ea67778254cbe 100644 --- a/Makefile +++ b/Makefile @@ -340,9 +340,10 @@ ifeq ($(BUNDLE_DEBUG_LIBS),1) $(INSTALL_M) $(build_bindir)/julia-debug $(DESTDIR)$(bindir)/ endif ifeq ($(OS),WINNT) - -$(INSTALL_M) $(build_bindir)/*.dll $(DESTDIR)$(bindir)/ + -$(INSTALL_M) $(filter-out $(build_bindir)/libjulia-debug.dll,$(wildcard $(build_bindir)/*.dll)) $(DESTDIR)$(bindir)/ -$(INSTALL_M) $(build_libdir)/libjulia.dll.a $(DESTDIR)$(libdir)/ ifeq ($(BUNDLE_DEBUG_LIBS),1) + -$(INSTALL_M) $(build_bindir)/libjulia-debug.dll $(DESTDIR)$(bindir)/ -$(INSTALL_M) $(build_libdir)/libjulia-debug.dll.a $(DESTDIR)$(libdir)/ endif -$(INSTALL_M) $(build_bindir)/libopenlibm.dll.a $(DESTDIR)$(libdir)/ diff --git a/NEWS.md b/NEWS.md index 82eabe62f81b2..9fb48d3a00af9 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,12 +1,15 @@ Julia v1.1 Release Notes -========================== +======================== New language features --------------------- - * An *exception stack* is maintained on each task to make exception handling more robust and enable root cause analysis using `catch_stack` ([#28878]). + * An *exception stack* is maintained on each task to make exception handling + more robust and enable root cause analysis. The stack may be accessed using + the experimental function `Base.catch_stack` ([#28878]). * The experimental macro `Base.@locals` returns a dictionary of current local variable names and values ([#29733]). + * Binary `~` can now be dotted, as in `x .~ y` ([#30341]). Language changes ---------------- @@ -25,13 +28,14 @@ Language changes the old behavior, or `CartesianIndices(a)[findall(in(b), a)]` to get the new behavior on previous Julia versions ([#30226]). * `findmin(::BitArray)` and `findmax(::BitArray)` now return a `CartesianIndex` when `a` is a matrix - or a higher-dimensional array, for consistency with for other array types. + or a higher-dimensional array, for consistency with other array types. Use `LinearIndices(a)[findmin(a)[2]]` to get the old behavior, or `CartesianIndices(a)[findmin(a)[2]]` to get the new behavior on previous Julia versions ([#30102]). * Method signatures such as `f(::Type{T}, ::T) where {T <: X}` and `f(::Type{X}, ::Any)` - are now considered ambiguous. Previously a bug caused the first one to be considered more specific ([#30160]). + are now considered ambiguous. Previously a bug caused the first one to be considered more specific in + some cases ([#30160]). Command-line option changes --------------------------- @@ -43,13 +47,14 @@ Command-line option changes New library functions --------------------- - * `splitpath(p::String)` function, which is the opposite of `joinpath(parts...)`: it splits a filepath into its components ([#28156]). - * `isnothing(::Any)` function, to check whether something is a `Nothing`, returns a `Bool` ([#29679]). + * `splitpath(p::String)` function, which is the opposite of `joinpath(parts...)`: it splits a filepath + into its components ([#28156]). + * `isnothing(::Any)` predicate, to check whether the argument is `nothing`. ([#29679]). * `getpid(::Process)` method ([#24064]). * `eachrow`, `eachcol` and `eachslice` functions provide efficient iterators over slices of arrays ([#29749]). - * `fieldtypes(T::Type)` which return the declared types of the field in type T ([#29600]). + * `fieldtypes(T::Type)` which returns the declared types of the field in type T ([#29600]). * `uuid5` has been added to the `UUIDs` standard library ([#28761]). - * Predicate functions `Sys.isfreebsd`, `Sys.isopenbsd`, `Sys.isnetbsd`, and `Sys.isdragonfly` for + * Predicates `Sys.isfreebsd`, `Sys.isopenbsd`, `Sys.isnetbsd`, and `Sys.isdragonfly` for detecting BSD systems have been added ([#30249]). * Internal `Base.disable_library_threading` that sets libraries to use one thread. It executes function hooks that have been registered with @@ -70,7 +75,7 @@ Standard library changes argument ([#29157]). * The use of scientific notation when printing `BigFloat` values is now consistent with other floating point types ([#29211]). - * `Regex` now behave like a scalar when used in broadcasting ([#29913]). + * `Regex` now behaves like a scalar when used in broadcasting ([#29913]). * `Char` now behaves like a read-only 0-dimensional array ([#29819]). * `parse` now allows strings representing integer 0 and 1 for type `Bool` ([#29980]). * `Base.tail` now works on named tuples ([#29595]). @@ -79,24 +84,21 @@ Standard library changes * `Base.julia_cmd` now propagates the `--inline=(yes|no)` flag ([#29858]). * `Base.@kwdef` can now be used for parametric structs, and for structs with supertypes ([#29316]). * `merge(::NamedTuple, ::NamedTuple...)` can now be used with more than 2 `NamedTuple`s ([#29259]). - * `Future.copy!` has been moved to `Base` ([#29178]). * New `ncodeunits(c::Char)` method as a fast equivalent to `ncodeunits(string(c))` ([#29153]). * New `sort!(::AbstractArray; dims)` method that can sort the array along the `dims` dimension ([#28902]). - * `range` now accept `stop` as a positional argument ([#28708]). - * `get(A::AbstractArray, (), default)` now returns the result of `A[]` if it can instead of always - returning an empty array ([#30270]). + * `range` now accepts `stop` as a positional argument ([#28708]). + * `get(A::AbstractArray, (), default)` now returns `A[]` instead of an empty array ([#30270]). * `parse(Bool, str)` is now supported ([#29997]). - * `copyto!(::AbstractMatrix, ::UniformScaling)` supports rectangular matrices now ([#28790]). - * In `put!(c::Channel{T}, v)`, `v` now gets converted to `T` as `put!` is being called ([#29092]). + * `copyto!(::AbstractMatrix, ::UniformScaling)` now supports rectangular matrices ([#28790]). * `current_project()` now searches the parent directories of a Git repository for a `Project.toml` file. This also affects the behavior of the `--project` command line option when using the default `--project=@.` ([#29108]). - * The `spawn` API is now more flexible and supports taking IOBuffer directly as a I/O stream, + * The `spawn` API is now more flexible and supports taking IOBuffer directly as an I/O stream, converting to a system pipe as needed ([#30278]). #### Dates * New `DateTime(::Date, ::Time)` constructor ([#29754]). - * `TimeZone` now behave like a scalar when used in broadcasting ([#30159]). + * `TimeZone` now behaves like a scalar when used in broadcasting ([#30159]). #### InteractiveUtils * `edit` can now be called on a module to edit the file that defines it ([#29636]). @@ -108,7 +110,8 @@ Standard library changes * `isdiag` and `isposdef` for `Diagonal` and `UniformScaling` ([#29638]). * `mul!`, `rmul!` and `lmul!` methods for `UniformScaling` ([#29506]). * `Symmetric` and `Hermitian` matrices now preserve the wrapper when scaled with a number ([#29469]). - * Exponentiation operator `^` now supports raising a `Irrational` to an `AbstractMatrix` power ([#29782]). + * Exponentiation operator `^` now supports raising an `Irrational` to an `AbstractMatrix` power ([#29782]). + * Added keyword arguments `rtol`, `atol` to `pinv`, `nullspace` and `rank` ([#29998], [#29926]). #### Random * `randperm` and `randcycle` now use the type of their argument to determine the element type of @@ -120,7 +123,7 @@ Standard library changes * `sprandn` now supports specifying the output element type ([#30083]). #### Statistics - * `mean` and `var` now handles the empty case ([#29033]). + * `mean` and `var` now handle more kinds of empty inputs ([#29033]). External dependencies --------------------- @@ -131,6 +134,7 @@ External dependencies * The source code for Pkg is no longer included in JuliaLang/julia. Pkg is instead downloaded during the build process ([#29615]). * LLVM has been upgraded to 6.0.1 and support for LLVM < 6.0 has been dropped ([#28745], [#28696]). + * Pkg has been upgraded to version 1.1 ([#30342]). Deprecated or removed --------------------- @@ -163,7 +167,6 @@ Deprecated or removed [#29153]: https://github.com/JuliaLang/julia/issues/29153 [#29157]: https://github.com/JuliaLang/julia/issues/29157 [#29173]: https://github.com/JuliaLang/julia/issues/29173 -[#29178]: https://github.com/JuliaLang/julia/issues/29178 [#29211]: https://github.com/JuliaLang/julia/issues/29211 [#29259]: https://github.com/JuliaLang/julia/issues/29259 [#29316]: https://github.com/JuliaLang/julia/issues/29316 @@ -198,8 +201,16 @@ Deprecated or removed [#29978]: https://github.com/JuliaLang/julia/issues/29978 [#29980]: https://github.com/JuliaLang/julia/issues/29980 [#29997]: https://github.com/JuliaLang/julia/issues/29997 +[#30004]: https://github.com/JuliaLang/julia/issues/30004 [#30022]: https://github.com/JuliaLang/julia/issues/30022 [#30035]: https://github.com/JuliaLang/julia/issues/30035 [#30083]: https://github.com/JuliaLang/julia/issues/30083 +[#30102]: https://github.com/JuliaLang/julia/issues/30102 +[#30151]: https://github.com/JuliaLang/julia/issues/30151 [#30159]: https://github.com/JuliaLang/julia/issues/30159 +[#30160]: https://github.com/JuliaLang/julia/issues/30160 +[#30226]: https://github.com/JuliaLang/julia/issues/30226 [#30249]: https://github.com/JuliaLang/julia/issues/30249 +[#30270]: https://github.com/JuliaLang/julia/issues/30270 +[#30278]: https://github.com/JuliaLang/julia/issues/30278 +[#30342]: https://github.com/JuliaLang/julia/issues/30342 diff --git a/base/Makefile b/base/Makefile index b569ed5227ffc..acdd4bb9f82d6 100644 --- a/base/Makefile +++ b/base/Makefile @@ -200,8 +200,15 @@ endif endif # WINNT symlink_libLLVM: $(build_private_libdir)/libLLVM.dylib +ifneq ($(USE_SYSTEM_LLVM),0) +LLVM_CONFIG_HOST_LIBS := $(shell $(LLVM_CONFIG_HOST) --libfiles) +# HACK: llvm-config doesn't correctly point to shared libs on all platforms +# https://github.com/JuliaLang/julia/issues/29981 +else +LLVM_CONFIG_HOST_LIBS := $(shell $(LLVM_CONFIG_HOST) --libdir)/libLLVM.$(SHLIB_EXT) +endif $(build_private_libdir)/libLLVM.dylib: - REALPATH=`$(LLVM_CONFIG_HOST) --libfiles` && \ + REALPATH=$(LLVM_CONFIG_HOST_LIBS) && \ $(call resolve_path,REALPATH) && \ [ -e "$$REALPATH" ] && \ ([ ! -e "$@" ] || rm "$@") && \ diff --git a/base/abstractset.jl b/base/abstractset.jl index 32aeb0c0f0230..4083c88de99c7 100644 --- a/base/abstractset.jl +++ b/base/abstractset.jl @@ -69,9 +69,11 @@ function union!(s::AbstractSet, sets...) end max_values(::Type) = typemax(Int) -max_values(T::Type{<:Union{Nothing,BitIntegerSmall}}) = 1 << (8*sizeof(T)) -max_values(T::Union) = max(max_values(T.a), max_values(T.b)) +max_values(T::Union{map(X -> Type{X}, BitIntegerSmall_types)...}) = 1 << (8*sizeof(T)) +# saturated addition to prevent overflow with typemax(Int) +max_values(T::Union) = max(max_values(T.a), max_values(T.b), max_values(T.a) + max_values(T.b)) max_values(::Type{Bool}) = 2 +max_values(::Type{Nothing}) = 1 function union!(s::AbstractSet{T}, itr) where T haslength(itr) && sizehint!(s, length(s) + length(itr)) diff --git a/base/array.jl b/base/array.jl index 0e7e0b71db2c6..f13c6ee08358e 100644 --- a/base/array.jl +++ b/base/array.jl @@ -512,10 +512,12 @@ function _collect(::Type{T}, itr, isz::SizeUnknown) where T end # make a collection similar to `c` and appropriate for collecting `itr` -_similar_for(c::AbstractArray, T, itr, ::SizeUnknown) = similar(c, T, 0) -_similar_for(c::AbstractArray, T, itr, ::HasLength) = similar(c, T, Int(length(itr)::Integer)) -_similar_for(c::AbstractArray, T, itr, ::HasShape) = similar(c, T, axes(itr)) -_similar_for(c, T, itr, isz) = similar(c, T) +_similar_for(c::AbstractArray, ::Type{T}, itr, ::SizeUnknown) where {T} = similar(c, T, 0) +_similar_for(c::AbstractArray, ::Type{T}, itr, ::HasLength) where {T} = + similar(c, T, Int(length(itr)::Integer)) +_similar_for(c::AbstractArray, ::Type{T}, itr, ::HasShape) where {T} = + similar(c, T, axes(itr)) +_similar_for(c, ::Type{T}, itr, isz) where {T} = similar(c, T) """ collect(collection) @@ -2333,7 +2335,7 @@ function filter!(f, a::AbstractVector) for acurr in a if f(acurr) - a[i] = acurr + @inbounds a[i] = acurr y = iterate(idx, state) y === nothing && (i += 1; break) i, state = y diff --git a/base/bitarray.jl b/base/bitarray.jl index 7f16d00185f4f..a93909a4bbbbd 100644 --- a/base/bitarray.jl +++ b/base/bitarray.jl @@ -5,9 +5,16 @@ # notes: bits are stored in contiguous chunks # unused bits must always be set to 0 """ - BitArray{N} <: DenseArray{Bool, N} + BitArray{N} <: AbstractArray{Bool, N} -Space-efficient `N`-dimensional boolean array, which stores one bit per boolean value. +Space-efficient `N`-dimensional boolean array, using just one bit for each boolean value. + +`BitArray`s pack up to 64 values into every 8 bytes, resulting in an 8x space efficiency +over `Array{Bool, N}` and allowing some operations to work on 64 values at once. + +By default, Julia returns `BitArrays` from [broadcasting](@ref Broadcasting) operations +that generate boolean elements (including dotted-comparisons like `.==`) as well as from +the functions [`trues`](@ref) and [`falses`](@ref). """ mutable struct BitArray{N} <: AbstractArray{Bool, N} chunks::Vector{UInt64} diff --git a/base/boot.jl b/base/boot.jl index 0f0d0b6d0851e..63c7f4b5b4821 100644 --- a/base/boot.jl +++ b/base/boot.jl @@ -624,7 +624,7 @@ toInt8(x::UInt16) = checked_trunc_sint(Int8, check_top_bit(x)) toInt8(x::UInt32) = checked_trunc_sint(Int8, check_top_bit(x)) toInt8(x::UInt64) = checked_trunc_sint(Int8, check_top_bit(x)) toInt8(x::UInt128) = checked_trunc_sint(Int8, check_top_bit(x)) -toInt8(x::Bool) = and_int(zext_int(Int8, x), Int8(1)) +toInt8(x::Bool) = and_int(bitcast(Int8, x), Int8(1)) toInt16(x::Int8) = sext_int(Int16, x) toInt16(x::Int16) = x toInt16(x::Int32) = checked_trunc_sint(Int16, x) @@ -679,7 +679,7 @@ toUInt8(x::UInt16) = checked_trunc_uint(UInt8, x) toUInt8(x::UInt32) = checked_trunc_uint(UInt8, x) toUInt8(x::UInt64) = checked_trunc_uint(UInt8, x) toUInt8(x::UInt128) = checked_trunc_uint(UInt8, x) -toUInt8(x::Bool) = and_int(zext_int(UInt8, x), UInt8(1)) +toUInt8(x::Bool) = and_int(bitcast(UInt8, x), UInt8(1)) toUInt16(x::Int8) = sext_int(UInt16, check_top_bit(x)) toUInt16(x::Int16) = bitcast(UInt16, check_top_bit(x)) toUInt16(x::Int32) = checked_trunc_uint(UInt16, x) diff --git a/base/broadcast.jl b/base/broadcast.jl index b7e49c376b6a5..4ebc1cfcd9f22 100644 --- a/base/broadcast.jl +++ b/base/broadcast.jl @@ -137,7 +137,7 @@ BroadcastStyle(a::AbstractArrayStyle, ::Style{Tuple}) = a BroadcastStyle(::A, ::A) where A<:ArrayStyle = A() BroadcastStyle(::ArrayStyle, ::ArrayStyle) = Unknown() BroadcastStyle(::A, ::A) where A<:AbstractArrayStyle = A() -function BroadcastStyle(a::A, b::B) where {A<:AbstractArrayStyle{M},B<:AbstractArrayStyle{N}} where {M,N} +Base.@pure function BroadcastStyle(a::A, b::B) where {A<:AbstractArrayStyle{M},B<:AbstractArrayStyle{N}} where {M,N} if Base.typename(A) === Base.typename(B) return A(Val(max(M, N))) end diff --git a/base/channels.jl b/base/channels.jl index 090fad3ad877f..e8cf5a977dfbe 100644 --- a/base/channels.jl +++ b/base/channels.jl @@ -1,5 +1,10 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license +""" + AbstractChannel{T} + +Representation of a channel passing objects of type `T`. +""" abstract type AbstractChannel{T} end """ diff --git a/base/compiler/abstractinterpretation.jl b/base/compiler/abstractinterpretation.jl index c4043ab15a161..b1fab2f0f4e69 100644 --- a/base/compiler/abstractinterpretation.jl +++ b/base/compiler/abstractinterpretation.jl @@ -104,7 +104,7 @@ function abstract_call_gf_by_type(@nospecialize(f), argtypes::Vector{Any}, @nosp # if there's a possibility we could constant-propagate a better result # (hopefully without doing too much work), try to do that now # TODO: it feels like this could be better integrated into abstract_call_method / typeinf_edge - const_rettype = abstract_call_method_with_const_args(f, argtypes, applicable[nonbot]::SimpleVector, sv) + const_rettype = abstract_call_method_with_const_args(rettype, f, argtypes, applicable[nonbot]::SimpleVector, sv) if const_rettype ⊑ rettype # use the better result, if it's a refinement of rettype rettype = const_rettype @@ -142,7 +142,7 @@ function abstract_call_gf_by_type(@nospecialize(f), argtypes::Vector{Any}, @nosp return rettype end -function abstract_call_method_with_const_args(@nospecialize(f), argtypes::Vector{Any}, match::SimpleVector, sv::InferenceState) +function abstract_call_method_with_const_args(@nospecialize(rettype), @nospecialize(f), argtypes::Vector{Any}, match::SimpleVector, sv::InferenceState) method = match[3]::Method nargs::Int = method.nargs method.isva && (nargs -= 1) @@ -159,7 +159,7 @@ function abstract_call_method_with_const_args(@nospecialize(f), argtypes::Vector end end end - haveconst || return Any + haveconst || improvable_via_constant_propagation(rettype) || return Any sig = match[1] sparams = match[2]::SimpleVector code = code_for_method(method, sig, sparams, sv.params.world) @@ -1060,7 +1060,7 @@ function typeinf_local(frame::InferenceState) elseif hd === :return pc´ = n + 1 rt = widenconditional(abstract_eval(stmt.args[1], s[pc], frame)) - if !isa(rt, Const) && !isa(rt, Type) && (!isa(rt, PartialTuple) || frame.cached) + if !isa(rt, Const) && !isa(rt, Type) && !isa(rt, PartialTuple) # only propagate information we know we can store # and is valid inter-procedurally rt = widenconst(rt) diff --git a/base/compiler/ssair/inlining.jl b/base/compiler/ssair/inlining.jl index bbebe610ea49b..418afe10fcb46 100644 --- a/base/compiler/ssair/inlining.jl +++ b/base/compiler/ssair/inlining.jl @@ -671,7 +671,7 @@ function analyze_method!(idx::Int, @nospecialize(f), @nospecialize(ft), @nospeci return ConstantCase(quoted(linfo.inferred_const), method, Any[methsp...], metharg) end - isconst, inferred = find_inferred(linfo, atypes, sv) + isconst, inferred = find_inferred(linfo, atypes, sv, stmttyp) if isconst return ConstantCase(inferred, method, Any[methsp...], metharg) end @@ -1152,7 +1152,7 @@ function ssa_substitute_op!(@nospecialize(val), arg_replacements::Vector{Any}, return urs[] end -function find_inferred(linfo::MethodInstance, @nospecialize(atypes), sv::OptimizationState) +function find_inferred(linfo::MethodInstance, @nospecialize(atypes), sv::OptimizationState, @nospecialize(rettype)) # see if the method has a InferenceResult in the current cache # or an existing inferred code info store in `.inferred` haveconst = false @@ -1163,7 +1163,7 @@ function find_inferred(linfo::MethodInstance, @nospecialize(atypes), sv::Optimiz break end end - if haveconst + if haveconst || improvable_via_constant_propagation(rettype) inf_result = cache_lookup(linfo, atypes, sv.params.cache) # Union{Nothing, InferenceResult} else inf_result = nothing diff --git a/base/compiler/typeinfer.jl b/base/compiler/typeinfer.jl index d9c7b7c415ce0..ff9273de3cfd5 100644 --- a/base/compiler/typeinfer.jl +++ b/base/compiler/typeinfer.jl @@ -495,15 +495,19 @@ function typeinf_edge(method::Method, @nospecialize(atypes), sparams::SimpleVect frame.parent = caller end typeinf(frame) - return frame.bestguess, frame.inferred ? frame.linfo : nothing + return widenconst_bestguess(frame.bestguess), frame.inferred ? frame.linfo : nothing elseif frame === true # unresolvable cycle return Any, nothing end frame = frame::InferenceState - return frame.bestguess, nothing + return widenconst_bestguess(frame.bestguess), nothing end +function widenconst_bestguess(bestguess) + !isa(bestguess, Const) && !isa(bestguess, Type) && return widenconst(bestguess) + return bestguess +end #### entry points for inferring a MethodInstance given a type signature #### diff --git a/base/compiler/typeutils.jl b/base/compiler/typeutils.jl index 9b60dd2971fe3..c77f329ef2341 100644 --- a/base/compiler/typeutils.jl +++ b/base/compiler/typeutils.jl @@ -160,3 +160,12 @@ function unioncomplexity(t::DataType) end unioncomplexity(u::UnionAll) = max(unioncomplexity(u.body), unioncomplexity(u.var.ub)) unioncomplexity(@nospecialize(x)) = 0 + +function improvable_via_constant_propagation(@nospecialize(t)) + if isconcretetype(t) && t <: Tuple + for p in t.parameters + p === DataType && return true + end + end + return false +end diff --git a/base/dict.jl b/base/dict.jl index 3f52110e8b8f9..fb27cc10cc04d 100644 --- a/base/dict.jl +++ b/base/dict.jl @@ -760,4 +760,5 @@ isempty(t::ImmutableDict) = !isdefined(t, :parent) empty(::ImmutableDict, ::Type{K}, ::Type{V}) where {K, V} = ImmutableDict{K,V}() _similar_for(c::Dict, ::Type{Pair{K,V}}, itr, isz) where {K, V} = empty(c, K, V) -_similar_for(c::AbstractDict, T, itr, isz) = throw(ArgumentError("for AbstractDicts, similar requires an element type of Pair;\n if calling map, consider a comprehension instead")) +_similar_for(c::AbstractDict, ::Type{T}, itr, isz) where {T} = + throw(ArgumentError("for AbstractDicts, similar requires an element type of Pair;\n if calling map, consider a comprehension instead")) diff --git a/base/error.jl b/base/error.jl index 488ddc6867386..ff13dbef2ec35 100644 --- a/base/error.jl +++ b/base/error.jl @@ -105,7 +105,8 @@ arbitrary task. This is useful for inspecting tasks which have failed due to uncaught exceptions. !!! compat "Julia 1.1" - This function requires at least Julia 1.1. + This function is experimental in Julia 1.1 and will likely be renamed in a + future release (see https://github.com/JuliaLang/julia/pull/29901). """ function catch_stack(task=current_task(); include_bt=true) raw = ccall(:jl_get_excstack, Any, (Any,Cint,Cint), task, include_bt, typemax(Cint)) diff --git a/base/exports.jl b/base/exports.jl index d9c3812b5aebf..3163d4914d3dc 100644 --- a/base/exports.jl +++ b/base/exports.jl @@ -682,7 +682,6 @@ export # errors backtrace, catch_backtrace, - catch_stack, error, rethrow, retry, diff --git a/base/float.jl b/base/float.jl index 81eb6a29b9c77..28254437c8c08 100644 --- a/base/float.jl +++ b/base/float.jl @@ -503,15 +503,18 @@ for Ti in (Int64,UInt64,Int128,UInt128) end end end +for op in (:(==), :<, :<=) + @eval begin + ($op)(x::Float16, y::Union{Int128,UInt128,Int64,UInt64}) = ($op)(Float64(x), Float64(y)) + ($op)(x::Union{Int128,UInt128,Int64,UInt64}, y::Float16) = ($op)(Float64(x), Float64(y)) -==(x::Float32, y::Union{Int32,UInt32}) = Float64(x)==Float64(y) -==(x::Union{Int32,UInt32}, y::Float32) = Float64(x)==Float64(y) - -<(x::Float32, y::Union{Int32,UInt32}) = Float64(x) 1 x == 0 && return 0 - b < 0 && return ndigits0znb(signed(x), b) - b == 2 && return sizeof(x)<<3 - leading_zeros(x) - b == 8 && return (sizeof(x)<<3 - leading_zeros(x) + 2) ÷ 3 - b == 16 && return sizeof(x)<<1 - leading_zeros(x)>>2 - b == 10 && return ndigits0z(x) + b = Int(b) + x = abs(x) + if x isa Base.BitInteger + x = unsigned(x) + b == 2 && return sizeof(x)<<3 - leading_zeros(x) + b == 8 && return (sizeof(x)<<3 - leading_zeros(x) + 2) ÷ 3 + b == 16 && return sizeof(x)<<1 - leading_zeros(x)>>2 + b == 10 && return ndigits0z(x) + end d = 0 while x > typemax(Int) @@ -471,8 +474,6 @@ function ndigits0zpb(x::Base.BitUnsigned, b::Int) return d end -ndigits0zpb(x::Base.BitSigned, b::Integer) = ndigits0zpb(unsigned(abs(x)), Int(b)) -ndigits0zpb(x::Base.BitUnsigned, b::Integer) = ndigits0zpb(x, Int(b)) ndigits0zpb(x::Bool, b::Integer) = x % Int # The suffix "0z" means that the output is 0 on input zero (cf. #16841) diff --git a/base/printf.jl b/base/printf.jl index d3c714efb8444..b6b98187d495a 100644 --- a/base/printf.jl +++ b/base/printf.jl @@ -10,7 +10,8 @@ const SmallNumber = Union{SmallFloatingPoint,Base.BitInteger} function gen(s::AbstractString) args = [] - blk = Expr(:block, :(local neg, pt, len, exp, do_out, args)) + blk = Expr(:block, :(local neg, pt, len, exp, do_out, args, buf)) + gotbuf = false for x in parse(s) if isa(x,AbstractString) push!(blk.args, :(print(out, $(length(x)==1 ? x[1] : x)))) @@ -24,6 +25,10 @@ function gen(s::AbstractString) c=='s' ? gen_s : c=='p' ? gen_p : gen_d + if !gotbuf && c != 'c' && c != 's' && c != 'p' + push!(blk.args, :(buf = $Grisu.getbuf())) + gotbuf = true + end arg, ex = f(x...) push!(args, arg) push!(blk.args, ex) @@ -212,8 +217,8 @@ function print_fixed_width(precision, pt, ndigits, trailingzeros=true) end # note: if print_fixed is changed, print_fixed_width should be changed accordingly -function print_fixed(out, precision, pt, ndigits, trailingzeros=true) - pdigits = pointer(Grisu.getbuf()) +function print_fixed(out, precision, pt, ndigits, trailingzeros=true, buf = Grisu.getbuf()) + pdigits = pointer(buf) if pt <= 0 # 0.0dddd0 print(out, '0') @@ -302,7 +307,7 @@ function gen_d(flags::String, width::Int, precision::Int, c::Char) else fn = :decode_dec end - push!(blk.args, :((do_out, args) = $fn(out, $x, $flags, $width, $precision, $c))) + push!(blk.args, :((do_out, args) = $fn(out, $x, $flags, $width, $precision, $c, buf))) ifblk = Expr(:if, :do_out, Expr(:block)) push!(blk.args, ifblk) blk = ifblk.args[2] @@ -346,7 +351,7 @@ function gen_d(flags::String, width::Int, precision::Int, c::Char) push!(blk.args, pad(width-1, zeros, '0')) end # print integer - push!(blk.args, :(unsafe_write(out, pointer($Grisu.getbuf()), pt))) + push!(blk.args, :(unsafe_write(out, pointer(buf), pt))) # print padding if padding !== nothing && '-' in flags push!(blk.args, pad(width-precision, padding, ' ')) @@ -369,7 +374,7 @@ function gen_f(flags::String, width::Int, precision::Int, c::Char) x, ex, blk = special_handler(flags,width) # interpret the number if precision < 0; precision = 6; end - push!(blk.args, :((do_out, args) = fix_dec(out, $x, $flags, $width, $precision, $c))) + push!(blk.args, :((do_out, args) = fix_dec(out, $x, $flags, $width, $precision, $c, buf))) ifblk = Expr(:if, :do_out, Expr(:block)) push!(blk.args, ifblk) blk = ifblk.args[2] @@ -403,9 +408,9 @@ function gen_f(flags::String, width::Int, precision::Int, c::Char) end # print digits if precision > 0 - push!(blk.args, :(print_fixed(out,$precision,pt,len))) + push!(blk.args, :(print_fixed(out,$precision,pt,len,true,buf))) else - push!(blk.args, :(unsafe_write(out, pointer($Grisu.getbuf()), len))) + push!(blk.args, :(unsafe_write(out, pointer(buf), len))) push!(blk.args, :(while pt >= (len+=1) print(out,'0') end)) '#' in flags && push!(blk.args, :(print(out, '.'))) end @@ -439,8 +444,8 @@ function gen_e(flags::String, width::Int, precision::Int, c::Char, inside_g::Boo # interpret the number if precision < 0; precision = 6; end ndigits = min(precision+1,length(Grisu.getbuf())-1) - push!(blk.args, :((do_out, args) = ini_dec(out,$x,$ndigits, $flags, $width, $precision, $c))) - push!(blk.args, :(digits = $Grisu.getbuf())) + push!(blk.args, :((do_out, args) = ini_dec(out,$x,$ndigits, $flags, $width, $precision, $c, buf))) + push!(blk.args, :(digits = buf)) ifblk = Expr(:if, :do_out, Expr(:block)) push!(blk.args, ifblk) blk = ifblk.args[2] @@ -552,12 +557,12 @@ function gen_a(flags::String, width::Int, precision::Int, c::Char) end # if no precision, print max non-zero if precision < 0 - push!(blk.args, :((do_out, args) = $fn(out,$x, $flags, $width, $precision, $c))) + push!(blk.args, :((do_out, args) = $fn(out,$x, $flags, $width, $precision, $c, buf))) else ndigits = min(precision+1,length(Grisu.getbuf())-1) - push!(blk.args, :((do_out, args) = $fn(out,$x,$ndigits, $flags, $width, $precision, $c))) + push!(blk.args, :((do_out, args) = $fn(out,$x,$ndigits, $flags, $width, $precision, $c, buf))) end - push!(blk.args, :(digits = $Grisu.getbuf())) + push!(blk.args, :(digits = buf)) ifblk = Expr(:if, :do_out, Expr(:block)) push!(blk.args, ifblk) blk = ifblk.args[2] @@ -752,7 +757,7 @@ function gen_g(flags::String, width::Int, precision::Int, c::Char) if precision < 0; precision = 6; end ndigits = min(precision+1,length(Grisu.getbuf())-1) # See if anyone else wants to handle it - push!(blk.args, :((do_out, args) = ini_dec(out,$x,$ndigits, $flags, $width, $precision, $c))) + push!(blk.args, :((do_out, args) = ini_dec(out,$x,$ndigits, $flags, $width, $precision, $c, buf))) ifblk = Expr(:if, :do_out, Expr(:block)) push!(blk.args, ifblk) blk = ifblk.args[2] @@ -768,7 +773,7 @@ function gen_g(flags::String, width::Int, precision::Int, c::Char) # Follow the same logic as gen_f() but more work has to be deferred until runtime # because precision is unknown until then. push!(fblk.args, :(fprec = $precision - (exp+1))) - push!(fblk.args, :((do_out, args) = fix_dec(out, $x, $flags, $width, fprec, $c - 1))) + push!(fblk.args, :((do_out, args) = fix_dec(out, $x, $flags, $width, fprec, $c - 1, buf))) fifblk = Expr(:if, :do_out, Expr(:block)) push!(fblk.args, fifblk) blk = fifblk.args[2] @@ -800,7 +805,7 @@ function gen_g(flags::String, width::Int, precision::Int, c::Char) $padexpr; end)) end # finally print value - push!(blk.args, :(print_fixed(out,fprec,pt,len,$('#' in flags)))) + push!(blk.args, :(print_fixed(out,fprec,pt,len,$('#' in flags),buf))) # print space padding if '-' in flags padexpr = dynamic_pad(:width, :padding, ' ') @@ -828,25 +833,25 @@ macro handle_zero(ex, digits) end end -decode_oct(out, d, flags::String, width::Int, precision::Int, c::Char) = (true, decode_oct(d)) -decode_0ct(out, d, flags::String, width::Int, precision::Int, c::Char) = (true, decode_0ct(d)) -decode_dec(out, d, flags::String, width::Int, precision::Int, c::Char) = (true, decode_dec(d)) -decode_hex(out, d, flags::String, width::Int, precision::Int, c::Char) = (true, decode_hex(d)) -decode_HEX(out, d, flags::String, width::Int, precision::Int, c::Char) = (true, decode_HEX(d)) -fix_dec(out, d, flags::String, width::Int, precision::Int, c::Char) = (true, fix_dec(d, precision)) -ini_dec(out, d, ndigits::Int, flags::String, width::Int, precision::Int, c::Char) = (true, ini_dec(d, ndigits)) -ini_hex(out, d, ndigits::Int, flags::String, width::Int, precision::Int, c::Char) = (true, ini_hex(d, ndigits)) -ini_HEX(out, d, ndigits::Int, flags::String, width::Int, precision::Int, c::Char) = (true, ini_HEX(d, ndigits)) -ini_hex(out, d, flags::String, width::Int, precision::Int, c::Char) = (true, ini_hex(d)) -ini_HEX(out, d, flags::String, width::Int, precision::Int, c::Char) = (true, ini_HEX(d)) +decode_oct(out, d, flags::String, width::Int, precision::Int, c::Char, digits) = (true, decode_oct(d, digits)) +decode_0ct(out, d, flags::String, width::Int, precision::Int, c::Char, digits) = (true, decode_0ct(d, digits)) +decode_dec(out, d, flags::String, width::Int, precision::Int, c::Char, digits) = (true, decode_dec(d, digits)) +decode_hex(out, d, flags::String, width::Int, precision::Int, c::Char, digits) = (true, decode_hex(d, digits)) +decode_HEX(out, d, flags::String, width::Int, precision::Int, c::Char, digits) = (true, decode_HEX(d, digits)) +fix_dec(out, d, flags::String, width::Int, precision::Int, c::Char, digits) = (true, fix_dec(d, precision, digits)) +ini_dec(out, d, ndigits::Int, flags::String, width::Int, precision::Int, c::Char, digits) = (true, ini_dec(d, ndigits, digits)) +ini_hex(out, d, ndigits::Int, flags::String, width::Int, precision::Int, c::Char, digits) = (true, ini_hex(d, ndigits, digits)) +ini_HEX(out, d, ndigits::Int, flags::String, width::Int, precision::Int, c::Char, digits) = (true, ini_HEX(d, ndigits, digits)) +ini_hex(out, d, flags::String, width::Int, precision::Int, c::Char, digits) = (true, ini_hex(d, digits)) +ini_HEX(out, d, flags::String, width::Int, precision::Int, c::Char, digits) = (true, ini_HEX(d, digits)) # fallbacks for Real types without explicit decode_* implementation -decode_oct(d::Real) = decode_oct(Integer(d)) -decode_0ct(d::Real) = decode_0ct(Integer(d)) -decode_dec(d::Real) = decode_dec(Integer(d)) -decode_hex(d::Real) = decode_hex(Integer(d)) -decode_HEX(d::Real) = decode_HEX(Integer(d)) +decode_oct(d::Real, digits) = decode_oct(Integer(d), digits) +decode_0ct(d::Real, digits) = decode_0ct(Integer(d), digits) +decode_dec(d::Real, digits) = decode_dec(Integer(d), digits) +decode_hex(d::Real, digits) = decode_hex(Integer(d), digits) +decode_HEX(d::Real, digits) = decode_HEX(Integer(d), digits) handlenegative(d::Unsigned) = (false, d) function handlenegative(d::Integer) @@ -857,9 +862,8 @@ function handlenegative(d::Integer) end end -function decode_oct(d::Integer) +function decode_oct(d::Integer, digits) neg, x = handlenegative(d) - digits = Grisu.getbuf() @handle_zero x digits pt = i = div((sizeof(x)<<3)-leading_zeros(x)+2,3) while i > 0 @@ -870,11 +874,10 @@ function decode_oct(d::Integer) return Int32(pt), Int32(pt), neg end -function decode_0ct(d::Integer) +function decode_0ct(d::Integer, digits) neg, x = handlenegative(d) # doesn't need special handling for zero pt = i = div((sizeof(x)<<3)-leading_zeros(x)+5,3) - digits = Grisu.getbuf() while i > 0 digits[i] = 48+(x&0x7) x >>= 3 @@ -883,9 +886,8 @@ function decode_0ct(d::Integer) return Int32(pt), Int32(pt), neg end -function decode_dec(d::Integer) +function decode_dec(d::Integer, digits) neg, x = handlenegative(d) - digits = Grisu.getbuf() @handle_zero x digits pt = i = Base.ndigits0z(x) while i > 0 @@ -896,9 +898,8 @@ function decode_dec(d::Integer) return Int32(pt), Int32(pt), neg end -function decode_hex(d::Integer, symbols::AbstractArray{UInt8,1}) +function decode_hex(d::Integer, symbols::AbstractArray{UInt8,1}, digits) neg, x = handlenegative(d) - digits = Grisu.getbuf() @handle_zero x digits pt = i = (sizeof(x)<<1)-(leading_zeros(x)>>2) while i > 0 @@ -912,27 +913,25 @@ end const hex_symbols = b"0123456789abcdef" const HEX_symbols = b"0123456789ABCDEF" -decode_hex(x::Integer) = decode_hex(x,hex_symbols) -decode_HEX(x::Integer) = decode_hex(x,HEX_symbols) +decode_hex(x::Integer, digits) = decode_hex(x,hex_symbols,digits) +decode_HEX(x::Integer, digits) = decode_hex(x,HEX_symbols,digits) -function decode(b::Int, x::BigInt) +function decode(b::Int, x::BigInt, digits) neg = x.size < 0 pt = Base.ndigits(x, base=abs(b)) - digits = Grisu.getbuf() length(digits) < pt+1 && resize!(digits, pt+1) neg && (x.size = -x.size) GMP.MPZ.get_str!(digits, b, x) neg && (x.size = -x.size) return Int32(pt), Int32(pt), neg end -decode_oct(x::BigInt) = decode(8, x) -decode_dec(x::BigInt) = decode(10, x) -decode_hex(x::BigInt) = decode(16, x) -decode_HEX(x::BigInt) = decode(-16, x) +decode_oct(x::BigInt, digits) = decode(8, x, digits) +decode_dec(x::BigInt, digits) = decode(10, x, digits) +decode_hex(x::BigInt, digits) = decode(16, x, digits) +decode_HEX(x::BigInt, digits) = decode(-16, x, digits) -function decode_0ct(x::BigInt) +function decode_0ct(x::BigInt, digits) neg = x.size < 0 - digits = Grisu.getbuf() digits[1] = '0' if x.size == 0 return Int32(1), Int32(1), neg @@ -960,8 +959,7 @@ end # - implies len = point # -function decode_dec(x::SmallFloatingPoint) - digits = Grisu.getbuf() +function decode_dec(x::SmallFloatingPoint, digits) if x == 0.0 digits[1] = '0' return (Int32(1), Int32(1), false) @@ -986,12 +984,11 @@ end # # fallback for Real types without explicit fix_dec implementation -fix_dec(x::Real, n::Int) = fix_dec(float(x),n) +fix_dec(x::Real, n::Int, digits) = fix_dec(float(x),n,digits) -fix_dec(x::Integer, n::Int) = decode_dec(x) +fix_dec(x::Integer, n::Int, digits) = decode_dec(x, digits) -function fix_dec(x::SmallFloatingPoint, n::Int) - digits = Grisu.getbuf() +function fix_dec(x::SmallFloatingPoint, n::Int, digits) if n > length(digits)-1; n = length(digits)-1; end len,pt,neg = grisu(x,Grisu.FIXED,n,digits) if len == 0 @@ -1008,12 +1005,11 @@ end # # fallback for Real types without explicit fix_dec implementation -ini_dec(x::Real, n::Int) = ini_dec(float(x),n) +ini_dec(x::Real, n::Int, digits) = ini_dec(float(x),n,digits) -function ini_dec(d::Integer, n::Int) +function ini_dec(d::Integer, n::Int, digits) neg, x = handlenegative(d) k = ndigits(x) - digits = Grisu.getbuf() if k <= n pt = k for i = k:-1:1 @@ -1043,26 +1039,26 @@ function ini_dec(d::Integer, n::Int) return n, pt, neg end -function ini_dec(x::SmallFloatingPoint, n::Int) +function ini_dec(x::SmallFloatingPoint, n::Int, digits) if x == 0.0 - ccall(:memset, Ptr{Cvoid}, (Ptr{Cvoid}, Cint, Csize_t), Grisu.getbuf(), '0', n) + ccall(:memset, Ptr{Cvoid}, (Ptr{Cvoid}, Cint, Csize_t), digits, '0', n) return Int32(1), Int32(1), signbit(x) else - len,pt,neg = grisu(x,Grisu.PRECISION,n,Grisu.getbuf()) + len,pt,neg = grisu(x,Grisu.PRECISION,n,digits) end return Int32(len), Int32(pt), neg end -function ini_dec(x::BigInt, n::Int) +function ini_dec(x::BigInt, n::Int, digits) if x.size == 0 - ccall(:memset, Ptr{Cvoid}, (Ptr{Cvoid}, Cint, Csize_t), Grisu.getbuf(), '0', n) + ccall(:memset, Ptr{Cvoid}, (Ptr{Cvoid}, Cint, Csize_t), digits, '0', n) return Int32(1), Int32(1), false end d = Base.ndigits0z(x) if d <= n info = decode_dec(x) d == n && return info - p = convert(Ptr{Cvoid}, Grisu.getbuf()) + info[2] + p = convert(Ptr{Cvoid}, digits) + info[2] ccall(:memset, Ptr{Cvoid}, (Ptr{Cvoid}, Cint, Csize_t), p, '0', n - info[2]) return info end @@ -1070,18 +1066,17 @@ function ini_dec(x::BigInt, n::Int) end -ini_hex(x::Real, n::Int) = ini_hex(x,n,hex_symbols) -ini_HEX(x::Real, n::Int) = ini_hex(x,n,HEX_symbols) +ini_hex(x::Real, n::Int, digits) = ini_hex(x,n,hex_symbols,digits) +ini_HEX(x::Real, n::Int, digits) = ini_hex(x,n,HEX_symbols,digits) -ini_hex(x::Real) = ini_hex(x,hex_symbols) -ini_HEX(x::Real) = ini_hex(x,HEX_symbols) +ini_hex(x::Real, digits) = ini_hex(x,hex_symbols,digits) +ini_HEX(x::Real, digits) = ini_hex(x,HEX_symbols,digits) -ini_hex(x::Real, n::Int, symbols::AbstractArray{UInt8,1}) = ini_hex(float(x), n, symbols) -ini_hex(x::Real, symbols::AbstractArray{UInt8,1}) = ini_hex(float(x), symbols) +ini_hex(x::Real, n::Int, symbols::AbstractArray{UInt8,1}, digits) = ini_hex(float(x), n, symbols, digits) +ini_hex(x::Real, symbols::AbstractArray{UInt8,1}, digits) = ini_hex(float(x), symbols, digits) -function ini_hex(x::SmallFloatingPoint, n::Int, symbols::AbstractArray{UInt8,1}) +function ini_hex(x::SmallFloatingPoint, n::Int, symbols::AbstractArray{UInt8,1}, digits) x = Float64(x) - digits = Grisu.getbuf() if x == 0.0 ccall(:memset, Ptr{Cvoid}, (Ptr{Cvoid}, Cint, Csize_t), digits, '0', n) return Int32(1), Int32(0), signbit(x) @@ -1105,9 +1100,8 @@ function ini_hex(x::SmallFloatingPoint, n::Int, symbols::AbstractArray{UInt8,1}) end end -function ini_hex(x::SmallFloatingPoint, symbols::AbstractArray{UInt8,1}) +function ini_hex(x::SmallFloatingPoint, symbols::AbstractArray{UInt8,1}, digits) x = Float64(x) - digits = Grisu.getbuf() if x == 0.0 ccall(:memset, Ptr{Cvoid}, (Ptr{Cvoid}, Cint, Csize_t), digits, '0', 1) return Int32(1), Int32(0), signbit(x) @@ -1127,28 +1121,28 @@ function ini_hex(x::SmallFloatingPoint, symbols::AbstractArray{UInt8,1}) end end -function ini_hex(x::Integer) - len,pt,neg = decode_hex(x) +function ini_hex(x::Integer, digits) + len,pt,neg = decode_hex(x, digits) pt = (len-1)<<2 len,pt,neg end -function ini_HEX(x::Integer) - len,pt,neg = decode_HEX(x) +function ini_HEX(x::Integer, digits) + len,pt,neg = decode_HEX(x, digits) pt = (len-1)<<2 len,pt,neg end # not implemented -ini_hex(x::Integer,ndigits::Int) = throw(MethodError(ini_hex,(x,ndigits))) +ini_hex(x::Integer,ndigits::Int,digits) = throw(MethodError(ini_hex,(x,ndigits,digits))) #BigFloat -fix_dec(out, d::BigFloat, flags::String, width::Int, precision::Int, c::Char) = bigfloat_printf(out, d, flags, width, precision, c) -ini_dec(out, d::BigFloat, ndigits::Int, flags::String, width::Int, precision::Int, c::Char) = bigfloat_printf(out, d, flags, width, precision, c) -ini_hex(out, d::BigFloat, ndigits::Int, flags::String, width::Int, precision::Int, c::Char) = bigfloat_printf(out, d, flags, width, precision, c) -ini_HEX(out, d::BigFloat, ndigits::Int, flags::String, width::Int, precision::Int, c::Char) = bigfloat_printf(out, d, flags, width, precision, c) -ini_hex(out, d::BigFloat, flags::String, width::Int, precision::Int, c::Char) = bigfloat_printf(out, d, flags, width, precision, c) -ini_HEX(out, d::BigFloat, flags::String, width::Int, precision::Int, c::Char) = bigfloat_printf(out, d, flags, width, precision, c) -function bigfloat_printf(out, d::BigFloat, flags::String, width::Int, precision::Int, c::Char) +fix_dec(out, d::BigFloat, flags::String, width::Int, precision::Int, c::Char, digits) = bigfloat_printf(out, d, flags, width, precision, c, digits) +ini_dec(out, d::BigFloat, ndigits::Int, flags::String, width::Int, precision::Int, c::Char, digits) = bigfloat_printf(out, d, flags, width, precision, c, digits) +ini_hex(out, d::BigFloat, ndigits::Int, flags::String, width::Int, precision::Int, c::Char, digits) = bigfloat_printf(out, d, flags, width, precision, c, digits) +ini_HEX(out, d::BigFloat, ndigits::Int, flags::String, width::Int, precision::Int, c::Char, digits) = bigfloat_printf(out, d, flags, width, precision, c, digits) +ini_hex(out, d::BigFloat, flags::String, width::Int, precision::Int, c::Char, digits) = bigfloat_printf(out, d, flags, width, precision, c, digits) +ini_HEX(out, d::BigFloat, flags::String, width::Int, precision::Int, c::Char, digits) = bigfloat_printf(out, d, flags, width, precision, c, digits) +function bigfloat_printf(out, d::BigFloat, flags::String, width::Int, precision::Int, c::Char, digits) fmt_len = sizeof(flags)+4 if width > 0 fmt_len += ndigits(width) @@ -1174,7 +1168,6 @@ function bigfloat_printf(out, d::BigFloat, flags::String, width::Int, precision: write(fmt, UInt8(0)) printf_fmt = take!(fmt) @assert length(printf_fmt) == fmt_len - digits = Grisu.getbuf() bufsiz = length(digits) lng = ccall((:mpfr_snprintf,:libmpfr), Int32, (Ptr{UInt8}, Culong, Ptr{UInt8}, Ref{BigFloat}...), diff --git a/base/range.jl b/base/range.jl index 785ade602f6bf..edf616d4d171f 100644 --- a/base/range.jl +++ b/base/range.jl @@ -627,8 +627,8 @@ function getindex(v::AbstractRange{T}, i::Integer) where T @_inline_meta ret = convert(T, first(v) + (i - 1)*step_hp(v)) ok = ifelse(step(v) > zero(step(v)), - (ret <= v.stop) & (ret >= v.start), - (ret <= v.start) & (ret >= v.stop)) + (ret <= last(v)) & (ret >= first(v)), + (ret <= first(v)) & (ret >= last(v))) @boundscheck ((i > 0) & ok) || throw_boundserror(v, i) ret end diff --git a/base/reinterpretarray.jl b/base/reinterpretarray.jl index 2ea21ec981b56..8d7a175d8252d 100644 --- a/base/reinterpretarray.jl +++ b/base/reinterpretarray.jl @@ -33,8 +33,8 @@ struct ReinterpretArray{T,N,S,A<:AbstractArray{S, N}} <: AbstractArray{T, N} isbitstype(T) || throwbits(S, T, T) isbitstype(S) || throwbits(S, T, S) (N != 0 || sizeof(T) == sizeof(S)) || throwsize0(S, T) - ax1 = axes(a)[1] if N != 0 && sizeof(S) != sizeof(T) + ax1 = axes(a)[1] dim = length(ax1) rem(dim*sizeof(S),sizeof(T)) == 0 || thrownonint(S, T, dim) first(ax1) == 1 || throwaxes1(S, T, ax1) @@ -74,6 +74,7 @@ function size(a::ReinterpretArray{T,N,S} where {N}) where {T,S} size1 = div(psize[1]*sizeof(S), sizeof(T)) tuple(size1, tail(psize)...) end +size(a::ReinterpretArray{T,0}) where {T} = () function axes(a::ReinterpretArray{T,N,S} where {N}) where {T,S} paxs = axes(a.parent) @@ -81,6 +82,7 @@ function axes(a::ReinterpretArray{T,N,S} where {N}) where {T,S} size1 = div(l*sizeof(S), sizeof(T)) tuple(oftype(paxs[1], f:f+size1-1), tail(paxs)...) end +axes(a::ReinterpretArray{T,0}) where {T} = () elsize(::Type{<:ReinterpretArray{T}}) where {T} = sizeof(T) unsafe_convert(::Type{Ptr{T}}, a::ReinterpretArray{T,N,S} where N) where {T,S} = Ptr{T}(unsafe_convert(Ptr{S},a.parent)) diff --git a/base/set.jl b/base/set.jl index 6afff54d7cf0a..0ed73407ca6b1 100644 --- a/base/set.jl +++ b/base/set.jl @@ -34,7 +34,7 @@ empty(s::AbstractSet{T}, ::Type{U}=T) where {T,U} = Set{U}() # by default, a Set is returned emptymutable(s::AbstractSet{T}, ::Type{U}=T) where {T,U} = Set{U}() -_similar_for(c::AbstractSet, T, itr, isz) = empty(c, T) +_similar_for(c::AbstractSet, ::Type{T}, itr, isz) where {T} = empty(c, T) function show(io::IO, s::Set) print(io, "Set(") @@ -167,15 +167,39 @@ julia> unique(x -> x^2, [1, -1, 3, -3, 4]) """ function unique(f, C) out = Vector{eltype(C)}() - seen = Set() - for x in C + + s = iterate(C) + if s === nothing + return out + end + (x, i) = s + y = f(x) + seen = Set{typeof(y)}() + push!(seen, y) + push!(out, x) + + return _unique!(f, out, C, seen, i) +end + +function _unique!(f, out::AbstractVector, C, seen::Set, i) + s = iterate(C, i) + while s !== nothing + (x, i) = s y = f(x) - if !in(y, seen) - push!(seen, y) + if y ∉ seen push!(out, x) + if y isa eltype(seen) + push!(seen, y) + else + seen2 = convert(Set{promote_typejoin(eltype(seen), typeof(y))}, seen) + push!(seen2, y) + return _unique!(f, out, C, seen2, i) + end end + s = iterate(C, i) end - out + + return out end """ @@ -184,6 +208,9 @@ end Selects one value from `A` for each unique value produced by `f` applied to elements of `A` , then return the modified A. +!!! compat "Julia 1.1" + This method is available as of Julia 1.1. + # Examples ```jldoctest julia> unique!(x -> x^2, [1, -1, 3, -3, 4]) @@ -205,22 +232,39 @@ julia> unique!(iseven, [2, 3, 5, 7, 9]) ``` """ function unique!(f, A::AbstractVector) - seen = Set() - idxs = eachindex(A) - y = iterate(idxs) - count = 0 - for x in A - t = f(x) - if t ∉ seen - push!(seen,t) - count += 1 - A[y[1]] = x - y = iterate(idxs, y[2]) + if length(A) <= 1 + return A + end + + i = firstindex(A) + x = @inbounds A[i] + y = f(x) + seen = Set{typeof(y)}() + push!(seen, y) + return _unique!(f, A, seen, i, i+1) +end + +function _unique!(f, A::AbstractVector, seen::Set, current::Integer, i::Integer) + while i <= lastindex(A) + x = @inbounds A[i] + y = f(x) + if y ∉ seen + current += 1 + @inbounds A[current] = x + if y isa eltype(seen) + push!(seen, y) + else + seen2 = convert(Set{promote_typejoin(eltype(seen), typeof(y))}, seen) + push!(seen2, y) + return _unique!(f, A, seen2, current, i+1) + end end + i += 1 end - resize!(A, count) + return resize!(A, current - firstindex(A) + 1) end + # If A is not grouped, then we will need to keep track of all of the elements that we have # seen so far. _unique!(A::AbstractVector) = unique!(identity, A::AbstractVector) diff --git a/base/show.jl b/base/show.jl index fefb5d2650dd1..164031b7a5884 100644 --- a/base/show.jl +++ b/base/show.jl @@ -1031,7 +1031,7 @@ function show_unquoted_quote_expr(io::IO, @nospecialize(value), indent::Int, pre print(io, ":") print(io, value) else - print(io, "Symbol(\"", escape_string(s), "\")") + print(io, "Symbol(", repr(s), ")") end else if isa(value,Expr) && value.head === :block diff --git a/base/subarray.jl b/base/subarray.jl index 5e593b95bcf99..2d6f8a709a642 100644 --- a/base/subarray.jl +++ b/base/subarray.jl @@ -222,13 +222,14 @@ end # In general, we simply re-index the parent indices by the provided ones SlowSubArray{T,N,P,I} = SubArray{T,N,P,I,false} -function getindex(V::SlowSubArray{T,N}, I::Vararg{Int,N}) where {T,N} +function getindex(V::SubArray{T,N}, I::Vararg{Int,N}) where {T,N} @_inline_meta @boundscheck checkbounds(V, I...) @inbounds r = V.parent[reindex(V, V.indices, I)...] r end +# But SubArrays with fast linear indexing pre-compute a stride and offset FastSubArray{T,N,P,I} = SubArray{T,N,P,I,true} function getindex(V::FastSubArray, i::Int) @_inline_meta @@ -246,8 +247,23 @@ function getindex(V::FastContiguousSubArray, i::Int) @inbounds r = V.parent[V.offset1 + i] r end +# For vector views with linear indexing, we disambiguate to favor the stride/offset +# computation as that'll generally be faster than (or just as fast as) re-indexing into a range. +function getindex(V::FastSubArray{<:Any, 1}, i::Int) + @_inline_meta + @boundscheck checkbounds(V, i) + @inbounds r = V.parent[V.offset1 + V.stride1*i] + r +end +function getindex(V::FastContiguousSubArray{<:Any, 1}, i::Int) + @_inline_meta + @boundscheck checkbounds(V, i) + @inbounds r = V.parent[V.offset1 + i] + r +end -function setindex!(V::SlowSubArray{T,N}, x, I::Vararg{Int,N}) where {T,N} +# Indexed assignment follows the same pattern as `getindex` above +function setindex!(V::SubArray{T,N}, x, I::Vararg{Int,N}) where {T,N} @_inline_meta @boundscheck checkbounds(V, I...) @inbounds V.parent[reindex(V, V.indices, I)...] = x @@ -265,6 +281,18 @@ function setindex!(V::FastContiguousSubArray, x, i::Int) @inbounds V.parent[V.offset1 + i] = x V end +function setindex!(V::FastSubArray{<:Any, 1}, x, i::Int) + @_inline_meta + @boundscheck checkbounds(V, i) + @inbounds V.parent[V.offset1 + V.stride1*i] = x + V +end +function setindex!(V::FastContiguousSubArray{<:Any, 1}, x, i::Int) + @_inline_meta + @boundscheck checkbounds(V, i) + @inbounds V.parent[V.offset1 + i] = x + V +end IndexStyle(::Type{<:FastSubArray}) = IndexLinear() IndexStyle(::Type{<:SubArray}) = IndexCartesian() diff --git a/deps/checksums/Pkg-193e494c22f7ce8b5956829286c6212133edcbf1.tar.gz/md5 b/deps/checksums/Pkg-193e494c22f7ce8b5956829286c6212133edcbf1.tar.gz/md5 deleted file mode 100644 index 58901a73acbe6..0000000000000 --- a/deps/checksums/Pkg-193e494c22f7ce8b5956829286c6212133edcbf1.tar.gz/md5 +++ /dev/null @@ -1 +0,0 @@ -006468f2f3090f1c5fd64eac3105981e diff --git a/deps/checksums/Pkg-193e494c22f7ce8b5956829286c6212133edcbf1.tar.gz/sha512 b/deps/checksums/Pkg-193e494c22f7ce8b5956829286c6212133edcbf1.tar.gz/sha512 deleted file mode 100644 index 90f2c54ebb74f..0000000000000 --- a/deps/checksums/Pkg-193e494c22f7ce8b5956829286c6212133edcbf1.tar.gz/sha512 +++ /dev/null @@ -1 +0,0 @@ -fee2e9731acfc70a2488fe7d0ff6656ccc36f3620ab654dc147e554006fe630409ccd823a1b44b9bd235ba008c7a4c649f785299dff435d68f118741aacacb68 diff --git a/deps/checksums/Pkg-853b3f1fd9895db32b402d89e9dee153b66b2316.tar.gz/md5 b/deps/checksums/Pkg-853b3f1fd9895db32b402d89e9dee153b66b2316.tar.gz/md5 new file mode 100644 index 0000000000000..aa9fda894b7d1 --- /dev/null +++ b/deps/checksums/Pkg-853b3f1fd9895db32b402d89e9dee153b66b2316.tar.gz/md5 @@ -0,0 +1 @@ +b51ae77c52564bcb0e7033b3fdcffba1 diff --git a/deps/checksums/Pkg-853b3f1fd9895db32b402d89e9dee153b66b2316.tar.gz/sha512 b/deps/checksums/Pkg-853b3f1fd9895db32b402d89e9dee153b66b2316.tar.gz/sha512 new file mode 100644 index 0000000000000..fbe7fcfb9ddf9 --- /dev/null +++ b/deps/checksums/Pkg-853b3f1fd9895db32b402d89e9dee153b66b2316.tar.gz/sha512 @@ -0,0 +1 @@ +f81ef6ec68b190d18a28562c4d2507b393b5f9d09d900fa682ab876564908c7700c282343e568fed66703ddc9a12ab0a425f70e5fe705002b2da6397274b30f8 diff --git a/doc/Makefile b/doc/Makefile index 3d0773342fc1d..99e60ee665c1f 100644 --- a/doc/Makefile +++ b/doc/Makefile @@ -20,7 +20,8 @@ help: @echo "To fix outdated doctests, use 'make doctest=fix'" -DOCUMENTER_OPTIONS := linkcheck=$(linkcheck) doctest=$(doctest) buildroot=$(call cygpath_w,$(BUILDROOT)) +DOCUMENTER_OPTIONS := linkcheck=$(linkcheck) doctest=$(doctest) buildroot=$(call cygpath_w,$(BUILDROOT)) \ + texplatform=$(texplatform) UnicodeData.txt: $(JLDOWNLOAD) http://www.unicode.org/Public/9.0.0/ucd/UnicodeData.txt diff --git a/doc/Manifest.toml b/doc/Manifest.toml index 609d04b817e2b..5cbd6d684b7ed 100644 --- a/doc/Manifest.toml +++ b/doc/Manifest.toml @@ -1,3 +1,5 @@ +# This file is machine-generated - editing it directly is not advised + [[Base64]] uuid = "2a0f44e3-6c83-55bd-87e4-b1978d98bd5f" @@ -6,35 +8,34 @@ deps = ["Printf"] uuid = "ade2ca70-3891-5945-98fb-dc099432e06a" [[Distributed]] -deps = ["LinearAlgebra", "Random", "Serialization", "Sockets"] +deps = ["Random", "Serialization", "Sockets"] uuid = "8ba89e20-285c-5b6f-9357-94700520ee1b" [[DocStringExtensions]] deps = ["LibGit2", "Markdown", "Pkg", "Test"] -git-tree-sha1 = "a016e0bfe98a748c4488e2248c2ef4c67d6fdd35" +git-tree-sha1 = "1df01539a1c952cef21f2d2d1c092c2bcf0177d7" uuid = "ffbed154-4ef7-542d-bbb7-c09d3a79fcae" -version = "0.5.0" +version = "0.6.0" [[Documenter]] deps = ["Base64", "DocStringExtensions", "InteractiveUtils", "LibGit2", "Logging", "Markdown", "Pkg", "REPL", "Random", "Test", "Unicode"] -git-tree-sha1 = "9f2135e0e7ecb63f9c3ef73ea15a31d8cdb79bb7" +git-tree-sha1 = "a6db1c69925cdc53aafb38caec4446be26e0c617" uuid = "e30172f5-a6a5-5a46-863b-614d45cd2de4" -version = "0.20.0" +version = "0.21.0" + +[[DocumenterLaTeX]] +deps = ["Documenter", "Test"] +git-tree-sha1 = "653299370be20ff580bccd707dc9f360c0852d7f" +uuid = "cd674d7a-5f81-5cf3-af33-235ef1834b99" +version = "0.2.0" [[InteractiveUtils]] -deps = ["LinearAlgebra", "Markdown"] +deps = ["Markdown"] uuid = "b77e0a4c-d291-57a0-90e8-8db25a27a240" [[LibGit2]] uuid = "76f85450-5226-5b5a-8eaa-529ad045b433" -[[Libdl]] -uuid = "8f399da3-3557-5675-b5ff-fb832c97cbdb" - -[[LinearAlgebra]] -deps = ["Libdl"] -uuid = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" - [[Logging]] uuid = "56ddb016-857b-54e1-b83d-db4d58db5568" diff --git a/doc/Project.toml b/doc/Project.toml index dfa65cd107d06..c09e74d6533a4 100644 --- a/doc/Project.toml +++ b/doc/Project.toml @@ -1,2 +1,3 @@ [deps] Documenter = "e30172f5-a6a5-5a46-863b-614d45cd2de4" +DocumenterLaTeX = "cd674d7a-5f81-5cf3-af33-235ef1834b99" diff --git a/doc/make.jl b/doc/make.jl index 6a89666da974d..bae4096990cac 100644 --- a/doc/make.jl +++ b/doc/make.jl @@ -6,7 +6,7 @@ pushfirst!(DEPOT_PATH, joinpath(@__DIR__, "deps")) using Pkg Pkg.instantiate() -using Documenter +using Documenter, DocumenterLaTeX # Include the `build_sysimg` file. @@ -159,6 +159,17 @@ let r = r"buildroot=(.+)", i = findfirst(x -> occursin(r, x), ARGS) global const buildroot = i === nothing ? (@__DIR__) : first(match(r, ARGS[i]).captures) end +const format = if render_pdf + LaTeX( + platform = "texplatform=docker" in ARGS ? "docker" : "native" + ) +else + Documenter.HTML( + prettyurls = ("deploy" in ARGS), + canonical = ("deploy" in ARGS) ? "https://docs.julialang.org/en/v1/" : nothing, + ) +end + makedocs( build = joinpath(buildroot, "doc", "_build", (render_pdf ? "pdf" : "html"), "en"), modules = [Base, Core, BuildSysImg, [Base.root_module(Base, stdlib.stdlib) for stdlib in STDLIB_DOCS]...], @@ -168,13 +179,11 @@ makedocs( linkcheck_ignore = ["https://bugs.kde.org/show_bug.cgi?id=136779"], # fails to load from nanosoldier? strict = true, checkdocs = :none, - format = render_pdf ? :latex : :html, + format = format, sitename = "The Julia Language", authors = "The Julia Project", analytics = "UA-28835595-6", pages = PAGES, - html_prettyurls = ("deploy" in ARGS), - html_canonical = ("deploy" in ARGS) ? "https://docs.julialang.org/en/v1/" : nothing, assets = ["assets/julia-manual.css", ] ) diff --git a/doc/src/index.md b/doc/src/index.md index b8fe2dc820fe3..ba11d6a3133c1 100644 --- a/doc/src/index.md +++ b/doc/src/index.md @@ -20,6 +20,18 @@ Markdown.parse(String(take!(io))) ``` Please read the [release notes](NEWS.md) to see what has changed since the last release. +```@eval +release = isempty(VERSION.prerelease) +file = release ? "julia-$(VERSION).pdf" : + "julia-$(VERSION.major).$(VERSION.minor).$(VERSION.patch)-$(first(VERSION.prerelease)).pdf" +url = "https://raw.githubusercontent.com/JuliaLang/docs.julialang.org/assets/$(file)" +import Markdown +Markdown.parse(""" +!!! note + The documentation is also available in PDF format: [$file]($url). +""") +``` + ### [Introduction](@id man-introduction) Scientific computing has traditionally required the highest performance, yet domain experts have diff --git a/doc/src/manual/code-loading.md b/doc/src/manual/code-loading.md index e88dbdc5bda2e..7e2652aa90a82 100644 --- a/doc/src/manual/code-loading.md +++ b/doc/src/manual/code-loading.md @@ -1,66 +1,71 @@ # Code Loading -Julia has two mechanisms for loading code: +!!! note + This chapter covers the technical details of package loading. To install packages, use [`Pkg`](@ref Pkg), Julia's built-in package manager, to add packages to your active environment. To use packages already in your active environment, write `import X` or `using X`, as described in the [Modules documentation](@ref modules). -1. **Code inclusion:** e.g. `include("source.jl")`. Inclusion allows you to split a single program across multiple source files. The expression `include("source.jl")` causes the contents of the file `source.jl` to be evaluated in the global scope of the module where the `include` call occurs. If `include("source.jl")` is called multiple times, `source.jl` is evaluated multiple times. The included path, `source.jl`, is interpreted relative to the file where the `include` call occurs. This makes it simple to relocate a subtree of source files. In the REPL, included paths are interpreted relative to the current working directory, `pwd()`. -2. **Package loading:** e.g. `import X` or `using X`. The import mechanism allows you to load a package—i.e. an independent, reusable collection of Julia code, wrapped in a module—and makes the resulting module available by the name `X` inside of the importing module. If the same `X` package is imported multiple times in the same Julia session, it is only loaded the first time—on subsequent imports, the importing module gets a reference to the same module. Note though, that `import X` can load different packages in different contexts: `X` can refer to one package named `X` in the main project but potentially different packages named `X` in each dependency. More on this below. +## Definitions -Code inclusion is quite straightforward: it simply parses and evaluates a source file in the context of the caller. Package loading is built on top of code inclusion and is a lot more complex. Therefore, the rest of this chapter focuses on the behavior and mechanics of package loading. +Julia has two mechanisms for loading code: -!!! note - You only need to read this chapter if you want to understand the technical details of package loading. If you just want to install and use packages, simply use Julia's built-in package manager to add packages to your environment and write `import X` or `using X` in your code to load packages that you've added. +1. **Code inclusion:** e.g. `include("source.jl")`. Inclusion allows you to split a single program across multiple source files. The expression `include("source.jl")` causes the contents of the file `source.jl` to be evaluated in the global scope of the module where the `include` call occurs. If `include("source.jl")` is called multiple times, `source.jl` is evaluated multiple times. The included path, `source.jl`, is interpreted relative to the file where the `include` call occurs. This makes it simple to relocate a subtree of source files. In the REPL, included paths are interpreted relative to the current working directory, [`pwd()`](@ref). +2. **Package loading:** e.g. `import X` or `using X`. The import mechanism allows you to load a package—i.e. an independent, reusable collection of Julia code, wrapped in a module—and makes the resulting module available by the name `X` inside of the importing module. If the same `X` package is imported multiple times in the same Julia session, it is only loaded the first time—on subsequent imports, the importing module gets a reference to the same module. Note though, that `import X` can load different packages in different contexts: `X` can refer to one package named `X` in the main project but potentially to different packages also named `X` in each dependency. More on this below. -A *package* is a source tree with a standard layout providing functionality that can be reused by other Julia projects. A package is loaded by `import X` or `using X` statements. These statements also make the module named `X`, which results from loading the package code, available within the module where the import statement occurs. The meaning of `X` in `import X` is context-dependent: which `X` package is loaded depends on what code the statement occurs in. The effect of `import X` depends on two questions: +Code inclusion is quite straightforward and simple: it evaluates the given source file in the context of the caller. Package loading is built on top of code inclusion and serves a [different purpose](@ref modules). The rest of this chapter focuses on the behavior and mechanics of package loading. -1. **What** package is `X` in this context? -2. **Where** can that `X` package be found? +A *package* is a source tree with a standard layout providing functionality that can be reused by other Julia projects. A package is loaded by `import X` or `using X` statements. These statements also make the module named `X`—which results from loading the package code—available within the module where the import statement occurs. The meaning of `X` in `import X` is context-dependent: which `X` package is loaded depends on what code the statement occurs in. Thus, handling of `import X` happens in two stages: first, it determines **what** package is defined to be `X` in this context; second, it determines **where** that particular `X` package is found. + +These questions are answered by searching through the project environments listed in [`LOAD_PATH`](@ref) for project files (`Project.toml` or `JuliaProject.toml`), manifest files (`Manifest.toml` or `JuliaManifest.toml`), or folders of source files. -Understanding how Julia answers these questions is key to understanding package loading. ## Federation of packages -Julia supports federated management of packages. This means that multiple independent parties can maintain both public and private packages and registries of them, and that projects can depend on a mix of public and private packages from different registries. Packages from various registries are installed and managed using a common set of tools and workflows. The `Pkg` package manager ships with Julia 0.7/1.0 and lets you install and manage your projects' dependencies. It does this by creating and manipulating project files that describe what your project depends on, and manifest files that snapshot exact versions of your project's complete dependency graph. +Most of the time, a package is uniquely identifiable simply from its name. However, sometimes a project might encounter a situation where it needs to use two different packages that share the same name. While you might be able fix this by renaming one of the packages, being forced to do so can be highly disruptive in a large, shared code base. Instead, Julia's code loading mechanism allows the same package name to refer to different packages in different components of an application. + +Julia supports federated package management, which means that multiple independent parties can maintain both public and private packages and registries of packages, and that projects can depend on a mix of public and private packages from different registries. Packages from various registries are installed and managed using a common set of tools and workflows. The `Pkg` package manager that ships with Julia lets you install and manage your projects' dependencies. It assists in creating and manipulating project files (which describe what other projects that your project depends on), and manifest files (which snapshot exact versions of your project's complete dependency graph). -One consequence of federation is that there cannot be a central authority for package naming. Different entities may use the same name to refer to unrelated packages. This possibility is unavoidable since these entities do not coordinate and may not even know about each other. Because of the lack of a central naming authority, a single project can quite possibly end up depending on different packages that have the same name. Julia's package loading mechanism handles this by not requiring package names to be globally unique, even within the dependency graph of a single project. Instead, packages are identified by [universally unique identifiers](https://en.wikipedia.org/wiki/Universally_unique_identifier) (UUIDs) which are assigned to them before they are registered. The question *"what is `X`?"* is answered by determining the UUID of `X`. +One consequence of federation is that there cannot be a central authority for package naming. Different entities may use the same name to refer to unrelated packages. This possibility is unavoidable since these entities do not coordinate and may not even know about each other. Because of the lack of a central naming authority, a single project may end up depending on different packages that have the same name. Julia's package loading mechanism does not require package names to be globally unique, even within the dependency graph of a single project. Instead, packages are identified by [universally unique identifiers](https://en.wikipedia.org/wiki/Universally_unique_identifier) (UUIDs), which get assigned when each package is created. Usually you won't have to work directly with these somewhat cumbersome 128-bit identifiers since `Pkg` will take care of generating and tracking them for you. However, these UUIDs provide the definitive answer to the question of *"what package does `X` refer to?"* -Since the decentralized naming problem is somewhat abstract, it may help to walk through a concrete scenario to understand the issue. Suppose you're developing an application called `App`, which uses two packages: `Pub` and `Priv`. `Priv` is a private package that you created, whereas `Pub` is a public package that you use but don't control. When you created `Priv`, there was no public package by that name. Subsequently, however, an unrelated package also named `Priv` has been published and become popular. In fact, the `Pub` package has started to use it. Therefore, when you next upgrade `Pub` to get the latest bug fixes and features, `App` will end up—through no action of yours other than upgrading—depending on two different packages named `Priv`. `App` has a direct dependency on your private `Priv` package, and an indirect dependency, through `Pub`, on the new public `Priv` package. Since these two `Priv` packages are different but both required for `App` to continue working correctly, the expression `import Priv` must refer to different `Priv` packages depending on whether it occurs in `App`'s code or in `Pub`'s code. Julia's package loading mechanism allows this by distinguishing the two `Priv` packages by context and UUID. How this distinction works is determined by environments, as explained in the following sections. +Since the decentralized naming problem is somewhat abstract, it may help to walk through a concrete scenario to understand the issue. Suppose you're developing an application called `App`, which uses two packages: `Pub` and `Priv`. `Priv` is a private package that you created, whereas `Pub` is a public package that you use but don't control. When you created `Priv`, there was no public package by the name `Priv`. Subsequently, however, an unrelated package also named `Priv` has been published and become popular. In fact, the `Pub` package has started to use it. Therefore, when you next upgrade `Pub` to get the latest bug fixes and features, `App` will end up depending on two different packages named `Priv`—through no action of yours other than upgrading. `App` has a direct dependency on your private `Priv` package, and an indirect dependency, through `Pub`, on the new public `Priv` package. Since these two `Priv` packages are different but are both required for `App` to continue working correctly, the expression `import Priv` must refer to different `Priv` packages depending on whether it occurs in `App`'s code or in `Pub`'s code. To handle this, Julia's package loading mechanism distinguishes the two `Priv` packages by their UUID and picks the correct one based on its context (the module that called `import`). How this distinction works is determined by environments, as explained in the following sections. ## Environments -An *environment* determines what `import X` and `using X` mean in various code contexts and what files these statements cause to be loaded. Julia understands three kinds of environments: +An *environment* determines what `import X` and `using X` mean in various code contexts and what files these statements cause to be loaded. Julia understands two kinds of environments: + +1. **A project environment** is a directory with a project file and an optional manifest file, and forms an *explicit environement*. The project file determines what the names and identities of the direct dependencies of a project are. The manifest file, if present, gives a complete dependency graph, including all direct and indirect dependencies, exact versions of each dependency, and sufficient information to locate and load the correct version. +2. **A package directory** is a directory containing the source trees of a set of packages as subdirectories, and forms an *implicit environment*. If `X` is a subdirectory of a package directory and `X/src/X.jl` exists, then the package `X` is available in the package directory environment and `X/src/X.jl` is the source file by which it is loaded. -1. **A project environment** is a directory with a project file and an optional manifest file. The project file determines what the names and identities of the direct dependencies of a project are. The manifest file, if present, gives a complete dependency graph, including all direct and indirect dependencies, exact versions of each dependency, and sufficient information to locate and load the correct version. -2. **A package directory** is a directory containing the source trees of a set of packages as subdirectories. This kind of environment was the only kind that existed in Julia 0.6 and earlier. If `X` is a subdirectory of a package directory and `X/src/X.jl` exists, then the package `X` is available in the package directory environment and `X/src/X.jl` is the source file by which it is loaded. -3. **A stacked environment** is an ordered set of project environments and package directories, overlaid to make a single composite environment in which all the packages available in its constituent environments are available. Julia's load path is a stacked environment, for example. +These can be intermixed to create **a stacked environment**: an ordered set of project environments and package directories, overlaid to make a single composite environment. The precedence and visibility rules then combine to determine which packages are available and where they get loaded from. Julia's load path forms a stacked environment, for example. -These three kinds of environment each serve a different purpose: +These environment each serve a different purpose: -* Project environments provide **reproducibility.** By checking a project environment into version control—e.g. a git repository—along with the rest of the project's source code, you can reproduce the exact state of the project _and_ all of its dependencies since the manifest file captures the exact version of every dependency. -* Package directories provide low-overhead **convenience** when a project environment isn't needed. Package directories are handy when you have a set of packages that you just want to put somewhere and use them as they are, without having to create and maintain a project environment for them. -* Stacked environments allow for **augmentation** of the primary environment with additional tools. You can push an environment including development tools onto the stack and they will be available from the REPL and scripts but not from inside packages. +* Project environments provide **reproducibility**. By checking a project environment into version control—e.g. a git repository—along with the rest of the project's source code, you can reproduce the exact state of the project and all of its dependencies. The manifest file, in particular, captures the exact version of every dependency, identified by a cryptographic hash of its source tree, which makes it possible for `Pkg` to retrieve the correct versions and be sure that you are running the exact code that was recorded for all dependencies. +* Package directories provide **convenience** when a full carefully-tracked project environment is unnecessary. They are useful when you want to put a set of packages somewhere and be able to directly use them, without needing to create a project environment for them. +* Stacked environments allow for **adding** tools to the primary environment. You can push an environment of development tools onto the end of the stack to make them available from the REPL and scripts, but not from inside packages. -As an abstraction, an environment provides three maps: `roots`, `graph` and `paths`. When resolving the meaning of `import X`, `roots` and `graph` are used to determine the identity of `X` and answer the question *"what is `X`?"*, while the `paths` map is used to locate the source code of `X` and answer the question *"where is `X`?"* The specific roles of the three maps are: +At a high-level, each environment conceptually defines three maps: roots, graph and paths. When resolving the meaning of `import X`, the roots and graph maps are used to determine the identity of `X`, while the paths map is used to locate the source code of `X`. The specific roles of the three maps are: - **roots:** `name::Symbol` ⟶ `uuid::UUID` - An environment's `roots` map assigns package names to UUIDs for all the top-level dependencies that the environment makes available to the main project (i.e. the ones that can be loaded in `Main`). When Julia encounters `import X` in the main project, it looks up the identity of `X` as `roots[:X]`. + An environment's roots map assigns package names to UUIDs for all the top-level dependencies that the environment makes available to the main project (i.e. the ones that can be loaded in `Main`). When Julia encounters `import X` in the main project, it looks up the identity of `X` as `roots[:X]`. - **graph:** `context::UUID` ⟶ `name::Symbol` ⟶ `uuid::UUID` - An environment's `graph` is a multilevel map which assigns, for each `context` UUID, a map from names to UUIDs, similar to the `roots` map but specific to that `context`. When Julia sees `import X` in the code of the package whose UUID is `context`, it looks up the identity of `X` as `graph[context][:X]`. In particular, this means that `import X` can refer to different packages depending on `context`. + An environment's graph is a multilevel map which assigns, for each `context` UUID, a map from names to UUIDs, similar to the roots map but specific to that `context`. When Julia sees `import X` in the code of the package whose UUID is `context`, it looks up the identity of `X` as `graph[context][:X]`. In particular, this means that `import X` can refer to different packages depending on `context`. - **paths:** `uuid::UUID` × `name::Symbol` ⟶ `path::String` - The `paths` map assigns to each package UUID-name pair, the location of that package's entry-point source file. After the identity of `X` in `import X` has been resolved to a UUID via `roots` or `graph` (depending on whether it is loaded from the main project or a dependency), Julia determines what file to load to acquire `X` by looking up `paths[uuid,:X]` in the environment. Including this file should create a module named `X`. Once this package is loaded, i.e. after its first import, any subsequent import resolving to the same `uuid` will simply create a new binding to the original already-loaded package module. + The paths map assigns to each package UUID-name pair, the location of that package's entry-point source file. After the identity of `X` in `import X` has been resolved to a UUID via roots or graph (depending on whether it is loaded from the main project or a dependency), Julia determines what file to load to acquire `X` by looking up `paths[uuid,:X]` in the environment. Including this file should define a module named `X`. Once this package is loaded, any subsequent import resolving to the same `uuid` will create a new binding to the already-loaded package module. Each kind of environment defines these three maps differently, as detailed in the following sections. !!! note - For ease of understanding, the examples throughout this chapter show full data structures for `roots`, `graph` and `paths`. However, for efficiency, Julia's package loading code does not actually create them. Instead, it queries them through internal APIs and lazily computes only as much of each structure as it needs to load a given package. + For ease of understanding, the examples throughout this chapter show full data structures for roots, graph and paths. However, Julia's package loading code does not explicitly create these. Instead, it lazily computes only as much of each structure as it needs to load a given package. ### Project environments -A project environment is determined by a directory containing a project file called `Project.toml`, and optionally a manifest file called `Manifest.toml`. These files may also be called `JuliaProject.toml` and `JuliaManifest.toml`, in which case `Project.toml` and `Manifest.toml` are ignored. (This allows for coexistence with other tools that might consider files called `Project.toml` and `Manifest.toml` significant.) For pure Julia projects, however, the names `Project.toml` and `Manifest.toml` are preferred. The `roots`, `graph` and `paths` maps of a project environment are defined as follows. +A project environment is determined by a directory containing a project file called `Project.toml`, and optionally a manifest file called `Manifest.toml`. These files may also be called `JuliaProject.toml` and `JuliaManifest.toml`, in which case `Project.toml` and `Manifest.toml` are ignored. This allows for coexistence with other tools that might consider files called `Project.toml` and `Manifest.toml` significant. For pure Julia projects, however, the names `Project.toml` and `Manifest.toml` are preferred. + +The roots, graph and paths maps of a project environment are defined as follows: **The roots map** of the environment is determined by the contents of the project file, specifically, its top-level `name` and `uuid` entries and its `[deps]` section (all optional). Consider the following example project file for the hypothetical application, `App`, as described earlier: @@ -73,7 +78,7 @@ Priv = "ba13f791-ae1d-465a-978b-69c3ad90f72b" Pub = "c07ecb7d-0dc9-4db7-8803-fadaaeaf08e1" ``` -This project file implies the following `roots` map, if it was represented by a Julia dictionary: +This project file implies the following roots map, if it was represented by a Julia dictionary: ```julia roots = Dict( @@ -83,9 +88,9 @@ roots = Dict( ) ``` -Given this `roots` map, in `App`'s code the statement `import Priv` will cause Julia to look up `roots[:Priv]`, which yields `ba13f791-ae1d-465a-978b-69c3ad90f72b`, the UUID of the `Priv` package that is to be loaded in that context. This UUID identifies which `Priv` package to load and use when the main application evaluates `import Priv`. +Given this roots map, in `App`'s code the statement `import Priv` will cause Julia to look up `roots[:Priv]`, which yields `ba13f791-ae1d-465a-978b-69c3ad90f72b`, the UUID of the `Priv` package that is to be loaded in that context. This UUID identifies which `Priv` package to load and use when the main application evaluates `import Priv`. -**The dependency graph** of a project environment is determined by the contents of the manifest file, if present. If there is no manifest file, `graph` is empty. A manifest file contains a stanza for each of a project's direct or indirect dependencies, including for each one, its UUID and a source tree hash or an explicit path to the source code. Consider the following example manifest file for `App`: +**The dependency graph** of a project environment is determined by the contents of the manifest file, if present. If there is no manifest file, graph is empty. A manifest file contains a stanza for each of a project's direct or indirect dependencies. For each dependency, the file lists the package's UUID and a source tree hash or an explicit path to the source code. Consider the following example manifest file for `App`: ```toml [[Priv]] # the private one @@ -115,29 +120,30 @@ version = "3.4.2" This manifest file describes a possible complete dependency graph for the `App` project: -- There are two different `Priv` packages that the application needs—a private one which is a direct dependency and a public one which is an indirect dependency through `Pub`: +- There are two different packages named `Priv` that the application uses. It uses a private package, which is a root dependency, and a public one, which is an indirect dependency through `Pub`. These are differentiated by their distinct UUIDs, and they have different deps: * The private `Priv` depends on the `Pub` and `Zebra` packages. * The public `Priv` has no dependencies. -- The application also depends on the `Pub` package, which in turn depends on the public `Priv ` and the same `Zebra` package which the private `Priv` package depends on. +- The application also depends on the `Pub` package, which in turn depends on the public `Priv ` and the same `Zebra` package that the private `Priv` package depends on. + -This dependency `graph` represented as a dictionary, looks like this: +This dependency graph represented as a dictionary, looks like this: ```julia -graph = Dict{UUID,Dict{Symbol,UUID}}( +graph = Dict( # Priv – the private one: - UUID("ba13f791-ae1d-465a-978b-69c3ad90f72b") => Dict{Symbol,UUID}( + UUID("ba13f791-ae1d-465a-978b-69c3ad90f72b") => Dict( :Pub => UUID("c07ecb7d-0dc9-4db7-8803-fadaaeaf08e1"), :Zebra => UUID("f7a24cb4-21fc-4002-ac70-f0e3a0dd3f62"), ), # Priv – the public one: - UUID("2d15fe94-a1f7-436c-a4d8-07a9a496e01c") => Dict{Symbol,UUID}(), + UUID("2d15fe94-a1f7-436c-a4d8-07a9a496e01c") => Dict(), # Pub: - UUID("c07ecb7d-0dc9-4db7-8803-fadaaeaf08e1") => Dict{Symbol,UUID}( + UUID("c07ecb7d-0dc9-4db7-8803-fadaaeaf08e1") => Dict( :Priv => UUID("2d15fe94-a1f7-436c-a4d8-07a9a496e01c"), :Zebra => UUID("f7a24cb4-21fc-4002-ac70-f0e3a0dd3f62"), ), # Zebra: - UUID("f7a24cb4-21fc-4002-ac70-f0e3a0dd3f62") => Dict{Symbol,UUID}(), + UUID("f7a24cb4-21fc-4002-ac70-f0e3a0dd3f62") => Dict(), ) ``` @@ -151,26 +157,32 @@ and gets `2d15fe94-a1f7-436c-a4d8-07a9a496e01c`, which indicates that in the con What happens if `import Zebra` is evaluated in the main `App` code base? Since `Zebra` does not appear in the project file, the import will fail even though `Zebra` *does* appear in the manifest file. Moreover, if `import Zebra` occurs in the public `Priv` package—the one with UUID `2d15fe94-a1f7-436c-a4d8-07a9a496e01c`—then that would also fail since that `Priv` package has no declared dependencies in the manifest file and therefore cannot load any packages. The `Zebra` package can only be loaded by packages for which it appear as an explicit dependency in the manifest file: the `Pub` package and one of the `Priv` packages. -**The paths map** of a project environment is also determined by the manifest file if present and is empty if there is no manifest. The path of a package `uuid` named `X` is determined by these two rules: +**The paths map** of a project environment is extracted from the manifest file. The path of a package `uuid` named `X` is determined by these rules (in order): -1. If the manifest stanza matching `uuid` has a `path` entry, use that path relative to the manifest file. -2. Otherwise, if the manifest stanza matching `uuid` has a `git-tree-sha1` entry, compute a deterministic hash function of `uuid` and `git-tree-sha1`—call it `slug`—and look for `packages/X/$slug` in each directory in the Julia `DEPOT_PATH` global array. Use the first such directory that exists. +1. If the project file in the directory matches `uuid` and name `X`, then either: + - It has a toplevel `path` entry, then `uuid` will be mapped to that path, interpreted relative to the directory containing the project file. + - Otherwise, `uuid` is mapped to `src/X.jl` relative to the directory containing the project file. +2. If the above is not the case and the project file has a corresponding manifest file and the manifest contains a stanza matching `uuid` then: + - If it has a `path` entry, use that path (relative to the directory containing the manifest file). + - If it has a `git-tree-sha1` entry, compute a deterministic hash function of `uuid` and `git-tree-sha1`—call it `slug`—and look for a directory named `packages/X/$slug` in each directory in the Julia `DEPOT_PATH` global array. Use the first such directory that exists. -If applying these rules doesn't find a loadable path, the package should be considered not installed and the system should raise an error or prompt the user to install the appropriate package version. +If any of these result in success, the path to the source code entry point will be either that result, the relative path from that result plus `src/X.jl`; otherwise, there is no path mapping for `uuid`. When loading `X`, if no source code path is found, the lookup will fail, and the user may be prompted to install the appropriate package version or to take other corrective action (e.g. declaring `X` as a dependency). In the example manifest file above, to find the path of the first `Priv` package—the one with UUID `ba13f791-ae1d-465a-978b-69c3ad90f72b`—Julia looks for its stanza in the manifest file, sees that it has a `path` entry, looks at `deps/Priv` relative to the `App` project directory—let's suppose the `App` code lives in `/home/me/projects/App`—sees that `/home/me/projects/App/deps/Priv` exists and therefore loads `Priv` from there. -If, on the other hand, Julia was loading the *other* `Priv` package—the one with UUID `2d15fe94-a1f7-436c-a4d8-07a9a496e01c`—it finds its stanza in the manifest, see that it does *not* have a `path` entry, but that it does have a `git-tree-sha1` entry. It then computes the `slug` for this UUID/SHA-1 pair, which is `HDkr` (the exact details of this computation aren't important, but it is consistent and deterministic). This means that the path to this `Priv` package will be `packages/Priv/HDkr/src/Priv.jl` in one of the package depots. Suppose the contents of `DEPOT_PATH` is `["/home/me/.julia", "/usr/local/julia"]`; then Julia will look at the following paths to see if they exist: +If, on the other hand, Julia was loading the *other* `Priv` package—the one with UUID `2d15fe94-a1f7-436c-a4d8-07a9a496e01c`—it finds its stanza in the manifest, see that it does *not* have a `path` entry, but that it does have a `git-tree-sha1` entry. It then computes the `slug` for this UUID/SHA-1 pair, which is `HDkrT` (the exact details of this computation aren't important, but it is consistent and deterministic). This means that the path to this `Priv` package will be `packages/Priv/HDkrT/src/Priv.jl` in one of the package depots. Suppose the contents of `DEPOT_PATH` is `["/home/me/.julia", "/usr/local/julia"]`, then Julia will look at the following paths to see if they exist: -1. `/home/me/.julia/packages/Priv/HDkr/src/Priv.jl` -2. `/usr/local/julia/packages/Priv/HDkr/src/Priv.jl` +1. `/home/me/.julia/packages/Priv/HDkrT` +2. `/usr/local/julia/packages/Priv/HDkrT` -Julia uses the first of these that exists to load the public `Priv` package. +Julia uses the first of these that exists to try to load the public `Priv` package from the file `packages/Priv/HDKrT/src/Priv.jl` in the depot where it was found. -Here is a representation of the `paths` map for the `App` project environment: +Here is a representation of a possible paths map for our example `App` project environment, +as provided in the Manifest given above for the dependency graph, +after searching the local file system: ```julia -paths = Dict{Tuple{UUID,Symbol},String}( +paths = Dict( # Priv – the private one: (UUID("ba13f791-ae1d-465a-978b-69c3ad90f72b"), :Priv) => # relative entry-point inside `App` repo: @@ -190,26 +202,37 @@ paths = Dict{Tuple{UUID,Symbol},String}( ) ``` -This example map includes three different kinds of package locations: +This example map includes three different kinds of package locations (the first and third are part of the default load path): 1. The private `Priv` package is "[vendored](https://stackoverflow.com/a/35109534/659248)" inside the `App` repository. 2. The public `Priv` and `Zebra` packages are in the system depot, where packages installed and managed by the system administrator live. These are available to all users on the system. 3. The `Pub` package is in the user depot, where packages installed by the user live. These are only available to the user who installed them. + ### Package directories -Package directories provide a kind of environment that approximates package loading in Julia 0.6 and earlier, and which resembles package loading in many other dynamic languages. The set of packages available in a package directory corresponds to the set of subdirectories it contains that look like packages: if `X/src/X.jl` is a file in a package directory, then `X` is considered to be a package and `X/src/X.jl` is the file Julia loads to get `X`. Which packages can "see" each other as dependencies depends on whether they contain project files, and if they do, on what appears in those project files' `[deps]` sections. +Package directories provide a simpler kind of environment without the ability to handle name collisions. In a package directory, the set of top-level packages is the set of subdirectories that "look like" packages. A package `X` is exists in a package directory if the directory contains one of the following "entry point" files: + +- `X.jl` +- `X/src/X.jl` +- `X.jl/src/X.jl` -**The roots map** is determined by the subdirectories `X` of a package directory for which `X/src/X.jl` exists and whether `X/Project.toml` exists and has a top-level `uuid` entry. Specifically `:X => uuid` goes in `roots` for each such `X` where `uuid` is defined as: +Which dependencies a package in a package directory can import depends on whether the package contains a project file: + +* If it has a project file, it can only import those packages which are identified in the `[deps]` section of the project file. +* If it does not have a project file, it can import any top-level package—i.e. the same packages that can be loaded in `Main` or the REPL. + +**The roots map** is determined by examining the contents of the package directory to generate a list of all packages that exist. +Additionally, a UUID will be assigned to each entry as follows: For a given package found inside the folder `X`... 1. If `X/Project.toml` exists and has a `uuid` entry, then `uuid` is that value. -2. If `X/Project.toml` exists and but does *not* have a top-level UUID entry, `uuid` is a dummy UUID generated by hashing the canonical path of `X/Project.toml`. -3. If `X/Project.toml` does not exist, then `uuid` is the all-zero [nil UUID](https://en.wikipedia.org/wiki/Universally_unique_identifier#Nil_UUID). +2. If `X/Project.toml` exists and but does *not* have a top-level UUID entry, `uuid` is a dummy UUID generated by hashing the canonical (real) path to `X/Project.toml`. +3. Otherwise (if `Project.toml` does not exist), then `uuid` is the all-zero [nil UUID](https://en.wikipedia.org/wiki/Universally_unique_identifier#Nil_UUID). **The dependency graph** of a project directory is determined by the presence and contents of project files in the subdirectory of each package. The rules are: -- If a package subdirectory has no project file, then it is omitted from `graph` and import statements in its code are treated as top-level, the same as the main project and REPL. -- If a package subdirectory has a project file, then the `graph` entry for its UUID is the `[deps]` map of the project file, which is considered to be empty if the section is absent. +- If a package subdirectory has no project file, then it is omitted from graph and import statements in its code are treated as top-level, the same as the main project and REPL. +- If a package subdirectory has a project file, then the graph entry for its UUID is the `[deps]` map of the project file, which is considered to be empty if the section is absent. As an example, suppose a package directory has the following structure and content: @@ -246,10 +269,10 @@ Dingo/ # no imports ``` -Here is a corresponding `roots` structure, represented as a dictionary: +Here is a corresponding roots structure, represented as a dictionary: ```julia -roots = Dict{Symbol,UUID}( +roots = Dict( :Aardvark => UUID("00000000-0000-0000-0000-000000000000"), # no project file, nil UUID :Bobcat => UUID("85ad11c7-31f6-5d08-84db-0a4914d4cadf"), # dummy UUID based on path :Cobra => UUID("4725e24d-f727-424b-bca0-c4307a3456fa"), # UUID from project file @@ -257,21 +280,21 @@ roots = Dict{Symbol,UUID}( ) ``` -Here is the corresponding `graph` structure, represented as a dictionary: +Here is the corresponding graph structure, represented as a dictionary: ```julia -graph = Dict{UUID,Dict{Symbol,UUID}}( +graph = Dict( # Bobcat: - UUID("85ad11c7-31f6-5d08-84db-0a4914d4cadf") => Dict{Symbol,UUID}( + UUID("85ad11c7-31f6-5d08-84db-0a4914d4cadf") => Dict( :Cobra => UUID("4725e24d-f727-424b-bca0-c4307a3456fa"), :Dingo => UUID("7a7925be-828c-4418-bbeb-bac8dfc843bc"), ), # Cobra: - UUID("4725e24d-f727-424b-bca0-c4307a3456fa") => Dict{Symbol,UUID}( + UUID("4725e24d-f727-424b-bca0-c4307a3456fa") => Dict( :Dingo => UUID("7a7925be-828c-4418-bbeb-bac8dfc843bc"), ), # Dingo: - UUID("7a7925be-828c-4418-bbeb-bac8dfc843bc") => Dict{Symbol,UUID}(), + UUID("7a7925be-828c-4418-bbeb-bac8dfc843bc") => Dict(), ) ``` @@ -293,7 +316,7 @@ Observe the following specific instances of these rules in our example: **The paths map** in a package directory is simple: it maps subdirectory names to their corresponding entry-point paths. In other words, if the path to our example project directory is `/home/me/animals` then the `paths` map could be represented by this dictionary: ```julia -paths = Dict{Tuple{UUID,Symbol},String}( +paths = Dict( (UUID("00000000-0000-0000-0000-000000000000"), :Aardvark) => "/home/me/AnimalPackages/Aardvark/src/Aardvark.jl", (UUID("85ad11c7-31f6-5d08-84db-0a4914d4cadf"), :Bobcat) => @@ -309,9 +332,9 @@ Since all packages in a package directory environment are, by definition, subdir ### Environment stacks -The third and final kind of environment is one that combines other environments by overlaying several of them, making the packages in each available in a single composite environment. These composite environments are called *environment stacks*. The Julia `LOAD_PATH` global defines an environment stack—the environment in which the Julia process operates. If you want your Julia process to have access only to the packages in one project or package directory, make it the only entry in `LOAD_PATH`. It is often quite useful, however, to have access to some of your favorite tools—standard libraries, profilers, debuggers, personal utilities, etc.—even if they are not dependencies of the project you're working on. By pushing an environment containing these tools onto the load path, you immediately have access to them in top-level code without needing to add them to your project. +The third and final kind of environment is one that combines other environments by overlaying several of them, making the packages in each available in a single composite environment. These composite environments are called *environment stacks*. The Julia `LOAD_PATH` global defines an environment stack—the environment in which the Julia process operates. If you want your Julia process to have access only to the packages in one project or package directory, make it the only entry in `LOAD_PATH`. It is often quite useful, however, to have access to some of your favorite tools—standard libraries, profilers, debuggers, personal utilities, etc.—even if they are not dependencies of the project you're working on. By adding an environment containing these tools to the load path, you immediately have access to them in top-level code without needing to add them to your project. -The mechanism for combining the `roots`, `graph` and `paths` data structures of the components of an environment stack is simple: they are simply merged as dictionaries, favoring earlier entries over later ones in the case of key collisions. In other words, if we have `stack = [env₁, env₂, …]` then we have: +The mechanism for combining the roots, graph and paths data structures of the components of an environment stack is simple: they are merged as dictionaries, favoring earlier entries over later ones in the case of key collisions. In other words, if we have `stack = [env₁, env₂, …]` then we have: ```julia roots = reduce(merge, reverse([roots₁, roots₂, …])) @@ -319,13 +342,13 @@ graph = reduce(merge, reverse([graph₁, graph₂, …])) paths = reduce(merge, reverse([paths₁, paths₂, …])) ``` -The subscripted `rootsᵢ`, `graphᵢ` and `pathsᵢ` variables correspond to the subscripted environments, `envᵢ`, contained `stack`. The `reverse` is present because `merge` favors the last argument rather than first when there are collisions between keys in its argument dictionaries. That's all there is to stacked environments. There are a couple of noteworthy features of this design: +The subscripted `rootsᵢ`, `graphᵢ` and `pathsᵢ` variables correspond to the subscripted environments, `envᵢ`, contained in `stack`. The `reverse` is present because `merge` favors the last argument rather than first when there are collisions between keys in its argument dictionaries. There are a couple of noteworthy features of this design: 1. The *primary environment*—i.e. the first environment in a stack—is faithfully embedded in a stacked environment. The full dependency graph of the first environment in a stack is guaranteed to be included intact in the stacked environment including the same versions of all dependencies. -2. Packages in non-primary environments can end up using incompatible versions of their dependencies even if their own environments are entirely compatible. This can happen when one of their dependencies is shadowed by a version in an earlier environment in the stack. +2. Packages in non-primary environments can end up using incompatible versions of their dependencies even if their own environments are entirely compatible. This can happen when one of their dependencies is shadowed by a version in an earlier environment in the stack (either by graph or path, or both). -Since the primary environment is typically the environment of a project you're working on, while environments later in the stack contain additional tools, this is the right tradeoff: it's better to break your dev tools but keep the project working. When such incompatibilities occur, you'll typically want to upgrade your dev tools to versions that are compatible with the main project. +Since the primary environment is typically the environment of a project you're working on, while environments later in the stack contain additional tools, this is the right trade-off: it's better to break your development tools but keep the project working. When such incompatibilities occur, you'll typically want to upgrade your dev tools to versions that are compatible with the main project. ## Conclusion -Federated package management and precise software reproducibility are difficult but worthy goals in a package system. In combination, these goals lead to a more complex package loading mechanism than most dynamic languages have, but it also yields scalability and reproducibility that is more commonly associated with static languages. Fortunately, most Julia users can remain oblivious to the technical details of code loading and simply use the built-in package manager to add a package `X` to the appropriate project and manifest files and then write `import X` to load `X` without a further thought. +Federated package management and precise software reproducibility are difficult but worthy goals in a package system. In combination, these goals lead to a more complex package loading mechanism than most dynamic languages have, but it also yields scalability and reproducibility that is more commonly associated with static languages. Typically, Julia users should be able to use the built-in package manager to manage their projects without needing a precise understanding of these interactions. A call to `Pkg.add("X")` will add to the appropriate project and manifest files, selected via `Pkg.activate("Y")`, so that a future call to `import X` will load `X` without further thought. diff --git a/doc/src/manual/control-flow.md b/doc/src/manual/control-flow.md index 9de3b8206c8a7..6d4cf729d502d 100644 --- a/doc/src/manual/control-flow.md +++ b/doc/src/manual/control-flow.md @@ -794,7 +794,7 @@ The power of the `try/catch` construct lies in the ability to unwind a deeply ne immediately to a much higher level in the stack of calling functions. There are situations where no error has occurred, but the ability to unwind the stack and pass a value to a higher level is desirable. Julia provides the [`rethrow`](@ref), [`backtrace`](@ref), [`catch_backtrace`](@ref) -and [`catch_stack`](@ref) functions for more advanced error handling. +and [`Base.catch_stack`](@ref) functions for more advanced error handling. ### `finally` Clauses diff --git a/doc/src/manual/environment-variables.md b/doc/src/manual/environment-variables.md index d92260dd376ff..c410adce6e5dd 100644 --- a/doc/src/manual/environment-variables.md +++ b/doc/src/manual/environment-variables.md @@ -1,25 +1,26 @@ # Environment Variables -Julia may be configured with a number of environment variables, either in the -usual way of the operating system, or in a portable way from within Julia. -Suppose you want to set the environment variable `JULIA_EDITOR` to -`vim`, then either type `ENV["JULIA_EDITOR"] = "vim"` for instance in the REPL -to make this change on a case by case basis, or add the same to the user -configuration file `~/.julia/config/startup.jl` in the user's home directory to have -a permanent effect. The current value of the same environment variable is +Julia can be configured with a number of environment variables, set either in +the usual way for each operating system, or in a portable way from within Julia. +Supposing that you want to set the environment variable `JULIA_EDITOR` to `vim`, +you can type `ENV["JULIA_EDITOR"] = "vim"` (for instance, in the REPL) to make +this change on a case by case basis, or add the same to the user configuration +file `~/.julia/config/startup.jl` in the user's home directory to have a +permanent effect. The current value of the same environment variable can be determined by evaluating `ENV["JULIA_EDITOR"]`. The environment variables that Julia uses generally start with `JULIA`. If -[`InteractiveUtils.versioninfo`](@ref) is called with `verbose` equal to `true`, then the +[`InteractiveUtils.versioninfo`](@ref) is called with the keyword `verbose=true`, then the output will list defined environment variables relevant for Julia, including those for which `JULIA` appears in the name. !!! note - Some variables, such as `JULIA_NUM_THREADS` and `JULIA_PROJECT` need to be set before Julia + Some variables, such as `JULIA_NUM_THREADS` and `JULIA_PROJECT`, need to be set before Julia starts, therefore adding these to `~/.julia/config/startup.jl` is too late in the startup process. - These must either be set manually before launching Julia through bash with - `export JULIA_NUM_THREADS=4` etc. or added to `-/.bashrc` and/or `~/.bash_profile` to achieve persistence. + In Bash, environment variables can either be set manually by running, e.g., + `export JULIA_NUM_THREADS=4` before starting Julia, or by adding the same command to + `-/.bashrc` or `~/.bash_profile` to set the variable each time Bash is started. ## File locations @@ -76,7 +77,7 @@ and a global configuration search path of A directory path that points to the current Julia project. Setting this environment variable has the same effect as specifying the `--project` start-up -option, but `--project` has higher precedence. If the variable is set to `@.`, +option, but `--project` has higher precedence. If the variable is set to `@.` then Julia tries to find a project directory that contains `Project.toml` or `JuliaProject.toml` file from the current directory and its parents. See also the chapter on [Code Loading](@ref). @@ -88,8 +89,8 @@ the chapter on [Code Loading](@ref). ### `JULIA_LOAD_PATH` A separated list of absolute paths that are to be appended to the variable -[`LOAD_PATH`](@ref). (In Unix-like systems, the path separator is `:`; in -Windows systems, the path separator is `;`.) The `LOAD_PATH` variable is where +[`LOAD_PATH`](@ref). (In Unix-like systems, `:` is the path separator; in +Windows systems, `;` is the path separator.) The `LOAD_PATH` variable is where [`Base.require`](@ref) and `Base.load_in_path()` look for code; it defaults to the absolute path `$JULIA_HOME/../share/julia/stdlib/v$(VERSION.major).$(VERSION.minor)` so that, @@ -150,7 +151,7 @@ logical CPU cores available. ### `JULIA_WORKER_TIMEOUT` -A [`Float64`](@ref) that sets the value of `Base.worker_timeout()` (default: `60.0`). +A [`Float64`](@ref) that sets the value of `Distributed.worker_timeout()` (default: `60.0`). This function gives the number of seconds a worker process will wait for a master process to establish a connection before dying. @@ -185,7 +186,7 @@ affinitized. Otherwise, Julia lets the operating system handle thread policy. Environment variables that determine how REPL output should be formatted at the terminal. Generally, these variables should be set to [ANSI terminal escape sequences](http://ascii-table.com/ansi-escape-sequences.php). Julia provides -a high-level interface with much of the same functionality: see the section on +a high-level interface with much of the same functionality; see the section on [The Julia REPL](@ref). ### `JULIA_ERROR_COLOR` @@ -283,11 +284,10 @@ event listener for just-in-time (JIT) profiling. This environment variable only has an effect if Julia was compiled with JIT profiling support, using either - -* Intel's [VTune™ Amplifier](https://software.intel.com/en-us/intel-vtune-amplifier-xe) - (`USE_INTEL_JITEVENTS` set to `1` in the build configuration), or -* [OProfile](http://oprofile.sourceforge.net/news/) (`USE_OPROFILE_JITEVENTS` set to `1` - in the build configuration). + * Intel's [VTune™ Amplifier](https://software.intel.com/en-us/intel-vtune-amplifier-xe) + (`USE_INTEL_JITEVENTS` set to `1` in the build configuration), or + * [OProfile](http://oprofile.sourceforge.net/news/) (`USE_OPROFILE_JITEVENTS` set to `1` + in the build configuration). ### `JULIA_LLVM_ARGS` diff --git a/doc/src/manual/stacktraces.md b/doc/src/manual/stacktraces.md index 01a3417d33031..8deff082140f1 100644 --- a/doc/src/manual/stacktraces.md +++ b/doc/src/manual/stacktraces.md @@ -187,7 +187,7 @@ ERROR: Whoops! [...] ``` -## Exception stacks and [`catch_stack`](@ref) +## Exception stacks and `catch_stack` !!! compat "Julia 1.1" Exception stacks requires at least Julia 1.1. @@ -197,7 +197,7 @@ identify the root cause of a problem. The julia runtime supports this by pushing *exception stack* as it occurs. When the code exits a `catch` normally, any exceptions which were pushed onto the stack in the associated `try` are considered to be successfully handled and are removed from the stack. -The stack of current exceptions can be accessed using the [`catch_stack`](@ref) function. For example, +The stack of current exceptions can be accessed using the experimental [`Base.catch_stack`](@ref) function. For example, ```julia-repl julia> try @@ -206,7 +206,7 @@ julia> try try error("(B) An exception while handling the exception") catch - for (exc, bt) in catch_stack() + for (exc, bt) in Base.catch_stack() showerror(stdout, exc, bt) println() end diff --git a/doc/src/manual/workflow-tips.md b/doc/src/manual/workflow-tips.md index 8cae4cefb0635..cdc74a45a68ff 100644 --- a/doc/src/manual/workflow-tips.md +++ b/doc/src/manual/workflow-tips.md @@ -8,75 +8,59 @@ As already elaborated in [The Julia REPL](@ref), Julia's REPL provides rich func that facilitates an efficient interactive workflow. Here are some tips that might further enhance your experience at the command line. -## Command-line-based basic editor/REPL workflow +### A basic editor/REPL workflow The most basic Julia workflows involve using a text editor in conjunction with the `julia` command line. A common pattern includes the following elements: - * **Generate a new project** - - ``` - $ julia -e 'using Pkg;Pkg.generate("Tmp")' -Generating project Tmp: - Tmp/Project.toml - Tmp/src/Tmp.jl - $ ls -R Tmp -Tmp: -Project.toml src - -Tmp/src: -Tmp.jl - $ cat -n Tmp/src/Tmp.jl - 1 module Tmp - 2 - 3 greet() = print("Hello World!") - 4 - 5 end # module - ``` - - * **Create a test folder** - ``` - $ mkdir Tmp/test - ``` - * **Put your test code in `test/runtests.jl` file.** + * **Put code under development in a temporary module.** Create a file, say `Tmp.jl`, and include + within it + ```julia + module Tmp + export say_hello + + say_hello() = println("Hello!") + + # your other definitions here + + end ``` - $ cat -n Tmp/test/runtests.jl - 1 using Tmp - 2 Tmp.greet() + * **Put your test code in another file.** Create another file, say `tst.jl`, which looks like + + ```julia + include("Tmp.jl") + import .Tmp + # using .Tmp # we can use `using` to bring the exported symbols in `Tmp` into our namespace + + Tmp.say_hello() + # say_hello() + + # your other test code here ``` - * **Run test** - ``` - $ julia -e 'using Pkg;Pkg.activate("Tmp");Pkg.test()' - Updating registry at `~/.julia/registries/General` - Updating git-repo `https://github.com/JuliaRegistries/General.git` - Resolving package versions... - Updating `~/Tmp/Project.toml` - [no changes] - Testing Tmp - Resolving package versions... -Hello World! Testing Tmp tests passed - ``` - * **Lather. Rinse. Repeat.** Explore ideas at the `julia` command prompt. Save good ideas in `Tmp.jl` and test with `runtests.jl`. - -## Simplify initialization - -To simplify restarting the REPL, put project-specific initialization code in a file, say `_init.jl`, -which you can run on startup by issuing the command: - -``` -julia -L _init.jl -``` - -If you further add the following to your `~/.julia/config/startup.jl` file - -```julia -isfile("_init.jl") && include(joinpath(pwd(), "_init.jl")) -``` - -then calling `julia` from that directory will run the initialization code without the additional -command line argument. + and includes tests for the contents of `Tmp`. + Alternatively, you can wrap the contents of your test file in a module, as + + ```julia + module Tst + include("Tmp.jl") + import .Tmp + #using .Tmp + + Tmp.say_hello() + # say_hello() + + # your other test code here + end + ``` + + The advantage is that your testing code is now contained in a module and does not use the global scope in `Main` for + definitions, which is a bit more tidy. + + * `include` the `tst.jl` file in the Julia REPL with `include("tst.jl")`. + + * **Lather. Rinse. Repeat.** Explore ideas at the `julia` command prompt. Save good ideas in `tst.jl`. To execute `tst.jl` after it has been changed, just `include` it again. ## Browser-based workflow diff --git a/src/Makefile b/src/Makefile index d8e1c6a49b115..e4da8c6357e02 100644 --- a/src/Makefile +++ b/src/Makefile @@ -89,7 +89,17 @@ endif PUBLIC_HEADER_TARGETS := $(addprefix $(build_includedir)/julia/,$(notdir $(PUBLIC_HEADERS)) $(UV_HEADERS)) ifeq ($(JULIACODEGEN),LLVM) +ifneq ($(USE_SYSTEM_LLVM),0) LLVMLINK += $(shell $(LLVM_CONFIG_HOST) --ldflags --libs --system-libs) +# HACK: llvm-config doesn't correctly point to shared libs on all platforms +# https://github.com/JuliaLang/julia/issues/29981 +else +ifneq ($(USE_LLVM_SHLIB),1) +LLVMLINK += $(shell $(LLVM_CONFIG_HOST) --ldflags) $(shell $(LLVM_CONFIG_HOST) --libs $(LLVM_LIBS)) $(shell $(LLVM_CONFIG_HOST) --ldflags) $(shell $(LLVM_CONFIG_HOST) --system-libs 2> /dev/null) +else +LLVMLINK += $(shell $(LLVM_CONFIG_HOST) --ldflags) -lLLVM +endif +endif ifeq ($(USE_LLVM_SHLIB),1) FLAGS += -DLLVM_SHLIB endif # USE_LLVM_SHLIB == 1 diff --git a/src/cgutils.cpp b/src/cgutils.cpp index 946065c7e6273..33373416d7ebc 100644 --- a/src/cgutils.cpp +++ b/src/cgutils.cpp @@ -1425,10 +1425,10 @@ static bool emit_getfield_unknownidx(jl_codectx_t &ctx, Value *idx, jl_datatype_t *stt, jl_value_t *inbounds) { size_t nfields = jl_datatype_nfields(stt); + bool maybe_null = (unsigned)stt->ninitialized != nfields; if (strct.ispointer()) { // boxed or stack if (is_datatype_all_pointers(stt)) { idx = emit_bounds_check(ctx, strct, (jl_value_t*)stt, idx, ConstantInt::get(T_size, nfields), inbounds); - bool maybe_null = (unsigned)stt->ninitialized != nfields; size_t minimum_field_size = std::numeric_limits::max(); size_t minimum_align = JL_HEAP_ALIGNMENT; for (size_t i = 0; i < nfields; ++i) { @@ -1458,7 +1458,7 @@ static bool emit_getfield_unknownidx(jl_codectx_t &ctx, jl_value_t *jt = jl_field_type(stt, 0); idx = emit_bounds_check(ctx, strct, (jl_value_t*)stt, idx, ConstantInt::get(T_size, nfields), inbounds); Value *ptr = maybe_decay_tracked(data_pointer(ctx, strct)); - if (!stt->mutabl) { + if (!stt->mutabl && !(maybe_null && jt == (jl_value_t*)jl_bool_type)) { // just compute the pointer and let user load it when necessary Type *fty = julia_type_to_llvm(jt); Value *addr = ctx.builder.CreateInBoundsGEP(fty, emit_bitcast(ctx, ptr, PointerType::get(fty, 0)), idx); @@ -1512,6 +1512,7 @@ static jl_cgval_t emit_getfield_knownidx(jl_codectx_t &ctx, const jl_cgval_t &st if (type_is_ghost(elty)) return ghostValue(jfty); Value *fldv = NULL; + bool maybe_null = idx >= (unsigned)jt->ninitialized; if (strct.ispointer()) { Value *staddr = maybe_decay_tracked(data_pointer(ctx, strct)); bool isboxed; @@ -1553,7 +1554,6 @@ static jl_cgval_t emit_getfield_knownidx(jl_codectx_t &ctx, const jl_cgval_t &st } unsigned align = jl_field_align(jt, idx); if (jl_field_isptr(jt, idx)) { - bool maybe_null = idx >= (unsigned)jt->ninitialized; Instruction *Load = maybe_mark_load_dereferenceable( ctx.builder.CreateLoad(T_prjlvalue, emit_bitcast(ctx, addr, T_pprjlvalue)), maybe_null, jl_field_type(jt, idx)); @@ -1586,7 +1586,7 @@ static jl_cgval_t emit_getfield_knownidx(jl_codectx_t &ctx, const jl_cgval_t &st } return mark_julia_slot(addr, jfty, tindex, strct.tbaa); } - else if (!jt->mutabl) { + else if (!jt->mutabl && !(maybe_null && jfty == (jl_value_t*)jl_bool_type)) { // just compute the pointer and let user load it when necessary return mark_julia_slot(addr, jfty, NULL, strct.tbaa); } diff --git a/src/crc32c.c b/src/crc32c.c index f9100a22abe93..9ad1991d3c804 100644 --- a/src/crc32c.c +++ b/src/crc32c.c @@ -43,6 +43,7 @@ #include "julia.h" #include "julia_internal.h" +#include "processor.h" #ifdef _CPU_AARCH64_ # include @@ -333,7 +334,7 @@ JL_DLLEXPORT uint32_t jl_crc32c(uint32_t crc, const char *buf, size_t len) # else static crc32c_func_t crc32c_dispatch(unsigned long hwcap) { - if (hwcap & HWCAP_CRC32) + if (hwcap & (1 << JL_AArch64_crc)) return crc32c_armv8; return jl_crc32c_sw; } diff --git a/src/debuginfo.cpp b/src/debuginfo.cpp index 737508301776a..c092bbf458a93 100644 --- a/src/debuginfo.cpp +++ b/src/debuginfo.cpp @@ -1087,7 +1087,8 @@ static int jl_getDylibFunctionInfo(jl_frame_t **frames, size_t pointer, int skip for (size_t i = 0; i < sysimg_fptrs.nclones; i++) { if (diff == sysimg_fptrs.clone_offsets[i]) { uint32_t idx = sysimg_fptrs.clone_idxs[i] & jl_sysimg_val_mask; - frame0->linfo = sysimg_fvars_linfo[idx]; + if (idx < sysimg_fvars_n) // items after this were cloned but not referenced directly by a method (such as our ccall PLT thunks) + frame0->linfo = sysimg_fvars_linfo[idx]; break; } } diff --git a/src/gf.c b/src/gf.c index ae4a1413b7849..4c8ae077192c1 100644 --- a/src/gf.c +++ b/src/gf.c @@ -2421,6 +2421,12 @@ static int ml_matches_visitor(jl_typemap_entry_t *ml, struct typemap_intersectio closure->max_valid = ml->max_world; } } + // In some corner cases type intersection is conservative and returns something + // for intersect(A, B) even though A is a dispatch tuple and !(A <: B). + // For dispatch purposes in such a case we know there's no match. This check + // fixes issue #30394. + if (jl_is_dispatch_tupletype(closure->match.type) && !closure->match.issubty) + return 1; // a method is shadowed if type <: S <: m->sig where S is the // signature of another applicable method /* diff --git a/src/julia-parser.scm b/src/julia-parser.scm index 8cd3564f7869d..37e6a24dde122 100644 --- a/src/julia-parser.scm +++ b/src/julia-parser.scm @@ -8,7 +8,8 @@ ;; be an operator. (define prec-assignment (append! (add-dots '(= += -= *= /= //= |\\=| ^= ÷= %= <<= >>= >>>= |\|=| &= ⊻= ≔ ⩴ ≕)) - '(:= ~ $=))) + (add-dots '(~)) + '(:= $=))) ;; comma - higher than assignment outside parentheses, lower when inside (define prec-pair (add-dots '(=>))) (define prec-conditional '(?)) @@ -742,7 +743,7 @@ ex (begin (take-token s) - (cond ((eq? t '~) ;; ~ is the only non-syntactic assignment-precedence operators + (cond ((or (eq? t '~) (eq? t '|.~|)) ;; ~ is the only non-syntactic assignment-precedence operators (if (and space-sensitive (ts:space? s) (not (space-before-next-token? s))) (begin (ts:put-back! s t (ts:space? s)) diff --git a/src/processor_arm.cpp b/src/processor_arm.cpp index 000894fb05d7d..7b5fe0003bb56 100644 --- a/src/processor_arm.cpp +++ b/src/processor_arm.cpp @@ -522,8 +522,8 @@ static inline unsigned long jl_getauxval(unsigned long type) { // First, try resolving getauxval in libc auto libc = jl_dlopen(nullptr, JL_RTLD_LOCAL); - static (unsigned long (*)(unsigned long) getauxval_p; - if (jl_dlsym(libc, "getauxval", &getauxval_p, 0) { + static unsigned long (*getauxval_p)(unsigned long) = NULL; + if (getauxval_p == NULL && jl_dlsym(libc, "getauxval", (void **)&getauxval_p, 0)) { return getauxval_p(type); } diff --git a/src/runtime_intrinsics.c b/src/runtime_intrinsics.c index 22f8866f143a5..d43ae3d5ff9af 100644 --- a/src/runtime_intrinsics.c +++ b/src/runtime_intrinsics.c @@ -400,8 +400,6 @@ static inline jl_value_t *jl_intrinsic_cvt(jl_value_t *ty, jl_value_t *a, const void *pr = alloca(osize); unsigned isize_bits = isize * host_char_bit; unsigned osize_bits = osize * host_char_bit; - if (aty == (jl_value_t*)jl_bool_type) - isize_bits = 1; op(isize_bits, pa, osize_bits, pr); return jl_new_bits(ty, pr); } diff --git a/src/staticdata.c b/src/staticdata.c index 921abb4b770be..363e0d716c3bb 100644 --- a/src/staticdata.c +++ b/src/staticdata.c @@ -1016,6 +1016,7 @@ static void jl_update_all_fptrs(jl_serializer_state *s) for (i = 0; i < sysimg_fvars_max; i++) { uintptr_t val = (uintptr_t)&linfos[i]; uint32_t offset = load_uint32(&val); + linfos[i] = NULL; if (offset != 0) { int specfunc = 1; if (offset & ((uintptr_t)1 << (8 * sizeof(uint32_t) - 1))) { diff --git a/src/subtype.c b/src/subtype.c index 56ce9ee96258c..a6e7605fc25d5 100644 --- a/src/subtype.c +++ b/src/subtype.c @@ -322,26 +322,6 @@ static int obviously_disjoint(jl_value_t *a, jl_value_t *b, int specificity) for(i=0; i < np; i++) { jl_value_t *ai = jl_tparam(ad,i); jl_value_t *bi = jl_tparam(bd,i); - if (!istuple && specificity && jl_has_free_typevars(ai)) { - // X{<:SomeDataType} and X{Union{Y,Z,...}} need to be disjoint to - // avoid this transitivity problem: - // A = Tuple{Type{LinearIndices{N,R}}, LinearIndices{N}} where {N,R} - // B = Tuple{Type{T},T} where T<:AbstractArray - // C = Tuple{Type{Union{Nothing, T}}, Union{Nothing, T}} where T - // A is more specific than B. It would be easy to think B is more specific - // than C, but we can't have that since A should not be more specific than C. - jl_value_t *aub = jl_is_typevar(ai) ? ((jl_tvar_t*)ai)->ub : ai; - jl_value_t *bub = jl_is_typevar(bi) ? ((jl_tvar_t*)bi)->ub : bi; - aub = jl_unwrap_unionall(aub); - bub = jl_unwrap_unionall(bub); - if ((jl_is_typevar(ai) + jl_is_typevar(bi) < 2) && - aub != (jl_value_t*)jl_any_type && bub != (jl_value_t*)jl_any_type && - ((jl_is_uniontype(aub) && jl_is_datatype(bub) && !in_union(aub, bub) && - (jl_is_typevar(bi) || !jl_is_typevar(ai))) || - (jl_is_uniontype(bub) && jl_is_datatype(aub) && !in_union(bub, aub) && - (jl_is_typevar(ai) || !jl_is_typevar(bi))))) - return 1; - } if (jl_is_typevar(ai) || jl_is_typevar(bi)) continue; if (jl_is_type(ai)) { @@ -1333,12 +1313,17 @@ static jl_value_t *intersect_all(jl_value_t *x, jl_value_t *y, jl_stenv_t *e); // intersect in nested union environment, similar to subtype_ccheck static jl_value_t *intersect_aside(jl_value_t *x, jl_value_t *y, jl_stenv_t *e, int depth) { - jl_value_t *res; + // band-aid for #30335 + if (x == (jl_value_t*)jl_any_type && !jl_is_typevar(y)) + return y; + if (y == (jl_value_t*)jl_any_type && !jl_is_typevar(x)) + return x; + int savedepth = e->invdepth; jl_unionstate_t oldRunions = e->Runions; e->invdepth = depth; - res = intersect_all(x, y, e); + jl_value_t *res = intersect_all(x, y, e); e->Runions = oldRunions; e->invdepth = savedepth; @@ -1466,6 +1451,8 @@ static jl_value_t *intersect_var(jl_tvar_t *b, jl_value_t *a, jl_stenv_t *e, int return (jl_value_t*)b; } else if (bb->constraintkind == 2) { + // TODO: removing this case fixes many test_brokens in test/subtype.jl + // but breaks other tests. if (!subtype_in_env(a, bb->ub, e)) return jl_bottom_type; jl_value_t *lb = simple_join(bb->lb, a); @@ -1624,6 +1611,10 @@ static jl_value_t *finish_unionall(jl_value_t *res JL_MAYBE_UNROOTED, jl_varbind // you can construct `T{x} where x` even if T's parameter is actually // limited. in that case we might get an invalid instantiation here. res = jl_substitute_var(res, vb->var, varval); + // simplify chains of UnionAlls where bounds become equal + while (jl_is_unionall(res) && obviously_egal(((jl_unionall_t*)res)->var->lb, + ((jl_unionall_t*)res)->var->ub)) + res = jl_instantiate_unionall((jl_unionall_t*)res, ((jl_unionall_t*)res)->var->lb); } JL_CATCH { res = jl_bottom_type; @@ -2883,8 +2874,9 @@ static int type_morespecific_(jl_value_t *a, jl_value_t *b, int invariant, jl_ty if (((jl_tvar_t*)b)->ub == jl_bottom_type) return 0; if (jl_has_free_typevars(a)) { - if (type_morespecific_(a, ((jl_tvar_t*)b)->ub, 0, env) || - eq_msp(a, ((jl_tvar_t*)b)->ub, env)) + if (type_morespecific_(a, ((jl_tvar_t*)b)->ub, 0, env)) + return 1; + if (eq_msp(a, ((jl_tvar_t*)b)->ub, env)) return num_occurs((jl_tvar_t*)b, env) < 2; return 0; } diff --git a/src/task.c b/src/task.c index 3dce377a01a89..b54bbbc2df32b 100644 --- a/src/task.c +++ b/src/task.c @@ -762,7 +762,9 @@ static void jl_start_fiber(jl_ucontext_t *lastt, jl_ucontext_t *t) asm(" mov sp, %0;\n" " mov lr, #0;\n" // Clear link register (lr) and frame pointer " mov fp, #0;\n" // (fp) to terminate unwinder. - " br %1;\n" // call `fn` with fake stack frame + " bx %1;\n" // call `fn` with fake stack frame. While `bx` can change + // the processor mode to thumb, this will never happen + // because all our addresses are word-aligned. " udf #0" // abort : : "r" (stk), "r"(fn) : "memory" ); #else diff --git a/stdlib/Distributed/Project.toml b/stdlib/Distributed/Project.toml index af0e5ca7c5806..ecec870290041 100644 --- a/stdlib/Distributed/Project.toml +++ b/stdlib/Distributed/Project.toml @@ -2,12 +2,13 @@ name = "Distributed" uuid = "8ba89e20-285c-5b6f-9357-94700520ee1b" [deps] -Serialization = "9e88b42a-f829-5b0c-bbe9-9e923198166b" Random = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c" +Serialization = "9e88b42a-f829-5b0c-bbe9-9e923198166b" Sockets = "6462fe0b-24de-5631-8697-dd941f90decc" [extras] +LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40" [targets] -test = ["Test"] +test = ["LinearAlgebra", "Test"] diff --git a/stdlib/LinearAlgebra/src/bidiag.jl b/stdlib/LinearAlgebra/src/bidiag.jl index 24c3a015dd3c9..eb055ffbe72f6 100644 --- a/stdlib/LinearAlgebra/src/bidiag.jl +++ b/stdlib/LinearAlgebra/src/bidiag.jl @@ -322,7 +322,14 @@ end *(A::Bidiagonal, B::Number) = Bidiagonal(A.dv*B, A.ev*B, A.uplo) *(B::Number, A::Bidiagonal) = A*B /(A::Bidiagonal, B::Number) = Bidiagonal(A.dv/B, A.ev/B, A.uplo) -==(A::Bidiagonal, B::Bidiagonal) = (A.uplo==B.uplo) && (A.dv==B.dv) && (A.ev==B.ev) + +function ==(A::Bidiagonal, B::Bidiagonal) + if A.uplo == B.uplo + return A.dv == B.dv && A.ev == B.ev + else + return iszero(A.ev) && iszero(B.ev) && A.dv == B.dv + end +end const BiTriSym = Union{Bidiagonal,Tridiagonal,SymTridiagonal} const BiTri = Union{Bidiagonal,Tridiagonal} diff --git a/stdlib/LinearAlgebra/src/dense.jl b/stdlib/LinearAlgebra/src/dense.jl index 14b9ddec25d83..f9fd39a18f11c 100644 --- a/stdlib/LinearAlgebra/src/dense.jl +++ b/stdlib/LinearAlgebra/src/dense.jl @@ -1237,19 +1237,21 @@ factorize(A::Transpose) = transpose(factorize(parent(A))) ## Moore-Penrose pseudoinverse """ - pinv(M[, rtol::Real]) + pinv(M; atol::Real=0, rtol::Real=atol>0 ? 0 : n*ϵ) + pinv(M, rtol::Real) = pinv(M; rtol=rtol) # to be deprecated in Julia 2.0 Computes the Moore-Penrose pseudoinverse. For matrices `M` with floating point elements, it is convenient to compute the pseudoinverse by inverting only singular values greater than -`rtol * maximum(svdvals(M))`. +`max(atol, rtol*σ₁)` where `σ₁` is the largest singular value of `M`. -The optimal choice of `rtol` varies both with the value of `M` and the intended application -of the pseudoinverse. The default value of `rtol` is -`eps(real(float(one(eltype(M)))))*minimum(size(M))`, which is essentially machine epsilon -for the real part of a matrix element multiplied by the larger matrix dimension. For -inverting dense ill-conditioned matrices in a least-squares sense, +The optimal choice of absolute (`atol`) and relative tolerance (`rtol`) varies +both with the value of `M` and the intended application of the pseudoinverse. +The default relative tolerance is `n*ϵ`, where `n` is the size of the smallest +dimension of `M`, and `ϵ` is the [`eps`](@ref) of the element type of `M`. + +For inverting dense ill-conditioned matrices in a least-squares sense, `rtol = sqrt(eps(real(float(one(eltype(M))))))` is recommended. For more information, see [^issue8859], [^B96], [^S84], [^KY88]. @@ -1280,7 +1282,7 @@ julia> M * N [^KY88]: Konstantinos Konstantinides and Kung Yao, "Statistical analysis of effective singular values in matrix rank determination", IEEE Transactions on Acoustics, Speech and Signal Processing, 36(5), 1988, 757-763. [doi:10.1109/29.1585](https://doi.org/10.1109/29.1585) """ -function pinv(A::AbstractMatrix{T}, rtol::Real) where T +function pinv(A::AbstractMatrix{T}; atol::Real = 0.0, rtol::Real = (eps(real(float(one(T))))*min(size(A)...))*iszero(atol)) where T m, n = size(A) Tout = typeof(zero(T)/sqrt(one(T) + one(T))) if m == 0 || n == 0 @@ -1289,9 +1291,10 @@ function pinv(A::AbstractMatrix{T}, rtol::Real) where T if istril(A) if istriu(A) maxabsA = maximum(abs.(diag(A))) + tol = max(rtol*maxabsA, atol) B = zeros(Tout, n, m) for i = 1:min(m, n) - if abs(A[i,i]) > rtol*maxabsA + if abs(A[i,i]) > tol Aii = inv(A[i,i]) if isfinite(Aii) B[i,i] = Aii @@ -1302,17 +1305,14 @@ function pinv(A::AbstractMatrix{T}, rtol::Real) where T end end SVD = svd(A, full = false) + tol = max(rtol*maximum(SVD.S), atol) Stype = eltype(SVD.S) Sinv = zeros(Stype, length(SVD.S)) - index = SVD.S .> rtol*maximum(SVD.S) + index = SVD.S .> tol Sinv[index] = one(Stype) ./ SVD.S[index] Sinv[findall(.!isfinite.(Sinv))] .= zero(Stype) return SVD.Vt' * (Diagonal(Sinv) * SVD.U') end -function pinv(A::AbstractMatrix{T}) where T - rtol = eps(real(float(one(T))))*min(size(A)...) - return pinv(A, rtol) -end function pinv(x::Number) xi = inv(x) return ifelse(isfinite(xi), xi, zero(xi)) @@ -1321,13 +1321,16 @@ end ## Basis for null space """ - nullspace(M[, rtol::Real]) + nullspace(M; atol::Real=0, rtol::Rea=atol>0 ? 0 : n*ϵ) + nullspace(M, rtol::Real) = nullspace(M; rtol=rtol) # to be deprecated in Julia 2.0 Computes a basis for the nullspace of `M` by including the singular -vectors of A whose singular have magnitude are greater than `rtol*σ₁`, -where `σ₁` is `A`'s largest singular values. By default, the value of -`rtol` is the smallest dimension of `A` multiplied by the [`eps`](@ref) -of the [`eltype`](@ref) of `A`. +vectors of A whose singular have magnitude are greater than `max(atol, rtol*σ₁)`, +where `σ₁` is `M`'s largest singularvalue. + +By default, the relative tolerance `rtol` is `n*ϵ`, where `n` +is the size of the smallest dimension of `M`, and `ϵ` is the [`eps`](@ref) of +the element type of `M`. # Examples ```jldoctest @@ -1343,21 +1346,29 @@ julia> nullspace(M) 0.0 1.0 -julia> nullspace(M, 2) +julia> nullspace(M, rtol=3) 3×3 Array{Float64,2}: 0.0 1.0 0.0 1.0 0.0 0.0 0.0 0.0 1.0 + +julia> nullspace(M, atol=0.95) +3×1 Array{Float64,2}: + 0.0 + 0.0 + 1.0 ``` """ -function nullspace(A::AbstractMatrix, rtol::Real = min(size(A)...)*eps(real(float(one(eltype(A)))))) +function nullspace(A::AbstractMatrix; atol::Real = 0.0, rtol::Real = (min(size(A)...)*eps(real(float(one(eltype(A))))))*iszero(atol)) m, n = size(A) (m == 0 || n == 0) && return Matrix{eltype(A)}(I, n, n) SVD = svd(A, full=true) - indstart = sum(s -> s .> SVD.S[1]*rtol, SVD.S) + 1 + tol = max(atol, SVD.S[1]*rtol) + indstart = sum(s -> s .> tol, SVD.S) + 1 return copy(SVD.Vt[indstart:end,:]') end -nullspace(a::AbstractVector, rtol::Real = min(size(a)...)*eps(real(float(one(eltype(a)))))) = nullspace(reshape(a, length(a), 1), rtol) + +nullspace(A::AbstractVector; atol::Real = 0.0, rtol::Real = (min(size(A)...)*eps(real(float(one(eltype(A))))))*iszero(atol)) = nullspace(reshape(A, length(A), 1), rtol= rtol, atol= atol) """ cond(M, p::Real=2) diff --git a/stdlib/LinearAlgebra/src/deprecated.jl b/stdlib/LinearAlgebra/src/deprecated.jl index b56241c2ab918..28c090634a2d8 100644 --- a/stdlib/LinearAlgebra/src/deprecated.jl +++ b/stdlib/LinearAlgebra/src/deprecated.jl @@ -2,3 +2,6 @@ # To be deprecated in 2.0 rank(A::AbstractMatrix, tol::Real) = rank(A,rtol=tol) +nullspace(A::AbstractVector, tol::Real) = nullspace(reshape(A, length(A), 1), rtol= tol) +nullspace(A::AbstractMatrix, tol::Real) = nullspace(A, rtol=tol) +pinv(A::AbstractMatrix{T}, tol::Real) where T = pinv(A, rtol=tol) diff --git a/stdlib/LinearAlgebra/src/generic.jl b/stdlib/LinearAlgebra/src/generic.jl index f124331f450d4..cdbffcf2665bc 100644 --- a/stdlib/LinearAlgebra/src/generic.jl +++ b/stdlib/LinearAlgebra/src/generic.jl @@ -31,7 +31,15 @@ mul!(C::AbstractArray, X::AbstractArray, s::Number) = generic_mul!(C, s, X) """ rmul!(A::AbstractArray, b::Number) -Scale an array `A` by a scalar `b` overwriting `A` in-place. +Scale an array `A` by a scalar `b` overwriting `A` in-place. Use +[`lmul!`](@ref) to multiply scalar from left. The scaling operation +respects the semantics of the multiplication [`*`](@ref) between an +element of `A` and `b`. In particular, this also applies to +multiplication involving non-finite numbers such as `NaN` and `±Inf`. + +!!! compat "Julia 1.1" + Prior to Julia 1.1, `NaN` and `±Inf` entries in `A` were treated + inconsistently. # Examples ```jldoctest @@ -44,6 +52,10 @@ julia> rmul!(A, 2) 2×2 Array{Int64,2}: 2 4 6 8 + +julia> rmul!([NaN], 0.0) +1-element Array{Float64,1}: + NaN ``` """ function rmul!(X::AbstractArray, s::Number) @@ -57,7 +69,15 @@ end """ lmul!(a::Number, B::AbstractArray) -Scale an array `B` by a scalar `a` overwriting `B` in-place. +Scale an array `B` by a scalar `a` overwriting `B` in-place. Use +[`rmul!`](@ref) to multiply scalar from right. The scaling operation +respects the semantics of the multiplication [`*`](@ref) between `a` +and an element of `B`. In particular, this also applies to +multiplication involving non-finite numbers such as `NaN` and `±Inf`. + +!!! compat "Julia 1.1" + Prior to Julia 1.1, `NaN` and `±Inf` entries in `B` were treated + inconsistently. # Examples ```jldoctest @@ -70,6 +90,10 @@ julia> lmul!(2, B) 2×2 Array{Int64,2}: 2 4 6 8 + +julia> lmul!(0.0, [Inf]) +1-element Array{Float64,1}: + NaN ``` """ function lmul!(s::Number, X::AbstractArray) @@ -713,7 +737,7 @@ end """ rank(A::AbstractMatrix; atol::Real=0, rtol::Real=atol>0 ? 0 : n*ϵ) - rank(A::AbstractMatrix, rtol::Real) = rank(A; rtol=rtol) # to be deprecated in Julia 2.0 + rank(A::AbstractMatrix, rtol::Real) Compute the rank of a matrix by counting how many singular values of `A` have magnitude greater than `max(atol, rtol*σ₁)` where `σ₁` is @@ -722,6 +746,11 @@ tolerances, respectively. The default relative tolerance is `n*ϵ`, where `n` is the size of the smallest dimension of `A`, and `ϵ` is the [`eps`](@ref) of the element type of `A`. +!!! compat "Julia 1.1" + The `atol` and `rtol` keyword arguments requires at least Julia 1.1. + In Julia 1.0 `rtol` is available as a positional argument, but this + will be deprecated in Julia 2.0. + # Examples ```jldoctest julia> rank(Matrix(I, 3, 3)) diff --git a/stdlib/LinearAlgebra/src/special.jl b/stdlib/LinearAlgebra/src/special.jl index 54fd00c402746..bad7ad8581de4 100644 --- a/stdlib/LinearAlgebra/src/special.jl +++ b/stdlib/LinearAlgebra/src/special.jl @@ -148,3 +148,25 @@ function fill!(A::Union{Diagonal,Bidiagonal,Tridiagonal,SymTridiagonal}, x) throw(ArgumentError("array of type $(typeof(A)) and size $(size(A)) can not be filled with $x, since some of its entries are constrained.")) end + +# equals and approx equals methods for structured matrices +# SymTridiagonal == Tridiagonal is already defined in tridiag.jl + +# SymTridiagonal and Bidiagonal have the same field names +==(A::Diagonal, B::Union{SymTridiagonal, Bidiagonal}) = iszero(B.ev) && A.diag == B.dv +==(B::Bidiagonal, A::Diagonal) = A == B + +==(A::Diagonal, B::Tridiagonal) = iszero(B.dl) && iszero(B.du) && A.diag == B.d +==(B::Tridiagonal, A::Diagonal) = A == B + +function ==(A::Bidiagonal, B::Tridiagonal) + if A.uplo == 'U' + return iszero(B.dl) && A.dv == B.d && A.ev == B.du + else + return iszero(B.du) && A.dv == B.d && A.ev == B.dl + end +end +==(B::Tridiagonal, A::Bidiagonal) = A == B + +==(A::Bidiagonal, B::SymTridiagonal) = iszero(B.ev) && iszero(A.ev) && A.dv == B.dv +==(B::SymTridiagonal, A::Bidiagonal) = A == B diff --git a/stdlib/LinearAlgebra/test/dense.jl b/stdlib/LinearAlgebra/test/dense.jl index 8f2dbb9760db3..ccff54921f58c 100644 --- a/stdlib/LinearAlgebra/test/dense.jl +++ b/stdlib/LinearAlgebra/test/dense.jl @@ -72,6 +72,8 @@ bimg = randn(n,2)/2 @test norm(a[:,1:n1]'a15null,Inf) ≈ zero(eltya) atol=300ε @test norm(a15null'a[:,1:n1],Inf) ≈ zero(eltya) atol=400ε @test size(nullspace(b), 2) == 0 + @test size(nullspace(b, rtol=0.001), 2) == 0 + @test size(nullspace(b, atol=100*εb), 2) == 0 @test size(nullspace(b, 100*εb), 2) == 0 @test nullspace(zeros(eltya,n)) == Matrix(I, 1, 1) @test nullspace(zeros(eltya,n), 0.1) == Matrix(I, 1, 1) @@ -82,6 +84,12 @@ bimg = randn(n,2)/2 end end # for eltyb +@testset "Test pinv (rtol, atol)" begin + M = [1 0 0; 0 1 0; 0 0 0] + @test pinv(M,atol=1)== zeros(3,3) + @test pinv(M,rtol=0.5)== M +end + for (a, a2) in ((copy(ainit), copy(ainit2)), (view(ainit, 1:n, 1:n), view(ainit2, 1:n, 1:n))) @testset "Test pinv" begin pinva15 = pinv(a[:,1:n1]) diff --git a/stdlib/LinearAlgebra/test/generic.jl b/stdlib/LinearAlgebra/test/generic.jl index 8facc9a94142b..40f8e201ec288 100644 --- a/stdlib/LinearAlgebra/test/generic.jl +++ b/stdlib/LinearAlgebra/test/generic.jl @@ -389,4 +389,16 @@ end @test LinearAlgebra.peakflops() > 0 end +@testset "NaN handling: Issue 28972" begin + @test all(isnan, rmul!([NaN], 0.0)) + @test all(isnan, rmul!(Any[NaN], 0.0)) + @test all(isnan, lmul!(0.0, [NaN])) + @test all(isnan, lmul!(0.0, Any[NaN])) + + @test all(!isnan, rmul!([NaN], false)) + @test all(!isnan, rmul!(Any[NaN], false)) + @test all(!isnan, lmul!(false, [NaN])) + @test all(!isnan, lmul!(false, Any[NaN])) +end + end # module TestGeneric diff --git a/stdlib/LinearAlgebra/test/special.jl b/stdlib/LinearAlgebra/test/special.jl index 2092122c33458..ecfa26d63837d 100644 --- a/stdlib/LinearAlgebra/test/special.jl +++ b/stdlib/LinearAlgebra/test/special.jl @@ -252,4 +252,28 @@ end @test isa((@inferred vcat(Float64[], spzeros(1))), SparseVector) end +@testset "== for structured matrices" begin + diag = rand(10) + offdiag = rand(9) + D = Diagonal(rand(10)) + Bup = Bidiagonal(diag, offdiag, 'U') + Blo = Bidiagonal(diag, offdiag, 'L') + Bupd = Bidiagonal(diag, zeros(9), 'U') + Blod = Bidiagonal(diag, zeros(9), 'L') + T = Tridiagonal(offdiag, diag, offdiag) + Td = Tridiagonal(zeros(9), diag, zeros(9)) + Tu = Tridiagonal(zeros(9), diag, offdiag) + Tl = Tridiagonal(offdiag, diag, zeros(9)) + S = SymTridiagonal(diag, offdiag) + Sd = SymTridiagonal(diag, zeros(9)) + + mats = [D, Bup, Blo, Bupd, Blod, T, Td, Tu, Tl, S, Sd] + + for a in mats + for b in mats + @test (a == b) == (Matrix(a) == Matrix(b)) == (b == a) == (Matrix(b) == Matrix(a)) + end + end +end + end # module TestSpecial diff --git a/stdlib/Pkg.version b/stdlib/Pkg.version index 2f8d270786fc3..bbc925802f99e 100644 --- a/stdlib/Pkg.version +++ b/stdlib/Pkg.version @@ -1,2 +1,2 @@ PKG_BRANCH = master -PKG_SHA1 = 193e494c22f7ce8b5956829286c6212133edcbf1 +PKG_SHA1 = 853b3f1fd9895db32b402d89e9dee153b66b2316 diff --git a/stdlib/Profile/src/Profile.jl b/stdlib/Profile/src/Profile.jl index 5cb34e132942f..8ae9542c2c2f4 100644 --- a/stdlib/Profile/src/Profile.jl +++ b/stdlib/Profile/src/Profile.jl @@ -514,6 +514,7 @@ function tree!(root::StackFrameTree{T}, all::Vector{UInt64}, lidict::Union{LineI # jump forward to the end of the inlining chain # avoiding an extra (slow) lookup of `ip` in `lidict` # and an extra chain of them in `down` + # note that we may even have this === parent (if we're ignoring this frame ip) this = builder_value[fastkey] let this = this while this !== parent @@ -532,8 +533,7 @@ function tree!(root::StackFrameTree{T}, all::Vector{UInt64}, lidict::Union{LineI frame = (frames isa Vector ? frames[i] : frames) !C && frame.from_c && continue key = (T === UInt64 ? ip : frame) - down = parent.down - this = get!(down, key) do + this = get!(parent.down, key) do return StackFrameTree{T}() end this.frame = frame diff --git a/stdlib/SparseArrays/Project.toml b/stdlib/SparseArrays/Project.toml index bffdfc775fdc6..53d4a9f064ad3 100644 --- a/stdlib/SparseArrays/Project.toml +++ b/stdlib/SparseArrays/Project.toml @@ -6,8 +6,9 @@ LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" Random = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c" [extras] -Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40" +Dates = "ade2ca70-3891-5945-98fb-dc099432e06a" InteractiveUtils = "b77e0a4c-d291-57a0-90e8-8db25a27a240" +Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40" [targets] -test = ["Test", "InteractiveUtils"] +test = ["Dates", "Test", "InteractiveUtils"] diff --git a/stdlib/SparseArrays/src/linalg.jl b/stdlib/SparseArrays/src/linalg.jl index 4350a2d922fc9..d8446d705d465 100644 --- a/stdlib/SparseArrays/src/linalg.jl +++ b/stdlib/SparseArrays/src/linalg.jl @@ -147,63 +147,104 @@ end *(A::Adjoint{<:Any,<:SparseMatrixCSC{Tv,Ti}}, B::Adjoint{<:Any,<:SparseMatrixCSC{Tv,Ti}}) where {Tv,Ti} = spmatmul(copy(A), copy(B)) *(A::Transpose{<:Any,<:SparseMatrixCSC{Tv,Ti}}, B::Transpose{<:Any,<:SparseMatrixCSC{Tv,Ti}}) where {Tv,Ti} = spmatmul(copy(A), copy(B)) -function spmatmul(A::SparseMatrixCSC{Tv,Ti}, B::SparseMatrixCSC{Tv,Ti}; - sortindices::Symbol = :sortcols) where {Tv,Ti} +# Gustavsen's matrix multiplication algorithm revisited. +# The result rowval vector is already sorted by construction. +# The auxiliary Vector{Ti} xb is replaced by a Vector{Bool} of same length. +# The optional argument controlling a sorting algorithm is obsolete. +# depending on expected execution speed the sorting of the result column is +# done by a quicksort of the row indices or by a full scan of the dense result vector. +# The last is faster, if more than ≈ 1/32 of the result column is nonzero. +# TODO: extend to SparseMatrixCSCUnion to allow for SubArrays (view(X, :, r)). +function spmatmul(A::SparseMatrixCSC{Tv,Ti}, B::SparseMatrixCSC{Tv,Ti}) where {Tv,Ti} mA, nA = size(A) - mB, nB = size(B) - nA==mB || throw(DimensionMismatch()) + nB = size(B, 2) + nA == size(B, 1) || throw(DimensionMismatch()) - colptrA = A.colptr; rowvalA = A.rowval; nzvalA = A.nzval - colptrB = B.colptr; rowvalB = B.rowval; nzvalB = B.nzval - # TODO: Need better estimation of result space - nnzC = min(mA*nB, length(nzvalA) + length(nzvalB)) + rowvalA = rowvals(A); nzvalA = nonzeros(A) + rowvalB = rowvals(B); nzvalB = nonzeros(B) + nnzC = max(estimate_mulsize(mA, nnz(A), nA, nnz(B), nB) * 11 ÷ 10, mA) colptrC = Vector{Ti}(undef, nB+1) rowvalC = Vector{Ti}(undef, nnzC) nzvalC = Vector{Tv}(undef, nnzC) + nzpercol = nnzC ÷ max(nB, 1) @inbounds begin ip = 1 - xb = zeros(Ti, mA) - x = zeros(Tv, mA) + xb = fill(false, mA) for i in 1:nB if ip + mA - 1 > nnzC - resize!(rowvalC, nnzC + max(nnzC,mA)) - resize!(nzvalC, nnzC + max(nnzC,mA)) - nnzC = length(nzvalC) + nnzC += max(mA, nnzC>>2) + resize!(rowvalC, nnzC) + resize!(nzvalC, nnzC) end - colptrC[i] = ip - for jp in colptrB[i]:(colptrB[i+1] - 1) + colptrC[i] = ip0 = ip + k0 = ip - 1 + for jp in nzrange(B, i) nzB = nzvalB[jp] j = rowvalB[jp] - for kp in colptrA[j]:(colptrA[j+1] - 1) + for kp in nzrange(A, j) nzC = nzvalA[kp] * nzB k = rowvalA[kp] - if xb[k] != i + if xb[k] + nzvalC[k+k0] += nzC + else + nzvalC[k+k0] = nzC + xb[k] = true rowvalC[ip] = k ip += 1 - xb[k] = i - x[k] = nzC - else - x[k] += nzC end end end - for vp in colptrC[i]:(ip - 1) - nzvalC[vp] = x[rowvalC[vp]] + if ip > ip0 + if prefer_sort(ip-k0, mA) + # in-place sort of indices. Effort: O(nnz*ln(nnz)). + sort!(rowvalC, ip0, ip-1, QuickSort, Base.Order.Forward) + for vp = ip0:ip-1 + k = rowvalC[vp] + xb[k] = false + nzvalC[vp] = nzvalC[k+k0] + end + else + # scan result vector (effort O(mA)) + for k = 1:mA + if xb[k] + xb[k] = false + rowvalC[ip0] = k + nzvalC[ip0] = nzvalC[k+k0] + ip0 += 1 + end + end + end end end colptrC[nB+1] = ip end - deleteat!(rowvalC, colptrC[end]:length(rowvalC)) - deleteat!(nzvalC, colptrC[end]:length(nzvalC)) + resize!(rowvalC, ip - 1) + resize!(nzvalC, ip - 1) - # The Gustavson algorithm does not guarantee the product to have sorted row indices. - Cunsorted = SparseMatrixCSC(mA, nB, colptrC, rowvalC, nzvalC) - C = SparseArrays.sortSparseMatrixCSC!(Cunsorted, sortindices=sortindices) + # This modification of Gustavson algorithm has sorted row indices + C = SparseMatrixCSC(mA, nB, colptrC, rowvalC, nzvalC) return C end +# estimated number of non-zeros in matrix product +# it is assumed, that the non-zero indices are distributed independently and uniformly +# in both matrices. Over-estimation is possible if that is not the case. +function estimate_mulsize(m::Integer, nnzA::Integer, n::Integer, nnzB::Integer, k::Integer) + p = (nnzA / (m * n)) * (nnzB / (n * k)) + p >= 1 ? m*k : p > 0 ? Int(ceil(-expm1(log1p(-p) * n)*m*k)) : 0 # (1-(1-p)^n)*m*k +end + +# determine if sort! shall be used or the whole column be scanned +# based on empirical data on i7-3610QM CPU +# measuring runtimes of the scanning and sorting loops of the algorithm. +# The parameters 6 and 3 might be modified for different architectures. +prefer_sort(nz::Integer, m::Integer) = m > 6 && 3 * ilog2(nz) * nz < m + +# minimal number of bits required to represent integer; ilog2(n) >= log2(n) +ilog2(n::Integer) = sizeof(n)<<3 - leading_zeros(n) + # Frobenius dot/inner product: trace(A'B) function dot(A::SparseMatrixCSC{T1,S1},B::SparseMatrixCSC{T2,S2}) where {T1,T2,S1,S2} m, n = size(A) diff --git a/stdlib/SparseArrays/src/sparsematrix.jl b/stdlib/SparseArrays/src/sparsematrix.jl index c4b335701400d..1ce5b41ce5356 100644 --- a/stdlib/SparseArrays/src/sparsematrix.jl +++ b/stdlib/SparseArrays/src/sparsematrix.jl @@ -517,7 +517,7 @@ supplied, `combine` defaults to `+` unless the elements of `V` are Booleans in w elements of `J` must satisfy `1 <= J[k] <= n`. Numerical zeros in (`I`, `J`, `V`) are retained as structural nonzeros; to drop numerical zeros, use [`dropzeros!`](@ref). -For additional documentation and an expert driver, see `Base.SparseArrays.sparse!`. +For additional documentation and an expert driver, see `SparseArrays.sparse!`. # Examples ```jldoctest @@ -903,7 +903,7 @@ to generate intermediate result `(AQ)^T` (`transpose(A[:,q])`) in `C`. (2) Colum The first step is a call to `halfperm!`, and the second is a variant on `halfperm!` that avoids an unnecessary length-`nnz(A)` array-sweep and associated recomputation of column -pointers. See [`halfperm!`](:func:Base.SparseArrays.halfperm!) for additional algorithmic +pointers. See [`halfperm!`](:func:SparseArrays.halfperm!) for additional algorithmic information. See also: `unchecked_aliasing_permute!` @@ -1215,7 +1215,7 @@ julia> A = sparse(Diagonal([1, 2, 3, 4])) [3, 3] = 3 [4, 4] = 4 -julia> Base.SparseArrays.fkeep!(A, (i, j, v) -> isodd(v)) +julia> SparseArrays.fkeep!(A, (i, j, v) -> isodd(v)) 4×4 SparseMatrixCSC{Int64,Int64} with 2 stored entries: [1, 1] = 1 [3, 3] = 3 @@ -1524,7 +1524,8 @@ function spzeros(::Type{Tv}, ::Type{Ti}, sz::Tuple{Integer,Integer}) where {Tv, spzeros(Tv, Ti, sz[1], sz[2]) end -function one(S::SparseMatrixCSC{T}) where T +import Base._one +function Base._one(unit::T, S::SparseMatrixCSC) where T S.m == S.n || throw(DimensionMismatch("multiplicative identity only defined for square matrices")) return SparseMatrixCSC{T}(I, S.m, S.n) end @@ -1973,8 +1974,8 @@ function getindex_cols(A::SparseMatrixCSC{Tv,Ti}, J::AbstractVector) where {Tv,T return SparseMatrixCSC(m, nJ, colptrS, rowvalS, nzvalS) end -getindex_traverse_col(::AbstractUnitRange, lo::Int, hi::Int) = lo:hi -getindex_traverse_col(I::StepRange, lo::Int, hi::Int) = step(I) > 0 ? (lo:1:hi) : (hi:-1:lo) +getindex_traverse_col(::AbstractUnitRange, lo::Integer, hi::Integer) = lo:hi +getindex_traverse_col(I::StepRange, lo::Integer, hi::Integer) = step(I) > 0 ? (lo:1:hi) : (hi:-1:lo) function getindex(A::SparseMatrixCSC{Tv,Ti}, I::AbstractRange, J::AbstractVector) where {Tv,Ti<:Integer} @assert !has_offset_axes(A, I, J) @@ -2923,7 +2924,7 @@ julia> A = sparse([1 2; 0 0]) [1, 1] = 1 [1, 2] = 2 -julia> Base.SparseArrays.dropstored!(A, 1, 2); A +julia> SparseArrays.dropstored!(A, 1, 2); A 2×2 SparseMatrixCSC{Int64,Int64} with 1 stored entry: [1, 1] = 1 ``` @@ -2963,7 +2964,7 @@ julia> A = sparse(Diagonal([1, 2, 3, 4])) [3, 3] = 3 [4, 4] = 4 -julia> Base.SparseArrays.dropstored!(A, [1, 2], [1, 1]) +julia> SparseArrays.dropstored!(A, [1, 2], [1, 1]) 4×4 SparseMatrixCSC{Int64,Int64} with 3 stored entries: [2, 2] = 2 [3, 3] = 3 diff --git a/stdlib/SparseArrays/test/sparse.jl b/stdlib/SparseArrays/test/sparse.jl index 60bd97f23da87..c46ab90c349b7 100644 --- a/stdlib/SparseArrays/test/sparse.jl +++ b/stdlib/SparseArrays/test/sparse.jl @@ -9,6 +9,7 @@ using Base.Printf: @printf using Random using Test: guardseed using InteractiveUtils: @which +using Dates @testset "issparse" begin @test issparse(sparse(fill(1,5,5))) @@ -92,6 +93,10 @@ do33 = fill(1.,3) end end +@testset "Issue #30006" begin + SparseMatrixCSC{Float64,Int32}(spzeros(3,3))[:, 1] == [1, 2, 3] +end + @testset "concatenation tests" begin sp33 = sparse(1.0I, 3, 3) @@ -317,8 +322,7 @@ end a = sprand(10, 5, 0.7) b = sprand(5, 15, 0.3) @test maximum(abs.(a*b - Array(a)*Array(b))) < 100*eps() - @test maximum(abs.(SparseArrays.spmatmul(a,b,sortindices=:sortcols) - Array(a)*Array(b))) < 100*eps() - @test maximum(abs.(SparseArrays.spmatmul(a,b,sortindices=:doubletranspose) - Array(a)*Array(b))) < 100*eps() + @test maximum(abs.(SparseArrays.spmatmul(a,b) - Array(a)*Array(b))) < 100*eps() f = Diagonal(rand(5)) @test Array(a*f) == Array(a)*f @test Array(f*b) == f*Array(b) @@ -709,6 +713,8 @@ end @test ss116[:,:] == copy(ss116) + @test convert(SparseMatrixCSC{Float32,Int32}, sd116)[2:5,:] == convert(SparseMatrixCSC{Float32,Int32}, sd116[2:5,:]) + # range indexing @test Array(ss116[i,:]) == aa116[i,:] @test Array(ss116[:,j]) == aa116[:,j] @@ -2350,4 +2356,12 @@ end @test success(pipeline(cmd; stdout=stdout, stderr=stderr)) end +@testset "oneunit of sparse matrix" begin + A = sparse([Second(0) Second(0); Second(0) Second(0)]) + @test oneunit(sprand(2, 2, 0.5)) isa SparseMatrixCSC{Float64} + @test oneunit(A) isa SparseMatrixCSC{Second} + @test one(sprand(2, 2, 0.5)) isa SparseMatrixCSC{Float64} + @test one(A) isa SparseMatrixCSC{Int} +end + end # module diff --git a/stdlib/SuiteSparse/src/cholmod.jl b/stdlib/SuiteSparse/src/cholmod.jl index 9260b648f83a2..c8dc6e83532cf 100644 --- a/stdlib/SuiteSparse/src/cholmod.jl +++ b/stdlib/SuiteSparse/src/cholmod.jl @@ -1686,10 +1686,18 @@ end (\)(L::Factor, B::SparseVecOrMat) = sparse(spsolve(CHOLMOD_A, L, Sparse(B, 0))) \(adjL::Adjoint{<:Any,<:Factor}, B::Dense) = (L = adjL.parent; solve(CHOLMOD_A, L, B)) -\(adjL::Adjoint{<:Any,<:Factor}, B::VecOrMat) = (L = adjL.parent; Matrix(solve(CHOLMOD_A, L, Dense(B)))) \(adjL::Adjoint{<:Any,<:Factor}, B::Sparse) = (L = adjL.parent; spsolve(CHOLMOD_A, L, B)) \(adjL::Adjoint{<:Any,<:Factor}, B::SparseVecOrMat) = (L = adjL.parent; \(adjoint(L), Sparse(B))) +function \(adjL::Adjoint{<:Any,<:Factor}, b::StridedVector) + L = adjL.parent + return Vector(solve(CHOLMOD_A, L, Dense(b))) +end +function \(adjL::Adjoint{<:Any,<:Factor}, B::StridedMatrix) + L = adjL.parent + return Matrix(solve(CHOLMOD_A, L, Dense(B))) +end + const RealHermSymComplexHermF64SSL = Union{ Symmetric{Float64,SparseMatrixCSC{Float64,SuiteSparse_long}}, Hermitian{Float64,SparseMatrixCSC{Float64,SuiteSparse_long}}, diff --git a/stdlib/SuiteSparse/test/cholmod.jl b/stdlib/SuiteSparse/test/cholmod.jl index f7e46ec3d4106..7c220267a1d59 100644 --- a/stdlib/SuiteSparse/test/cholmod.jl +++ b/stdlib/SuiteSparse/test/cholmod.jl @@ -676,6 +676,11 @@ end @test_throws ArgumentError logdet(Fnew) end +@testset "Issue #28985" begin + @test typeof(cholesky(sparse(I, 4, 4))'\rand(4)) == Array{Float64, 1} + @test typeof(cholesky(sparse(I, 4, 4))'\rand(4,1)) == Array{Float64, 2} +end + @testset "Issue with promotion during conversion to CHOLMOD.Dense" begin @test CHOLMOD.Dense(fill(1, 5)) == fill(1, 5, 1) @test CHOLMOD.Dense(fill(1f0, 5)) == fill(1, 5, 1) diff --git a/test/compiler/inference.jl b/test/compiler/inference.jl index a3066f99b939d..b89c4feb3a437 100644 --- a/test/compiler/inference.jl +++ b/test/compiler/inference.jl @@ -2151,3 +2151,36 @@ g30098() = (h30098(:f30098); 4) h30098(f) = getfield(@__MODULE__, f)() @test @inferred(g30098()) == 4 # make sure that this @test @inferred(f30098()) == 3 # doesn't pollute the inference cache of this + +# issue #30394 +mutable struct Base30394 + a::Int +end + +mutable struct Foo30394 + foo_inner::Base30394 + Foo30394() = new(Base30394(1)) +end + +mutable struct Foo30394_2 + foo_inner::Foo30394 + Foo30394_2() = new(Foo30394()) +end + +f30394(foo::T1, ::Type{T2}) where {T2, T1 <: T2} = foo + +f30394(foo, T2) = f30394(foo.foo_inner, T2) + +@test Base.return_types(f30394, (Foo30394_2, Type{Base30394})) == Any[Base30394] + +# PR #30385 + +g30385(args...) = h30385(args...) +h30385(f, args...) = f(args...) +f30385(T, y) = g30385(getfield, g30385(tuple, T, y), 1) +k30385(::Type{AbstractFloat}) = 1 +k30385(x) = "dummy" +j30385(T, y) = k30385(f30385(T, y)) + +@test @inferred(j30385(AbstractFloat, 1)) == 1 +@test @inferred(j30385(:dummy, 1)) == "dummy" diff --git a/test/exceptions.jl b/test/exceptions.jl index 6bbeebd88e4c5..e1a415a2c6c0d 100644 --- a/test/exceptions.jl +++ b/test/exceptions.jl @@ -1,4 +1,5 @@ using Test +using Base: catch_stack @testset "Basic exception stack handling" begin # Exiting the catch block normally pops the exception diff --git a/test/numbers.jl b/test/numbers.jl index 39c96eebd3d23..7199a75c7b304 100644 --- a/test/numbers.jl +++ b/test/numbers.jl @@ -993,6 +993,16 @@ end @test Float64(UInt128(3.7e19)) == 3.7e19 @test Float64(UInt128(3.7e30)) == 3.7e30 end +@testset "Float16 vs Int comparisons" begin + @test Inf16 != typemax(Int16) + @test Inf16 != typemax(Int32) + @test Inf16 != typemax(Int64) + @test Inf16 != typemax(Int128) + @test Inf16 != typemax(UInt16) + @test Inf16 != typemax(UInt32) + @test Inf16 != typemax(UInt64) + @test Inf16 != typemax(UInt128) +end @testset "NaN comparisons" begin @test !(NaN <= 1) @test !(NaN >= 1) diff --git a/test/parse.jl b/test/parse.jl index 00d6ced46a26c..45e13a95b7f90 100644 --- a/test/parse.jl +++ b/test/parse.jl @@ -332,3 +332,9 @@ end @test_throws ArgumentError parse(Bool, "2") @test_throws ArgumentError parse(Bool, "02") end + +@testset "issue #30341" begin + @test Meta.parse("x .~ y") == Expr(:call, :.~, :x, :y) + # Ensure dotting binary doesn't break dotting unary + @test Meta.parse(".~[1,2]") == Expr(:call, :.~, Expr(:vect, 1, 2)) +end diff --git a/test/ranges.jl b/test/ranges.jl index f699eca7a1d98..55ef8dded94e5 100644 --- a/test/ranges.jl +++ b/test/ranges.jl @@ -1412,6 +1412,13 @@ end @test getindex((typemax(UInt64)//one(UInt64):typemax(UInt64)//one(UInt64)), 1) == typemax(UInt64)//one(UInt64) end +@testset "Issue #30006" begin + @test Base.Slice(Base.OneTo(5))[Int32(1)] == Int32(1) + @test Base.Slice(Base.OneTo(3))[Int8(2)] == Int8(2) + @test Base.Slice(1:10)[Int32(2)] == Int32(2) + @test Base.Slice(1:10)[Int8(2)] == Int8(2) +end + @testset "allocation of TwicePrecision call" begin 0:286.493442:360 0:286:360 diff --git a/test/reinterpretarray.jl b/test/reinterpretarray.jl index c053bb5ef13ca..70899c8b6ee53 100644 --- a/test/reinterpretarray.jl +++ b/test/reinterpretarray.jl @@ -160,3 +160,12 @@ let a = [0.1 0.2; 0.3 0.4], at = reshape([(i,i+1) for i = 1:2:8], 2, 2) r = reinterpret(Int, vt) @test r == OffsetArray(reshape(1:8, 2, 2, 2), (0, offsetvt...)) end + +# Test 0-dimensional Arrays +A = zeros(UInt32) +B = reinterpret(Int32,A) +@test size(B) == () +@test axes(B) == () +B[] = Int32(5) +@test B[] === Int32(5) +@test A[] === UInt32(5) diff --git a/test/sets.jl b/test/sets.jl index ebe9db8ba90d9..2e5448d989d9d 100644 --- a/test/sets.jl +++ b/test/sets.jl @@ -628,6 +628,27 @@ end end end +@testset "optimized union! with max_values" begin + # issue #30315 + T = Union{Nothing, Bool} + @test Base.max_values(T) == 3 + d = Set{T}() + union!(d, (nothing, true, false)) + @test length(d) == 3 + @test d == Set((nothing, true, false)) + @test nothing in d + @test true in d + @test false in d + + for X = (Int8, Int16, Int32, Int64) + @test Base.max_values(Union{Nothing, X}) == (sizeof(X) < sizeof(Int) ? + 2^(8*sizeof(X)) + 1 : + typemax(Int)) + end + # this does not account for non-empty intersections of the unioned types + @test Base.max_values(Union{Int8,Int16}) == 2^8 + 2^16 +end + struct OpenInterval{T} lower::T upper::T diff --git a/test/show.jl b/test/show.jl index a480812f4618e..b48b33a43d560 100644 --- a/test/show.jl +++ b/test/show.jl @@ -1416,3 +1416,6 @@ end replstrcolor(x) = sprint((io, x) -> show(IOContext(io, :limit => true, :color => true), MIME("text/plain"), x), x) @test occursin("\e[", replstrcolor(`curl abc`)) + +# issue #30303 +@test repr(Symbol("a\$")) == "Symbol(\"a\\\$\")" diff --git a/test/specificity.jl b/test/specificity.jl index 95c01b288b74b..a34ed8a15eccb 100644 --- a/test/specificity.jl +++ b/test/specificity.jl @@ -230,8 +230,8 @@ let N = Tuple{Type{Union{Nothing, T}}, Union{Nothing, T}} where T, LI = Tuple{Type{LinearIndices{N,R}}, LinearIndices{N}} where {N,R}, A = Tuple{Type{T},T} where T<:AbstractArray @test args_morespecific(LI, A) - @test !args_morespecific(A, N) - @test !args_morespecific(LI, N) + @test args_morespecific(A, N) + @test args_morespecific(LI, N) end # issue #29528 @@ -298,3 +298,11 @@ end @test args_morespecific(Tuple{Type{Missing},Any}, Tuple{Type{Union{Nothing, T}},Any} where T) + +let A = Tuple{Type{SubString{S}},AbstractString} where S<:AbstractString, + B = Tuple{Type{T},AbstractString} where T<:AbstractString, + C = Tuple{Type{Union{Missing, Nothing, T}},Union{Missing, Nothing, T}} where T + @test args_morespecific(A, B) + @test args_morespecific(B, C) + @test args_morespecific(A, C) +end diff --git a/test/subtype.jl b/test/subtype.jl index aa9ddc7a9ca7a..4bda72de57126 100644 --- a/test/subtype.jl +++ b/test/subtype.jl @@ -1399,3 +1399,24 @@ end @testintersect(Tuple{Pair{Int64,2}, NTuple}, Tuple{Pair{F,N},Tuple{Vararg{F,N}}} where N where F, Tuple{Pair{Int64,2}, Tuple{Int64,Int64}}) + +# issue #30335 +@testintersect(Tuple{Any,Rational{Int},Int}, + Tuple{LT,R,I} where LT<:Union{I, R} where R<:Rational{I} where I<:Integer, + Tuple{LT,Rational{Int},Int} where LT<:Union{Rational{Int},Int}) + +#@testintersect(Tuple{Any,Tuple{Int},Int}, +# Tuple{LT,R,I} where LT<:Union{I, R} where R<:Tuple{I} where I<:Integer, +# Tuple{LT,Tuple{Int},Int} where LT<:Union{Tuple{Int},Int}) +# fails due to this: +let U = Tuple{Union{LT, LT1},Union{R, R1},Int} where LT1<:R1 where R1<:Tuple{Int} where LT<:Int where R<:Tuple{Int}, + U2 = Union{Tuple{LT,R,Int} where LT<:Int where R<:Tuple{Int}, Tuple{LT,R,Int} where LT<:R where R<:Tuple{Int}}, + V = Tuple{Union{Tuple{Int},Int},Tuple{Int},Int}, + V2 = Tuple{L,Tuple{Int},Int} where L<:Union{Tuple{Int},Int} + @test U == U2 + @test U == V + @test U == V2 + @test V == V2 + @test U2 == V + @test_broken U2 == V2 +end