diff --git a/base/abstractarray.jl b/base/abstractarray.jl index 3e60aeb387646..df165c1c49916 100644 --- a/base/abstractarray.jl +++ b/base/abstractarray.jl @@ -123,10 +123,42 @@ ndims(::AbstractArray{T,N}) where {T,N} = N ndims(::Type{AbstractArray{T,N}}) where {T,N} = N ndims(::Type{T}) where {T<:AbstractArray} = ndims(supertype(T)) +""" + length(collection) -> Integer + +Return the number of elements in the collection. + +Use [`endof`](@ref) to get the last valid index of an indexable collection. + +# Examples +```jldoctest +julia> length(1:5) +5 + +julia> length([1, 2, 3, 4]) +4 + +julia> length([1 2; 3 4]) +4 +``` +""" length(t::AbstractArray) = (@_inline_meta; prod(size(t))) _length(A::AbstractArray) = (@_inline_meta; prod(map(unsafe_length, indices(A)))) # circumvent missing size _length(A) = (@_inline_meta; length(A)) + +""" + endof(collection) -> Integer + +Returns the last index of the collection. + +# Examples +```jldoctest +julia> endof([1,2,4]) +3 +``` +""" endof(a::AbstractArray) = (@_inline_meta; last(linearindices(a))) + first(a::AbstractArray) = a[first(eachindex(a))] """ @@ -1346,6 +1378,21 @@ hcat(X...) = cat(Val(2), X...) typed_vcat(T::Type, X...) = cat_t(Val(1), T, X...) typed_hcat(T::Type, X...) = cat_t(Val(2), T, X...) +""" + cat(dims, A...) + +Concatenate the input arrays along the specified dimensions in the iterable `dims`. For +dimensions not in `dims`, all input arrays should have the same size, which will also be the +size of the output array along that dimension. For dimensions in `dims`, the size of the +output array is the sum of the sizes of the input arrays along that dimension. If `dims` is +a single number, the different arrays are tightly stacked along that dimension. If `dims` is +an iterable containing several dimensions, this allows one to construct block diagonal +matrices and their higher-dimensional analogues by simultaneously increasing several +dimensions for every new input array and putting zero blocks elsewhere. For example, +`cat([1,2], matrices...)` builds a block diagonal matrix, i.e. a block matrix with +`matrices[1]`, `matrices[2]`, ... as diagonal blocks and matching zero blocks away from the +diagonal. +""" cat(catdims, A::AbstractArray{T}...) where {T} = cat_t(catdims, T, A...) # The specializations for 1 and 2 inputs are important diff --git a/base/array.jl b/base/array.jl index 7d3f231f691b8..86acf04af3086 100644 --- a/base/array.jl +++ b/base/array.jl @@ -122,6 +122,16 @@ end ## copy ## +""" + unsafe_copy!(dest::Ptr{T}, src::Ptr{T}, N) + +Copy `N` elements from a source pointer to a destination, with no checking. The size of an +element is determined by the type of the pointers. + +The `unsafe` prefix on this function indicates that no validation is performed on the +pointers `dest` and `src` to ensure that they are valid. Incorrect usage may corrupt or +segfault your program, in the same manner as C. +""" function unsafe_copy!(dest::Ptr{T}, src::Ptr{T}, n) where T # Do not use this to copy data between pointer arrays. # It can't be made safe no matter how carefully you checked. @@ -130,6 +140,16 @@ function unsafe_copy!(dest::Ptr{T}, src::Ptr{T}, n) where T return dest end +""" + unsafe_copy!(dest::Array, do, src::Array, so, N) + +Copy `N` elements from a source array to a destination, starting at offset `so` in the +source and `do` in the destination (1-indexed). + +The `unsafe` prefix on this function indicates that no validation is performed to ensure +that N is inbounds on either array. Incorrect usage may corrupt or segfault your program, in +the same manner as C. +""" function unsafe_copy!(dest::Array{T}, doffs, src::Array{T}, soffs, n) where T if isbits(T) unsafe_copy!(pointer(dest, doffs), pointer(src, soffs), n) @@ -140,6 +160,12 @@ function unsafe_copy!(dest::Array{T}, doffs, src::Array{T}, soffs, n) where T return dest end +""" + copy!(dest, do, src, so, N) + +Copy `N` elements from collection `src` starting at offset `so`, to array `dest` starting at +offset `do`. Returns `dest`. +""" function copy!(dest::Array{T}, doffs::Integer, src::Array{T}, soffs::Integer, n::Integer) where T n == 0 && return dest n > 0 || throw(ArgumentError(string("tried to copy n=", n, " elements, but n should be nonnegative"))) @@ -151,6 +177,13 @@ end copy!(dest::Array{T}, src::Array{T}) where {T} = copy!(dest, 1, src, 1, length(src)) +""" + copy(x) + +Create a shallow copy of `x`: the outer structure is copied, but not all internal values. +For example, copying an array produces a new array with identically-same elements as the +original. +""" copy(a::T) where {T<:Array} = ccall(:jl_array_copy, Ref{T}, (Any,), a) function reinterpret(::Type{T}, a::Array{S,1}) where T where S @@ -295,6 +328,92 @@ dims)` will return an array filled with the result of evaluating `Foo()` once. fill(v, dims::Dims) = fill!(Array{typeof(v)}(dims), v) fill(v, dims::Integer...) = fill!(Array{typeof(v)}(dims...), v) +""" + zeros([A::AbstractArray,] [T=eltype(A)::Type,] [dims=size(A)::Tuple]) + +Create an array of all zeros with the same layout as `A`, element type `T` and size `dims`. +The `A` argument can be skipped, which behaves like `Array{Float64,0}()` was passed. +For convenience `dims` may also be passed in variadic form. + +# Examples +```jldoctest +julia> zeros(1) +1-element Array{Float64,1}: + 0.0 + +julia> zeros(Int8, 2, 3) +2×3 Array{Int8,2}: + 0 0 0 + 0 0 0 + +julia> A = [1 2; 3 4] +2×2 Array{Int64,2}: + 1 2 + 3 4 + +julia> zeros(A) +2×2 Array{Int64,2}: + 0 0 + 0 0 + +julia> zeros(A, Float64) +2×2 Array{Float64,2}: + 0.0 0.0 + 0.0 0.0 + +julia> zeros(A, Bool, (3,)) +3-element Array{Bool,1}: + false + false + false +``` +See also [`ones`](@ref), [`similar`](@ref). +""" +function zeros end + +""" + ones([A::AbstractArray,] [T=eltype(A)::Type,] [dims=size(A)::Tuple]) + +Create an array of all ones with the same layout as `A`, element type `T` and size `dims`. +The `A` argument can be skipped, which behaves like `Array{Float64,0}()` was passed. +For convenience `dims` may also be passed in variadic form. + +# Examples +```jldoctest +julia> ones(Complex128, 2, 3) +2×3 Array{Complex{Float64},2}: + 1.0+0.0im 1.0+0.0im 1.0+0.0im + 1.0+0.0im 1.0+0.0im 1.0+0.0im + +julia> ones(1,2) +1×2 Array{Float64,2}: + 1.0 1.0 + +julia> A = [1 2; 3 4] +2×2 Array{Int64,2}: + 1 2 + 3 4 + +julia> ones(A) +2×2 Array{Int64,2}: + 1 1 + 1 1 + +julia> ones(A, Float64) +2×2 Array{Float64,2}: + 1.0 1.0 + 1.0 1.0 + +julia> ones(A, Bool, (3,)) +3-element Array{Bool,1}: + true + true + true +``` +See also [`zeros`](@ref), [`similar`](@ref). +""" +function ones end + for (fname, felt) in ((:zeros,:zero), (:ones,:one)) @eval begin # allow signature of similar @@ -593,6 +712,25 @@ done(a::Array,i) = (@_inline_meta; i == length(a)+1) ## Indexing: getindex ## +""" + getindex(collection, key...) + +Retrieve the value(s) stored at the given key or index within a collection. The syntax +`a[i,j,...]` is converted by the compiler to `getindex(a, i, j, ...)`. + +# Examples +```jldoctest +julia> A = Dict("a" => 1, "b" => 2) +Dict{String,Int64} with 2 entries: + "b" => 2 + "a" => 1 + +julia> getindex(A, "a") +1 +``` +""" +function getindex end + # This is more complicated than it needs to be in order to get Win64 through bootstrap getindex(A::Array, i1::Int) = arrayref(A, i1) getindex(A::Array, i1::Int, i2::Int, I::Int...) = (@_inline_meta; arrayref(A, i1, i2, I...)) # TODO: REMOVE FOR #14770 @@ -623,6 +761,15 @@ function getindex(A::Array{S}, I::Range{Int}) where S end ## Indexing: setindex! ## + +""" + setindex!(collection, value, key...) + +Store the given value at the given key or index within a collection. The syntax `a[i,j,...] = +x` is converted by the compiler to `(setindex!(a, x, i, j, ...); x)`. +""" +function setindex! end + setindex!(A::Array{T}, x, i1::Int) where {T} = arrayset(A, convert(T,x)::T, i1) setindex!(A::Array{T}, x, i1::Int, i2::Int, I::Int...) where {T} = (@_inline_meta; arrayset(A, convert(T,x)::T, i1, i2, I...)) # TODO: REMOVE FOR #14770 @@ -697,6 +844,29 @@ _deleteat!(a::Vector, i::Integer, delta::Integer) = ## Dequeue functionality ## +""" + push!(collection, items...) -> collection + +Insert one or more `items` at the end of `collection`. + +# Examples +```jldoctest +julia> push!([1, 2, 3], 4, 5, 6) +6-element Array{Int64,1}: + 1 + 2 + 3 + 4 + 5 + 6 +``` + +Use [`append!`](@ref) to add all the elements of another collection to +`collection`. The result of the preceding example is equivalent to `append!([1, 2, 3], [4, +5, 6])`. +""" +function push! end + function push!(a::Array{T,1}, item) where T # convert first so we don't grow the array if the assignment won't work itemT = convert(T, item) @@ -711,6 +881,33 @@ function push!(a::Array{Any,1}, @nospecialize item) return a end +""" + append!(collection, collection2) -> collection. + +Add the elements of `collection2` to the end of `collection`. + +# Examples +```jldoctest +julia> append!([1],[2,3]) +3-element Array{Int64,1}: + 1 + 2 + 3 + +julia> append!([1, 2, 3], [4, 5, 6]) +6-element Array{Int64,1}: + 1 + 2 + 3 + 4 + 5 + 6 +``` + +Use [`push!`](@ref) to add individual items to `collection` which are not already +themselves in another collection. The result is of the preceding example is equivalent to +`push!([1, 2, 3], 4, 5, 6)`. +""" function append!(a::Array{<:Any,1}, items::AbstractVector) itemindices = eachindex(items) n = length(itemindices) @@ -832,11 +1029,53 @@ function resize!(a::Vector, nl::Integer) return a end +""" + sizehint!(s, n) + +Suggest that collection `s` reserve capacity for at least `n` elements. This can improve performance. +""" +function sizehint! end + function sizehint!(a::Vector, sz::Integer) ccall(:jl_array_sizehint, Void, (Any, UInt), a, sz) a end +""" + pop!(collection) -> item + +Remove an item in `collection` and return it. If `collection` is an +ordered container, the last item is returned. + +# Examples +```jldoctest +julia> A=[1, 2, 3] +3-element Array{Int64,1}: + 1 + 2 + 3 + +julia> pop!(A) +3 + +julia> A +2-element Array{Int64,1}: + 1 + 2 + +julia> S = Set([1, 2]) +Set([2, 1]) + +julia> pop!(S) +2 + +julia> S +Set([1]) + +julia> pop!(Dict(1=>2)) +1 => 2 +``` +""" function pop!(a::Vector) if isempty(a) throw(ArgumentError("array must be non-empty")) @@ -870,6 +1109,34 @@ function unshift!(a::Array{T,1}, item) where T return a end +""" + shift!(collection) -> item + +Remove the first `item` from `collection`. + +# Examples +```jldoctest +julia> A = [1, 2, 3, 4, 5, 6] +6-element Array{Int64,1}: + 1 + 2 + 3 + 4 + 5 + 6 + +julia> shift!(A) +1 + +julia> A +5-element Array{Int64,1}: + 2 + 3 + 4 + 5 + 6 +``` +""" function shift!(a::Vector) if isempty(a) throw(ArgumentError("array must be non-empty")) @@ -1158,6 +1425,46 @@ function ==(a::Arr, b::Arr) where Arr <: BitIntegerArray{1} :memcmp, Int32, (Ptr{Void}, Ptr{Void}, UInt), a, b, sizeof(eltype(Arr)) * len) end +""" + reverse(v [, start=1 [, stop=length(v) ]] ) + +Return a copy of `v` reversed from start to stop. + +# Examples +```jldoctest +julia> A = collect(1:5) +5-element Array{Int64,1}: + 1 + 2 + 3 + 4 + 5 + +julia> reverse(A) +5-element Array{Int64,1}: + 5 + 4 + 3 + 2 + 1 + +julia> reverse(A, 1, 4) +5-element Array{Int64,1}: + 4 + 3 + 2 + 1 + 5 + +julia> reverse(A, 3, 5) +5-element Array{Int64,1}: + 1 + 2 + 5 + 4 + 3 +``` +""" function reverse(A::AbstractVector, s=first(linearindices(A)), n=last(linearindices(A))) B = similar(A) for i = first(linearindices(A)):s-1 @@ -1176,6 +1483,11 @@ function reverseind(a::AbstractVector, i::Integer) first(li) + last(li) - i end +""" + reverse!(v [, start=1 [, stop=length(v) ]]) -> v + +In-place version of [`reverse`](@ref). +""" function reverse!(v::AbstractVector, s=first(linearindices(v)), n=last(linearindices(v))) liv = linearindices(v) if n <= s # empty case; ok diff --git a/base/c.jl b/base/c.jl index bd9a37ac5eaab..c57ce27d6130b 100644 --- a/base/c.jl +++ b/base/c.jl @@ -4,6 +4,18 @@ import Core.Intrinsics: cglobal, bitcast +""" + cglobal((symbol, library) [, type=Void]) + +Obtain a pointer to a global variable in a C-exported shared library, specified exactly as +in [`ccall`](@ref). +Returns a `Ptr{Type}`, defaulting to `Ptr{Void}` if no `Type` argument is +supplied. +The values can be read or written by [`unsafe_load`](@ref) or [`unsafe_store!`](@ref), +respectively. +""" +cglobal + """ cfunction(f::Function, returntype::Type, argtypes::Type) -> Ptr{Void} @@ -87,6 +99,17 @@ convert(::Type{Ptr{Cwchar_t}}, p::Cwstring) = bitcast(Ptr{Cwchar_t}, p) # construction from untyped pointers convert(::Type{T}, p::Ptr{Void}) where {T<:Union{Cstring,Cwstring}} = bitcast(T, p) +""" + pointer(array [, index]) + +Get the native address of an array or string element. Be careful to ensure that a Julia +reference to `a` exists as long as this pointer will be used. This function is "unsafe" like +`unsafe_convert`. + +Calling `Ref(array[, index])` is generally preferable to this function. +""" +function pointer end + pointer(p::Cstring) = convert(Ptr{UInt8}, p) pointer(p::Cwstring) = convert(Ptr{Cwchar_t}, p) diff --git a/base/coreio.jl b/base/coreio.jl index b15fca1ea1003..fcc6bd519e355 100644 --- a/base/coreio.jl +++ b/base/coreio.jl @@ -1,6 +1,5 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license -show(x) = show(STDOUT::IO, x) print(xs...) = print(STDOUT::IO, xs...) println(xs...) = println(STDOUT::IO, xs...) println(io::IO) = print(io, '\n') diff --git a/base/datafmt.jl b/base/datafmt.jl index 746da60f004b3..573350853bbfd 100644 --- a/base/datafmt.jl +++ b/base/datafmt.jl @@ -616,6 +616,11 @@ function dlm_parse(dbuff::String, eol::D, dlm::D, qchar::D, cchar::D, return (nrows, ncols) end +""" + readcsv(source, [T::Type]; options...) + +Equivalent to [`readdlm`](@ref) with `delim` set to comma, and type optionally defined by `T`. +""" readcsv(io; opts...) = readdlm(io, ','; opts...) readcsv(io, T::Type; opts...) = readdlm(io, ',', T; opts...) diff --git a/base/dict.jl b/base/dict.jl index e0ddcaaee649e..4dad63bed4d51 100644 --- a/base/dict.jl +++ b/base/dict.jl @@ -437,7 +437,50 @@ function setindex!(h::Dict{K,V}, v0, key::K) where V where K return h end +""" + get!(collection, key, default) + +Return the value stored for the given key, or if no mapping for the key is present, store +`key => default`, and return `default`. + +# Examples +```jldoctest +julia> d = Dict("a"=>1, "b"=>2, "c"=>3); + +julia> get!(d, "a", 5) +1 + +julia> get!(d, "d", 4) +4 + +julia> d +Dict{String,Int64} with 4 entries: + "c" => 3 + "b" => 2 + "a" => 1 + "d" => 4 +``` +""" +get!(collection, key, default) + get!(h::Dict{K,V}, key0, default) where {K,V} = get!(()->default, h, key0) + +""" + get!(f::Function, collection, key) + +Return the value stored for the given key, or if no mapping for the key is present, store +`key => f()`, and return `f()`. + +This is intended to be called using `do` block syntax: +```julia +get!(dict, key) do + # default value calculated here + time() +end +``` +""" +get!(f::Function, collection, key) + function get!(default::Callable, h::Dict{K,V}, key0) where V where K key = convert(K, key0) if !isequal(key, key0) @@ -480,11 +523,47 @@ function getindex(h::Dict{K,V}, key) where V where K return (index < 0) ? throw(KeyError(key)) : h.vals[index]::V end +""" + get(collection, key, default) + +Return the value stored for the given key, or the given default value if no mapping for the +key is present. + +# Examples +```jldoctest +julia> d = Dict("a"=>1, "b"=>2); + +julia> get(d, "a", 3) +1 + +julia> get(d, "c", 3) +3 +``` +""" +get(collection, key, default) + function get(h::Dict{K,V}, key, default) where V where K index = ht_keyindex(h, key) return (index < 0) ? default : h.vals[index]::V end +""" + get(f::Function, collection, key) + +Return the value stored for the given key, or if no mapping for the key is present, return +`f()`. Use [`get!`](@ref) to also store the default value in the dictionary. + +This is intended to be called using `do` block syntax + +```julia +get(dict, key) do + # default value calculated here + time() +end +``` +""" +get(::Function, collection, key) + function get(default::Callable, h::Dict{K,V}, key) where V where K index = ht_keyindex(h, key) return (index < 0) ? default() : h.vals[index]::V @@ -545,6 +624,30 @@ function pop!(h::Dict, key) return index > 0 ? _pop!(h, index) : throw(KeyError(key)) end +""" + pop!(collection, key[, default]) + +Delete and return the mapping for `key` if it exists in `collection`, otherwise return +`default`, or throw an error if `default` is not specified. + +# Examples +```jldoctest +julia> d = Dict("a"=>1, "b"=>2, "c"=>3); + +julia> pop!(d, "a") +1 + +julia> pop!(d, "d") +ERROR: KeyError: key "d" not found +Stacktrace: + [1] pop!(::Dict{String,Int64}, ::String) at ./dict.jl:539 + +julia> pop!(d, "e", 4) +4 +``` +""" +pop!(collection, key, default) + function pop!(h::Dict, key, default) index = ht_keyindex(h, key) return index > 0 ? _pop!(h, index) : default @@ -569,6 +672,25 @@ function _delete!(h::Dict, index) return h end +""" + delete!(collection, key) + +Delete the mapping for the given key in a collection, and return the collection. + +# Examples +```jldoctest +julia> d = Dict("a"=>1, "b"=>2) +Dict{String,Int64} with 2 entries: + "b" => 2 + "a" => 1 + +julia> delete!(d, "b") +Dict{String,Int64} with 1 entry: + "a" => 1 +``` +""" +delete!(collection, key) + function delete!(h::Dict, key) index = ht_keyindex(h, key) if index > 0 diff --git a/base/docs/basedocs.jl b/base/docs/basedocs.jl index 1a2691f324782..c64b71aaa4786 100644 --- a/base/docs/basedocs.jl +++ b/base/docs/basedocs.jl @@ -750,6 +750,25 @@ The item or field is not defined for the given object. """ UndefRefError +""" + Float32(x [, mode::RoundingMode]) + +Create a Float32 from `x`. If `x` is not exactly representable then `mode` determines how +`x` is rounded. + +# Examples +```jldoctest +julia> Float32(1/3, RoundDown) +0.3333333f0 + +julia> Float32(1/3, RoundUp) +0.33333334f0 +``` + +See [`RoundingMode`](@ref) for available rounding modes. +""" +Float32(x) + """ Float64(x [, mode::RoundingMode]) @@ -1046,6 +1065,162 @@ for bit in (8, 16, 32, 64, 128) end end +""" + Symbol(x...) -> Symbol + +Create a `Symbol` by concatenating the string representations of the arguments together. +""" +Symbol + +""" + tuple(xs...) + +Construct a tuple of the given objects. + +# Examples +```jldoctest +julia> tuple(1, 'a', pi) +(1, 'a', π = 3.1415926535897...) +``` +""" +tuple + +""" + getfield(value, name::Symbol) + +Extract a named field from a `value` of composite type. The syntax `a.b` calls +`getfield(a, :b)`. + +# Examples +```jldoctest +julia> a = 1//2 +1//2 + +julia> getfield(a, :num) +1 +``` +""" +getfield + +""" + setfield!(value, name::Symbol, x) + +Assign `x` to a named field in `value` of composite type. The syntax `a.b = c` calls +`setfield!(a, :b, c)`. +""" +setfield! + +""" + typeof(x) + +Get the concrete type of `x`. +""" +typeof + +""" + isdefined(m::Module, s::Symbol) + isdefined(object, s::Symbol) + isdefined(object, index::Int) + +Tests whether an assignable location is defined. The arguments can be a module and a symbol +or a composite object and field name (as a symbol) or index. +""" +isdefined + + +""" + Vector{T}(n) + +Construct an uninitialized [`Vector{T}`](@ref) of length `n`. + +# Examples +```julia-repl +julia> Vector{Float64}(3) +3-element Array{Float64,1}: + 6.90966e-310 + 6.90966e-310 + 6.90966e-310 +``` +""" +Vector{T}(n) + +""" + Matrix{T}(m, n) + +Construct an uninitialized [`Matrix{T}`](@ref) of size `m`×`n`. + +# Examples +```julia-repl +julia> Matrix{Float64}(2, 3) +2×3 Array{Float64,2}: + 6.93517e-310 6.93517e-310 6.93517e-310 + 6.93517e-310 6.93517e-310 1.29396e-320 +``` +""" +Matrix{T}(m, n) + +""" + Array{T}(dims) + Array{T,N}(dims) + +Construct an uninitialized `N`-dimensional [`Array`](@ref) +containing elements of type `T`. `N` can either be supplied explicitly, +as in `Array{T,N}(dims)`, or be determined by the length or number of `dims`. +`dims` may be a tuple or a series of integer arguments corresponding to the lengths +in each dimension. If the rank `N` is supplied explicitly, then it must +match the length or number of `dims`. + +# Examples +```julia-repl +julia> A = Array{Float64,2}(2, 3) # N given explicitly +2×3 Array{Float64,2}: + 6.90198e-310 6.90198e-310 6.90198e-310 + 6.90198e-310 6.90198e-310 0.0 + +julia> B = Array{Float64}(2) # N determined by the input +2-element Array{Float64,1}: + 1.87103e-320 + 0.0 +``` +""" +Array{T,N}(dims) + +""" + +(x, y...) + +Addition operator. `x+y+z+...` calls this function with all arguments, i.e. `+(x, y, z, ...)`. +""" +(+)(x, y...) + +""" + -(x) + +Unary minus operator. +""" +-(x) + +""" + -(x, y) + +Subtraction operator. +""" +-(x, y) + +""" + *(x, y...) + +Multiplication operator. `x*y*z*...` calls this function with all arguments, i.e. `*(x, y, z, ...)`. +""" +(*)(x, y...) + +""" + /(x, y) + +Right division operator: multiplication of `x` by the inverse of `y` on the right. Gives +floating-point results for integer arguments. +""" +/(x, y) + """ ArgumentError(msg) diff --git a/base/docs/helpdb.jl b/base/docs/helpdb.jl deleted file mode 100644 index 5e2a4fe44b28a..0000000000000 --- a/base/docs/helpdb.jl +++ /dev/null @@ -1,3 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -include(joinpath("helpdb", "Base.jl")) diff --git a/base/docs/helpdb/Base.jl b/base/docs/helpdb/Base.jl deleted file mode 100644 index bd96ddbae5b05..0000000000000 --- a/base/docs/helpdb/Base.jl +++ /dev/null @@ -1,1882 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# Base - -""" - fill!(A, x) - -Fill array `A` with the value `x`. If `x` is an object reference, all elements will refer to -the same object. `fill!(A, Foo())` will return `A` filled with the result of evaluating -`Foo()` once. - -# Examples -```jldoctest -julia> A = zeros(2,3) -2×3 Array{Float64,2}: - 0.0 0.0 0.0 - 0.0 0.0 0.0 - -julia> fill!(A, 2.) -2×3 Array{Float64,2}: - 2.0 2.0 2.0 - 2.0 2.0 2.0 - -julia> a = [1, 1, 1]; A = fill!(Vector{Vector{Int}}(3), a); a[1] = 2; A -3-element Array{Array{Int64,1},1}: - [2, 1, 1] - [2, 1, 1] - [2, 1, 1] - -julia> x = 0; f() = (global x += 1; x); fill!(Vector{Int}(3), f()) -3-element Array{Int64,1}: - 1 - 1 - 1 -``` -""" -fill! - -""" - read!(stream::IO, array::Union{Array, BitArray}) - read!(filename::AbstractString, array::Union{Array, BitArray}) - -Read binary data from an I/O stream or file, filling in `array`. -""" -read! - -""" - pointer(array [, index]) - -Get the native address of an array or string element. Be careful to ensure that a Julia -reference to `a` exists as long as this pointer will be used. This function is "unsafe" like -`unsafe_convert`. - -Calling `Ref(array[, index])` is generally preferable to this function. -""" -pointer - -""" - precision(num::AbstractFloat) - -Get the precision of a floating point number, as defined by the effective number of bits in -the mantissa. -""" -precision - -""" - -(x) - -Unary minus operator. -""" --(x) - -""" - -(x, y) - -Subtraction operator. -""" --(x, y) - -""" - bits(n) - -A string giving the literal bit representation of a number. - -# Examples -```jldoctest -julia> bits(4) -"0000000000000000000000000000000000000000000000000000000000000100" - -julia> bits(2.2) -"0100000000000001100110011001100110011001100110011001100110011010" -``` -""" -bits - -""" - getindex(collection, key...) - -Retrieve the value(s) stored at the given key or index within a collection. The syntax -`a[i,j,...]` is converted by the compiler to `getindex(a, i, j, ...)`. - -# Examples -```jldoctest -julia> A = Dict("a" => 1, "b" => 2) -Dict{String,Int64} with 2 entries: - "b" => 2 - "a" => 1 - -julia> getindex(A, "a") -1 -``` -""" -getindex(collection, key...) - -""" - cconvert(T,x) - -Convert `x` to a value to be passed to C code as type `T`, typically by calling `convert(T, x)`. - -In cases where `x` cannot be safely converted to `T`, unlike [`convert`](@ref), `cconvert` may -return an object of a type different from `T`, which however is suitable for -[`unsafe_convert`](@ref) to handle. The result of this function should be kept valid (for the GC) -until the result of [`unsafe_convert`](@ref) is not needed anymore. -This can be used to allocate memory that will be accessed by the `ccall`. -If multiple objects need to be allocated, a tuple of the objects can be used as return value. - -Neither `convert` nor `cconvert` should take a Julia object and turn it into a `Ptr`. -""" -cconvert - -""" - unsafe_copy!(dest::Ptr{T}, src::Ptr{T}, N) - -Copy `N` elements from a source pointer to a destination, with no checking. The size of an -element is determined by the type of the pointers. - -The `unsafe` prefix on this function indicates that no validation is performed on the -pointers `dest` and `src` to ensure that they are valid. Incorrect usage may corrupt or -segfault your program, in the same manner as C. -""" -unsafe_copy!{T}(dest::Ptr{T}, src::Ptr{T}, N) - -""" - unsafe_copy!(dest::Array, do, src::Array, so, N) - -Copy `N` elements from a source array to a destination, starting at offset `so` in the -source and `do` in the destination (1-indexed). - -The `unsafe` prefix on this function indicates that no validation is performed to ensure -that N is inbounds on either array. Incorrect usage may corrupt or segfault your program, in -the same manner as C. -""" -unsafe_copy!(dest::Array, d, src::Array, so, N) - -""" - Float32(x [, mode::RoundingMode]) - -Create a Float32 from `x`. If `x` is not exactly representable then `mode` determines how -`x` is rounded. - -# Examples -```jldoctest -julia> Float32(1/3, RoundDown) -0.3333333f0 - -julia> Float32(1/3, RoundUp) -0.33333334f0 -``` - -See [`RoundingMode`](@ref) for available rounding modes. -""" -Float32(x) - -""" - Mmap.mmap(io::Union{IOStream,AbstractString,Mmap.AnonymousMmap}[, type::Type{Array{T,N}}, dims, offset]; grow::Bool=true, shared::Bool=true) - Mmap.mmap(type::Type{Array{T,N}}, dims) - -Create an `Array` whose values are linked to a file, using memory-mapping. This provides a -convenient way of working with data too large to fit in the computer's memory. - -The type is an `Array{T,N}` with a bits-type element of `T` and dimension `N` that -determines how the bytes of the array are interpreted. Note that the file must be stored in -binary format, and no format conversions are possible (this is a limitation of operating -systems, not Julia). - -`dims` is a tuple or single [`Integer`](@ref) specifying the size or length of the array. - -The file is passed via the stream argument, either as an open `IOStream` or filename string. -When you initialize the stream, use `"r"` for a "read-only" array, and `"w+"` to create a -new array used to write values to disk. - -If no `type` argument is specified, the default is `Vector{UInt8}`. - -Optionally, you can specify an offset (in bytes) if, for example, you want to skip over a -header in the file. The default value for the offset is the current stream position for an -`IOStream`. - -The `grow` keyword argument specifies whether the disk file should be grown to accommodate -the requested size of array (if the total file size is < requested array size). Write -privileges are required to grow the file. - -The `shared` keyword argument specifies whether the resulting `Array` and changes made to it -will be visible to other processes mapping the same file. - -For example, the following code - -```julia -# Create a file for mmapping -# (you could alternatively use mmap to do this step, too) -A = rand(1:20, 5, 30) -s = open("/tmp/mmap.bin", "w+") -# We'll write the dimensions of the array as the first two Ints in the file -write(s, size(A,1)) -write(s, size(A,2)) -# Now write the data -write(s, A) -close(s) - -# Test by reading it back in -s = open("/tmp/mmap.bin") # default is read-only -m = read(s, Int) -n = read(s, Int) -A2 = Mmap.mmap(s, Matrix{Int}, (m,n)) -``` - -creates a `m`-by-`n` `Matrix{Int}`, linked to the file associated with stream `s`. - -A more portable file would need to encode the word size -- 32 bit or 64 bit -- and endianness -information in the header. In practice, consider encoding binary data using standard formats -like HDF5 (which can be used with memory-mapping). -""" -Mmap.mmap(io, ::Type, dims, offset) - -""" - Mmap.mmap(io, BitArray, [dims, offset]) - -Create a `BitArray` whose values are linked to a file, using memory-mapping; it has the same -purpose, works in the same way, and has the same arguments, as [`mmap`](@ref Mmap.mmap), but -the byte representation is different. - -**Example**: `B = Mmap.mmap(s, BitArray, (25,30000))` - -This would create a 25-by-30000 `BitArray`, linked to the file associated with stream `s`. -""" -Mmap.mmap(io, ::BitArray, dims, offset) - -""" - sizeof(T) - -Size, in bytes, of the canonical binary representation of the given DataType `T`, if any. - -# Examples -```jldoctest -julia> sizeof(Float32) -4 - -julia> sizeof(Complex128) -16 -``` - -If `T` does not have a specific size, an error is thrown. - -```jldoctest -julia> sizeof(Base.LinAlg.LU) -ERROR: argument is an abstract type; size is indeterminate -Stacktrace: - [1] sizeof(::Type{T} where T) at ./essentials.jl:150 -``` -""" -sizeof(::Type) - -""" - ceil([T,] x, [digits, [base]]) - -`ceil(x)` returns the nearest integral value of the same type as `x` that is greater than or -equal to `x`. - -`ceil(T, x)` converts the result to type `T`, throwing an `InexactError` if the value is not -representable. - -`digits` and `base` work as for [`round`](@ref). -""" -ceil - -""" - oftype(x, y) - -Convert `y` to the type of `x` (`convert(typeof(x), y)`). -""" -oftype - -""" - push!(collection, items...) -> collection - -Insert one or more `items` at the end of `collection`. - -# Examples -```jldoctest -julia> push!([1, 2, 3], 4, 5, 6) -6-element Array{Int64,1}: - 1 - 2 - 3 - 4 - 5 - 6 -``` - -Use [`append!`](@ref) to add all the elements of another collection to -`collection`. The result of the preceding example is equivalent to `append!([1, 2, 3], [4, -5, 6])`. -""" -push! - -""" - promote(xs...) - -Convert all arguments to their common promotion type (if any), and return them all (as a tuple). - -# Examples -```jldoctest -julia> promote(Int8(1), Float16(4.5), Float32(4.1)) -(1.0f0, 4.5f0, 4.1f0) -``` -""" -promote - -""" - fd(stream) - -Returns the file descriptor backing the stream or file. Note that this function only applies -to synchronous `File`'s and `IOStream`'s not to any of the asynchronous streams. -""" -fd - -""" - ones([A::AbstractArray,] [T=eltype(A)::Type,] [dims=size(A)::Tuple]) - -Create an array of all ones with the same layout as `A`, element type `T` and size `dims`. -The `A` argument can be skipped, which behaves like `Array{Float64,0}()` was passed. -For convenience `dims` may also be passed in variadic form. - -# Examples -```jldoctest -julia> ones(Complex128, 2, 3) -2×3 Array{Complex{Float64},2}: - 1.0+0.0im 1.0+0.0im 1.0+0.0im - 1.0+0.0im 1.0+0.0im 1.0+0.0im - -julia> ones(1,2) -1×2 Array{Float64,2}: - 1.0 1.0 - -julia> A = [1 2; 3 4] -2×2 Array{Int64,2}: - 1 2 - 3 4 - -julia> ones(A) -2×2 Array{Int64,2}: - 1 1 - 1 1 - -julia> ones(A, Float64) -2×2 Array{Float64,2}: - 1.0 1.0 - 1.0 1.0 - -julia> ones(A, Bool, (3,)) -3-element Array{Bool,1}: - true - true - true -``` -See also [`zeros`](@ref), [`similar`](@ref). -""" -ones - -""" - randsubseq!(S, A, p) - -Like [`randsubseq`](@ref), but the results are stored in `S` -(which is resized as needed). -""" -randsubseq! - -""" - /(x, y) - -Right division operator: multiplication of `x` by the inverse of `y` on the right. Gives -floating-point results for integer arguments. -""" -Base.:(/) - -""" - dump(x) - -Show every part of the representation of a value. -""" -dump - -""" - tuple(xs...) - -Construct a tuple of the given objects. - -# Examples -```jldoctest -julia> tuple(1, 'a', pi) -(1, 'a', π = 3.1415926535897...) -``` -""" -tuple - -""" - eachmatch(r::Regex, s::AbstractString[, overlap::Bool=false]) - -Search for all matches of a the regular expression `r` in `s` and return a iterator over the -matches. If overlap is `true`, the matching sequences are allowed to overlap indices in the -original string, otherwise they must be from distinct character ranges. -""" -eachmatch - -""" - truncate(file,n) - -Resize the file or buffer given by the first argument to exactly `n` bytes, filling -previously unallocated space with '\\0' if the file or buffer is grown. -""" -truncate - -""" - exp10(x) - -Compute ``10^x``. - -# Examples -```jldoctest -julia> exp10(2) -100.0 - -julia> exp10(0.2) -1.5848931924611136 -``` -""" -exp10 - -""" - select(v, k, [by=,] [lt=,] [rev=false]) - -Variant of [`select!`](@ref) which copies `v` before partially sorting it, thereby returning the -same thing as `select!` but leaving `v` unmodified. -""" -select - -""" - accept(server[,client]) - -Accepts a connection on the given server and returns a connection to the client. An -uninitialized client stream may be provided, in which case it will be used instead of -creating a new stream. -""" -accept - -""" - Mmap.Anonymous(name, readonly, create) - -Create an `IO`-like object for creating zeroed-out mmapped-memory that is not tied to a file -for use in `Mmap.mmap`. Used by `SharedArray` for creating shared memory arrays. -""" -Mmap.Anonymous - -""" - floor([T,] x, [digits, [base]]) - -`floor(x)` returns the nearest integral value of the same type as `x` that is less than or -equal to `x`. - -`floor(T, x)` converts the result to type `T`, throwing an `InexactError` if the value is -not representable. - -`digits` and `base` work as for [`round`](@ref). -""" -floor - -""" - reverse(v [, start=1 [, stop=length(v) ]] ) - -Return a copy of `v` reversed from start to stop. - -# Examples -```jldoctest -julia> A = collect(1:5) -5-element Array{Int64,1}: - 1 - 2 - 3 - 4 - 5 - -julia> reverse(A) -5-element Array{Int64,1}: - 5 - 4 - 3 - 2 - 1 - -julia> reverse(A, 1, 4) -5-element Array{Int64,1}: - 4 - 3 - 2 - 1 - 5 - -julia> reverse(A, 3, 5) -5-element Array{Int64,1}: - 1 - 2 - 5 - 4 - 3 -``` -""" -reverse - -""" - reverse!(v [, start=1 [, stop=length(v) ]]) -> v - -In-place version of [`reverse`](@ref). -""" -reverse! - -""" - append!(collection, collection2) -> collection. - -Add the elements of `collection2` to the end of `collection`. - -# Examples -```jldoctest -julia> append!([1],[2,3]) -3-element Array{Int64,1}: - 1 - 2 - 3 - -julia> append!([1, 2, 3], [4, 5, 6]) -6-element Array{Int64,1}: - 1 - 2 - 3 - 4 - 5 - 6 -``` - -Use [`push!`](@ref) to add individual items to `collection` which are not already -themselves in another collection. The result is of the preceding example is equivalent to -`push!([1, 2, 3], 4, 5, 6)`. -""" -append! - -""" - skip(s, offset) - -Seek a stream relative to the current position. -""" -skip - -""" - copysign(x, y) -> z - -Return `z` which has the magnitude of `x` and the same sign as `y`. - -# Examples -```jldoctest -julia> copysign(1, -2) --1 - -julia> copysign(-1, 2) -1 -``` -""" -copysign - -""" - getfield(value, name::Symbol) - -Extract a named field from a `value` of composite type. The syntax `a.b` calls -`getfield(a, :b)`. - -# Examples -```jldoctest -julia> a = 1//2 -1//2 - -julia> getfield(a, :num) -1 -``` -""" -getfield - -""" - select!(v, k, [by=,] [lt=,] [rev=false]) - -Partially sort the vector `v` in place, according to the order specified by `by`, `lt` and -`rev` so that the value at index `k` (or range of adjacent values if `k` is a range) occurs -at the position where it would appear if the array were fully sorted via a non-stable -algorithm. If `k` is a single index, that value is returned; if `k` is a range, an array of -values at those indices is returned. Note that `select!` does not fully sort the input -array. - -# Examples -```jldoctest -julia> a = [1, 2, 4, 3, 4] -5-element Array{Int64,1}: - 1 - 2 - 4 - 3 - 4 - -julia> select!(a, 4) -4 - -julia> a -5-element Array{Int64,1}: - 1 - 2 - 3 - 4 - 4 - -julia> a = [1, 2, 4, 3, 4] -5-element Array{Int64,1}: - 1 - 2 - 4 - 3 - 4 - -julia> select!(a, 4, rev=true) -2 - -julia> a -5-element Array{Int64,1}: - 4 - 4 - 3 - 2 - 1 -``` -""" -select! - -""" - union(s1,s2...) - ∪(s1,s2...) - -Construct the union of two or more sets. Maintains order with arrays. - -# Examples -```jldoctest -julia> union([1, 2], [3, 4]) -4-element Array{Int64,1}: - 1 - 2 - 3 - 4 - -julia> union([1, 2], [2, 4]) -3-element Array{Int64,1}: - 1 - 2 - 4 - -julia> union([4, 2], [1, 2]) -3-element Array{Int64,1}: - 4 - 2 - 1 -``` -""" -union - -""" - realmax(T) - -The highest finite value representable by the given floating-point DataType `T`. - -# Examples -```jldoctest -julia> realmax(Float16) -Float16(6.55e4) - -julia> realmax(Float32) -3.4028235f38 -``` -""" -realmax - -""" - serialize(stream, value) - -Write an arbitrary value to a stream in an opaque format, such that it can be read back by -[`deserialize`](@ref). The read-back value will be as identical as possible to the original. In -general, this process will not work if the reading and writing are done by different -versions of Julia, or an instance of Julia with a different system image. `Ptr` values are -serialized as all-zero bit patterns (`NULL`). -""" -serialize - -""" - typemin(T) - -The lowest value representable by the given (real) numeric DataType `T`. - -# Examples -```jldoctest -julia> typemin(Float16) --Inf16 - -julia> typemin(Float32) --Inf32 -``` -""" -typemin - -""" - typeof(x) - -Get the concrete type of `x`. -""" -typeof - -""" - trunc([T,] x, [digits, [base]]) - -`trunc(x)` returns the nearest integral value of the same type as `x` whose absolute value -is less than or equal to `x`. - -`trunc(T, x)` converts the result to type `T`, throwing an `InexactError` if the value is -not representable. - -`digits` and `base` work as for [`round`](@ref). -""" -trunc - -""" - unsafe_convert(T,x) - -Convert `x` to a C argument of type `T` -where the input `x` must be the return value of `cconvert(T, ...)`. - -In cases where [`convert`](@ref) would need to take a Julia object -and turn it into a `Ptr`, this function should be used to define and perform -that conversion. - -Be careful to ensure that a Julia reference to `x` exists as long as the result of this -function will be used. Accordingly, the argument `x` to this function should never be an -expression, only a variable name or field reference. For example, `x=a.b.c` is acceptable, -but `x=[a,b,c]` is not. - -The `unsafe` prefix on this function indicates that using the result of this function after -the `x` argument to this function is no longer accessible to the program may cause undefined -behavior, including program corruption or segfaults, at any later time. - -See also [`cconvert`](@ref) -""" -unsafe_convert - -""" - seek(s, pos) - -Seek a stream to the given position. -""" -seek - -""" - cglobal((symbol, library) [, type=Void]) - -Obtain a pointer to a global variable in a C-exported shared library, specified exactly as -in [`ccall`](@ref). -Returns a `Ptr{Type}`, defaulting to `Ptr{Void}` if no `Type` argument is -supplied. -The values can be read or written by [`unsafe_load`](@ref) or [`unsafe_store!`](@ref), -respectively. -""" -cglobal - -""" - endof(collection) -> Integer - -Returns the last index of the collection. - -# Examples -```jldoctest -julia> endof([1,2,4]) -3 -``` -""" -endof - -""" - next(iter, state) -> item, state - -For a given iterable object and iteration state, return the current item and the next iteration state. - -# Examples -```jldoctest -julia> next(1:5, 3) -(3, 4) - -julia> next(1:5, 5) -(5, 6) -``` -""" -next - -""" - sizehint!(s, n) - -Suggest that collection `s` reserve capacity for at least `n` elements. This can improve performance. -""" -sizehint! - -""" - finalize(x) - -Immediately run finalizers registered for object `x`. -""" -finalize - -""" - parse(str, start; greedy=true, raise=true) - -Parse the expression string and return an expression (which could later be passed to eval -for execution). `start` is the index of the first character to start parsing. If `greedy` is -`true` (default), `parse` will try to consume as much input as it can; otherwise, it will -stop as soon as it has parsed a valid expression. Incomplete but otherwise syntactically -valid expressions will return `Expr(:incomplete, "(error message)")`. If `raise` is `true` -(default), syntax errors other than incomplete expressions will raise an error. If `raise` -is `false`, `parse` will return an expression that will raise an error upon evaluation. - -```jldoctest -julia> parse("x = 3, y = 5", 7) -(:(y = 5), 13) - -julia> parse("x = 3, y = 5", 5) -(:((3, y) = 5), 13) -``` -""" -parse(str, start) - -""" - parse(str; raise=true) - -Parse the expression string greedily, returning a single expression. An error is thrown if -there are additional characters after the first expression. If `raise` is `true` (default), -syntax errors will raise an error; otherwise, `parse` will return an expression that will -raise an error upon evaluation. - -```jldoctest -julia> parse("x = 3") -:(x = 3) - -julia> parse("x = ") -:($(Expr(:incomplete, "incomplete: premature end of input"))) - -julia> parse("1.0.2") -ERROR: ParseError("invalid numeric constant \\\"1.0.\\\"") -Stacktrace: -[...] - -julia> parse("1.0.2"; raise = false) -:($(Expr(:error, "invalid numeric constant \"1.0.\""))) -``` -""" -parse(str) - -""" - parse(type, str, [base]) - -Parse a string as a number. If the type is an integer type, then a base can be specified -(the default is 10). If the type is a floating point type, the string is parsed as a decimal -floating point number. If the string does not contain a valid number, an error is raised. - -```jldoctest -julia> parse(Int, "1234") -1234 - -julia> parse(Int, "1234", 5) -194 - -julia> parse(Int, "afc", 16) -2812 - -julia> parse(Float64, "1.2e-3") -0.0012 -``` -""" -parse(T::Type, str, base=Int) - -""" - position(s) - -Get the current position of a stream. -""" -position - -""" - selectperm(v, k, [alg=,] [by=,] [lt=,] [rev=false]) - -Return a partial permutation of the vector `v`, according to the order specified by -`by`, `lt` and `rev`, so that `v[output]` returns the first `k` (or range of adjacent values -if `k` is a range) values of a fully sorted version of `v`. If `k` is a single index -(Integer), an array of the first `k` indices is returned; if `k` is a range, an array of -those indices is returned. Note that the handling of integer values for `k` is different -from [`select`](@ref) in that it returns a vector of `k` elements instead of just the `k` th -element. Also note that this is equivalent to, but more efficient than, calling -`sortperm(...)[k]`. -""" -selectperm - -""" - reinterpret(type, A) - -Change the type-interpretation of a block of memory. -For arrays, this constructs an array with the same binary data as the given -array, but with the specified element type. -For example, -`reinterpret(Float32, UInt32(7))` interprets the 4 bytes corresponding to `UInt32(7)` as a -[`Float32`](@ref). - -!!! warning - - It is not allowed to `reinterpret` an array to an element type with a larger alignment then - the alignment of the array. For a normal `Array`, this is the alignment of its element type. - For a reinterpreted array, this is the alignment of the `Array` it was reinterpreted from. - For example, `reinterpret(UInt32, UInt8[0, 0, 0, 0])` is not allowed but - `reinterpret(UInt32, reinterpret(UInt8, Float32[1.0]))` is allowed. - -# Examples -```jldoctest -julia> reinterpret(Float32, UInt32(7)) -1.0f-44 - -julia> reinterpret(Float32, UInt32[1 2 3 4 5]) -1×5 Array{Float32,2}: - 1.4013f-45 2.8026f-45 4.2039f-45 5.60519f-45 7.00649f-45 -``` -""" -reinterpret - -""" - bswap(n) - -Byte-swap an integer. Flip the bits of its binary representation. - -# Examples -```jldoctest -julia> a = bswap(4) -288230376151711744 - -julia> bswap(a) -4 - -julia> bin(1) -"1" - -julia> bin(bswap(1)) -"100000000000000000000000000000000000000000000000000000000" -``` -""" -bswap - -""" - delete!(collection, key) - -Delete the mapping for the given key in a collection, and return the collection. - -# Examples -```jldoctest -julia> d = Dict("a"=>1, "b"=>2) -Dict{String,Int64} with 2 entries: - "b" => 2 - "a" => 1 - -julia> delete!(d, "b") -Dict{String,Int64} with 1 entry: - "a" => 1 -``` -""" -delete! - -""" - big(x) - -Convert a number to a maximum precision representation (typically [`BigInt`](@ref) or -`BigFloat`). See [`BigFloat`](@ref) for information about some pitfalls with floating-point numbers. -""" -big - -""" - typejoin(T, S) - -Compute a type that contains both `T` and `S`. -""" -typejoin - -""" - selectperm!(ix, v, k, [alg=,] [by=,] [lt=,] [rev=false,] [initialized=false]) - -Like [`selectperm`](@ref), but accepts a preallocated index vector `ix`. If `initialized` is `false` -(the default), ix is initialized to contain the values `1:length(ix)`. -""" -selectperm! - -""" - precompile(f,args::Tuple{Vararg{Any}}) - -Compile the given function `f` for the argument tuple (of types) `args`, but do not execute it. -""" -precompile - -""" - get(collection, key, default) - -Return the value stored for the given key, or the given default value if no mapping for the -key is present. - -# Examples -```jldoctest -julia> d = Dict("a"=>1, "b"=>2); - -julia> get(d, "a", 3) -1 - -julia> get(d, "c", 3) -3 -``` -""" -get(collection,key,default) - -""" - get(f::Function, collection, key) - -Return the value stored for the given key, or if no mapping for the key is present, return -`f()`. Use [`get!`](@ref) to also store the default value in the dictionary. - -This is intended to be called using `do` block syntax - -```julia -get(dict, key) do - # default value calculated here - time() -end -``` -""" -get - -""" - Mmap.sync!(array) - -Forces synchronization between the in-memory version of a memory-mapped `Array` or -`BitArray` and the on-disk version. -""" -Mmap.sync! - -""" - hash(x[, h::UInt]) - -Compute an integer hash code such that `isequal(x,y)` implies `hash(x)==hash(y)`. The -optional second argument `h` is a hash code to be mixed with the result. - -New types should implement the 2-argument form, typically by calling the 2-argument `hash` -method recursively in order to mix hashes of the contents with each other (and with `h`). -Typically, any type that implements `hash` should also implement its own `==` (hence -`isequal`) to guarantee the property mentioned above. -""" -hash - -""" - read(stream::IO, T) - -Read a single value of type `T` from `stream`, in canonical binary representation. - - read(stream::IO, String) - -Read the entirety of `stream`, as a String. -""" -read(stream, t) - -""" - shift!(collection) -> item - -Remove the first `item` from `collection`. - -# Examples -```jldoctest -julia> A = [1, 2, 3, 4, 5, 6] -6-element Array{Int64,1}: - 1 - 2 - 3 - 4 - 5 - 6 - -julia> shift!(A) -1 - -julia> A -5-element Array{Int64,1}: - 2 - 3 - 4 - 5 - 6 -``` -""" -shift! - -""" - spawn(command) - -Run a command object asynchronously, returning the resulting `Process` object. -""" -spawn - -""" - isdefined(m::Module, s::Symbol) - isdefined(object, s::Symbol) - isdefined(object, index::Int) - -Tests whether an assignable location is defined. The arguments can be a module and a symbol -or a composite object and field name (as a symbol) or index. -""" -isdefined - -""" - wait([x]) - -Block the current task until some event occurs, depending on the type of the argument: - -* [`RemoteChannel`](@ref) : Wait for a value to become available on the specified remote - channel. -* [`Future`](@ref) : Wait for a value to become available for the specified future. -* [`Channel`](@ref): Wait for a value to be appended to the channel. -* [`Condition`](@ref): Wait for [`notify`](@ref) on a condition. -* `Process`: Wait for a process or process chain to exit. The `exitcode` field of a process - can be used to determine success or failure. -* [`Task`](@ref): Wait for a `Task` to finish, returning its result value. If the task fails - with an exception, the exception is propagated (re-thrown in the task that called `wait`). -* `RawFD`: Wait for changes on a file descriptor (see [`poll_fd`](@ref) for keyword - arguments and return code) - -If no argument is passed, the task blocks for an undefined period. A task can only be -restarted by an explicit call to [`schedule`](@ref) or [`yieldto`](@ref). - -Often `wait` is called within a `while` loop to ensure a waited-for condition is met before -proceeding. -""" -wait - -""" - copy(x) - -Create a shallow copy of `x`: the outer structure is copied, but not all internal values. -For example, copying an array produces a new array with identically-same elements as the -original. -""" -copy - -""" - isempty(collection) -> Bool - -Determine whether a collection is empty (has no elements). - -# Examples -```jldoctest -julia> isempty([]) -true - -julia> isempty([1 2 3]) -false -``` -""" -isempty - -""" - typemax(T) - -The highest value representable by the given (real) numeric `DataType`. -""" -typemax - -""" - ==(x, y) - -Generic equality operator, giving a single [`Bool`](@ref) result. Falls back to `===`. -Should be implemented for all types with a notion of equality, based on the abstract value -that an instance represents. For example, all numeric types are compared by numeric value, -ignoring type. Strings are compared as sequences of characters, ignoring encoding. - -Follows IEEE semantics for floating-point numbers. - -Collections should generally implement `==` by calling `==` recursively on all contents. - -New numeric types should implement this function for two arguments of the new type, and -handle comparison to other types via promotion rules where possible. -""" -Base.:(==) - -""" - seekstart(s) - -Seek a stream to its beginning. -""" -seekstart - -""" - show(stream, mime, x) - -The [`display`](@ref) functions ultimately call `show` in order to write an object `x` as a -given `mime` type to a given I/O `stream` (usually a memory buffer), if possible. In order -to provide a rich multimedia representation of a user-defined type `T`, it is only necessary -to define a new `show` method for `T`, via: `show(stream, ::MIME"mime", x::T) = ...`, -where `mime` is a MIME-type string and the function body calls `write` (or similar) to write -that representation of `x` to `stream`. (Note that the `MIME""` notation only supports -literal strings; to construct `MIME` types in a more flexible manner use -`MIME{Symbol("")}`.) - -For example, if you define a `MyImage` type and know how to write it to a PNG file, you -could define a function `show(stream, ::MIME"image/png", x::MyImage) = ...` to allow -your images to be displayed on any PNG-capable `Display` (such as IJulia). As usual, be sure -to `import Base.show` in order to add new methods to the built-in Julia function -`show`. - -The default MIME type is `MIME"text/plain"`. There is a fallback definition for `text/plain` -output that calls `show` with 2 arguments. Therefore, this case should be handled by -defining a 2-argument `show(stream::IO, x::MyType)` method. - -Technically, the `MIME"mime"` macro defines a singleton type for the given `mime` string, -which allows us to exploit Julia's dispatch mechanisms in determining how to display objects -of any given type. - -The first argument to `show` can be an [`IOContext`](@ref) specifying output format properties. -See [`IOContext`](@ref) for details. -""" -show(stream, mime, x) - -""" - isless(x, y) - -Test whether `x` is less than `y`, according to a canonical total order. Values that are -normally unordered, such as `NaN`, are ordered in an arbitrary but consistent fashion. This -is the default comparison used by [`sort`](@ref). Non-numeric types with a canonical total order -should implement this function. Numeric types only need to implement it if they have special -values such as `NaN`. -""" -isless - -""" - error(message::AbstractString) - -Raise an `ErrorException` with the given message. -""" -error - -""" - readcsv(source, [T::Type]; options...) - -Equivalent to [`readdlm`](@ref) with `delim` set to comma, and type optionally defined by `T`. -""" -readcsv - -""" - gc() - -Perform garbage collection. This should not generally be used. -""" -gc - -""" - unsafe_trunc(T, x) - -`unsafe_trunc(T, x)` returns the nearest integral value of type `T` whose absolute value is -less than or equal to `x`. If the value is not representable by `T`, an arbitrary value will -be returned. -""" -unsafe_trunc - -""" - parent(A) - -Returns the "parent array" of an array view type (e.g., `SubArray`), or the array itself if -it is not a view. - -# Examples -```jldoctest -julia> a = [1 2; 3 4] -2×2 Array{Int64,2}: - 1 2 - 3 4 - -julia> s_a = Symmetric(a) -2×2 Symmetric{Int64,Array{Int64,2}}: - 1 2 - 2 4 - -julia> parent(s_a) -2×2 Array{Int64,2}: - 1 2 - 3 4 -``` -""" -parent - -""" - gc_enable(on::Bool) - -Control whether garbage collection is enabled using a boolean argument (`true` for enabled, -`false` for disabled). Returns previous GC state. Disabling garbage collection should be -used only with extreme caution, as it can cause memory use to grow without bound. -""" -gc_enable - -""" - object_id(x) - -Get a hash value for `x` based on object identity. `object_id(x)==object_id(y)` if `x === y`. -""" -object_id - -""" - cat(dims, A...) - -Concatenate the input arrays along the specified dimensions in the iterable `dims`. For -dimensions not in `dims`, all input arrays should have the same size, which will also be the -size of the output array along that dimension. For dimensions in `dims`, the size of the -output array is the sum of the sizes of the input arrays along that dimension. If `dims` is -a single number, the different arrays are tightly stacked along that dimension. If `dims` is -an iterable containing several dimensions, this allows one to construct block diagonal -matrices and their higher-dimensional analogues by simultaneously increasing several -dimensions for every new input array and putting zero blocks elsewhere. For example, -`cat([1,2], matrices...)` builds a block diagonal matrix, i.e. a block matrix with -`matrices[1]`, `matrices[2]`, ... as diagonal blocks and matching zero blocks away from the -diagonal. -""" -cat - -""" - show(x) - -Write an informative text representation of a value to the current output stream. New types -should overload `show(io, x)` where the first argument is a stream. The representation used -by `show` generally includes Julia-specific formatting and type information. -""" -show(x) - -""" - finalizer(x, f) - -Register a function `f(x)` to be called when there are no program-accessible references to -`x`. The type of `x` must be a `mutable struct`, otherwise the behavior of this function is -unpredictable. -""" -finalizer - -""" - setfield!(value, name::Symbol, x) - -Assign `x` to a named field in `value` of composite type. The syntax `a.b = c` calls -`setfield!(a, :b, c)`. -""" -setfield! - -""" -``` -*(x, y...) -``` - -Multiplication operator. `x*y*z*...` calls this function with all arguments, i.e. `*(x, y, z, ...)`. -""" -Base.:(*)(x, y...) - -""" - time() - -Get the system time in seconds since the epoch, with fairly high (typically, microsecond) resolution. -""" -time() - -""" - ismatch(r::Regex, s::AbstractString) -> Bool - -Test whether a string contains a match of the given regular expression. -""" -ismatch - -""" - matchall(r::Regex, s::AbstractString[, overlap::Bool=false]) -> Vector{AbstractString} - -Return a vector of the matching substrings from [`eachmatch`](@ref). -""" -matchall - -""" - get!(collection, key, default) - -Return the value stored for the given key, or if no mapping for the key is present, store -`key => default`, and return `default`. - -# Examples -```jldoctest -julia> d = Dict("a"=>1, "b"=>2, "c"=>3); - -julia> get!(d, "a", 5) -1 - -julia> get!(d, "d", 4) -4 - -julia> d -Dict{String,Int64} with 4 entries: - "c" => 3 - "b" => 2 - "a" => 1 - "d" => 4 -``` -""" -get!(collection,key,default) - -""" - get!(f::Function, collection, key) - -Return the value stored for the given key, or if no mapping for the key is present, store -`key => f()`, and return `f()`. - -This is intended to be called using `do` block syntax: -```julia -get!(dict, key) do - # default value calculated here - time() -end -``` -""" -get!(f::Function,collection,key) -:@assert - -""" - deserialize(stream) - -Read a value written by [`serialize`](@ref). `deserialize` assumes the binary data read from -`stream` is correct and has been serialized by a compatible implementation of [`serialize`](@ref). -It has been designed with simplicity and performance as a goal and does not validate -the data read. Malformed data can result in process termination. The caller has to ensure -the integrity and correctness of data read from `stream`. -""" -deserialize - -""" - length(collection) -> Integer - -Return the number of elements in the collection. - -Use [`endof`](@ref) to get the last valid index of an indexable collection. - -# Examples -```jldoctest -julia> length(1:5) -5 - -julia> length([1, 2, 3, 4]) -4 - -julia> length([1 2; 3 4]) -4 -``` -""" -length(collection) - -""" - issubnormal(f) -> Bool - -Test whether a floating point number is subnormal. -""" -issubnormal - -""" - NullException() - -An attempted access to a [`Nullable`](@ref) with no defined value. - -# Examples -```jldoctest -julia> a = Nullable{Int}() -Nullable{Int64}() - -julia> get(a) -ERROR: NullException() -Stacktrace: - [1] get(::Nullable{Int64}) at ./nullable.jl:92 -``` -""" -NullException - -""" - intersect(s1,s2...) - ∩(s1,s2) - -Construct the intersection of two or more sets. -Maintains order and multiplicity of the first argument for arrays and ranges. - -# Examples -```jldoctest -julia> intersect([1, 2, 3], [3, 4, 5]) -1-element Array{Int64,1}: - 3 - -julia> intersect([1, 4, 4, 5, 6], [4, 6, 6, 7, 8]) -3-element Array{Int64,1}: - 4 - 4 - 6 -``` -""" -intersect - -""" - promote_rule(type1, type2) - -Specifies what type should be used by [`promote`](@ref) when given values of types `type1` and -`type2`. This function should not be called directly, but should have definitions added to -it for new types as appropriate. -""" -promote_rule - -""" - match(r::Regex, s::AbstractString[, idx::Integer[, addopts]]) - -Search for the first match of the regular expression `r` in `s` and return a `RegexMatch` -object containing the match, or nothing if the match failed. The matching substring can be -retrieved by accessing `m.match` and the captured sequences can be retrieved by accessing -`m.captures` The optional `idx` argument specifies an index at which to start the search. -""" -match - -""" - start(iter) -> state - -Get initial iteration state for an iterable object. - -# Examples -```jldoctest -julia> start(1:5) -1 - -julia> start([1;2;3]) -1 - -julia> start([4;2;3]) -1 -``` -""" -start - -""" - done(iter, state) -> Bool - -Test whether we are done iterating. - -# Examples -```jldoctest -julia> done(1:5, 3) -false - -julia> done(1:5, 5) -false - -julia> done(1:5, 6) -true -``` -""" -done - -""" - convert(T, x) - -Convert `x` to a value of type `T`. - -If `T` is an [`Integer`](@ref) type, an [`InexactError`](@ref) will be raised if `x` -is not representable by `T`, for example if `x` is not integer-valued, or is outside the -range supported by `T`. - -# Examples -```jldoctest -julia> convert(Int, 3.0) -3 - -julia> convert(Int, 3.5) -ERROR: InexactError: convert(Int64, 3.5) -Stacktrace: - [1] convert(::Type{Int64}, ::Float64) at ./float.jl:680 -``` - -If `T` is a [`AbstractFloat`](@ref) or [`Rational`](@ref) type, -then it will return the closest value to `x` representable by `T`. - -```jldoctest -julia> x = 1/3 -0.3333333333333333 - -julia> convert(Float32, x) -0.33333334f0 - -julia> convert(Rational{Int32}, x) -1//3 - -julia> convert(Rational{Int64}, x) -6004799503160661//18014398509481984 -``` - -If `T` is a collection type and `x` a collection, the result of `convert(T, x)` may alias -`x`. -```jldoctest -julia> x = Int[1,2,3]; - -julia> y = convert(Vector{Int}, x); - -julia> y === x -true -``` -Similarly, if `T` is a composite type and `x` a related instance, the result of -`convert(T, x)` may alias part or all of `x`. -```jldoctest -julia> x = speye(5); - -julia> typeof(x) -SparseMatrixCSC{Float64,Int64} - -julia> y = convert(SparseMatrixCSC{Float64,Int64}, x); - -julia> z = convert(SparseMatrixCSC{Float32,Int64}, y); - -julia> y === x -true - -julia> z === x -false - -julia> z.colptr === x.colptr -true -``` -""" -convert - -""" - fma(x, y, z) - -Computes `x*y+z` without rounding the intermediate result `x*y`. On some systems this is -significantly more expensive than `x*y+z`. `fma` is used to improve accuracy in certain -algorithms. See [`muladd`](@ref). -""" -fma - -""" - copy!(dest, do, src, so, N) - -Copy `N` elements from collection `src` starting at offset `so`, to array `dest` starting at -offset `do`. Returns `dest`. -""" -copy!(dest,d,src,so,N) - -""" - +(x, y...) - -Addition operator. `x+y+z+...` calls this function with all arguments, i.e. `+(x, y, z, ...)`. -""" -+ - -""" - setindex!(collection, value, key...) - -Store the given value at the given key or index within a collection. The syntax `a[i,j,...] = -x` is converted by the compiler to `(setindex!(a, x, i, j, ...); x)`. -""" -setindex!(collection,value,key...) - -""" - zeros([A::AbstractArray,] [T=eltype(A)::Type,] [dims=size(A)::Tuple]) - -Create an array of all zeros with the same layout as `A`, element type `T` and size `dims`. -The `A` argument can be skipped, which behaves like `Array{Float64,0}()` was passed. -For convenience `dims` may also be passed in variadic form. - -# Examples -```jldoctest -julia> zeros(1) -1-element Array{Float64,1}: - 0.0 - -julia> zeros(Int8, 2, 3) -2×3 Array{Int8,2}: - 0 0 0 - 0 0 0 - -julia> A = [1 2; 3 4] -2×2 Array{Int64,2}: - 1 2 - 3 4 - -julia> zeros(A) -2×2 Array{Int64,2}: - 0 0 - 0 0 - -julia> zeros(A, Float64) -2×2 Array{Float64,2}: - 0.0 0.0 - 0.0 0.0 - -julia> zeros(A, Bool, (3,)) -3-element Array{Bool,1}: - false - false - false -``` -See also [`ones`](@ref), [`similar`](@ref). -""" -zeros - -""" - Symbol(x...) -> Symbol - -Create a `Symbol` by concatenating the string representations of the arguments together. -""" -Symbol - -""" - isvalid(value) -> Bool - -Returns `true` if the given value is valid for its type, which currently can be either -`Char` or `String`. -""" -isvalid(value) - -""" - isvalid(T, value) -> Bool - -Returns `true` if the given value is valid for that type. Types currently can -be either `Char` or `String`. Values for `Char` can be of type `Char` or [`UInt32`](@ref). -Values for `String` can be of that type, or `Vector{UInt8}`. -""" -isvalid(T,value) - -""" - pop!(collection, key[, default]) - -Delete and return the mapping for `key` if it exists in `collection`, otherwise return -`default`, or throw an error if `default` is not specified. - -# Examples -```jldoctest -julia> d = Dict("a"=>1, "b"=>2, "c"=>3); - -julia> pop!(d, "a") -1 - -julia> pop!(d, "d") -ERROR: KeyError: key "d" not found -Stacktrace: - [1] pop!(::Dict{String,Int64}, ::String) at ./dict.jl:539 - -julia> pop!(d, "e", 4) -4 -``` -""" -pop!(collection,key,default) - -""" - pop!(collection) -> item - -Remove an item in `collection` and return it. If `collection` is an -ordered container, the last item is returned. - -# Examples -```jldoctest -julia> A=[1, 2, 3] -3-element Array{Int64,1}: - 1 - 2 - 3 - -julia> pop!(A) -3 - -julia> A -2-element Array{Int64,1}: - 1 - 2 - -julia> S = Set([1, 2]) -Set([2, 1]) - -julia> pop!(S) -2 - -julia> S -Set([1]) - -julia> pop!(Dict(1=>2)) -1 => 2 -``` -""" -pop!(collection) - -""" - seekend(s) - -Seek a stream to its end. -""" -seekend - -""" - Vector{T}(n) - -Construct an uninitialized [`Vector{T}`](@ref) of length `n`. - -# Examples -```julia-repl -julia> Vector{Float64}(3) -3-element Array{Float64,1}: - 6.90966e-310 - 6.90966e-310 - 6.90966e-310 -``` -""" -Vector{T}(n) - -""" - Matrix{T}(m, n) - -Construct an uninitialized [`Matrix{T}`](@ref) of size `m`×`n`. - -# Examples -```julia-repl -julia> Matrix{Float64}(2, 3) -2×3 Array{Float64,2}: - 6.93517e-310 6.93517e-310 6.93517e-310 - 6.93517e-310 6.93517e-310 1.29396e-320 -``` -""" -Matrix{T}(m, n) - -""" - Array{T}(dims) - Array{T,N}(dims) - -Construct an uninitialized `N`-dimensional [`Array`](@ref) -containing elements of type `T`. `N` can either be supplied explicitly, -as in `Array{T,N}(dims)`, or be determined by the length or number of `dims`. -`dims` may be a tuple or a series of integer arguments corresponding to the lengths -in each dimension. If the rank `N` is supplied explicitly, then it must -match the length or number of `dims`. - -# Examples -```julia-repl -julia> A = Array{Float64,2}(2, 3) # N given explicitly -2×3 Array{Float64,2}: - 6.90198e-310 6.90198e-310 6.90198e-310 - 6.90198e-310 6.90198e-310 0.0 - -julia> B = Array{Float64}(2) # N determined by the input -2-element Array{Float64,1}: - 1.87103e-320 - 0.0 -``` -""" -Array{T,N}(dims) diff --git a/base/error.jl b/base/error.jl index 06508810e00b0..170a5252cefc5 100644 --- a/base/error.jl +++ b/base/error.jl @@ -25,6 +25,11 @@ throw ## native julia error handling ## +""" + error(message::AbstractString) + +Raise an `ErrorException` with the given message. +""" error(s::AbstractString) = throw(ErrorException(s)) """ diff --git a/base/essentials.jl b/base/essentials.jl index 7e57b60ff973c..f9450df49d487 100644 --- a/base/essentials.jl +++ b/base/essentials.jl @@ -61,6 +61,77 @@ macro _propagate_inbounds_meta() Expr(:meta, :inline, :propagate_inbounds) end +""" + convert(T, x) + +Convert `x` to a value of type `T`. + +If `T` is an [`Integer`](@ref) type, an [`InexactError`](@ref) will be raised if `x` +is not representable by `T`, for example if `x` is not integer-valued, or is outside the +range supported by `T`. + +# Examples +```jldoctest +julia> convert(Int, 3.0) +3 + +julia> convert(Int, 3.5) +ERROR: InexactError: convert(Int64, 3.5) +Stacktrace: + [1] convert(::Type{Int64}, ::Float64) at ./float.jl:680 +``` + +If `T` is a [`AbstractFloat`](@ref) or [`Rational`](@ref) type, +then it will return the closest value to `x` representable by `T`. + +```jldoctest +julia> x = 1/3 +0.3333333333333333 + +julia> convert(Float32, x) +0.33333334f0 + +julia> convert(Rational{Int32}, x) +1//3 + +julia> convert(Rational{Int64}, x) +6004799503160661//18014398509481984 +``` + +If `T` is a collection type and `x` a collection, the result of `convert(T, x)` may alias +`x`. +```jldoctest +julia> x = Int[1,2,3]; + +julia> y = convert(Vector{Int}, x); + +julia> y === x +true +``` +Similarly, if `T` is a composite type and `x` a related instance, the result of +`convert(T, x)` may alias part or all of `x`. +```jldoctest +julia> x = speye(5); + +julia> typeof(x) +SparseMatrixCSC{Float64,Int64} + +julia> y = convert(SparseMatrixCSC{Float64,Int64}, x); + +julia> z = convert(SparseMatrixCSC{Float32,Int64}, y); + +julia> y === x +true + +julia> z === x +false + +julia> z.colptr === x.colptr +true +``` +""" +function convert end + convert(::Type{Any}, @nospecialize(x)) = x convert(::Type{T}, x::T) where {T} = x @@ -201,7 +272,12 @@ convert(::Type{T}, x::Tuple{Any, Vararg{Any}}) where {T<:Tuple} = #convert(::Type{Tuple{}}, ::Tuple{}) = () #convert(::Type{Tuple{Vararg{S}}} where S, ::Tuple{}) = () -oftype(x, c) = convert(typeof(x), c) +""" + oftype(x, y) + +Convert `y` to the type of `x` (`convert(typeof(x), y)`). +""" +oftype(x, y) = convert(typeof(x), y) unsigned(x::Int) = reinterpret(UInt, x) signed(x::UInt) = reinterpret(Int, x) @@ -211,16 +287,83 @@ ptr_arg_cconvert(::Type{Ptr{T}}, x) where {T} = cconvert(T, x) ptr_arg_unsafe_convert(::Type{Ptr{T}}, x) where {T} = unsafe_convert(T, x) ptr_arg_unsafe_convert(::Type{Ptr{Void}}, x) = x +""" + cconvert(T,x) + +Convert `x` to a value to be passed to C code as type `T`, typically by calling `convert(T, x)`. + +In cases where `x` cannot be safely converted to `T`, unlike [`convert`](@ref), `cconvert` may +return an object of a type different from `T`, which however is suitable for +[`unsafe_convert`](@ref) to handle. The result of this function should be kept valid (for the GC) +until the result of [`unsafe_convert`](@ref) is not needed anymore. +This can be used to allocate memory that will be accessed by the `ccall`. +If multiple objects need to be allocated, a tuple of the objects can be used as return value. + +Neither `convert` nor `cconvert` should take a Julia object and turn it into a `Ptr`. +""" +function cconvert end + cconvert(T::Type, x) = convert(T, x) # do the conversion eagerly in most cases cconvert(::Type{<:Ptr}, x) = x # but defer the conversion to Ptr to unsafe_convert unsafe_convert(::Type{T}, x::T) where {T} = x # unsafe_convert (like convert) defaults to assuming the convert occurred unsafe_convert(::Type{T}, x::T) where {T<:Ptr} = x # to resolve ambiguity with the next method unsafe_convert(::Type{P}, x::Ptr) where {P<:Ptr} = convert(P, x) +""" + reinterpret(type, A) + +Change the type-interpretation of a block of memory. +For arrays, this constructs an array with the same binary data as the given +array, but with the specified element type. +For example, +`reinterpret(Float32, UInt32(7))` interprets the 4 bytes corresponding to `UInt32(7)` as a +[`Float32`](@ref). + +!!! warning + + It is not allowed to `reinterpret` an array to an element type with a larger alignment then + the alignment of the array. For a normal `Array`, this is the alignment of its element type. + For a reinterpreted array, this is the alignment of the `Array` it was reinterpreted from. + For example, `reinterpret(UInt32, UInt8[0, 0, 0, 0])` is not allowed but + `reinterpret(UInt32, reinterpret(UInt8, Float32[1.0]))` is allowed. + +# Examples +```jldoctest +julia> reinterpret(Float32, UInt32(7)) +1.0f-44 + +julia> reinterpret(Float32, UInt32[1 2 3 4 5]) +1×5 Array{Float32,2}: + 1.4013f-45 2.8026f-45 4.2039f-45 5.60519f-45 7.00649f-45 +``` +""" reinterpret(::Type{T}, x) where {T} = bitcast(T, x) reinterpret(::Type{Unsigned}, x::Float16) = reinterpret(UInt16,x) reinterpret(::Type{Signed}, x::Float16) = reinterpret(Int16,x) +""" + sizeof(T) + +Size, in bytes, of the canonical binary representation of the given DataType `T`, if any. + +# Examples +```jldoctest +julia> sizeof(Float32) +4 + +julia> sizeof(Complex128) +16 +``` + +If `T` does not have a specific size, an error is thrown. + +```jldoctest +julia> sizeof(Base.LinAlg.LU) +ERROR: argument is an abstract type; size is indeterminate +Stacktrace: + [1] sizeof(::Type{T} where T) at ./essentials.jl:150 +``` +""" sizeof(x) = Core.sizeof(x) function append_any(xs...) @@ -247,6 +390,11 @@ end # simple Array{Any} operations needed for bootstrap setindex!(A::Array{Any}, @nospecialize(x), i::Int) = Core.arrayset(A, x, i) +""" + precompile(f, args::Tuple{Vararg{Any}}) + +Compile the given function `f` for the argument tuple (of types) `args`, but do not execute it. +""" function precompile(@nospecialize(f), args::Tuple) ccall(:jl_compile_hint, Int32, (Any,), Tuple{Core.Typeof(f), args...}) != 0 end @@ -442,8 +590,6 @@ function as_kwargs(xs) return to end -isempty(itr) = done(itr, start(itr)) - """ invokelatest(f, args...; kwargs...) @@ -459,3 +605,75 @@ function invokelatest(f, args...; kwargs...) inner() = f(args...; kwargs...) Core._apply_latest(inner) end + +# iteration protocol + +""" + next(iter, state) -> item, state + +For a given iterable object and iteration state, return the current item and the next iteration state. + +# Examples +```jldoctest +julia> next(1:5, 3) +(3, 4) + +julia> next(1:5, 5) +(5, 6) +``` +""" +function next end + +""" + start(iter) -> state + +Get initial iteration state for an iterable object. + +# Examples +```jldoctest +julia> start(1:5) +1 + +julia> start([1;2;3]) +1 + +julia> start([4;2;3]) +1 +``` +""" +function start end + +""" + done(iter, state) -> Bool + +Test whether we are done iterating. + +# Examples +```jldoctest +julia> done(1:5, 3) +false + +julia> done(1:5, 5) +false + +julia> done(1:5, 6) +true +``` +""" +function done end + +""" + isempty(collection) -> Bool + +Determine whether a collection is empty (has no elements). + +# Examples +```jldoctest +julia> isempty([]) +true + +julia> isempty([1 2 3]) +false +``` +""" +isempty(itr) = done(itr, start(itr)) diff --git a/base/event.jl b/base/event.jl index 6dfbe2a8fc176..74bb6ba3069a3 100644 --- a/base/event.jl +++ b/base/event.jl @@ -18,6 +18,29 @@ mutable struct Condition Condition() = new([]) end +""" + wait([x]) + +Block the current task until some event occurs, depending on the type of the argument: + +* [`RemoteChannel`](@ref) : Wait for a value to become available on the specified remote + channel. +* [`Future`](@ref) : Wait for a value to become available for the specified future. +* [`Channel`](@ref): Wait for a value to be appended to the channel. +* [`Condition`](@ref): Wait for [`notify`](@ref) on a condition. +* `Process`: Wait for a process or process chain to exit. The `exitcode` field of a process + can be used to determine success or failure. +* [`Task`](@ref): Wait for a `Task` to finish, returning its result value. If the task fails + with an exception, the exception is propagated (re-thrown in the task that called `wait`). +* `RawFD`: Wait for changes on a file descriptor (see [`poll_fd`](@ref) for keyword + arguments and return code) + +If no argument is passed, the task blocks for an undefined period. A task can only be +restarted by an explicit call to [`schedule`](@ref) or [`yieldto`](@ref). + +Often `wait` is called within a `while` loop to ensure a waited-for condition is met before +proceeding. +""" function wait(c::Condition) ct = current_task() diff --git a/base/float.jl b/base/float.jl index bdf9a47f0adcc..8a611cf38f8e8 100644 --- a/base/float.jl +++ b/base/float.jl @@ -278,6 +278,15 @@ Float64 float(::Type{T}) where {T<:Number} = typeof(float(zero(T))) float(::Type{T}) where {T<:AbstractFloat} = T +""" + unsafe_trunc(T, x) + +`unsafe_trunc(T, x)` returns the nearest integral value of type `T` whose absolute value is +less than or equal to `x`. If the value is not representable by `T`, an arbitrary value will +be returned. +""" +function unsafe_trunc end + for Ti in (Int8, Int16, Int32, Int64) @eval begin unsafe_trunc(::Type{$Ti}, x::Float16) = unsafe_trunc($Ti, Float32(x)) @@ -565,7 +574,14 @@ hash(x::Float64, h::UInt) = isnan(x) ? (hx_NaN ⊻ h) : hx(fptoui(UInt64, abs(x) hash(x::Union{Bool,Int8,UInt8,Int16,UInt16,Int32,UInt32}, h::UInt) = hash(Int64(x), h) hash(x::Float32, h::UInt) = hash(Float64(x), h) -## precision, as defined by the effective number of bits in the mantissa ## +""" + precision(num::AbstractFloat) + +Get the precision of a floating point number, as defined by the effective number of bits in +the mantissa. +""" +function precision end + precision(::Type{Float16}) = 11 precision(::Type{Float32}) = 24 precision(::Type{Float64}) = 53 @@ -690,6 +706,13 @@ for Ti in (Int8, Int16, Int32, Int64, Int128, UInt8, UInt16, UInt32, UInt64, UIn end end +""" + issubnormal(f) -> Bool + +Test whether a floating point number is subnormal. +""" +function issubnormal end + @eval begin issubnormal(x::Float32) = (abs(x) < $(bitcast(Float32, 0x00800000))) & (x!=0) issubnormal(x::Float64) = (abs(x) < $(bitcast(Float64, 0x0010000000000000))) & (x!=0) @@ -710,17 +733,6 @@ end realmax(::Type{Float32}) = $(bitcast(Float32, 0x7f7fffff)) realmax(::Type{Float64}) = $(bitcast(Float64, 0x7fefffffffffffff)) - """ - realmin(T) - - The smallest in absolute value non-subnormal value representable by the given - floating-point DataType `T`. - """ - realmin(x::T) where {T<:AbstractFloat} = realmin(T) - realmax(x::T) where {T<:AbstractFloat} = realmax(T) - realmin() = realmin(Float64) - realmax() = realmax(Float64) - eps(x::AbstractFloat) = isfinite(x) ? abs(x) >= realmin(x) ? ldexp(eps(typeof(x)), exponent(x)) : nextfloat(zero(x)) : oftype(x, NaN) eps(::Type{Float16}) = $(bitcast(Float16, 0x1400)) eps(::Type{Float32}) = $(bitcast(Float32, 0x34000000)) @@ -728,6 +740,33 @@ end eps() = eps(Float64) end +""" + realmin(T) + +The smallest in absolute value non-subnormal value representable by the given +floating-point DataType `T`. +""" +realmin(x::T) where {T<:AbstractFloat} = realmin(T) + +""" + realmax(T) + +The highest finite value representable by the given floating-point DataType `T`. + +# Examples +```jldoctest +julia> realmax(Float16) +Float16(6.55e4) + +julia> realmax(Float32) +3.4028235f38 +``` +""" +realmax(x::T) where {T<:AbstractFloat} = realmax(T) + +realmin() = realmin(Float64) +realmax() = realmax(Float64) + """ eps(::Type{T}) where T<:AbstractFloat eps() diff --git a/base/floatfuncs.jl b/base/floatfuncs.jl index 39b30c73c2e6b..6cde2b86a9bc0 100644 --- a/base/floatfuncs.jl +++ b/base/floatfuncs.jl @@ -237,6 +237,16 @@ function rtoldefault(x::Union{T,Type{T}}, y::Union{S,Type{S}}, atol::Real) where end # fused multiply-add + +""" + fma(x, y, z) + +Computes `x*y+z` without rounding the intermediate result `x*y`. On some systems this is +significantly more expensive than `x*y+z`. `fma` is used to improve accuracy in certain +algorithms. See [`muladd`](@ref). +""" +function fma end + fma_libm(x::Float32, y::Float32, z::Float32) = ccall(("fmaf", libm_name), Float32, (Float32,Float32,Float32), x, y, z) fma_libm(x::Float64, y::Float64, z::Float64) = diff --git a/base/gcutils.jl b/base/gcutils.jl index 3d8f04362ba57..e42cc9e6de303 100644 --- a/base/gcutils.jl +++ b/base/gcutils.jl @@ -4,6 +4,13 @@ ==(w::WeakRef, v) = isequal(w.value, v) ==(w, v::WeakRef) = isequal(w, v.value) +""" + finalizer(x, f) + +Register a function `f(x)` to be called when there are no program-accessible references to +`x`. The type of `x` must be a `mutable struct`, otherwise the behavior of this function is +unpredictable. +""" function finalizer(@nospecialize(o), @nospecialize(f)) if isimmutable(o) error("objects of type ", typeof(o), " cannot be finalized") @@ -11,6 +18,7 @@ function finalizer(@nospecialize(o), @nospecialize(f)) ccall(:jl_gc_add_finalizer_th, Void, (Ptr{Void}, Any, Any), Core.getptls(), o, f) end + function finalizer(o::T, f::Ptr{Void}) where T @_inline_meta if isimmutable(T) @@ -20,8 +28,26 @@ function finalizer(o::T, f::Ptr{Void}) where T Core.getptls(), o, f) end +""" + finalize(x) + +Immediately run finalizers registered for object `x`. +""" finalize(@nospecialize(o)) = ccall(:jl_finalize_th, Void, (Ptr{Void}, Any,), Core.getptls(), o) +""" + gc() + +Perform garbage collection. This should not generally be used. +""" gc(full::Bool=true) = ccall(:jl_gc_collect, Void, (Int32,), full) + +""" + gc_enable(on::Bool) + +Control whether garbage collection is enabled using a boolean argument (`true` for enabled, +`false` for disabled). Returns previous GC state. Disabling garbage collection should be +used only with extreme caution, as it can cause memory use to grow without bound. +""" gc_enable(on::Bool) = ccall(:jl_gc_enable, Int32, (Int32,), on) != 0 diff --git a/base/gmp.jl b/base/gmp.jl index 6ae010c511521..bf12ec5401307 100644 --- a/base/gmp.jl +++ b/base/gmp.jl @@ -392,6 +392,14 @@ convert(::Type{Float16}, n::BigInt) = Float16(n,RoundNearest) promote_rule(::Type{BigInt}, ::Type{<:Integer}) = BigInt +""" + big(x) + +Convert a number to a maximum precision representation (typically [`BigInt`](@ref) or +`BigFloat`). See [`BigFloat`](@ref) for information about some pitfalls with floating-point numbers. +""" +function big end + big(::Type{<:Integer}) = BigInt big(::Type{<:Rational}) = Rational{BigInt} diff --git a/base/hashing.jl b/base/hashing.jl index 331d6c214ea3e..ee4be4d384941 100644 --- a/base/hashing.jl +++ b/base/hashing.jl @@ -2,6 +2,17 @@ ## hashing a single value ## +""" + hash(x[, h::UInt]) + +Compute an integer hash code such that `isequal(x,y)` implies `hash(x)==hash(y)`. The +optional second argument `h` is a hash code to be mixed with the result. + +New types should implement the 2-argument form, typically by calling the 2-argument `hash` +method recursively in order to mix hashes of the contents with each other (and with `h`). +Typically, any type that implements `hash` should also implement its own `==` (hence +`isequal`) to guarantee the property mentioned above. +""" hash(x::Any) = hash(x, zero(UInt)) hash(w::WeakRef, h::UInt) = hash(w.value, h) diff --git a/base/int.jl b/base/int.jl index 29f206dab146c..7650c6e5a1bb6 100644 --- a/base/int.jl +++ b/base/int.jl @@ -294,6 +294,26 @@ julia> 4 | 1 (|)(x::T, y::T) where {T<:BitInteger} = or_int(x, y) xor(x::T, y::T) where {T<:BitInteger} = xor_int(x, y) +""" + bswap(n) + +Byte-swap an integer. Flip the bits of its binary representation. + +# Examples +```jldoctest +julia> a = bswap(4) +288230376151711744 + +julia> bswap(a) +4 + +julia> bin(1) +"1" + +julia> bin(bswap(1)) +"100000000000000000000000000000000000000000000000000000000" +``` +""" bswap(x::Union{Int8, UInt8}) = x bswap(x::Union{Int16, UInt16, Int32, UInt32, Int64, UInt64, Int128, UInt128}) = bswap_int(x) @@ -513,6 +533,45 @@ convert(::Type{Unsigned}, x::Union{Float32, Float64, Bool}) = convert(UInt, x) convert(::Type{Integer}, x::Integer) = x convert(::Type{Integer}, x::Real) = convert(Signed, x) +""" + trunc([T,] x, [digits, [base]]) + +`trunc(x)` returns the nearest integral value of the same type as `x` whose absolute value +is less than or equal to `x`. + +`trunc(T, x)` converts the result to type `T`, throwing an `InexactError` if the value is +not representable. + +`digits` and `base` work as for [`round`](@ref). +""" +function trunc end + +""" + floor([T,] x, [digits, [base]]) + +`floor(x)` returns the nearest integral value of the same type as `x` that is less than or +equal to `x`. + +`floor(T, x)` converts the result to type `T`, throwing an `InexactError` if the value is +not representable. + +`digits` and `base` work as for [`round`](@ref). +""" +function floor end + +""" + ceil([T,] x, [digits, [base]]) + +`ceil(x)` returns the nearest integral value of the same type as `x` that is greater than or +equal to `x`. + +`ceil(T, x)` converts the result to type `T`, throwing an `InexactError` if the value is not +representable. + +`digits` and `base` work as for [`round`](@ref). +""" +function ceil end + round(x::Integer) = x trunc(x::Integer) = x floor(x::Integer) = x @@ -568,6 +627,29 @@ _default_type(::Union{Type{Integer},Type{Signed}}) = Int ## traits ## +""" + typemin(T) + +The lowest value representable by the given (real) numeric DataType `T`. + +# Examples +```jldoctest +julia> typemin(Float16) +-Inf16 + +julia> typemin(Float32) +-Inf32 +``` +""" +function typemin end + +""" + typemax(T) + +The highest value representable by the given (real) numeric `DataType`. +""" +function typemax end + typemin(::Type{Int8 }) = Int8(-128) typemax(::Type{Int8 }) = Int8(127) typemin(::Type{UInt8 }) = UInt8(0) diff --git a/base/intfuncs.jl b/base/intfuncs.jl index d6c782e33a89e..da4fa67d9f22a 100644 --- a/base/intfuncs.jl +++ b/base/intfuncs.jl @@ -700,6 +700,22 @@ julia> dec(20, 3) """ dec +""" + bits(n) + +A string giving the literal bit representation of a number. + +# Examples +```jldoctest +julia> bits(4) +"0000000000000000000000000000000000000000000000000000000000000100" + +julia> bits(2.2) +"0100000000000001100110011001100110011001100110011001100110011010" +``` +""" +function bits end + bits(x::Union{Bool,Int8,UInt8}) = bin(reinterpret(UInt8,x),8) bits(x::Union{Int16,UInt16,Float16}) = bin(reinterpret(UInt16,x),16) bits(x::Union{Char,Int32,UInt32,Float32}) = bin(reinterpret(UInt32,x),32) diff --git a/base/io.jl b/base/io.jl index b08f62e5df4c1..34829dae03a0e 100644 --- a/base/io.jl +++ b/base/io.jl @@ -77,6 +77,17 @@ function iswritable end function copy end function eof end +""" + read(stream::IO, T) + +Read a single value of type `T` from `stream`, in canonical binary representation. + + read(stream::IO, String) + +Read the entirety of `stream`, as a String. +""" +read(stream, t) + """ write(stream::IO, x) write(filename::AbstractString, x) @@ -190,6 +201,15 @@ Open a file and read its contents. `args` is passed to `read`: this is equivalen Read the entire contents of a file as a string. """ read(filename::AbstractString, args...) = open(io->read(io, args...), filename) + +""" + read!(stream::IO, array::Union{Array, BitArray}) + read!(filename::AbstractString, array::Union{Array, BitArray}) + +Read binary data from an I/O stream or file, filling in `array`. +""" +function read! end + read!(filename::AbstractString, a) = open(io->read!(io, a), filename) """ diff --git a/base/iostream.jl b/base/iostream.jl index 3ee3c315d36c3..7ae9f112f50f6 100644 --- a/base/iostream.jl +++ b/base/iostream.jl @@ -26,7 +26,15 @@ IOStream(name::AbstractString) = IOStream(name, true) unsafe_convert(T::Type{Ptr{Void}}, s::IOStream) = convert(T, pointer(s.ios)) show(io::IO, s::IOStream) = print(io, "IOStream(", s.name, ")") + +""" + fd(stream) + +Returns the file descriptor backing the stream or file. Note that this function only applies +to synchronous `File`'s and `IOStream`'s not to any of the asynchronous streams. +""" fd(s::IOStream) = Int(ccall(:jl_ios_fd, Clong, (Ptr{Void},), s.ios)) + stat(s::IOStream) = stat(fd(s)) close(s::IOStream) = ccall(:ios_close, Void, (Ptr{Void},), s.ios) isopen(s::IOStream) = ccall(:ios_isopen, Cint, (Ptr{Void},), s.ios)!=0 @@ -39,11 +47,22 @@ end iswritable(s::IOStream) = ccall(:ios_get_writable, Cint, (Ptr{Void},), s.ios)!=0 isreadable(s::IOStream) = ccall(:ios_get_readable, Cint, (Ptr{Void},), s.ios)!=0 +""" + truncate(file,n) + +Resize the file or buffer given by the first argument to exactly `n` bytes, filling +previously unallocated space with '\\0' if the file or buffer is grown. +""" function truncate(s::IOStream, n::Integer) systemerror("truncate", ccall(:ios_trunc, Cint, (Ptr{Void}, Csize_t), s.ios, n) != 0) return s end +""" + seek(s, pos) + +Seek a stream to the given position. +""" function seek(s::IOStream, n::Integer) ret = ccall(:ios_seek, Int64, (Ptr{Void}, Int64), s.ios, n) systemerror("seek", ret == -1) @@ -51,13 +70,28 @@ function seek(s::IOStream, n::Integer) return s end +""" + seekstart(s) + +Seek a stream to its beginning. +""" seekstart(s::IO) = seek(s,0) +""" + seekend(s) + +Seek a stream to its end. +""" function seekend(s::IOStream) systemerror("seekend", ccall(:ios_seek_end, Int64, (Ptr{Void},), s.ios) != 0) return s end +""" + skip(s, offset) + +Seek a stream relative to the current position. +""" function skip(s::IOStream, delta::Integer) ret = ccall(:ios_skip, Int64, (Ptr{Void}, Int64), s.ios, delta) systemerror("skip", ret == -1) @@ -65,6 +99,11 @@ function skip(s::IOStream, delta::Integer) return s end +""" + position(s) + +Get the current position of a stream. +""" function position(s::IOStream) pos = ccall(:ios_pos, Int64, (Ptr{Void},), s.ios) systemerror("position", pos == -1) diff --git a/base/libc.jl b/base/libc.jl index 98f254416166d..810cda11e448f 100644 --- a/base/libc.jl +++ b/base/libc.jl @@ -220,6 +220,12 @@ end Converts a `TmStruct` struct to a number of seconds since the epoch. """ time(tm::TmStruct) = Float64(ccall(:mktime, Int, (Ptr{TmStruct},), &tm)) + +""" + time() + +Get the system time in seconds since the epoch, with fairly high (typically, microsecond) resolution. +""" time() = ccall(:jl_clock_now, Float64, ()) ## process-related functions ## diff --git a/base/mmap.jl b/base/mmap.jl index edc8c332ee7a4..c8d111e037330 100644 --- a/base/mmap.jl +++ b/base/mmap.jl @@ -11,7 +11,14 @@ mutable struct Anonymous <: IO create::Bool end +""" + Mmap.Anonymous(name, readonly, create) + +Create an `IO`-like object for creating zeroed-out mmapped-memory that is not tied to a file +for use in `Mmap.mmap`. Used by `SharedArray` for creating shared memory arrays. +""" Anonymous() = Anonymous("",false,true) + Base.isopen(::Anonymous) = true Base.isreadable(::Anonymous) = true Base.iswritable(a::Anonymous) = !a.readonly @@ -94,6 +101,65 @@ else end # os-test # core implementation of mmap + +""" + Mmap.mmap(io::Union{IOStream,AbstractString,Mmap.AnonymousMmap}[, type::Type{Array{T,N}}, dims, offset]; grow::Bool=true, shared::Bool=true) + Mmap.mmap(type::Type{Array{T,N}}, dims) + +Create an `Array` whose values are linked to a file, using memory-mapping. This provides a +convenient way of working with data too large to fit in the computer's memory. + +The type is an `Array{T,N}` with a bits-type element of `T` and dimension `N` that +determines how the bytes of the array are interpreted. Note that the file must be stored in +binary format, and no format conversions are possible (this is a limitation of operating +systems, not Julia). + +`dims` is a tuple or single [`Integer`](@ref) specifying the size or length of the array. + +The file is passed via the stream argument, either as an open `IOStream` or filename string. +When you initialize the stream, use `"r"` for a "read-only" array, and `"w+"` to create a +new array used to write values to disk. + +If no `type` argument is specified, the default is `Vector{UInt8}`. + +Optionally, you can specify an offset (in bytes) if, for example, you want to skip over a +header in the file. The default value for the offset is the current stream position for an +`IOStream`. + +The `grow` keyword argument specifies whether the disk file should be grown to accommodate +the requested size of array (if the total file size is < requested array size). Write +privileges are required to grow the file. + +The `shared` keyword argument specifies whether the resulting `Array` and changes made to it +will be visible to other processes mapping the same file. + +For example, the following code + +```julia +# Create a file for mmapping +# (you could alternatively use mmap to do this step, too) +A = rand(1:20, 5, 30) +s = open("/tmp/mmap.bin", "w+") +# We'll write the dimensions of the array as the first two Ints in the file +write(s, size(A,1)) +write(s, size(A,2)) +# Now write the data +write(s, A) +close(s) + +# Test by reading it back in +s = open("/tmp/mmap.bin") # default is read-only +m = read(s, Int) +n = read(s, Int) +A2 = Mmap.mmap(s, Matrix{Int}, (m,n)) +``` + +creates a `m`-by-`n` `Matrix{Int}`, linked to the file associated with stream `s`. + +A more portable file would need to encode the word size -- 32 bit or 64 bit -- and endianness +information in the header. In practice, consider encoding binary data using standard formats +like HDF5 (which can be used with memory-mapping). +""" function mmap(io::IO, ::Type{Array{T,N}}=Vector{UInt8}, dims::NTuple{N,Integer}=(div(filesize(io)-position(io),sizeof(T)),), @@ -165,6 +231,17 @@ mmap(file::AbstractString, ::Type{T}, len::Integer, offset::Integer=Int64(0); gr mmap(::Type{T}, dims::NTuple{N,Integer}; shared::Bool=true) where {T<:Array,N} = mmap(Anonymous(), T, dims, Int64(0); shared=shared) mmap(::Type{T}, i::Integer...; shared::Bool=true) where {T<:Array} = mmap(Anonymous(), T, convert(Tuple{Vararg{Int}},i), Int64(0); shared=shared) +""" + Mmap.mmap(io, BitArray, [dims, offset]) + +Create a `BitArray` whose values are linked to a file, using memory-mapping; it has the same +purpose, works in the same way, and has the same arguments, as [`mmap`](@ref Mmap.mmap), but +the byte representation is different. + +**Example**: `B = Mmap.mmap(s, BitArray, (25,30000))` + +This would create a 25-by-30000 `BitArray`, linked to the file associated with stream `s`. +""" function mmap(io::IOStream, ::Type{<:BitArray}, dims::NTuple{N,Integer}, offset::Int64=position(io); grow::Bool=true, shared::Bool=true) where N n = prod(dims) @@ -204,6 +281,12 @@ const MS_ASYNC = 1 const MS_INVALIDATE = 2 const MS_SYNC = 4 +""" + Mmap.sync!(array) + +Forces synchronization between the in-memory version of a memory-mapped `Array` or +`BitArray` and the on-disk version. +""" function sync!(m::Array{T}, flags::Integer=MS_SYNC) where T offset = rem(UInt(pointer(m)), PAGESIZE) ptr = pointer(m) - offset diff --git a/base/multidimensional.jl b/base/multidimensional.jl index 36afa13727d0b..a70c0dd5b2e2a 100644 --- a/base/multidimensional.jl +++ b/base/multidimensional.jl @@ -854,6 +854,38 @@ end ### from abstractarray.jl +""" + fill!(A, x) + +Fill array `A` with the value `x`. If `x` is an object reference, all elements will refer to +the same object. `fill!(A, Foo())` will return `A` filled with the result of evaluating +`Foo()` once. + +# Examples +```jldoctest +julia> A = zeros(2,3) +2×3 Array{Float64,2}: + 0.0 0.0 0.0 + 0.0 0.0 0.0 + +julia> fill!(A, 2.) +2×3 Array{Float64,2}: + 2.0 2.0 2.0 + 2.0 2.0 2.0 + +julia> a = [1, 1, 1]; A = fill!(Vector{Vector{Int}}(3), a); a[1] = 2; A +3-element Array{Array{Int64,1},1}: + [2, 1, 1] + [2, 1, 1] + [2, 1, 1] + +julia> x = 0; f() = (global x += 1; x); fill!(Vector{Int}(3), f()) +3-element Array{Int64,1}: + 1 + 1 + 1 +``` +""" function fill!(A::AbstractArray{T}, x) where T xT = convert(T, x) for I in eachindex(A) diff --git a/base/multimedia.jl b/base/multimedia.jl index 31e35bfbd4ad8..59fdd6aab7d20 100644 --- a/base/multimedia.jl +++ b/base/multimedia.jl @@ -44,6 +44,37 @@ false mimewritable(::MIME{mime}, x) where {mime} = method_exists(show, Tuple{IO, MIME{mime}, typeof(x)}) +""" + show(stream, mime, x) + +The [`display`](@ref) functions ultimately call `show` in order to write an object `x` as a +given `mime` type to a given I/O `stream` (usually a memory buffer), if possible. In order +to provide a rich multimedia representation of a user-defined type `T`, it is only necessary +to define a new `show` method for `T`, via: `show(stream, ::MIME"mime", x::T) = ...`, +where `mime` is a MIME-type string and the function body calls `write` (or similar) to write +that representation of `x` to `stream`. (Note that the `MIME""` notation only supports +literal strings; to construct `MIME` types in a more flexible manner use +`MIME{Symbol("")}`.) + +For example, if you define a `MyImage` type and know how to write it to a PNG file, you +could define a function `show(stream, ::MIME"image/png", x::MyImage) = ...` to allow +your images to be displayed on any PNG-capable `Display` (such as IJulia). As usual, be sure +to `import Base.show` in order to add new methods to the built-in Julia function +`show`. + +The default MIME type is `MIME"text/plain"`. There is a fallback definition for `text/plain` +output that calls `show` with 2 arguments. Therefore, this case should be handled by +defining a 2-argument `show(stream::IO, x::MyType)` method. + +Technically, the `MIME"mime"` macro defines a singleton type for the given `mime` string, +which allows us to exploit Julia's dispatch mechanisms in determining how to display objects +of any given type. + +The first argument to `show` can be an [`IOContext`](@ref) specifying output format properties. +See [`IOContext`](@ref) for details. +""" +show(stream, mime, x) + # it is convenient to accept strings instead of ::MIME show(io::IO, m::AbstractString, x) = show(io, MIME(m), x) mimewritable(m::AbstractString, x) = mimewritable(MIME(m), x) diff --git a/base/nullable.jl b/base/nullable.jl index 8d7d6f685825a..5a4d4f0c46fc4 100644 --- a/base/nullable.jl +++ b/base/nullable.jl @@ -1,5 +1,21 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license +""" + NullException() + +An attempted access to a [`Nullable`](@ref) with no defined value. + +# Examples +```jldoctest +julia> a = Nullable{Int}() +Nullable{Int64}() + +julia> get(a) +ERROR: NullException() +Stacktrace: + [1] get(::Nullable{Int64}) at ./nullable.jl:92 +``` +""" struct NullException <: Exception end diff --git a/base/number.jl b/base/number.jl index 255ceebf9af6c..1a95f2dee6a77 100644 --- a/base/number.jl +++ b/base/number.jl @@ -146,6 +146,21 @@ julia> flipsign(5, -3) ``` """ flipsign(x::Real, y::Real) = ifelse(signbit(y), -x, +x) # the + is for type-stability on Bool + +""" + copysign(x, y) -> z + +Return `z` which has the magnitude of `x` and the same sign as `y`. + +# Examples +```jldoctest +julia> copysign(1, -2) +-1 + +julia> copysign(-1, 2) +1 +``` +""" copysign(x::Real, y::Real) = ifelse(signbit(x)!=signbit(y), -x, +x) conj(x::Real) = x diff --git a/base/operators.jl b/base/operators.jl index 0228d78bc6d4a..08fa05c50705c 100644 --- a/base/operators.jl +++ b/base/operators.jl @@ -50,6 +50,21 @@ end ## generic comparison ## +""" + ==(x, y) + +Generic equality operator, giving a single [`Bool`](@ref) result. Falls back to `===`. +Should be implemented for all types with a notion of equality, based on the abstract value +that an instance represents. For example, all numeric types are compared by numeric value, +ignoring type. Strings are compared as sequences of characters, ignoring encoding. + +Follows IEEE semantics for floating-point numbers. + +Collections should generally implement `==` by calling `==` recursively on all contents. + +New numeric types should implement this function for two arguments of the new type, and +handle comparison to other types via promotion rules where possible. +""" ==(x, y) = x === y """ @@ -95,6 +110,17 @@ isequal(x::AbstractFloat, y::AbstractFloat) = (isnan(x) & isnan(y)) | signequal( isequal(x::Real, y::AbstractFloat) = (isnan(x) & isnan(y)) | signequal(x, y) & (x == y) isequal(x::AbstractFloat, y::Real ) = (isnan(x) & isnan(y)) | signequal(x, y) & (x == y) +""" + isless(x, y) + +Test whether `x` is less than `y`, according to a canonical total order. Values that are +normally unordered, such as `NaN`, are ordered in an arbitrary but consistent fashion. This +is the default comparison used by [`sort`](@ref). Non-numeric types with a canonical total order +should implement this function. Numeric types only need to implement it if they have special +values such as `NaN`. +""" +function isless end + isless(x::AbstractFloat, y::AbstractFloat) = (!isnan(x) & isnan(y)) | signless(x, y) | (x < y) isless(x::Real, y::AbstractFloat) = (!isnan(x) & isnan(y)) | signless(x, y) | (x < y) isless(x::AbstractFloat, y::Real ) = (!isnan(x) & isnan(y)) | signless(x, y) | (x < y) diff --git a/base/parse.jl b/base/parse.jl index 1ef3f91278cb6..91e1d0f5ab422 100644 --- a/base/parse.jl +++ b/base/parse.jl @@ -4,6 +4,29 @@ import Base.Checked: add_with_overflow, mul_with_overflow ## string to integer functions ## +""" + parse(type, str, [base]) + +Parse a string as a number. If the type is an integer type, then a base can be specified +(the default is 10). If the type is a floating point type, the string is parsed as a decimal +floating point number. If the string does not contain a valid number, an error is raised. + +```jldoctest +julia> parse(Int, "1234") +1234 + +julia> parse(Int, "1234", 5) +194 + +julia> parse(Int, "afc", 16) +2812 + +julia> parse(Float64, "1.2e-3") +0.0012 +``` +""" +parse(T::Type, str, base=Int) + function parse(::Type{T}, c::Char, base::Integer=36) where T<:Integer a::Int = (base <= 36 ? 10 : 36) 2 <= base <= 62 || throw(ArgumentError("invalid base: base must be 2 ≤ base ≤ 62, got $base")) @@ -227,6 +250,25 @@ mutable struct ParseError <: Exception msg::AbstractString end +""" + parse(str, start; greedy=true, raise=true) + +Parse the expression string and return an expression (which could later be passed to eval +for execution). `start` is the index of the first character to start parsing. If `greedy` is +`true` (default), `parse` will try to consume as much input as it can; otherwise, it will +stop as soon as it has parsed a valid expression. Incomplete but otherwise syntactically +valid expressions will return `Expr(:incomplete, "(error message)")`. If `raise` is `true` +(default), syntax errors other than incomplete expressions will raise an error. If `raise` +is `false`, `parse` will return an expression that will raise an error upon evaluation. + +```jldoctest +julia> parse("x = 3, y = 5", 7) +(:(y = 5), 13) + +julia> parse("x = 3, y = 5", 5) +(:((3, y) = 5), 13) +``` +""" function parse(str::AbstractString, pos::Int; greedy::Bool=true, raise::Bool=true) # pos is one based byte offset. # returns (expr, end_pos). expr is () in case of parse error. @@ -244,6 +286,30 @@ function parse(str::AbstractString, pos::Int; greedy::Bool=true, raise::Bool=tru return ex, pos+1 # C is zero-based, Julia is 1-based end +""" + parse(str; raise=true) + +Parse the expression string greedily, returning a single expression. An error is thrown if +there are additional characters after the first expression. If `raise` is `true` (default), +syntax errors will raise an error; otherwise, `parse` will return an expression that will +raise an error upon evaluation. + +```jldoctest +julia> parse("x = 3") +:(x = 3) + +julia> parse("x = ") +:($(Expr(:incomplete, "incomplete: premature end of input"))) + +julia> parse("1.0.2") +ERROR: ParseError("invalid numeric constant \\\"1.0.\\\"") +Stacktrace: +[...] + +julia> parse("1.0.2"; raise = false) +:($(Expr(:error, "invalid numeric constant \"1.0.\""))) +``` +""" function parse(str::AbstractString; raise::Bool=true) ex, pos = parse(str, 1, greedy=true, raise=raise) if isa(ex,Expr) && ex.head === :error diff --git a/base/pointer.jl b/base/pointer.jl index fee9420a39950..2e3e0e957d8e5 100644 --- a/base/pointer.jl +++ b/base/pointer.jl @@ -32,6 +32,30 @@ convert(::Type{Ptr{T}}, p::Ptr{T}) where {T} = p convert(::Type{Ptr{T}}, p::Ptr) where {T} = bitcast(Ptr{T}, p) # object to pointer (when used with ccall) + +""" + unsafe_convert(T, x) + +Convert `x` to a C argument of type `T` +where the input `x` must be the return value of `cconvert(T, ...)`. + +In cases where [`convert`](@ref) would need to take a Julia object +and turn it into a `Ptr`, this function should be used to define and perform +that conversion. + +Be careful to ensure that a Julia reference to `x` exists as long as the result of this +function will be used. Accordingly, the argument `x` to this function should never be an +expression, only a variable name or field reference. For example, `x=a.b.c` is acceptable, +but `x=[a,b,c]` is not. + +The `unsafe` prefix on this function indicates that using the result of this function after +the `x` argument to this function is no longer accessible to the program may cause undefined +behavior, including program corruption or segfaults, at any later time. + +See also [`cconvert`](@ref) +""" +function unsafe_convert end + unsafe_convert(::Type{Ptr{UInt8}}, x::Symbol) = ccall(:jl_symbol_name, Ptr{UInt8}, (Any,), x) unsafe_convert(::Type{Ptr{Int8}}, x::Symbol) = ccall(:jl_symbol_name, Ptr{Int8}, (Any,), x) unsafe_convert(::Type{Ptr{UInt8}}, s::String) = convert(Ptr{UInt8}, pointer_from_objref(s)+sizeof(Int)) diff --git a/base/process.jl b/base/process.jl index 31791b8d83af8..781e1d3ea1f94 100644 --- a/base/process.jl +++ b/base/process.jl @@ -550,6 +550,11 @@ spawn_opts_inherit(stdios::StdIOSet) = (stdios,) spawn_opts_inherit(in::Redirectable=RawFD(0), out::Redirectable=RawFD(1), err::Redirectable=RawFD(2), args...) = ((in, out, err), args...) +""" + spawn(command) + +Run a command object asynchronously, returning the resulting `Process` object. +""" spawn(cmds::AbstractCmd, args...; chain::Nullable{ProcessChain}=Nullable{ProcessChain}()) = spawn(cmds, spawn_opts_swallow(args...)...; chain=chain) diff --git a/base/promotion.jl b/base/promotion.jl index ca79a451bfa07..d51f4811e9d61 100644 --- a/base/promotion.jl +++ b/base/promotion.jl @@ -2,6 +2,11 @@ ## type join (closest common ancestor, or least upper bound) ## +""" + typejoin(T, S) + +Compute a type that contains both `T` and `S`. +""" typejoin() = (@_pure_meta; Bottom) typejoin(@nospecialize(t)) = (@_pure_meta; t) typejoin(@nospecialize(t), ts...) = (@_pure_meta; typejoin(t, typejoin(ts...))) @@ -163,6 +168,15 @@ function promote_type(::Type{T}, ::Type{S}) where {T,S} promote_result(T, S, promote_rule(T,S), promote_rule(S,T)) end +""" + promote_rule(type1, type2) + +Specifies what type should be used by [`promote`](@ref) when given values of types `type1` and +`type2`. This function should not be called directly, but should have definitions added to +it for new types as appropriate. +""" +function promote_rule end + promote_rule(::Type{<:Any}, ::Type{<:Any}) = Bottom promote_result(::Type{<:Any},::Type{<:Any},::Type{T},::Type{S}) where {T,S} = (@_inline_meta; promote_type(T,S)) @@ -170,6 +184,19 @@ promote_result(::Type{<:Any},::Type{<:Any},::Type{T},::Type{S}) where {T,S} = (@ # case use typejoin on the original types instead. promote_result(::Type{T},::Type{S},::Type{Bottom},::Type{Bottom}) where {T,S} = (@_inline_meta; typejoin(T, S)) +""" + promote(xs...) + +Convert all arguments to their common promotion type (if any), and return them all (as a tuple). + +# Examples +```jldoctest +julia> promote(Int8(1), Float16(4.5), Float32(4.1)) +(1.0f0, 4.5f0, 4.1f0) +``` +""" +function promote end + promote() = () promote(x) = (x,) function promote(x::T, y::S) where {T,S} diff --git a/base/random.jl b/base/random.jl index 6a332d05f555d..04a7fcb39fe25 100644 --- a/base/random.jl +++ b/base/random.jl @@ -1683,6 +1683,13 @@ end # each element of A is included in S with independent probability p. # (Note that this is different from the problem of finding a random # size-m subset of A where m is fixed!) + +""" + randsubseq!(S, A, p) + +Like [`randsubseq`](@ref), but the results are stored in `S` +(which is resized as needed). +""" function randsubseq!(r::AbstractRNG, S::AbstractArray, A::AbstractArray, p::Real) 0 <= p <= 1 || throw(ArgumentError("probability $p not in [0,1]")) n = length(A) diff --git a/base/reflection.jl b/base/reflection.jl index 032c20c4b4009..f654458446948 100644 --- a/base/reflection.jl +++ b/base/reflection.jl @@ -216,7 +216,11 @@ macro isdefined(s::Symbol) return Expr(:isdefined, esc(s)) end -# return an integer such that object_id(x)==object_id(y) if x===y +""" + object_id(x) + +Get a hash value for `x` based on object identity. `object_id(x)==object_id(y)` if `x === y`. +""" object_id(@nospecialize(x)) = ccall(:jl_object_id, UInt, (Any,), x) struct DataTypeLayout diff --git a/base/regex.jl b/base/regex.jl index fec921d0c810d..ffea88ec79eb8 100644 --- a/base/regex.jl +++ b/base/regex.jl @@ -141,6 +141,11 @@ function getindex(m::RegexMatch, name::Symbol) end getindex(m::RegexMatch, name::AbstractString) = m[Symbol(name)] +""" + ismatch(r::Regex, s::AbstractString) -> Bool + +Test whether a string contains a match of the given regular expression. +""" function ismatch(r::Regex, s::AbstractString, offset::Integer=0) compile(r) return PCRE.exec(r.regex, String(s), offset, r.match_options, @@ -155,6 +160,16 @@ end (r::Regex)(s) = ismatch(r, s) +""" + match(r::Regex, s::AbstractString[, idx::Integer[, addopts]]) + +Search for the first match of the regular expression `r` in `s` and return a `RegexMatch` +object containing the match, or nothing if the match failed. The matching substring can be +retrieved by accessing `m.match` and the captured sequences can be retrieved by accessing +`m.captures` The optional `idx` argument specifies an index at which to start the search. +""" +function match end + function match(re::Regex, str::Union{SubString{String}, String}, idx::Integer, add_opts::UInt32=UInt32(0)) compile(re) opts = re.match_options | add_opts @@ -175,6 +190,11 @@ match(r::Regex, s::AbstractString, i::Integer) = throw(ArgumentError( "regex matching is only available for the String type; use String(s) to convert" )) +""" + matchall(r::Regex, s::AbstractString[, overlap::Bool=false]) -> Vector{AbstractString} + +Return a vector of the matching substrings from [`eachmatch`](@ref). +""" function matchall(re::Regex, str::String, overlap::Bool=false) regex = compile(re).regex n = sizeof(str) @@ -362,6 +382,13 @@ function eachmatch(re::Regex, str::AbstractString, ovr::Bool) RegexMatchIterator(re,str,ovr) end +""" + eachmatch(r::Regex, s::AbstractString[, overlap::Bool=false]) + +Search for all matches of a the regular expression `r` in `s` and return a iterator over the +matches. If overlap is `true`, the matching sequences are allowed to overlap indices in the +original string, otherwise they must be from distinct character ranges. +""" eachmatch(re::Regex, str::AbstractString) = RegexMatchIterator(re,str) ## comparison ## diff --git a/base/serialize.jl b/base/serialize.jl index 6a6847a850e90..b78b658430fe5 100644 --- a/base/serialize.jl +++ b/base/serialize.jl @@ -637,10 +637,28 @@ function serialize_any(s::AbstractSerializer, @nospecialize(x)) end end +""" + serialize(stream, value) + +Write an arbitrary value to a stream in an opaque format, such that it can be read back by +[`deserialize`](@ref). The read-back value will be as identical as possible to the original. In +general, this process will not work if the reading and writing are done by different +versions of Julia, or an instance of Julia with a different system image. `Ptr` values are +serialized as all-zero bit patterns (`NULL`). +""" serialize(s::IO, x) = serialize(SerializationState(s), x) ## deserializing values ## +""" + deserialize(stream) + +Read a value written by [`serialize`](@ref). `deserialize` assumes the binary data read from +`stream` is correct and has been serialized by a compatible implementation of [`serialize`](@ref). +It has been designed with simplicity and performance as a goal and does not validate +the data read. Malformed data can result in process termination. The caller has to ensure +the integrity and correctness of data read from `stream`. +""" deserialize(s::IO) = deserialize(SerializationState(s)) function deserialize(s::AbstractSerializer) diff --git a/base/set.jl b/base/set.jl index 51603130e01b7..f5ced5e45d779 100644 --- a/base/set.jl +++ b/base/set.jl @@ -65,6 +65,36 @@ done(s::Set, state) = done(s.dict, state) # NOTE: manually optimized to take advantage of Dict representation next(s::Set, i) = (s.dict.keys[i], skip_deleted(s.dict, i+1)) +""" + union(s1,s2...) + ∪(s1,s2...) + +Construct the union of two or more sets. Maintains order with arrays. + +# Examples +```jldoctest +julia> union([1, 2], [3, 4]) +4-element Array{Int64,1}: + 1 + 2 + 3 + 4 + +julia> union([1, 2], [2, 4]) +3-element Array{Int64,1}: + 1 + 2 + 4 + +julia> union([4, 2], [1, 2]) +3-element Array{Int64,1}: + 4 + 2 + 1 +``` +""" +function union end + union(s::Set) = copy(s) function union(s::Set, sets...) u = Set{join_eltype(s, sets...)}() @@ -103,6 +133,28 @@ end join_eltype() = Bottom join_eltype(v1, vs...) = typejoin(eltype(v1), join_eltype(vs...)) +""" + intersect(s1,s2...) + ∩(s1,s2) + +Construct the intersection of two or more sets. +Maintains order and multiplicity of the first argument for arrays and ranges. + +# Examples +```jldoctest +julia> intersect([1, 2, 3], [3, 4, 5]) +1-element Array{Int64,1}: + 3 + +julia> intersect([1, 4, 4, 5, 6], [4, 6, 6, 7, 8]) +3-element Array{Int64,1}: + 4 + 4 + 6 +``` +""" +function intersect end + intersect(s::Set) = copy(s) function intersect(s::Set, sets...) i = similar(s) diff --git a/base/show.jl b/base/show.jl index 303055c80b633..79678aab589a3 100644 --- a/base/show.jl +++ b/base/show.jl @@ -122,7 +122,17 @@ function show_circular(io::IOContext, @nospecialize(x)) return false end +""" + show(x) + +Write an informative text representation of a value to the current output stream. New types +should overload `show(io, x)` where the first argument is a stream. The representation used +by `show` generally includes Julia-specific formatting and type information. +""" +show(x) = show(STDOUT::IO, x) + show(io::IO, @nospecialize(x)) = show_default(io, x) + function show_default(io::IO, @nospecialize(x)) t = typeof(x)::DataType show(io, t) @@ -1362,6 +1372,12 @@ end dump(io::IO, x::DataType; maxdepth=8) = ((x.abstract ? dumptype : dump)(io, x, maxdepth, ""); println(io)) dump(io::IO, arg; maxdepth=8) = (dump(io, arg, maxdepth, ""); println(io)) + +""" + dump(x) + +Show every part of the representation of a value. +""" dump(arg; maxdepth=8) = dump(IOContext(STDOUT::IO, :limit => true), arg; maxdepth=maxdepth) diff --git a/base/socket.jl b/base/socket.jl index fd1298fdb5f9f..588e0097a69a5 100644 --- a/base/socket.jl +++ b/base/socket.jl @@ -333,6 +333,13 @@ _jl_sockaddr_from_addrinfo(addrinfo::Ptr{Void}) = _jl_sockaddr_set_port(ptr::Ptr{Void}, port::UInt16) = ccall(:jl_sockaddr_set_port, Void, (Ptr{Void}, UInt16), ptr, port) +""" + accept(server[,client]) + +Accepts a connection on the given server and returns a connection to the client. An +uninitialized client stream may be provided, in which case it will be used instead of +creating a new stream. +""" accept(server::TCPServer) = accept(server, TCPSocket()) # Libuv will internally reset the readable and writable flags on diff --git a/base/sort.jl b/base/sort.jl index 717de598a23aa..090a2f880a957 100644 --- a/base/sort.jl +++ b/base/sort.jl @@ -87,10 +87,68 @@ function select!(v::AbstractVector, k::Union{Int,OrdinalRange}, o::Ordering) sort!(v, first(inds), last(inds), PartialQuickSort(k), o) v[k] end + +""" + select!(v, k, [by=,] [lt=,] [rev=false]) + +Partially sort the vector `v` in place, according to the order specified by `by`, `lt` and +`rev` so that the value at index `k` (or range of adjacent values if `k` is a range) occurs +at the position where it would appear if the array were fully sorted via a non-stable +algorithm. If `k` is a single index, that value is returned; if `k` is a range, an array of +values at those indices is returned. Note that `select!` does not fully sort the input +array. + +# Examples +```jldoctest +julia> a = [1, 2, 4, 3, 4] +5-element Array{Int64,1}: + 1 + 2 + 4 + 3 + 4 + +julia> select!(a, 4) +4 + +julia> a +5-element Array{Int64,1}: + 1 + 2 + 3 + 4 + 4 + +julia> a = [1, 2, 4, 3, 4] +5-element Array{Int64,1}: + 1 + 2 + 4 + 3 + 4 + +julia> select!(a, 4, rev=true) +2 + +julia> a +5-element Array{Int64,1}: + 4 + 4 + 3 + 2 + 1 +``` +""" select!(v::AbstractVector, k::Union{Int,OrdinalRange}; lt=isless, by=identity, rev::Bool=false, order::Ordering=Forward) = select!(v, k, ord(lt,by,rev,order)) +""" + select(v, k, [by=,] [lt=,] [rev=false]) + +Variant of [`select!`](@ref) which copies `v` before partially sorting it, thereby returning the +same thing as `select!` but leaving `v` unmodified. +""" select(v::AbstractVector, k::Union{Int,OrdinalRange}; kws...) = select!(copymutable(v), k; kws...) @@ -611,9 +669,27 @@ sort(v::AbstractVector; kws...) = sort!(copymutable(v); kws...) ## selectperm: the permutation to sort the first k elements of an array ## +""" + selectperm(v, k, [alg=,] [by=,] [lt=,] [rev=false]) + +Return a partial permutation of the vector `v`, according to the order specified by +`by`, `lt` and `rev`, so that `v[output]` returns the first `k` (or range of adjacent values +if `k` is a range) values of a fully sorted version of `v`. If `k` is a single index +(Integer), an array of the first `k` indices is returned; if `k` is a range, an array of +those indices is returned. Note that the handling of integer values for `k` is different +from [`select`](@ref) in that it returns a vector of `k` elements instead of just the `k` th +element. Also note that this is equivalent to, but more efficient than, calling +`sortperm(...)[k]`. +""" selectperm(v::AbstractVector, k::Union{Integer,OrdinalRange}; kwargs...) = selectperm!(similar(Vector{eltype(k)}, indices(v,1)), v, k; kwargs..., initialized=false) +""" + selectperm!(ix, v, k, [alg=,] [by=,] [lt=,] [rev=false,] [initialized=false]) + +Like [`selectperm`](@ref), but accepts a preallocated index vector `ix`. If `initialized` is `false` +(the default), ix is initialized to contain the values `1:length(ix)`. +""" function selectperm!(ix::AbstractVector{<:Integer}, v::AbstractVector, k::Union{Int, OrdinalRange}; lt::Function=isless, diff --git a/base/special/exp10.jl b/base/special/exp10.jl index 2cfb4ff50057e..d8ce280468b6c 100644 --- a/base/special/exp10.jl +++ b/base/special/exp10.jl @@ -67,6 +67,20 @@ MIN_EXP10(::Type{Float32}) = -45.15449934959718f0 # log10 2^-150 @eval exp10_small_thres(::Type{Float64}) = $(2.0^-29) @eval exp10_small_thres(::Type{Float32}) = $(2.0f0^-14) +""" + exp10(x) + +Compute ``10^x``. + +# Examples +```jldoctest +julia> exp10(2) +100.0 + +julia> exp10(0.2) +1.5848931924611136 +``` +""" function exp10(x::T) where T<:Union{Float32,Float64} xa = reinterpret(Unsigned, x) & ~sign_mask(T) xsb = signbit(x) diff --git a/base/strings/utf8proc.jl b/base/strings/utf8proc.jl index a3ebd46ca0414..434ceb06bf85e 100644 --- a/base/strings/utf8proc.jl +++ b/base/strings/utf8proc.jl @@ -13,6 +13,24 @@ export normalize_string, graphemes, is_assigned_char, charwidth, isvalid, iscntrl, ispunct, isspace, isprint, isgraph # whether codepoints are valid Unicode scalar values, i.e. 0-0xd7ff, 0xe000-0x10ffff + +""" + isvalid(value) -> Bool + +Returns `true` if the given value is valid for its type, which currently can be either +`Char` or `String`. +""" +isvalid(value) + +""" + isvalid(T, value) -> Bool + +Returns `true` if the given value is valid for that type. Types currently can +be either `Char` or `String`. Values for `Char` can be of type `Char` or [`UInt32`](@ref). +Values for `String` can be of that type, or `Vector{UInt8}`. +""" +isvalid(T,value) + isvalid(::Type{Char}, ch::Unsigned) = !((ch - 0xd800 < 0x800) | (ch > 0x10ffff)) isvalid(::Type{Char}, ch::Integer) = isvalid(Char, Unsigned(ch)) isvalid(::Type{Char}, ch::Char) = isvalid(Char, UInt32(ch)) diff --git a/base/subarray.jl b/base/subarray.jl index ad591d6ad5e9c..b2a9c3e258834 100644 --- a/base/subarray.jl +++ b/base/subarray.jl @@ -57,6 +57,30 @@ size(V::SubArray) = (@_inline_meta; map(n->Int(unsafe_length(n)), indices(V))) similar(V::SubArray, T::Type, dims::Dims) = similar(V.parent, T, dims) +""" + parent(A) + +Returns the "parent array" of an array view type (e.g., `SubArray`), or the array itself if +it is not a view. + +# Examples +```jldoctest +julia> a = [1 2; 3 4] +2×2 Array{Int64,2}: + 1 2 + 3 4 + +julia> s_a = Symmetric(a) +2×2 Symmetric{Int64,Array{Int64,2}}: + 1 2 + 2 4 + +julia> parent(s_a) +2×2 Array{Int64,2}: + 1 2 + 3 4 +``` +""" parent(V::SubArray) = V.parent parentindexes(V::SubArray) = V.indexes diff --git a/base/sysimg.jl b/base/sysimg.jl index dec8dc77b5586..df4a606d00bc2 100644 --- a/base/sysimg.jl +++ b/base/sysimg.jl @@ -163,6 +163,12 @@ include("reshapedarray.jl") include("bitarray.jl") include("intset.jl") include("associative.jl") + +if !isdefined(Core, :Inference) + include("docs/core.jl") + Core.atdoc!(CoreDocs.docm) +end + include("dict.jl") include("set.jl") include("iterators.jl") @@ -189,11 +195,6 @@ include(string((length(Core.ARGS)>=2 ? Core.ARGS[2] : ""), "version_git.jl")) # include("osutils.jl") include("c.jl") -if !isdefined(Core, :Inference) - include("docs/core.jl") - Core.atdoc!(CoreDocs.docm) -end - # Core I/O include("io.jl") include("iostream.jl") @@ -417,7 +418,6 @@ include("threadcall.jl") include("deprecated.jl") # Some basic documentation -include("docs/helpdb.jl") include("docs/basedocs.jl") # Documentation -- should always be included last in sysimg. diff --git a/doc/src/stdlib/base.md b/doc/src/stdlib/base.md index 6ba310f9cb9bd..663abf299dd99 100644 --- a/doc/src/stdlib/base.md +++ b/doc/src/stdlib/base.md @@ -140,8 +140,8 @@ Base.@nospecialize Base.gensym Base.@gensym Base.@polly -Base.parse(::Any, ::Any) -Base.parse(::Any) +Base.parse(::AbstractString, ::Int) +Base.parse(::AbstractString) ``` ## Nullables diff --git a/doc/src/stdlib/c.md b/doc/src/stdlib/c.md index 42199b752c001..19ecaa72c0c22 100644 --- a/doc/src/stdlib/c.md +++ b/doc/src/stdlib/c.md @@ -9,9 +9,8 @@ Base.cconvert Base.unsafe_load Base.unsafe_store! Base.unsafe_copy!{T}(::Ptr{T}, ::Ptr{T}, ::Any) -Base.unsafe_copy!(::Array, ::Any, ::Array, ::Any, ::Any) -Base.copy!(::Any, ::Any) -Base.copy!(::Any, ::Any, ::Any, ::Any, ::Any) +Base.unsafe_copy!{T}(::Array{T}, ::Any, ::Array{T}, ::Any, ::Any) +Base.copy! Base.pointer Base.unsafe_wrap{T,N}(::Union{Type{Array},Type{Array{T}},Type{Array{T,N}}}, ::Ptr{T}, ::NTuple{N,Int}) Base.pointer_from_objref diff --git a/doc/src/stdlib/collections.md b/doc/src/stdlib/collections.md index 9415ae0fc1ce6..9b611ed598174 100644 --- a/doc/src/stdlib/collections.md +++ b/doc/src/stdlib/collections.md @@ -53,7 +53,7 @@ Fully implemented by: ```@docs Base.isempty Base.empty! -Base.length(::Any) +Base.length ``` Fully implemented by: @@ -137,8 +137,8 @@ Base.filter! ## Indexable Collections ```@docs -Base.getindex(::Any, ::Any...) -Base.setindex!(::Any, ::Any, ::Any...) +Base.getindex +Base.setindex! Base.endof ``` @@ -249,7 +249,7 @@ Partially implemented by: ```@docs Base.push! -Base.pop!(::Any) +Base.pop! Base.unshift! Base.shift! Base.insert! diff --git a/doc/src/stdlib/io-network.md b/doc/src/stdlib/io-network.md index 3c94efcc2e339..6b750b7cad0e5 100644 --- a/doc/src/stdlib/io-network.md +++ b/doc/src/stdlib/io-network.md @@ -148,8 +148,7 @@ Base.Multimedia.istextmime ```@docs Base.Mmap.Anonymous -Base.Mmap.mmap(::Any, ::Type, ::Any, ::Any) -Base.Mmap.mmap(::Any, ::BitArray, ::Any, ::Any) +Base.Mmap.mmap Base.Mmap.sync! ```