From 2dab3fd0c8f98aaf28d77e98a2fc60c83ae09acc Mon Sep 17 00:00:00 2001 From: Andy Ferris Date: Wed, 13 Dec 2017 22:31:20 +1000 Subject: [PATCH] Rename `indices` as `axes` --- NEWS.md | 3 + base/abstractarray.jl | 66 ++++++++++----------- base/abstractarraymath.jl | 16 ++--- base/array.jl | 14 ++--- base/arraymath.jl | 10 ++-- base/arrayshow.jl | 16 ++--- base/bitarray.jl | 2 +- base/broadcast.jl | 12 ++-- base/cartesian.jl | 8 +-- base/deprecated.jl | 8 ++- base/essentials.jl | 6 +- base/exports.jl | 2 +- base/generator.jl | 2 +- base/indices.jl | 16 ++--- base/iterators.jl | 20 +++---- base/linalg/adjtrans.jl | 6 +- base/linalg/generic.jl | 4 +- base/linalg/linalg.jl | 12 ++-- base/linalg/rowvector.jl | 4 +- base/linalg/transpose.jl | 16 ++--- base/linalg/uniformscaling.jl | 2 +- base/markdown/GitHub/table.jl | 6 +- base/multidimensional.jl | 52 ++++++++-------- base/number.jl | 4 +- base/permuteddimsarray.jl | 16 ++--- base/reducedim.jl | 26 ++++---- base/repl/LineEdit.jl | 4 +- base/reshapedarray.jl | 2 +- base/serialize.jl | 2 +- base/show.jl | 2 +- base/sort.jl | 38 ++++++------ base/sparse/higherorderfns.jl | 2 +- base/sparse/sparsematrix.jl | 2 +- base/sparse/sparsevector.jl | 2 +- base/statistics.jl | 8 +-- base/subarray.jl | 12 ++-- doc/src/devdocs/boundscheck.md | 4 +- doc/src/devdocs/offset-arrays.md | 28 ++++----- doc/src/manual/arrays.md | 8 +-- doc/src/manual/interfaces.md | 4 +- doc/src/manual/performance-tips.md | 8 +-- doc/src/stdlib/arrays.md | 4 +- stdlib/DelimitedFiles/src/DelimitedFiles.jl | 6 +- stdlib/Test/src/Test.jl | 8 +-- test/TestHelpers.jl | 10 ++-- test/abstractarray.jl | 10 ++-- test/arrayops.jl | 2 +- test/copy.jl | 4 +- test/inference.jl | 2 +- test/linalg/adjtrans.jl | 8 +-- test/numbers.jl | 6 +- test/offsetarray.jl | 42 ++++++------- test/reducedim.jl | 4 +- test/sparse/higherorderfns.jl | 8 +-- test/subarray.jl | 14 ++--- 55 files changed, 305 insertions(+), 298 deletions(-) diff --git a/NEWS.md b/NEWS.md index 7fed73e627ab89..e05e85f1eec25e 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1406,6 +1406,9 @@ Deprecated or removed `similar(::Associative, ::Pair{K, V})` has been deprecated in favour of `empty(::Associative, K, V)` ([#24390]). + * `indices(a)` and `indices(a,d)` have been deprecated in favor of `axes(a)` and + `axes(a, d)` ([#25057]). + Command-line option changes --------------------------- diff --git a/base/abstractarray.jl b/base/abstractarray.jl index 6c2568a14cb5ed..4c1ad65d92dd3f 100644 --- a/base/abstractarray.jl +++ b/base/abstractarray.jl @@ -34,7 +34,7 @@ size(x, d1::Integer, d2::Integer, dx::Vararg{Integer, N}) where {N} = (size(x, d1), size(x, d2), ntuple(k->size(x, dx[k]), Val(N))...) """ - indices(A, d) + axes(A, d) Return the valid range of indices for array `A` along dimension `d`. @@ -42,17 +42,17 @@ Return the valid range of indices for array `A` along dimension `d`. ```jldoctest julia> A = ones(5,6,7); -julia> indices(A,2) +julia> axes(A,2) Base.OneTo(6) ``` """ -function indices(A::AbstractArray{T,N}, d) where {T,N} +function axes(A::AbstractArray{T,N}, d) where {T,N} @_inline_meta - d <= N ? indices(A)[d] : OneTo(1) + d <= N ? axes(A)[d] : OneTo(1) end """ - indices(A) + axes(A) Return the tuple of valid indices for array `A`. @@ -60,23 +60,23 @@ Return the tuple of valid indices for array `A`. ```jldoctest julia> A = ones(5,6,7); -julia> indices(A) +julia> axes(A) (Base.OneTo(5), Base.OneTo(6), Base.OneTo(7)) ``` """ -function indices(A) +function axes(A) @_inline_meta map(OneTo, size(A)) end -# Performance optimization: get rid of a branch on `d` in `indices(A, d)` +# Performance optimization: get rid of a branch on `d` in `axes(A, d)` # for d=1. 1d arrays are heavily used, and the first dimension comes up # in other applications. indices1(A::AbstractArray{<:Any,0}) = OneTo(1) -indices1(A::AbstractArray) = (@_inline_meta; indices(A)[1]) +indices1(A::AbstractArray) = (@_inline_meta; axes(A)[1]) indices1(iter) = OneTo(length(iter)) -unsafe_indices(A) = indices(A) +unsafe_indices(A) = axes(A) unsafe_indices(r::AbstractRange) = (OneTo(unsafe_length(r)),) # Ranges use checked_sub for size """ @@ -86,7 +86,7 @@ Return a `UnitRange` specifying the valid range of indices for `A[i]` where `i` is an `Int`. For arrays with conventional indexing (indices start at 1), or any multidimensional array, this is `1:length(A)`; however, for one-dimensional arrays with unconventional indices, this -is `indices(A, 1)`. +is `axes(A, 1)`. Calling this function is the "safe" way to write algorithms that exploit linear indexing. @@ -104,7 +104,7 @@ julia> extrema(b) linearindices(A::AbstractArray) = (@_inline_meta; OneTo(_length(A))) linearindices(A::AbstractVector) = (@_inline_meta; indices1(A)) -keys(a::AbstractArray) = CartesianRange(indices(a)) +keys(a::AbstractArray) = CartesianRange(axes(a)) keys(a::AbstractVector) = linearindices(a) prevind(::AbstractArray, i::Integer) = Int(i)-1 @@ -150,7 +150,7 @@ julia> length([1 2; 3 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::AbstractArray) = (@_inline_meta; prod(map(unsafe_length, axes(A)))) # circumvent missing size _length(A) = (@_inline_meta; length(A)) """ @@ -376,7 +376,7 @@ false """ function checkbounds(::Type{Bool}, A::AbstractArray, I...) @_inline_meta - checkbounds_indices(Bool, indices(A), I) + checkbounds_indices(Bool, axes(A), I) end # Linear indexing is explicitly allowed when there is only one (non-cartesian) index function checkbounds(::Type{Bool}, A::AbstractArray, i) @@ -386,7 +386,7 @@ end # As a special extension, allow using logical arrays that match the source array exactly function checkbounds(::Type{Bool}, A::AbstractArray{<:Any,N}, I::AbstractArray{Bool,N}) where N @_inline_meta - indices(A) == indices(I) + axes(A) == axes(I) end """ @@ -519,7 +519,7 @@ julia> similar(falses(10), Float64, 2, 4) """ similar(a::AbstractArray{T}) where {T} = similar(a, T) -similar(a::AbstractArray, ::Type{T}) where {T} = similar(a, T, to_shape(indices(a))) +similar(a::AbstractArray, ::Type{T}) where {T} = similar(a, T, to_shape(axes(a))) similar(a::AbstractArray{T}, dims::Tuple) where {T} = similar(a, T, to_shape(dims)) similar(a::AbstractArray{T}, dims::DimOrInd...) where {T} = similar(a, T, to_shape(dims)) similar(a::AbstractArray, ::Type{T}, dims::DimOrInd...) where {T} = similar(a, T, to_shape(dims)) @@ -545,7 +545,7 @@ argument. `storagetype` might be a type or a function. **Examples**: - similar(Array{Int}, indices(A)) + similar(Array{Int}, axes(A)) creates an array that "acts like" an `Array{Int}` (and might indeed be backed by one), but which is indexed identically to `A`. If `A` has @@ -553,12 +553,12 @@ conventional indexing, this will be identical to `Array{Int}(uninitialized, size(A))`, but if `A` has unconventional indexing then the indices of the result will match `A`. - similar(BitArray, (indices(A, 2),)) + similar(BitArray, (axes(A, 2),)) would create a 1-dimensional logical array whose indices match those of the columns of `A`. - similar(dims->zeros(Int, dims), indices(A)) + similar(dims->zeros(Int, dims), axes(A)) would create an array of `Int`, initialized to zero, matching the indices of `A`. @@ -869,7 +869,7 @@ convert(::Type{Array}, A::AbstractArray{T,N}) where {T,N} = convert(Array{T,N}, Represents the array `y` as an array having the same indices type as `x`. """ -of_indices(x, y) = similar(dims->y, oftype(indices(x), indices(y))) +of_indices(x, y) = similar(dims->y, oftype(axes(x), axes(y))) ## range conversions ## @@ -986,11 +986,11 @@ function _to_subscript_indices(A::AbstractArray{T,N}, I::Int...) where {T,N} _to_subscript_indices(A, J, Jrem) end _to_subscript_indices(A::AbstractArray, J::Tuple, Jrem::Tuple{}) = - __to_subscript_indices(A, indices(A), J, Jrem) + __to_subscript_indices(A, axes(A), J, Jrem) function __to_subscript_indices(A::AbstractArray, ::Tuple{AbstractUnitRange,Vararg{AbstractUnitRange}}, J::Tuple, Jrem::Tuple{}) @_inline_meta - (J..., map(first, tail(_remaining_size(J, indices(A))))...) + (J..., map(first, tail(_remaining_size(J, axes(A))))...) end _to_subscript_indices(A, J::Tuple, Jrem::Tuple) = J # already bounds-checked, safe to drop _to_subscript_indices(A::AbstractArray{T,N}, I::Vararg{Int,N}) where {T,N} = I @@ -1200,7 +1200,7 @@ cat_size(A, d) = 1 cat_size(A::AbstractArray, d) = size(A, d) cat_indices(A, d) = OneTo(1) -cat_indices(A::AbstractArray, d) = indices(A, d) +cat_indices(A::AbstractArray, d) = axes(A, d) cat_similar(A, T, shape) = Array{T}(uninitialized, shape) cat_similar(A::AbstractArray, T, shape) = similar(A, T, shape) @@ -1543,7 +1543,7 @@ end function isequal(A::AbstractArray, B::AbstractArray) if A === B return true end - if indices(A) != indices(B) + if axes(A) != axes(B) return false end if isa(A,AbstractRange) != isa(B,AbstractRange) @@ -1566,7 +1566,7 @@ function lexcmp(A::AbstractArray, B::AbstractArray) end function (==)(A::AbstractArray, B::AbstractArray) - if indices(A) != indices(B) + if axes(A) != axes(B) return false end if isa(A,AbstractRange) != isa(B,AbstractRange) @@ -1588,7 +1588,7 @@ end # fallbacks function sub2ind(A::AbstractArray, I...) @_inline_meta - sub2ind(indices(A), I...) + sub2ind(axes(A), I...) end """ @@ -1609,7 +1609,7 @@ julia> ind2sub(A,70) """ function ind2sub(A::AbstractArray, ind) @_inline_meta - ind2sub(indices(A), ind) + ind2sub(axes(A), ind) end # 0-dimensional arrays and indexing with [] @@ -1835,16 +1835,16 @@ function mapslices(f, A::AbstractArray, dims::AbstractVector) return map(f,A) end - dimsA = [indices(A)...] + dimsA = [axes(A)...] ndimsA = ndims(A) alldims = [1:ndimsA;] otherdims = setdiff(alldims, dims) - idx = Any[first(ind) for ind in indices(A)] + idx = Any[first(ind) for ind in axes(A)] itershape = tuple(dimsA[otherdims]...) for d in dims - idx[d] = Slice(indices(A, d)) + idx[d] = Slice(axes(A, d)) end # Apply the function to the first slice in order to determine the next steps @@ -1867,13 +1867,13 @@ function mapslices(f, A::AbstractArray, dims::AbstractVector) if eltype(Rsize) == Int Rsize[dims] = [size(r1)..., ntuple(d->1, nextra)...] else - Rsize[dims] = [indices(r1)..., ntuple(d->OneTo(1), nextra)...] + Rsize[dims] = [axes(r1)..., ntuple(d->OneTo(1), nextra)...] end R = similar(r1, tuple(Rsize...,)) - ridx = Any[map(first, indices(R))...] + ridx = Any[map(first, axes(R))...] for d in dims - ridx[d] = indices(R,d) + ridx[d] = axes(R,d) end R[ridx...] = r1 diff --git a/base/abstractarraymath.jl b/base/abstractarraymath.jl index d7496360e2f5c7..8a8650da284858 100644 --- a/base/abstractarraymath.jl +++ b/base/abstractarraymath.jl @@ -67,7 +67,7 @@ julia> squeeze(a,3) function squeeze(A::AbstractArray, dims::Dims) for i in 1:length(dims) 1 <= dims[i] <= ndims(A) || throw(ArgumentError("squeezed dims must be in range 1:ndims(A)")) - length(indices(A, dims[i])) == 1 || throw(ArgumentError("squeezed dims must all be size 1")) + length(axes(A, dims[i])) == 1 || throw(ArgumentError("squeezed dims must all be size 1")) for j = 1:i-1 dims[j] == dims[i] && throw(ArgumentError("squeezed dims must be unique")) end @@ -75,10 +75,10 @@ function squeeze(A::AbstractArray, dims::Dims) d = () for i = 1:ndims(A) if !in(i, dims) - d = tuple(d..., indices(A, i)) + d = tuple(d..., axes(A, i)) end end - reshape(A, d::typeof(_sub(indices(A), dims))) + reshape(A, d::typeof(_sub(axes(A), dims))) end squeeze(A::AbstractArray, dim::Integer) = squeeze(A, (Int(dim),)) @@ -120,7 +120,7 @@ function slicedim(A::AbstractArray, d::Integer, i) d >= 1 || throw(ArgumentError("dimension must be ≥ 1")) nd = ndims(A) d > nd && (i == 1 || throw_boundserror(A, (ntuple(k->Colon(),nd)..., ntuple(k->1,d-1-nd)..., i))) - A[setindex(indices(A), i, d)...] + A[setindex(axes(A), i, d)...] end """ @@ -149,7 +149,7 @@ function flipdim(A::AbstractArray, d::Integer) elseif nd == 1 return reverse(A) end - inds = indices(A) + inds = axes(A) B = similar(A) nnd = 0 for i = 1:nd @@ -165,7 +165,7 @@ function flipdim(A::AbstractArray, d::Integer) return B end let B=B # workaround #15276 - alli = [ indices(B,n) for n in 1:nd ] + alli = [ axes(B,n) for n in 1:nd ] for i in indsd B[[ n==d ? sd-i : alli[n] for n in 1:nd ]...] = slicedim(A, d, i) end @@ -371,10 +371,10 @@ cat_fill!(R, X::AbstractArray, inds) = fill!(view(R, inds...), X) # fill the first inner block if all(x -> x == 1, inner) - R[indices(A)...] = A + R[axes(A)...] = A else inner_indices = [1:n for n in inner] - for c in CartesianRange(indices(A)) + for c in CartesianRange(axes(A)) for i in 1:ndims(A) n = inner[i] inner_indices[i] = (1:n) .+ ((c[i] - 1) * n) diff --git a/base/array.jl b/base/array.jl index 76a19b0665aa88..0e1ffaa91a27f8 100644 --- a/base/array.jl +++ b/base/array.jl @@ -433,7 +433,7 @@ julia> collect(Float64, 1:2:5) collect(::Type{T}, itr) where {T} = _collect(T, itr, iteratorsize(itr)) _collect(::Type{T}, itr, isz::HasLength) where {T} = copy!(Vector{T}(uninitialized, Int(length(itr)::Integer)), itr) -_collect(::Type{T}, itr, isz::HasShape) where {T} = copy!(similar(Array{T}, indices(itr)), itr) +_collect(::Type{T}, itr, isz::HasShape) where {T} = copy!(similar(Array{T}, axes(itr)), itr) function _collect(::Type{T}, itr, isz::SizeUnknown) where T a = Vector{T}() for x in itr @@ -445,7 +445,7 @@ end # make a collection similar to `c` and appropriate for collecting `itr` _similar_for(c::AbstractArray, T, itr, ::SizeUnknown) = similar(c, T, 0) _similar_for(c::AbstractArray, T, itr, ::HasLength) = similar(c, T, Int(length(itr)::Integer)) -_similar_for(c::AbstractArray, T, itr, ::HasShape) = similar(c, T, indices(itr)) +_similar_for(c::AbstractArray, T, itr, ::HasShape) = similar(c, T, axes(itr)) _similar_for(c, T, itr, isz) = similar(c, T) """ @@ -470,7 +470,7 @@ julia> collect(1:2:13) """ collect(itr) = _collect(1:1 #= Array =#, itr, iteratoreltype(itr), iteratorsize(itr)) -collect(A::AbstractArray) = _collect_indices(indices(A), A) +collect(A::AbstractArray) = _collect_indices(axes(A), A) collect_similar(cont, itr) = _collect(cont, itr, iteratoreltype(itr), iteratorsize(itr)) @@ -490,7 +490,7 @@ _collect_indices(indsA::Tuple{Vararg{OneTo}}, A) = copy!(Array{eltype(A)}(uninitialized, length.(indsA)), A) function _collect_indices(indsA, A) B = Array{eltype(A)}(uninitialized, length.(indsA)) - copy!(B, CartesianRange(indices(B)), A, CartesianRange(indsA)) + copy!(B, CartesianRange(axes(B)), A, CartesianRange(indsA)) end # define this as a macro so that the call to Inference @@ -510,7 +510,7 @@ else end _array_for(::Type{T}, itr, ::HasLength) where {T} = Vector{T}(uninitialized, Int(length(itr)::Integer)) -_array_for(::Type{T}, itr, ::HasShape) where {T} = similar(Array{T}, indices(itr))::Array{T} +_array_for(::Type{T}, itr, ::HasShape) where {T} = similar(Array{T}, axes(itr))::Array{T} function collect(itr::Generator) isz = iteratorsize(itr.iter) @@ -1799,7 +1799,7 @@ function findn(A::AbstractMatrix) I = similar(A, Int, nnzA) J = similar(A, Int, nnzA) cnt = 1 - for j=indices(A,2), i=indices(A,1) + for j=axes(A,2), i=axes(A,1) if A[i,j] != 0 I[cnt] = i J[cnt] = j @@ -1834,7 +1834,7 @@ function findnz(A::AbstractMatrix{T}) where T NZs = Vector{T}(uninitialized, nnzA) cnt = 1 if nnzA > 0 - for j=indices(A,2), i=indices(A,1) + for j=axes(A,2), i=axes(A,1) Aij = A[i,j] if Aij != 0 I[cnt] = i diff --git a/base/arraymath.jl b/base/arraymath.jl index 55ddbe68cd0e23..3677496cd8233e 100644 --- a/base/arraymath.jl +++ b/base/arraymath.jl @@ -138,10 +138,10 @@ julia> rotl90(a) ``` """ function rotl90(A::AbstractMatrix) - ind1, ind2 = indices(A) + ind1, ind2 = axes(A) B = similar(A, (ind2,ind1)) n = first(ind2)+last(ind2) - for i=indices(A,1), j=ind2 + for i=axes(A,1), j=ind2 B[n-j,i] = A[i,j] end return B @@ -166,10 +166,10 @@ julia> rotr90(a) ``` """ function rotr90(A::AbstractMatrix) - ind1, ind2 = indices(A) + ind1, ind2 = axes(A) B = similar(A, (ind2,ind1)) m = first(ind1)+last(ind1) - for i=ind1, j=indices(A,2) + for i=ind1, j=axes(A,2) B[j,m-i] = A[i,j] end return B @@ -194,7 +194,7 @@ julia> rot180(a) """ function rot180(A::AbstractMatrix) B = similar(A) - ind1, ind2 = indices(A,1), indices(A,2) + ind1, ind2 = axes(A,1), axes(A,2) m, n = first(ind1)+last(ind1), first(ind2)+last(ind2) for j=ind2, i=ind1 B[m-i,n-j] = A[i,j] diff --git a/base/arrayshow.jl b/base/arrayshow.jl index fd7757d69cabe6..c287cdb0418709 100644 --- a/base/arrayshow.jl +++ b/base/arrayshow.jl @@ -78,7 +78,7 @@ function alignment(io::IO, X::AbstractVecOrMat, break end end - if 1 < length(a) < length(indices(X,2)) + if 1 < length(a) < length(axes(X,2)) while sum(map(sum,a)) + sep*length(a) >= cols_otherwise pop!(a) end @@ -96,7 +96,7 @@ is specified as string sep. function print_matrix_row(io::IO, X::AbstractVecOrMat, A::Vector, i::Integer, cols::AbstractVector, sep::AbstractString) - isempty(A) || first(indices(cols,1)) == 1 || throw(DimensionMismatch("indices of cols ($(indices(cols,1))) must start at 1")) + isempty(A) || first(axes(cols,1)) == 1 || throw(DimensionMismatch("indices of cols ($(axes(cols,1))) must start at 1")) for k = 1:length(A) j = cols[k] if isassigned(X,Int(i),Int(j)) # isassigned accepts only `Int` indices @@ -168,7 +168,7 @@ function print_matrix(io::IO, X::AbstractVecOrMat, postsp = "" @assert Unicode.textwidth(hdots) == Unicode.textwidth(ddots) sepsize = length(sep) - rowsA, colsA = indices(X,1), indices(X,2) + rowsA, colsA = axes(X,1), axes(X,2) m, n = length(rowsA), length(colsA) # To figure out alignments, only need to look at as many rows as could # fit down screen. If screen has at least as many rows as A, look at A. @@ -259,7 +259,7 @@ function show_nd(io::IO, a::AbstractArray, print_matrix::Function, label_slices: if isempty(a) return end - tailinds = tail(tail(indices(a))) + tailinds = tail(tail(axes(a))) nd = ndims(a)-2 for I in CartesianRange(tailinds) idxs = I.I @@ -270,7 +270,7 @@ function show_nd(io::IO, a::AbstractArray, print_matrix::Function, label_slices: if length(ind) > 10 if ii == ind[4] && all(d->idxs[d]==first(tailinds[d]),1:i-1) for j=i+1:nd - szj = length(indices(a, j+2)) + szj = length(axes(a, j+2)) indj = tailinds[j] if szj>10 && first(indj)+2 < idxs[j] <= last(indj)-3 @goto skip @@ -291,7 +291,7 @@ function show_nd(io::IO, a::AbstractArray, print_matrix::Function, label_slices: for i = 1:(nd-1); print(io, "$(idxs[i]), "); end println(io, idxs[end], "] =") end - slice = view(a, indices(a,1), indices(a,2), idxs...) + slice = view(a, axes(a,1), axes(a,2), idxs...) print_matrix(io, slice) print(io, idxs == map(last,tailinds) ? "" : "\n\n") @label skip @@ -314,7 +314,7 @@ print_array(io::IO, X::AbstractArray) = show_nd(io, X, print_matrix, true) # implements: show(io::IO, ::MIME"text/plain", X::AbstractArray) function _display(io::IO, X::AbstractArray) # 0) compute new IOContext - if !haskey(io, :compact) && length(indices(X, 2)) > 1 + if !haskey(io, :compact) && length(axes(X, 2)) > 1 io = IOContext(io, :compact => true) end if get(io, :limit, false) && eltype(X) === Method @@ -360,7 +360,7 @@ preceded by `prefix`, supposed to encode the type of the elements. function _show_nonempty(io::IO, X::AbstractMatrix, prefix::String) @assert !isempty(X) limit = get(io, :limit, false)::Bool - indr, indc = indices(X,1), indices(X,2) + indr, indc = axes(X,1), axes(X,2) nr, nc = length(indr), length(indc) rdots, cdots = false, false rr1, rr2 = UnitRange{Int}(indr), 1:0 diff --git a/base/bitarray.jl b/base/bitarray.jl index 8e786b68e91d64..4b4fe4165ebe7e 100644 --- a/base/bitarray.jl +++ b/base/bitarray.jl @@ -562,7 +562,7 @@ gen_bitarray(isz::IteratorSize, itr) = gen_bitarray_from_itr(itr, start(itr)) # generic iterable with known shape function gen_bitarray(::HasShape, itr) B = BitArray(uninitialized, size(itr)) - for (I,x) in zip(CartesianRange(indices(itr)), itr) + for (I,x) in zip(CartesianRange(axes(itr)), itr) B[I] = x end return B diff --git a/base/broadcast.jl b/base/broadcast.jl index 7168971c2ac316..185bb1c6fae6c3 100644 --- a/base/broadcast.jl +++ b/base/broadcast.jl @@ -226,7 +226,7 @@ broadcast_indices(::Scalar, A) = () broadcast_indices(::Style{Nullable}, A) = () broadcast_indices(::Style{Tuple}, A) = (OneTo(length(A)),) broadcast_indices(::DefaultArrayStyle{0}, A::Ref) = () -broadcast_indices(::AbstractArrayStyle, A) = Base.indices(A) +broadcast_indices(::AbstractArrayStyle, A) = Base.axes(A) """ Base.broadcast_indices(::SrcStyle, A) @@ -243,7 +243,7 @@ broadcast_indices broadcast(f, x::Number...) = f(x...) @inline broadcast(f, t::NTuple{N,Any}, ts::Vararg{NTuple{N,Any}}) where {N} = map(f, t, ts...) @inline broadcast!(::typeof(identity), x::AbstractArray{T,N}, y::AbstractArray{S,N}) where {T,S,N} = - Base.indices(x) == Base.indices(y) ? copy!(x, y) : _broadcast!(identity, x, y) + Base.axes(x) == Base.axes(y) ? copy!(x, y) : _broadcast!(identity, x, y) # special cases for "X .= ..." (broadcast!) assignments broadcast!(::typeof(identity), X::AbstractArray, x::Number) = fill!(X, x) @@ -349,7 +349,7 @@ end # newindexer(shape, A) generates `keep` and `Idefault` (for use by # `newindex` above) for a particular array `A`, given the # broadcast indices `shape` -# `keep` is equivalent to map(==, indices(A), shape) (but see #17126) +# `keep` is equivalent to map(==, axes(A), shape) (but see #17126) @inline newindexer(shape, A) = shapeindexer(shape, broadcast_indices(A)) @inline shapeindexer(shape, indsA::Tuple{}) = (), () @inline function shapeindexer(shape, indsA::Tuple) @@ -762,9 +762,9 @@ broadcast_getindex(src::AbstractArray, I::AbstractArray...) = Isplat = Expr[:(I[$d]) for d = 1:N] quote @nexprs $N d->(I_d = I[d]) - check_broadcast_indices(Base.indices(dest), $(Isplat...)) # unnecessary if this function is never called directly + check_broadcast_indices(Base.axes(dest), $(Isplat...)) # unnecessary if this function is never called directly checkbounds(src, $(Isplat...)) - @nexprs $N d->(@nexprs $N k->(Ibcast_d_k = Base.indices(I_k, d) == OneTo(1))) + @nexprs $N d->(@nexprs $N k->(Ibcast_d_k = Base.axes(I_k, d) == OneTo(1))) @nloops $N i dest d->(@nexprs $N k->(j_d_k = Ibcast_d_k ? 1 : i_d)) begin @nexprs $N k->(@inbounds J_k = @nref $N I_k d->j_d_k) @inbounds (@nref $N dest i) = (@nref $N src J) @@ -795,7 +795,7 @@ See [`broadcast_getindex`](@ref) for examples of the treatment of `inds`. checkbounds(A, $(Isplat...)) shape = combine_indices($(Isplat...)) @nextract $N shape d->(length(shape) < d ? OneTo(1) : shape[d]) - @nexprs $N d->(@nexprs $N k->(Ibcast_d_k = Base.indices(I_k, d) == 1:1)) + @nexprs $N d->(@nexprs $N k->(Ibcast_d_k = Base.axes(I_k, d) == 1:1)) if !isa(x, AbstractArray) xA = convert(eltype(A), x) @nloops $N i d->shape_d d->(@nexprs $N k->(j_d_k = Ibcast_d_k ? 1 : i_d)) begin diff --git a/base/cartesian.jl b/base/cartesian.jl index f0fbd28be75db7..102c5a2eee3ec7 100644 --- a/base/cartesian.jl +++ b/base/cartesian.jl @@ -13,7 +13,7 @@ export @nloops, @nref, @ncall, @nexprs, @nextract, @nall, @nany, @ntuple, @nif Generate `N` nested loops, using `itersym` as the prefix for the iteration variables. `rangeexpr` may be an anonymous-function expression, or a simple symbol `var` in which case -the range is `indices(var, d)` for dimension `d`. +the range is `axes(var, d)` for dimension `d`. Optionally, you can provide "pre" and "post" expressions. These get executed first and last, respectively, in the body of each loop. For example: @@ -24,9 +24,9 @@ respectively, in the body of each loop. For example: would generate: - for i_2 = indices(A, 2) + for i_2 = axes(A, 2) j_2 = min(i_2, 5) - for i_1 = indices(A, 1) + for i_1 = axes(A, 1) j_1 = min(i_1, 5) s += A[j_1, j_2] end @@ -41,7 +41,7 @@ end function _nloops(N::Int, itersym::Symbol, arraysym::Symbol, args::Expr...) @gensym d - _nloops(N, itersym, :($d->Base.indices($arraysym, $d)), args...) + _nloops(N, itersym, :($d->Base.axes($arraysym, $d)), args...) end function _nloops(N::Int, itersym::Symbol, rangeexpr::Expr, args::Expr...) diff --git a/base/deprecated.jl b/base/deprecated.jl index 5f48ad7e237e30..fd7b210b26b1c3 100644 --- a/base/deprecated.jl +++ b/base/deprecated.jl @@ -536,8 +536,8 @@ function gen_broadcast_body_zpreserving(f::Function, is_first_sparse::Bool) op2 = :(val1) end quote - Base.Broadcast.check_broadcast_indices(indices(B), $A1) - Base.Broadcast.check_broadcast_indices(indices(B), $A2) + Base.Broadcast.check_broadcast_indices(axes(B), $A1) + Base.Broadcast.check_broadcast_indices(axes(B), $A2) nnzB = isempty(B) ? 0 : nnz($A1) * div(B.n, ($A1).n) * div(B.m, ($A1).m) @@ -3033,6 +3033,10 @@ end # Associative -> AbstractDict (#25012) @deprecate_binding Associative AbstractDict +# PR #25057 +@deprecate indices(a) axes(a) +@deprecate indices(a, d) axes(a, d) + # END 0.7 deprecations # BEGIN 1.0 deprecations diff --git a/base/essentials.jl b/base/essentials.jl index acb38a7698c672..cf7505bddbb59f 100644 --- a/base/essentials.jl +++ b/base/essentials.jl @@ -550,9 +550,9 @@ start(v::SimpleVector) = 1 next(v::SimpleVector,i) = (v[i],i+1) done(v::SimpleVector,i) = (length(v) < i) isempty(v::SimpleVector) = (length(v) == 0) -indices(v::SimpleVector) = (OneTo(length(v)),) -linearindices(v::SimpleVector) = indices(v, 1) -indices(v::SimpleVector, d) = d <= 1 ? indices(v)[d] : OneTo(1) +axes(v::SimpleVector) = (OneTo(length(v)),) +linearindices(v::SimpleVector) = axes(v, 1) +axes(v::SimpleVector, d) = d <= 1 ? axes(v)[d] : OneTo(1) function ==(v1::SimpleVector, v2::SimpleVector) length(v1)==length(v2) || return false diff --git a/base/exports.jl b/base/exports.jl index 3a374bf6789634..d7e33a7e4367af 100644 --- a/base/exports.jl +++ b/base/exports.jl @@ -412,6 +412,7 @@ export lbeta, # arrays + axes, broadcast!, broadcast, broadcast_getindex, @@ -454,7 +455,6 @@ export hvcat, ind2sub, indexin, - indices, indmax, indmin, invperm, diff --git a/base/generator.jl b/base/generator.jl index 3eb6adfd1ad46b..28f9134e95547d 100644 --- a/base/generator.jl +++ b/base/generator.jl @@ -114,7 +114,7 @@ iteratorsize(::Type{<:AbstractArray}) = HasShape() iteratorsize(::Type{Generator{I,F}}) where {I,F} = iteratorsize(I) length(g::Generator) = length(g.iter) size(g::Generator) = size(g.iter) -indices(g::Generator) = indices(g.iter) +axes(g::Generator) = axes(g.iter) ndims(g::Generator) = ndims(g.iter) iteratoreltype(::Type{Generator{I,T}}) where {I,T} = EltypeUnknown() diff --git a/base/indices.jl b/base/indices.jl index ca693d01988f91..9911e42cc6e36c 100644 --- a/base/indices.jl +++ b/base/indices.jl @@ -67,7 +67,7 @@ function promote_shape(a::Dims, b::Dims) end function promote_shape(a::AbstractArray, b::AbstractArray) - promote_shape(indices(a), indices(b)) + promote_shape(axes(a), axes(b)) end function promote_shape(a::Indices, b::Indices) @@ -105,12 +105,12 @@ function setindex_shape_check(X::AbstractArray, I::Integer...) lj = length(I) i = j = 1 while true - ii = length(indices(X,i)) + ii = length(axes(X,i)) jj = I[j] if i == li || j == lj while i < li i += 1 - ii *= length(indices(X,i)) + ii *= length(axes(X,i)) end while j < lj j += 1 @@ -150,7 +150,7 @@ function setindex_shape_check(X::AbstractArray{<:Any,2}, i::Integer, j::Integer) if length(X) != i*j throw_setindex_mismatch(X, (i,j)) end - sx1 = length(indices(X,1)) + sx1 = length(axes(X,1)) if !(i == 1 || i == sx1 || sx1 == 1) throw_setindex_mismatch(X, (i,j)) end @@ -208,11 +208,11 @@ to provide custom indexing behaviors. More complicated index types may require more context about the dimension into which they index. To support those cases, `to_indices(A, I)` calls -`to_indices(A, indices(A), I)`, which then recursively walks through both the +`to_indices(A, axes(A), I)`, which then recursively walks through both the given tuple of indices and the dimensional indices of `A` in tandem. As such, not all index types are guaranteed to propagate to `Base.to_index`. """ -to_indices(A, I::Tuple) = (@_inline_meta; to_indices(A, indices(A), I)) +to_indices(A, I::Tuple) = (@_inline_meta; to_indices(A, axes(A), I)) to_indices(A, I::Tuple{Any}) = (@_inline_meta; to_indices(A, (linearindices(A),), I)) to_indices(A, inds, ::Tuple{}) = () to_indices(A, inds, I::Tuple{Any, Vararg{Any}}) = @@ -235,12 +235,12 @@ iterate over all the wrapped indices, even supporting offset indices. struct Slice{T<:AbstractUnitRange} <: AbstractUnitRange{Int} indices::T end -indices(S::Slice) = (S.indices,) +axes(S::Slice) = (S.indices,) unsafe_indices(S::Slice) = (S.indices,) indices1(S::Slice) = S.indices first(S::Slice) = first(S.indices) last(S::Slice) = last(S.indices) -errmsg(A) = error("size not supported for arrays with indices $(indices(A)); see https://docs.julialang.org/en/latest/devdocs/offset-arrays/") +errmsg(A) = error("size not supported for arrays with indices $(axes(A)); see https://docs.julialang.org/en/latest/devdocs/offset-arrays/") size(S::Slice) = first(S.indices) == 1 ? (length(S.indices),) : errmsg(S) length(S::Slice) = first(S.indices) == 1 ? length(S.indices) : errmsg(S) unsafe_length(S::Slice) = first(S.indices) == 1 ? unsafe_length(S.indices) : errmsg(S) diff --git a/base/iterators.jl b/base/iterators.jl index 5c99c4876eecf4..d4efdad74629f7 100644 --- a/base/iterators.jl +++ b/base/iterators.jl @@ -5,7 +5,7 @@ Methods for working with Iterators. """ module Iterators -import Base: start, done, next, isempty, length, size, eltype, iteratorsize, iteratoreltype, indices, ndims, pairs, last, first +import Base: start, done, next, isempty, length, size, eltype, iteratorsize, iteratoreltype, axes, ndims, pairs, last, first using Base: tail, tuple_type_head, tuple_type_tail, tuple_type_cons, SizeUnknown, HasLength, HasShape, IsInfinite, EltypeUnknown, HasEltype, OneTo, @propagate_inbounds, Generator, AbstractRange @@ -191,14 +191,14 @@ CartesianIndex(2, 2) e See also: [`IndexStyle`](@ref), [`indices`](@ref). """ pairs(::IndexLinear, A::AbstractArray) = IndexValue(A, linearindices(A)) -pairs(::IndexCartesian, A::AbstractArray) = IndexValue(A, CartesianRange(indices(A))) +pairs(::IndexCartesian, A::AbstractArray) = IndexValue(A, CartesianRange(axes(A))) # faster than zip(keys(a), values(a)) for arrays pairs(A::AbstractArray) = pairs(IndexCartesian(), A) pairs(A::AbstractVector) = pairs(IndexLinear(), A) length(v::IndexValue) = length(v.itr) -indices(v::IndexValue) = indices(v.itr) +axes(v::IndexValue) = axes(v.itr) size(v::IndexValue) = size(v.itr) @inline start(v::IndexValue) = start(v.itr) @propagate_inbounds function next(v::IndexValue, state) @@ -232,7 +232,7 @@ end zip(a) = Zip1(a) length(z::Zip1) = length(z.a) size(z::Zip1) = size(z.a) -indices(z::Zip1) = indices(z.a) +axes(z::Zip1) = axes(z.a) eltype(::Type{Zip1{I}}) where {I} = Tuple{eltype(I)} @inline start(z::Zip1) = start(z.a) @propagate_inbounds function next(z::Zip1, st) @@ -251,7 +251,7 @@ end zip(a, b) = Zip2(a, b) length(z::Zip2) = _min_length(z.a, z.b, iteratorsize(z.a), iteratorsize(z.b)) size(z::Zip2) = promote_shape(size(z.a), size(z.b)) -indices(z::Zip2) = promote_shape(indices(z.a), indices(z.b)) +axes(z::Zip2) = promote_shape(axes(z.a), axes(z.b)) eltype(::Type{Zip2{I1,I2}}) where {I1,I2} = Tuple{eltype(I1), eltype(I2)} @inline start(z::Zip2) = (start(z.a), start(z.b)) @propagate_inbounds function next(z::Zip2, st) @@ -301,7 +301,7 @@ julia> first(c) zip(a, b, c...) = Zip(a, zip(b, c...)) length(z::Zip) = _min_length(z.a, z.z, iteratorsize(z.a), iteratorsize(z.z)) size(z::Zip) = promote_shape(size(z.a), size(z.z)) -indices(z::Zip) = promote_shape(indices(z.a), indices(z.z)) +axes(z::Zip) = promote_shape(axes(z.a), axes(z.z)) eltype(::Type{Zip{I,Z}}) where {I,Z} = tuple_type_cons(eltype(I), eltype(Z)) @inline start(z::Zip) = tuple(start(z.a), start(z.z)) @propagate_inbounds function next(z::Zip, st) @@ -693,17 +693,17 @@ _prod_size1(a, ::HasLength) = (length(a),) _prod_size1(a, A) = throw(ArgumentError("Cannot compute size for object of type $(typeof(a))")) -indices(P::ProductIterator) = _prod_indices(P.iterators) +axes(P::ProductIterator) = _prod_indices(P.iterators) _prod_indices(::Tuple{}) = () _prod_indices(t::Tuple) = (_prod_indices1(t[1], iteratorsize(t[1]))..., _prod_indices(tail(t))...) -_prod_indices1(a, ::HasShape) = indices(a) +_prod_indices1(a, ::HasShape) = axes(a) _prod_indices1(a, ::HasLength) = (OneTo(length(a)),) _prod_indices1(a, A) = throw(ArgumentError("Cannot compute indices for object of type $(typeof(a))")) -ndims(p::ProductIterator) = length(indices(p)) +ndims(p::ProductIterator) = length(axes(p)) length(P::ProductIterator) = prod(size(P)) -_length(p::ProductIterator) = prod(map(unsafe_length, indices(p))) +_length(p::ProductIterator) = prod(map(unsafe_length, axes(p))) iteratoreltype(::Type{ProductIterator{Tuple{}}}) = HasEltype() iteratoreltype(::Type{ProductIterator{Tuple{I}}}) where {I} = iteratoreltype(I) diff --git a/base/linalg/adjtrans.jl b/base/linalg/adjtrans.jl index d9e931d278fa64..984370318a36e3 100644 --- a/base/linalg/adjtrans.jl +++ b/base/linalg/adjtrans.jl @@ -1,7 +1,7 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license using Base: @pure, @propagate_inbounds, _return_type, _default_type, _isleaftype, @_inline_meta -import Base: length, size, indices, IndexStyle, getindex, setindex!, parent, vec, convert, similar +import Base: length, size, axes, IndexStyle, getindex, setindex!, parent, vec, convert, similar ### basic definitions (types, aliases, constructors, abstractarray interface, sundry similar) @@ -68,8 +68,8 @@ wrappertype(::Type{<:Transpose}) = Transpose length(A::AdjOrTrans) = length(A.parent) size(v::AdjOrTransAbsVec) = (1, length(v.parent)) size(A::AdjOrTransAbsMat) = reverse(size(A.parent)) -indices(v::AdjOrTransAbsVec) = (Base.OneTo(1), indices(v.parent)...) -indices(A::AdjOrTransAbsMat) = reverse(indices(A.parent)) +axes(v::AdjOrTransAbsVec) = (Base.OneTo(1), axes(v.parent)...) +axes(A::AdjOrTransAbsMat) = reverse(axes(A.parent)) IndexStyle(::Type{<:AdjOrTransAbsVec}) = IndexLinear() IndexStyle(::Type{<:AdjOrTransAbsMat}) = IndexCartesian() @propagate_inbounds getindex(v::AdjOrTransAbsVec, i::Int) = wrappertype(v)(v.parent[i]) diff --git a/base/linalg/generic.jl b/base/linalg/generic.jl index 8ec784332a418d..40373f13cc36c2 100644 --- a/base/linalg/generic.jl +++ b/base/linalg/generic.jl @@ -937,7 +937,7 @@ false ``` """ function issymmetric(A::AbstractMatrix) - indsm, indsn = indices(A) + indsm, indsn = axes(A) if indsm != indsn return false end @@ -976,7 +976,7 @@ true ``` """ function ishermitian(A::AbstractMatrix) - indsm, indsn = indices(A) + indsm, indsn = axes(A) if indsm != indsn return false end diff --git a/base/linalg/linalg.jl b/base/linalg/linalg.jl index cf926063bdb1b1..c9ad1c6fbe2dae 100644 --- a/base/linalg/linalg.jl +++ b/base/linalg/linalg.jl @@ -31,12 +31,12 @@ module LinAlg import Base: \, /, *, ^, +, -, == import Base: A_mul_Bt, At_ldiv_Bt, A_rdiv_Bc, At_ldiv_B, Ac_mul_Bc, A_mul_Bc, Ac_mul_B, Ac_ldiv_B, Ac_ldiv_Bc, At_mul_Bt, A_rdiv_Bt, At_mul_B -import Base: USE_BLAS64, abs, acos, acosh, acot, acoth, acsc, acsch, adjoint, asec, asech, asin, - asinh, atan, atanh, big, broadcast, ceil, conj, convert, copy, copy!, cos, cosh, cot, coth, csc, - csch, eltype, exp, findmax, findmin, fill!, floor, getindex, hcat, imag, indices, - inv, isapprox, isone, IndexStyle, kron, length, log, map, ndims, oneunit, parent, - power_by_squaring, print_matrix, promote_rule, real, round, sec, sech, setindex!, show, similar, - sin, sincos, sinh, size, sqrt, tan, tanh, transpose, trunc, typed_hcat, vec +import Base: USE_BLAS64, abs, acos, acosh, acot, acoth, acsc, acsch, adjoint, asec, asech, + asin, asinh, atan, atanh, axes, big, broadcast, ceil, conj, convert, copy, copy!, cos, + cosh, cot, coth, csc, csch, eltype, exp, findmax, findmin, fill!, floor, getindex, hcat, + imag, inv, isapprox, isone, IndexStyle, kron, length, log, map, ndims, oneunit, parent, + power_by_squaring, print_matrix, promote_rule, real, round, sec, sech, setindex!, show, + similar, sin, sincos, sinh, size, sqrt, tan, tanh, transpose, trunc, typed_hcat, vec using Base: hvcat_fill, iszero, IndexLinear, _length, promote_op, promote_typeof, @propagate_inbounds, @pure, reduce, typed_vcat # We use `_length` because of non-1 indices; releases after julia 0.5 diff --git a/base/linalg/rowvector.jl b/base/linalg/rowvector.jl index 0044114277e464..6d228c3a7da6cb 100644 --- a/base/linalg/rowvector.jl +++ b/base/linalg/rowvector.jl @@ -152,8 +152,8 @@ julia> conj(v) @inline length(rowvec::RowVector) = length(rowvec.vec) @inline size(rowvec::RowVector) = (1, length(rowvec.vec)) @inline size(rowvec::RowVector, d) = ifelse(d==2, length(rowvec.vec), 1) -@inline indices(rowvec::RowVector) = (Base.OneTo(1), indices(rowvec.vec)[1]) -@inline indices(rowvec::RowVector, d) = ifelse(d == 2, indices(rowvec.vec)[1], Base.OneTo(1)) +@inline axes(rowvec::RowVector) = (Base.OneTo(1), axes(rowvec.vec)[1]) +@inline axes(rowvec::RowVector, d) = ifelse(d == 2, axes(rowvec.vec)[1], Base.OneTo(1)) IndexStyle(::RowVector) = IndexLinear() IndexStyle(::Type{<:RowVector}) = IndexLinear() diff --git a/base/linalg/transpose.jl b/base/linalg/transpose.jl index bc29c5ec346f9a..ef08fc3d57ddd4 100644 --- a/base/linalg/transpose.jl +++ b/base/linalg/transpose.jl @@ -75,26 +75,26 @@ julia> A """ adjoint!(B::AbstractMatrix, A::AbstractMatrix) = transpose_f!(adjoint, B, A) function transpose!(B::AbstractVector, A::AbstractMatrix) - indices(B,1) == indices(A,2) && indices(A,1) == 1:1 || throw(DimensionMismatch("transpose")) + axes(B,1) == axes(A,2) && axes(A,1) == 1:1 || throw(DimensionMismatch("transpose")) copy!(B, A) end function transpose!(B::AbstractMatrix, A::AbstractVector) - indices(B,2) == indices(A,1) && indices(B,1) == 1:1 || throw(DimensionMismatch("transpose")) + axes(B,2) == axes(A,1) && axes(B,1) == 1:1 || throw(DimensionMismatch("transpose")) copy!(B, A) end function adjoint!(B::AbstractVector, A::AbstractMatrix) - indices(B,1) == indices(A,2) && indices(A,1) == 1:1 || throw(DimensionMismatch("transpose")) + axes(B,1) == axes(A,2) && axes(A,1) == 1:1 || throw(DimensionMismatch("transpose")) ccopy!(B, A) end function adjoint!(B::AbstractMatrix, A::AbstractVector) - indices(B,2) == indices(A,1) && indices(B,1) == 1:1 || throw(DimensionMismatch("transpose")) + axes(B,2) == axes(A,1) && axes(B,1) == 1:1 || throw(DimensionMismatch("transpose")) ccopy!(B, A) end const transposebaselength=64 function transpose_f!(f, B::AbstractMatrix, A::AbstractMatrix) - inds = indices(A) - indices(B,1) == inds[2] && indices(B,2) == inds[1] || throw(DimensionMismatch(string(f))) + inds = axes(A) + axes(B,1) == inds[2] && axes(B,2) == inds[1] || throw(DimensionMismatch(string(f))) m, n = length(inds[1]), length(inds[2]) if m*n<=4*transposebaselength @@ -169,12 +169,12 @@ julia> transpose(A) ``` """ function transpose(A::AbstractMatrix) - ind1, ind2 = indices(A) + ind1, ind2 = axes(A) B = similar(A, (ind2, ind1)) transpose!(B, A) end function adjoint(A::AbstractMatrix) - ind1, ind2 = indices(A) + ind1, ind2 = axes(A) B = similar(A, (ind2, ind1)) adjoint!(B, A) end diff --git a/base/linalg/uniformscaling.jl b/base/linalg/uniformscaling.jl index e159b647d9fe83..f2cc28db9b2079 100644 --- a/base/linalg/uniformscaling.jl +++ b/base/linalg/uniformscaling.jl @@ -225,7 +225,7 @@ function ==(A::StridedMatrix, J::UniformScaling) size(A, 1) == size(A, 2) || return false iszero(J.λ) && return iszero(A) isone(J.λ) && return isone(A) - for j in indices(A, 2), i in indices(A, 1) + for j in axes(A, 2), i in axes(A, 1) ifelse(i == j, A[i, j] == J.λ, iszero(A[i, j])) || return false end return true diff --git a/base/markdown/GitHub/table.jl b/base/markdown/GitHub/table.jl index 72fa7a5e4314d6..3b10945e37ae15 100644 --- a/base/markdown/GitHub/table.jl +++ b/base/markdown/GitHub/table.jl @@ -88,7 +88,7 @@ padding(width, twidth, a) = function padcells!(rows, align; len = length, min = 0) widths = colwidths(rows, len = len, min = min) - for i = 1:length(rows), j = indices(rows[1],1) + for i = 1:length(rows), j = axes(rows[1],1) cell = rows[i][j] lpad, rpad = padding(len(cell), widths[j], align[j]) rows[i][j] = " "^lpad * cell * " "^rpad @@ -107,13 +107,13 @@ function plain(io::IO, md::Table) replace(plaininline(each), "|", "\\|") end padcells!(cells, md.align, len = length, min = 3) - for i = indices(cells,1) + for i = axes(cells,1) print(io, "| ") join(io, cells[i], " | ") println(io, " |") if i == 1 print(io, "|") - join(io, [_dash(length(cells[i][j]), md.align[j]) for j = indices(cells[1],1)], "|") + join(io, [_dash(length(cells[i][j]), md.align[j]) for j = axes(cells[1],1)], "|") println(io, "|") end end diff --git a/base/multidimensional.jl b/base/multidimensional.jl index e7978079d3da46..f5f79853eacd1c 100644 --- a/base/multidimensional.jl +++ b/base/multidimensional.jl @@ -144,7 +144,7 @@ module IteratorsMD # nextind with CartesianIndex function Base.nextind(a::AbstractArray{<:Any,N}, i::CartesianIndex{N}) where {N} - _, ni = next(CartesianRange(indices(a)), i) + _, ni = next(CartesianRange(axes(a)), i) return ni end @@ -226,7 +226,7 @@ module IteratorsMD ndims(::Type{CartesianRange{N}}) where {N} = N ndims(::Type{CartesianRange{N,TT}}) where {N,TT} = N - eachindex(::IndexCartesian, A::AbstractArray) = CartesianRange(indices(A)) + eachindex(::IndexCartesian, A::AbstractArray) = CartesianRange(axes(A)) @inline eachindex(::IndexCartesian, A::AbstractArray, B::AbstractArray...) = CartesianRange(maxsize(A, B...)) @@ -356,7 +356,7 @@ using .IteratorsMD # Disallow linear indexing with CartesianIndex function checkbounds(::Type{Bool}, A::AbstractArray, i::Union{CartesianIndex, AbstractArray{<:CartesianIndex}}) @_inline_meta - checkbounds_indices(Bool, indices(A), (i,)) + checkbounds_indices(Bool, axes(A), (i,)) end @inline checkbounds_indices(::Type{Bool}, ::Tuple{}, I::Tuple{CartesianIndex,Vararg{Any}}) = @@ -435,7 +435,7 @@ index_lengths() = () # returns a Tuple{Vararg{AbstractUnitRange}} of indices index_shape() = () @inline index_shape(::Real, rest...) = index_shape(rest...) -@inline index_shape(A::AbstractArray, rest...) = (indices(A)..., index_shape(rest...)...) +@inline index_shape(A::AbstractArray, rest...) = (axes(A)..., index_shape(rest...)...) """ LogicalIndex(mask) @@ -467,7 +467,7 @@ show(io::IO, r::LogicalIndex) = print(io, "Base.LogicalIndex(", r.mask, ")") return (r, start(r), 1) end @inline function start(L::LogicalIndex{<:CartesianIndex}) - r = CartesianRange(indices(L.mask)) + r = CartesianRange(axes(L.mask)) return (r, start(r), 1) end @propagate_inbounds function next(L::LogicalIndex, s) @@ -498,15 +498,15 @@ end @inline checkbounds(::Type{Bool}, A::AbstractArray, I::LogicalIndex{<:Any,<:AbstractArray{Bool,1}}) = linearindices(A) == linearindices(I.mask) -@inline checkbounds(::Type{Bool}, A::AbstractArray, I::LogicalIndex) = indices(A) == indices(I.mask) -@inline checkindex(::Type{Bool}, indx::AbstractUnitRange, I::LogicalIndex) = (indx,) == indices(I.mask) +@inline checkbounds(::Type{Bool}, A::AbstractArray, I::LogicalIndex) = axes(A) == axes(I.mask) +@inline checkindex(::Type{Bool}, indx::AbstractUnitRange, I::LogicalIndex) = (indx,) == axes(I.mask) checkindex(::Type{Bool}, inds::Tuple, I::LogicalIndex) = false ensure_indexable(I::Tuple{}) = () @inline ensure_indexable(I::Tuple{Any, Vararg{Any}}) = (I[1], ensure_indexable(tail(I))...) @inline ensure_indexable(I::Tuple{LogicalIndex, Vararg{Any}}) = (collect(I[1]), ensure_indexable(tail(I))...) -# In simple cases, we know that we don't need to use indices(A). Optimize those +# In simple cases, we know that we don't need to use axes(A). Optimize those # until Julia gets smart enough to elide the call on its own: to_indices(A, I::Tuple{}) = () @inline to_indices(A, I::Tuple{Vararg{Union{Integer, CartesianIndex}}}) = to_indices(A, (), I) @@ -560,7 +560,7 @@ function _unsafe_getindex(::IndexStyle, A::AbstractArray, I::Vararg{Union{Real, # This is specifically not inlined to prevent excessive allocations in type unstable code shape = index_shape(I...) dest = similar(A, shape) - map(unsafe_length, indices(dest)) == map(unsafe_length, shape) || throw_checksize_error(dest, shape) + map(unsafe_length, axes(dest)) == map(unsafe_length, shape) || throw_checksize_error(dest, shape) _unsafe_getindex!(dest, A, I...) # usually a generated function, don't allow it to impact inference result return dest end @@ -882,8 +882,8 @@ See also [`accumulate`](@ref). """ function accumulate!(op, B, A, dim::Integer) dim > 0 || throw(ArgumentError("dim must be a positive integer")) - inds_t = indices(A) - indices(B) == inds_t || throw(DimensionMismatch("shape of B must match A")) + inds_t = axes(A) + axes(B) == inds_t || throw(DimensionMismatch("shape of B must match A")) dim > ndims(A) && return copy!(B, A) isempty(inds_t[dim]) && return B if dim == 1 @@ -899,8 +899,8 @@ function accumulate!(op, B, A, dim::Integer) end end else - R1 = CartesianRange(indices(A)[1:dim-1]) # not type-stable - R2 = CartesianRange(indices(A)[dim+1:end]) + R1 = CartesianRange(axes(A)[1:dim-1]) # not type-stable + R2 = CartesianRange(axes(A)[dim+1:end]) _accumulate!(op, B, A, R1, inds_t[dim], R2) # use function barrier end return B @@ -1029,7 +1029,7 @@ Copy all elements from collection `src` to array `dest`. copy!(dest, src) function copy!(dest::AbstractArray{T,N}, src::AbstractArray{T,N}) where {T,N} - @boundscheck checkbounds(dest, indices(src)...) + @boundscheck checkbounds(dest, axes(src)...) for I in eachindex(IndexStyle(src,dest), src) @inbounds dest[I] = src[I] end @@ -1084,8 +1084,8 @@ See also [`circshift`](@ref). """ @noinline function circshift!(dest::AbstractArray{T,N}, src, shiftamt::DimsInteger) where {T,N} dest === src && throw(ArgumentError("dest and src must be separate arrays")) - inds = indices(src) - indices(dest) == inds || throw(ArgumentError("indices of src and dest must match (got $inds and $(indices(dest)))")) + inds = axes(src) + axes(dest) == inds || throw(ArgumentError("indices of src and dest must match (got $inds and $(axes(dest)))")) _circshift!(dest, (), src, (), inds, fill_to_length(shiftamt, 0, Val(N))) end circshift!(dest::AbstractArray, src, shiftamt) = circshift!(dest, src, (shiftamt...,)) @@ -1157,7 +1157,7 @@ true """ function circcopy!(dest, src) dest === src && throw(ArgumentError("dest and src must be separate arrays")) - indssrc, indsdest = indices(src), indices(dest) + indssrc, indsdest = axes(src), axes(dest) if (szsrc = map(length, indssrc)) != (szdest = map(length, indsdest)) throw(DimensionMismatch("src and dest must have the same sizes (got $szsrc and $szdest)")) end @@ -1476,10 +1476,10 @@ function permutedims(B::StridedArray, perm) end function checkdims_perm(P::AbstractArray{TP,N}, B::AbstractArray{TB,N}, perm) where {TP,TB,N} - indsB = indices(B) + indsB = axes(B) length(perm) == N || throw(ArgumentError("expected permutation of size $N, but length(perm)=$(length(perm))")) isperm(perm) || throw(ArgumentError("input is not a permutation")) - indsP = indices(P) + indsP = axes(P) for i = 1:length(perm) indsP[i] == indsB[perm[i]] || throw(DimensionMismatch("destination tensor of incorrect size")) end @@ -1571,7 +1571,7 @@ julia> unique(A, 3) inds = inds -> zeros(UInt, inds) quote 1 <= dim <= $N || return copy(A) - hashes = similar($inds, indices(A, dim)) + hashes = similar($inds, axes(A, dim)) # Compute hash for each row k = 0 @@ -1580,15 +1580,15 @@ julia> unique(A, 3) end # Collect index of first row for each hash - uniquerow = similar(Array{Int}, indices(A, dim)) + uniquerow = similar(Array{Int}, axes(A, dim)) firstrow = Dict{Prehashed,Int}() - for k = indices(A, dim) + for k = axes(A, dim) uniquerow[k] = get!(firstrow, Prehashed(hashes[k]), k) end uniquerows = collect(values(firstrow)) # Check for collisions - collided = similar(falses, indices(A, dim)) + collided = similar(falses, axes(A, dim)) @inbounds begin @nloops $N i A d->(if d == dim k = i_d @@ -1603,11 +1603,11 @@ julia> unique(A, 3) end if any(collided) - nowcollided = similar(BitArray, indices(A, dim)) + nowcollided = similar(BitArray, axes(A, dim)) while any(collided) # Collect index of first row for each collided hash empty!(firstrow) - for j = indices(A, dim) + for j = axes(A, dim) collided[j] || continue uniquerow[j] = get!(firstrow, Prehashed(hashes[j]), j) end @@ -1634,7 +1634,7 @@ julia> unique(A, 3) end end - @nref $N A d->d == dim ? sort!(uniquerows) : (indices(A, d)) + @nref $N A d->d == dim ? sort!(uniquerows) : (axes(A, d)) end end diff --git a/base/number.jl b/base/number.jl index 18bee75b761cd0..18f63c386f578d 100644 --- a/base/number.jl +++ b/base/number.jl @@ -41,8 +41,8 @@ isone(x) = x == one(x) # fallback method size(x::Number) = () size(x::Number,d) = convert(Int,d)<1 ? throw(BoundsError()) : 1 -indices(x::Number) = () -indices(x::Number,d) = convert(Int,d)<1 ? throw(BoundsError()) : OneTo(1) +axes(x::Number) = () +axes(x::Number,d) = convert(Int,d)<1 ? throw(BoundsError()) : OneTo(1) eltype(::Type{T}) where {T<:Number} = T ndims(x::Number) = 0 ndims(::Type{<:Number}) = 0 diff --git a/base/permuteddimsarray.jl b/base/permuteddimsarray.jl index 0e7f79b230710c..20e5fba8579ae0 100644 --- a/base/permuteddimsarray.jl +++ b/base/permuteddimsarray.jl @@ -47,7 +47,7 @@ end Base.parent(A::PermutedDimsArray) = A.parent Base.size(A::PermutedDimsArray{T,N,perm}) where {T,N,perm} = genperm(size(parent(A)), perm) -Base.indices(A::PermutedDimsArray{T,N,perm}) where {T,N,perm} = genperm(indices(parent(A)), perm) +Base.axes(A::PermutedDimsArray{T,N,perm}) where {T,N,perm} = genperm(axes(parent(A)), perm) Base.unsafe_convert(::Type{Ptr{T}}, A::PermutedDimsArray{T}) where {T} = Base.unsafe_convert(Ptr{T}, parent(A)) @@ -109,7 +109,7 @@ julia> permutedims(A, [3, 2, 1]) ``` """ function permutedims(A::AbstractArray, perm) - dest = similar(A, genperm(indices(A), perm)) + dest = similar(A, genperm(axes(A), perm)) permutedims!(dest, A, perm) end @@ -147,7 +147,7 @@ function permutedims!(dest, src::AbstractArray, perm) end function Base.copy!(dest::PermutedDimsArray{T,N}, src::AbstractArray{T,N}) where {T,N} - checkbounds(dest, indices(src)...) + checkbounds(dest, axes(src)...) _copy!(dest, src) end Base.copy!(dest::PermutedDimsArray, src::AbstractArray) = _copy!(dest, src) @@ -162,17 +162,17 @@ function _copy!(P::PermutedDimsArray{T,N,perm}, src) where {T,N,perm} if d == ndims(src) copy!(parent(P), src) # it's not permuted else - R1 = CartesianRange(indices(src)[1:d]) + R1 = CartesianRange(axes(src)[1:d]) d1 = findfirst(equalto(d+1), perm) # first permuted dim of dest - R2 = CartesianRange(indices(src)[d+2:d1-1]) - R3 = CartesianRange(indices(src)[d1+1:end]) + R2 = CartesianRange(axes(src)[d+2:d1-1]) + R3 = CartesianRange(axes(src)[d1+1:end]) _permutedims!(P, src, R1, R2, R3, d+1, d1) end return P end @noinline function _permutedims!(P::PermutedDimsArray, src, R1::CartesianRange{0}, R2, R3, ds, dp) - ip, is = indices(src, dp), indices(src, ds) + ip, is = axes(src, dp), axes(src, ds) for jo in first(ip):8:last(ip), io in first(is):8:last(is) for I3 in R3, I2 in R2 for j in jo:min(jo+7, last(ip)) @@ -186,7 +186,7 @@ end end @noinline function _permutedims!(P::PermutedDimsArray, src, R1, R2, R3, ds, dp) - ip, is = indices(src, dp), indices(src, ds) + ip, is = axes(src, dp), axes(src, ds) for jo in first(ip):8:last(ip), io in first(is):8:last(is) for I3 in R3, I2 in R2 for j in jo:min(jo+7, last(ip)) diff --git a/base/reducedim.jl b/base/reducedim.jl index 3b1bf5e5a0a4df..7c5bcb1e3c45aa 100644 --- a/base/reducedim.jl +++ b/base/reducedim.jl @@ -3,10 +3,10 @@ ## Functions to compute the reduced shape # for reductions that expand 0 dims to 1 -reduced_indices(a::AbstractArray, region) = reduced_indices(indices(a), region) +reduced_indices(a::AbstractArray, region) = reduced_indices(axes(a), region) # for reductions that keep 0 dims as 0 -reduced_indices0(a::AbstractArray, region) = reduced_indices0(indices(a), region) +reduced_indices0(a::AbstractArray, region) = reduced_indices0(axes(a), region) function reduced_indices(inds::Indices{N}, d::Int, rd::AbstractUnitRange) where N d < 1 && throw(ArgumentError("dimension must be ≥ 1, got $d")) @@ -174,7 +174,7 @@ function check_reducedims(R, A) lsiz = 1 had_nonreduc = false for i = 1:ndims(A) - Ri, Ai = indices(R, i), indices(A, i) + Ri, Ai = axes(R, i), axes(A, i) sRi, sAi = length(Ri), length(Ai) if sRi == 1 if sAi > 1 @@ -185,7 +185,7 @@ function check_reducedims(R, A) end end else - Ri == Ai || throw(DimensionMismatch("reduction on array with indices $(indices(A)) with output with indices $(indices(R))")) + Ri == Ai || throw(DimensionMismatch("reduction on array with indices $(axes(A)) with output with indices $(axes(R))")) had_nonreduc = true end end @@ -199,8 +199,8 @@ copyfirst!(R::AbstractArray, A::AbstractArray) = mapfirst!(identity, R, A) function mapfirst!(f, R::AbstractArray, A::AbstractArray) lsiz = check_reducedims(R, A) - iA = indices(A) - iR = indices(R) + iA = axes(A) + iR = axes(R) t = [] for i in 1:length(iR) iAi = iA[i] @@ -223,7 +223,7 @@ function _mapreducedim!(f, op, R::AbstractArray, A::AbstractArray) end return R end - indsAt, indsRt = safe_tail(indices(A)), safe_tail(indices(R)) # handle d=1 manually + indsAt, indsRt = safe_tail(axes(A)), safe_tail(axes(R)) # handle d=1 manually keep, Idefault = Broadcast.shapeindexer(indsAt, indsRt) if reducedim1(R, A) # keep the accumulator as a local variable when reducing along the first dimension @@ -231,7 +231,7 @@ function _mapreducedim!(f, op, R::AbstractArray, A::AbstractArray) @inbounds for IA in CartesianRange(indsAt) IR = Broadcast.newindex(IA, keep, Idefault) r = R[i1,IR] - @simd for i in indices(A, 1) + @simd for i in axes(A, 1) r = op(r, f(A[i, IA])) end R[i1,IR] = r @@ -239,7 +239,7 @@ function _mapreducedim!(f, op, R::AbstractArray, A::AbstractArray) else @inbounds for IA in CartesianRange(indsAt) IR = Broadcast.newindex(IA, keep, Idefault) - @simd for i in indices(A, 1) + @simd for i in axes(A, 1) R[i,IR] = op(R[i,IR], f(A[i,IA])) end end @@ -641,11 +641,11 @@ function findminmax!(f, Rval, Rind, A::AbstractArray{T,N}) where {T,N} (isempty(Rval) || isempty(A)) && return Rval, Rind lsiz = check_reducedims(Rval, A) for i = 1:N - indices(Rval, i) == indices(Rind, i) || throw(DimensionMismatch("Find-reduction: outputs must have the same indices")) + axes(Rval, i) == axes(Rind, i) || throw(DimensionMismatch("Find-reduction: outputs must have the same indices")) end # If we're reducing along dimension 1, for efficiency we can make use of a temporary. # Otherwise, keep the result in Rval/Rind so that we traverse A in storage order. - indsAt, indsRt = safe_tail(indices(A)), safe_tail(indices(Rval)) + indsAt, indsRt = safe_tail(axes(A)), safe_tail(axes(Rval)) keep, Idefault = Broadcast.shapeindexer(indsAt, indsRt) ks = keys(A) k, kss = next(ks, start(ks)) @@ -656,7 +656,7 @@ function findminmax!(f, Rval, Rind, A::AbstractArray{T,N}) where {T,N} IR = Broadcast.newindex(IA, keep, Idefault) tmpRv = Rval[i1,IR] tmpRi = Rind[i1,IR] - for i in indices(A,1) + for i in axes(A,1) tmpAv = A[i,IA] if tmpRi == zi || (tmpRv == tmpRv && (tmpAv != tmpAv || f(tmpAv, tmpRv))) tmpRv = tmpAv @@ -670,7 +670,7 @@ function findminmax!(f, Rval, Rind, A::AbstractArray{T,N}) where {T,N} else @inbounds for IA in CartesianRange(indsAt) IR = Broadcast.newindex(IA, keep, Idefault) - for i in indices(A, 1) + for i in axes(A, 1) tmpAv = A[i,IA] tmpRv = Rval[i,IR] tmpRi = Rind[i,IR] diff --git a/base/repl/LineEdit.jl b/base/repl/LineEdit.jl index deda700e72e804..e01560d22e2880 100644 --- a/base/repl/LineEdit.jl +++ b/base/repl/LineEdit.jl @@ -106,9 +106,9 @@ region(s) = Pair(extrema(_region(s))...) bufend(s) = buffer(s).size -indexes(reg::Region) = first(reg)+1:last(reg) +axes(reg::Region) = first(reg)+1:last(reg) -content(s, reg::Region = 0=>bufend(s)) = String(buffer(s).data[indexes(reg)]) +content(s, reg::Region = 0=>bufend(s)) = String(buffer(s).data[axes(reg)]) function activate_region(s::PromptState, state::Symbol) @assert state in (:mark, :shift, :off) diff --git a/base/reshapedarray.jl b/base/reshapedarray.jl index fef634061165bc..e4f7daa2c56454 100644 --- a/base/reshapedarray.jl +++ b/base/reshapedarray.jl @@ -114,7 +114,7 @@ end reshape(parent::AbstractArray{T,N}, ndims::Val{N}) where {T,N} = parent function reshape(parent::AbstractArray, ndims::Val{N}) where N - reshape(parent, rdims(Val(N), indices(parent))) + reshape(parent, rdims(Val(N), axes(parent))) end # Move elements from inds to out until out reaches the desired diff --git a/base/serialize.jl b/base/serialize.jl index 2efe10e480de63..429d7f52fe3f4a 100644 --- a/base/serialize.jl +++ b/base/serialize.jl @@ -288,7 +288,7 @@ _trimmedsubarray(A, V, newindexes, index::ViewIndex, indexes...) = _trimmedsubar trimmedindex(P, d, i::Real) = oftype(i, 1) trimmedindex(P, d, i::Colon) = i trimmedindex(P, d, i::Slice) = i -trimmedindex(P, d, i::AbstractArray) = oftype(i, reshape(linearindices(i), indices(i))) +trimmedindex(P, d, i::AbstractArray) = oftype(i, reshape(linearindices(i), axes(i))) function serialize(s::AbstractSerializer, ss::String) len = sizeof(ss) diff --git a/base/show.jl b/base/show.jl index 8c81eece49d07c..903e255449a10d 100644 --- a/base/show.jl +++ b/base/show.jl @@ -1656,7 +1656,7 @@ dims2string(d::Dims) = isempty(d) ? "0-dimensional" : inds2string(inds::Indices) = join(map(string,inds), '×') # anything array-like gets summarized e.g. 10-element Array{Int64,1} -summary(io::IO, a::AbstractArray) = summary(io, a, indices(a)) +summary(io::IO, a::AbstractArray) = summary(io, a, axes(a)) function summary(io::IO, a, inds::Tuple{Vararg{OneTo}}) print(io, dims2string(length.(inds)), " ") showarg(io, a, true) diff --git a/base/sort.jl b/base/sort.jl index ca7bbf651afe5d..f2cff89c34e82c 100644 --- a/base/sort.jl +++ b/base/sort.jl @@ -83,7 +83,7 @@ issorted(itr; issorted(itr, ord(lt,by,rev,order)) function partialsort!(v::AbstractVector, k::Union{Int,OrdinalRange}, o::Ordering) - inds = indices(v, 1) + inds = axes(v, 1) sort!(v, first(inds), last(inds), PartialQuickSort(k), o) @views v[k] end @@ -270,7 +270,7 @@ searchsorted(a::AbstractRange{<:Real}, x::Real, o::DirectOrdering) = for s in [:searchsortedfirst, :searchsortedlast, :searchsorted] @eval begin - $s(v::AbstractVector, x, o::Ordering) = (inds = indices(v, 1); $s(v,x,first(inds),last(inds),o)) + $s(v::AbstractVector, x, o::Ordering) = (inds = axes(v, 1); $s(v,x,first(inds),last(inds),o)) $s(v::AbstractVector, x; lt=isless, by=identity, rev::Union{Bool,Void}=nothing, order::Ordering=Forward) = $s(v,x,ord(lt,by,rev,order)) @@ -556,7 +556,7 @@ defalg(v::AbstractArray) = DEFAULT_STABLE defalg(v::AbstractArray{<:Number}) = DEFAULT_UNSTABLE function sort!(v::AbstractVector, alg::Algorithm, order::Ordering) - inds = indices(v,1) + inds = axes(v,1) sort!(v,first(inds),last(inds),alg,order) end @@ -682,7 +682,7 @@ these positions is returned. Note that this is equivalent to, but more efficient than, calling `sortperm(...)[k]`. """ partialsortperm(v::AbstractVector, k::Union{Integer,OrdinalRange}; kwargs...) = - partialsortperm!(similar(Vector{eltype(k)}, indices(v,1)), v, k; kwargs..., initialized=false) + partialsortperm!(similar(Vector{eltype(k)}, axes(v,1)), v, k; kwargs..., initialized=false) """ partialsortperm!(ix, v, k, [alg=,] [by=,] [lt=,] [rev=false,] [initialized=false]) @@ -698,7 +698,7 @@ function partialsortperm!(ix::AbstractVector{<:Integer}, v::AbstractVector, order::Ordering=Forward, initialized::Bool=false) if !initialized - @inbounds for i = indices(ix,1) + @inbounds for i = axes(ix,1) ix[i] = i end end @@ -759,8 +759,8 @@ function sortperm(v::AbstractVector; end end end - p = similar(Vector{Int}, indices(v, 1)) - for (i,ind) in zip(eachindex(p), indices(v, 1)) + p = similar(Vector{Int}, axes(v, 1)) + for (i,ind) in zip(eachindex(p), axes(v, 1)) p[i] = ind end sort!(p, alg, Perm(ordr,v)) @@ -797,11 +797,11 @@ function sortperm!(x::AbstractVector{<:Integer}, v::AbstractVector; rev::Union{Bool,Void}=nothing, order::Ordering=Forward, initialized::Bool=false) - if indices(x,1) != indices(v,1) - throw(ArgumentError("index vector must have the same indices as the source vector, $(indices(x,1)) != $(indices(v,1))")) + if axes(x,1) != axes(v,1) + throw(ArgumentError("index vector must have the same indices as the source vector, $(axes(x,1)) != $(axes(v,1))")) end if !initialized - @inbounds for i = indices(v,1) + @inbounds for i = axes(v,1) x[i] = i end end @@ -868,7 +868,7 @@ function sort(A::AbstractArray, dim::Integer; Base.depwarn("`initialized` keyword argument is deprecated", :sort) end order = ord(lt,by,rev,order) - n = length(indices(A, dim)) + n = length(axes(A, dim)) if dim != 1 pdims = (dim, setdiff(1:ndims(A), dim)...) # put the selected dimension first Ap = permutedims(A, pdims) @@ -878,7 +878,7 @@ function sort(A::AbstractArray, dim::Integer; else Av = A[:] sort_chunks!(Av, n, alg, order) - reshape(Av, indices(A)) + reshape(Av, axes(A)) end end @@ -920,9 +920,9 @@ julia> sortrows([7 3 5; -1 6 4; 9 -2 8], rev=true) ``` """ function sortrows(A::AbstractMatrix; kws...) - inds = indices(A,1) + inds = axes(A,1) T = slicetypeof(A, inds, :) - rows = similar(A, T, indices(A, 1)) + rows = similar(A, T, axes(A, 1)) for i in inds rows[i] = view(A, i, :) end @@ -959,9 +959,9 @@ julia> sortcols([7 3 5; 6 -1 -4; 9 -2 8], rev=true) ``` """ function sortcols(A::AbstractMatrix; kws...) - inds = indices(A,2) + inds = axes(A,2) T = slicetypeof(A, :, inds) - cols = similar(A, T, indices(A, 2)) + cols = similar(A, T, axes(A, 2)) for i in inds cols[i] = view(A, :, i) end @@ -1004,7 +1004,7 @@ lt(::Right, x::T, y::T) where {T<:Floats} = slt_int(x, y) isnan(o::DirectOrdering, x::Floats) = (x!=x) isnan(o::Perm, i::Int) = isnan(o.order,o.data[i]) -function nans2left!(v::AbstractVector, o::Ordering, lo::Int=first(indices(v,1)), hi::Int=last(indices(v,1))) +function nans2left!(v::AbstractVector, o::Ordering, lo::Int=first(axes(v,1)), hi::Int=last(axes(v,1))) i = lo @inbounds while i <= hi && isnan(o,v[i]) i += 1 @@ -1019,7 +1019,7 @@ function nans2left!(v::AbstractVector, o::Ordering, lo::Int=first(indices(v,1)), end return i, hi end -function nans2right!(v::AbstractVector, o::Ordering, lo::Int=first(indices(v,1)), hi::Int=last(indices(v,1))) +function nans2right!(v::AbstractVector, o::Ordering, lo::Int=first(axes(v,1)), hi::Int=last(axes(v,1))) i = hi @inbounds while lo <= i && isnan(o,v[i]) i -= 1 @@ -1060,7 +1060,7 @@ end fpsort!(v::AbstractVector, a::Sort.PartialQuickSort, o::Ordering) = - sort!(v, first(indices(v,1)), last(indices(v,1)), a, o) + sort!(v, first(axes(v,1)), last(axes(v,1)), a, o) sort!(v::AbstractVector{<:Floats}, a::Algorithm, o::DirectOrdering) = fpsort!(v,a,o) sort!(v::Vector{Int}, a::Algorithm, o::Perm{<:DirectOrdering,<:Vector{<:Floats}}) = fpsort!(v,a,o) diff --git a/base/sparse/higherorderfns.jl b/base/sparse/higherorderfns.jl index 447d2477468382..3b4b3744b60bbe 100644 --- a/base/sparse/higherorderfns.jl +++ b/base/sparse/higherorderfns.jl @@ -108,7 +108,7 @@ function broadcast!(f::Tf, C::SparseVecOrMat) where Tf end function broadcast!(f::Tf, C::SparseVecOrMat, A::SparseVecOrMat, Bs::Vararg{SparseVecOrMat,N}) where {Tf,N} _aresameshape(C, A, Bs...) && return _noshapecheck_map!(f, C, A, Bs...) - Base.Broadcast.check_broadcast_indices(indices(C), A, Bs...) + Base.Broadcast.check_broadcast_indices(axes(C), A, Bs...) fofzeros = f(_zeros_eltypes(A, Bs...)...) fpreszeros = _iszero(fofzeros) return fpreszeros ? _broadcast_zeropres!(f, C, A, Bs...) : diff --git a/base/sparse/sparsematrix.jl b/base/sparse/sparsematrix.jl index 0567b91758877c..f0a80e8d9da629 100644 --- a/base/sparse/sparsematrix.jl +++ b/base/sparse/sparsematrix.jl @@ -46,7 +46,7 @@ const SparseMatrixCSCView{Tv,Ti} = const SparseMatrixCSCUnion{Tv,Ti} = Union{SparseMatrixCSC{Tv,Ti}, SparseMatrixCSCView{Tv,Ti}} getcolptr(S::SparseMatrixCSC) = S.colptr -getcolptr(S::SparseMatrixCSCView) = view(S.parent.colptr, first(indices(S, 2)):(last(indices(S, 2)) + 1)) +getcolptr(S::SparseMatrixCSCView) = view(S.parent.colptr, first(axes(S, 2)):(last(axes(S, 2)) + 1)) getrowval(S::SparseMatrixCSC) = S.rowval getrowval(S::SparseMatrixCSCView) = S.parent.rowval getnzval( S::SparseMatrixCSC) = S.nzval diff --git a/base/sparse/sparsevector.jl b/base/sparse/sparsevector.jl index 8e04f78f1d74d8..293a9d5925954a 100644 --- a/base/sparse/sparsevector.jl +++ b/base/sparse/sparsevector.jl @@ -1555,7 +1555,7 @@ function LinAlg.lowrankupdate!(A::StridedMatrix, x::StridedVector, y::SparseVect nzv = nonzeros(y) @inbounds for (j,v) in zip(nzi,nzv) αv = α*v' - for i in indices(x, 1) + for i in axes(x, 1) A[i,j] += x[i]*αv end end diff --git a/base/statistics.jl b/base/statistics.jl index b0080206005e97..91a9660b451e2a 100644 --- a/base/statistics.jl +++ b/base/statistics.jl @@ -140,7 +140,7 @@ function centralize_sumabs2!(R::AbstractArray{S}, A::AbstractArray, means::Abstr end return R end - indsAt, indsRt = safe_tail(indices(A)), safe_tail(indices(R)) # handle d=1 manually + indsAt, indsRt = safe_tail(axes(A)), safe_tail(axes(R)) # handle d=1 manually keep, Idefault = Broadcast.shapeindexer(indsAt, indsRt) if reducedim1(R, A) i1 = first(indices1(R)) @@ -148,7 +148,7 @@ function centralize_sumabs2!(R::AbstractArray{S}, A::AbstractArray, means::Abstr IR = Broadcast.newindex(IA, keep, Idefault) r = R[i1,IR] m = means[i1,IR] - @simd for i in indices(A, 1) + @simd for i in axes(A, 1) r += abs2(A[i,IA] - m) end R[i1,IR] = r @@ -156,7 +156,7 @@ function centralize_sumabs2!(R::AbstractArray{S}, A::AbstractArray, means::Abstr else @inbounds for IA in CartesianRange(indsAt) IR = Broadcast.newindex(IA, keep, Idefault) - @simd for i in indices(A, 1) + @simd for i in axes(A, 1) R[i,IR] += abs2(A[i,IA] - means[i,IR]) end end @@ -597,7 +597,7 @@ function median!(v::AbstractVector) isnan(x) && return x end end - inds = indices(v, 1) + inds = axes(v, 1) n = length(inds) mid = div(first(inds)+last(inds),2) if isodd(n) diff --git a/base/subarray.jl b/base/subarray.jl index 2e765519013764..9625161781a385 100644 --- a/base/subarray.jl +++ b/base/subarray.jl @@ -53,7 +53,7 @@ viewindexing(I::Tuple{Vararg{Any}}) = IndexCartesian() viewindexing(I::Tuple{AbstractArray, Vararg{Any}}) = IndexCartesian() # Simple utilities -size(V::SubArray) = (@_inline_meta; map(n->Int(unsafe_length(n)), indices(V))) +size(V::SubArray) = (@_inline_meta; map(n->Int(unsafe_length(n)), axes(V))) similar(V::SubArray, T::Type, dims::Dims) = similar(V.parent, T, dims) @@ -263,7 +263,7 @@ substrides(s, parent, dim, I::Tuple{Any, Vararg{Any}}) = throw(ArgumentError("st stride(V::SubArray, d::Integer) = d <= ndims(V) ? strides(V)[d] : strides(V)[end] * size(V)[end] compute_stride1(parent::AbstractArray, I::NTuple{N,Any}) where {N} = - (@_inline_meta; compute_stride1(1, fill_to_length(indices(parent), OneTo(1), Val(N)), I)) + (@_inline_meta; compute_stride1(1, fill_to_length(axes(parent), OneTo(1), Val(N)), I)) compute_stride1(s, inds, I::Tuple{}) = s compute_stride1(s, inds, I::Tuple{ScalarIndex, Vararg{Any}}) = (@_inline_meta; compute_stride1(s*unsafe_length(inds[1]), tail(inds), tail(I))) @@ -294,13 +294,13 @@ compute_offset1(parent::AbstractVector, stride1::Integer, I::Tuple{AbstractRange compute_offset1(parent, stride1::Integer, I::Tuple) = (@_inline_meta; compute_offset1(parent, stride1, find_extended_dims(1, I...), find_extended_inds(I...), I)) compute_offset1(parent, stride1::Integer, dims::Tuple{Int}, inds::Tuple{Slice}, I::Tuple) = - (@_inline_meta; compute_linindex(parent, I) - stride1*first(indices(parent, dims[1]))) # index-preserving case + (@_inline_meta; compute_linindex(parent, I) - stride1*first(axes(parent, dims[1]))) # index-preserving case compute_offset1(parent, stride1::Integer, dims, inds, I::Tuple) = (@_inline_meta; compute_linindex(parent, I) - stride1) # linear indexing starts with 1 function compute_linindex(parent, I::NTuple{N,Any}) where N @_inline_meta - IP = fill_to_length(indices(parent), OneTo(1), Val(N)) + IP = fill_to_length(axes(parent), OneTo(1), Val(N)) compute_linindex(1, 1, IP, I) end function compute_linindex(f, s, IP::Tuple, I::Tuple{ScalarIndex, Vararg{Any}}) @@ -329,7 +329,7 @@ pointer(V::FastSubArray, i::Int) = pointer(V.parent, V.offset1 + V.stride1*i) pointer(V::FastContiguousSubArray, i::Int) = pointer(V.parent, V.offset1 + i) pointer(V::SubArray, i::Int) = _pointer(V, i) _pointer(V::SubArray{<:Any,1}, i::Int) = pointer(V, (i,)) -_pointer(V::SubArray, i::Int) = pointer(V, ind2sub(indices(V), i)) +_pointer(V::SubArray, i::Int) = pointer(V, ind2sub(axes(V), i)) function pointer(V::SubArray{T,N,<:Array,<:Tuple{Vararg{RangeIndex}}}, is::Tuple{Vararg{Int}}) where {T,N} index = first_index(V) @@ -343,7 +343,7 @@ end # indices are taken from the range/vector # Since bounds-checking is performance-critical and uses # indices, it's worth optimizing these implementations thoroughly -indices(S::SubArray) = (@_inline_meta; _indices_sub(S, S.indexes...)) +axes(S::SubArray) = (@_inline_meta; _indices_sub(S, S.indexes...)) _indices_sub(S::SubArray) = () _indices_sub(S::SubArray, ::Real, I...) = (@_inline_meta; _indices_sub(S, I...)) function _indices_sub(S::SubArray, i1::AbstractArray, I...) diff --git a/doc/src/devdocs/boundscheck.md b/doc/src/devdocs/boundscheck.md index 9eed150ea1497b..aaf5d1a250efa1 100644 --- a/doc/src/devdocs/boundscheck.md +++ b/doc/src/devdocs/boundscheck.md @@ -54,11 +54,11 @@ The overall hierarchy is: * `checkbounds(Bool, A, I...)` which calls - * `checkbounds_indices(Bool, indices(A), I)` which recursively calls + * `checkbounds_indices(Bool, axes(A), I)` which recursively calls * `checkindex` for each dimension -Here `A` is the array, and `I` contains the "requested" indices. `indices(A)` returns a tuple +Here `A` is the array, and `I` contains the "requested" indices. `axes(A)` returns a tuple of "permitted" indices of `A`. `checkbounds(A, I...)` throws an error if the indices are invalid, whereas `checkbounds(Bool, A, I...)` diff --git a/doc/src/devdocs/offset-arrays.md b/doc/src/devdocs/offset-arrays.md index 7ad1dfb7bc6e6c..4e6f77224faa16 100644 --- a/doc/src/devdocs/offset-arrays.md +++ b/doc/src/devdocs/offset-arrays.md @@ -20,7 +20,7 @@ As an overview, the steps are: * replace many uses of `size` with `indices` * replace `1:length(A)` with `eachindex(A)`, or in some cases `linearindices(A)` * replace `length(A)` with `length(linearindices(A))` - * replace explicit allocations like `Array{Int}(size(B))` with `similar(Array{Int}, indices(B))` + * replace explicit allocations like `Array{Int}(size(B))` with `similar(Array{Int}, axes(B))` These are described in more detail below. @@ -54,10 +54,10 @@ to check the code, and inspect it for whether it needs to be generalized. ### Using `indices` for bounds checks and loop iteration -`indices(A)` (reminiscent of `size(A)`) returns a tuple of `AbstractUnitRange` objects, specifying +`axes(A)` (reminiscent of `size(A)`) returns a tuple of `AbstractUnitRange` objects, specifying the range of valid indices along each dimension of `A`. When `A` has unconventional indexing, the ranges may not start at 1. If you just want the range for a particular dimension `d`, there -is `indices(A, d)`. +is `axes(A, d)`. Base implements a custom range type, `OneTo`, where `OneTo(n)` means the same thing as `1:n` but in a form that guarantees (via the type system) that the lower index is 1. For any new [`AbstractArray`](@ref) @@ -66,7 +66,7 @@ type, this is the default returned by `indices`, and it indicates that this arra you can add the following line: ```julia -@assert all(x->isa(x, Base.OneTo), indices(A)) +@assert all(x->isa(x, Base.OneTo), axes(A)) ``` at the top of any function. @@ -79,7 +79,7 @@ can sometimes simplify such tests. Some algorithms are most conveniently (or efficiently) written in terms of a single linear index, `A[i]` even if `A` is multi-dimensional. Regardless of the array's native indices, linear indices always range from `1:length(A)`. However, this raises an ambiguity for one-dimensional arrays (a.k.a., [`AbstractVector`](@ref)): does `v[i]` mean linear indexing , or Cartesian indexing with the array's native indices? -For this reason, your best option may be to iterate over the array with `eachindex(A)`, or, if you require the indices to be sequential integers, to get the index range by calling `linearindices(A)`. This will return `indices(A, 1)` if A is an AbstractVector, and the equivalent of `1:length(A)` otherwise. +For this reason, your best option may be to iterate over the array with `eachindex(A)`, or, if you require the indices to be sequential integers, to get the index range by calling `linearindices(A)`. This will return `axes(A, 1)` if A is an AbstractVector, and the equivalent of `1:length(A)` otherwise. By this definition, 1-dimensional arrays always use Cartesian indexing with the array's native indices. To help enforce this, it's worth noting that sub2ind(shape, i...) and ind2sub(shape, ind) will throw an error if shape indicates a 1-dimensional array with unconventional indexing (i.e., is a `Tuple{UnitRange}` rather than a tuple of `OneTo`). For arrays with conventional indexing, these functions continue to work the same as always. @@ -87,7 +87,7 @@ Using `indices` and `linearindices`, here is one way you could rewrite `mycopy!` ```julia function mycopy!(dest::AbstractVector, src::AbstractVector) - indices(dest) == indices(src) || throw(DimensionMismatch("vectors must match")) + axes(dest) == axes(src) || throw(DimensionMismatch("vectors must match")) for i in linearindices(src) @inbounds dest[i] = src[i] end @@ -106,13 +106,13 @@ underlying "conventional" behavior you'd like, e.g., `Array{Int}` or `BitArray` a convenient way of producing an all-zeros array that matches the indices of A is simply `zeros(A)`. Let's walk through a couple of explicit examples. First, if `A` has conventional indices, then -`similar(Array{Int}, indices(A))` would end up calling `Array{Int}(size(A))`, and thus return -an array. If `A` is an `AbstractArray` type with unconventional indexing, then `similar(Array{Int}, indices(A))` +`similar(Array{Int}, axes(A))` would end up calling `Array{Int}(size(A))`, and thus return +an array. If `A` is an `AbstractArray` type with unconventional indexing, then `similar(Array{Int}, axes(A))` should return something that "behaves like" an `Array{Int}` but with a shape (including indices) that matches `A`. (The most obvious implementation is to allocate an `Array{Int}(uninitialized, size(A))` and then "wrap" it in a type that shifts the indices.) -Note also that `similar(Array{Int}, (indices(A, 2),))` would allocate an `AbstractVector{Int}` +Note also that `similar(Array{Int}, (axes(A, 2),))` would allocate an `AbstractVector{Int}` (i.e., 1-dimensional array) that matches the indices of the columns of `A`. ### Deprecations @@ -171,26 +171,26 @@ can sometimes be used to avoid the need to write your own `ZeroRange` type. Once you have your `AbstractUnitRange` type, then specialize `indices`: ```julia -Base.indices(A::ZeroArray) = map(n->ZeroRange(n), A.size) +Base.axes(A::ZeroArray) = map(n->ZeroRange(n), A.size) ``` where here we imagine that `ZeroArray` has a field called `size` (there would be other ways to implement this). -In some cases, the fallback definition for `indices(A, d)`: +In some cases, the fallback definition for `axes(A, d)`: ```julia -indices(A::AbstractArray{T,N}, d) where {T,N} = d <= N ? indices(A)[d] : OneTo(1) +axes(A::AbstractArray{T,N}, d) where {T,N} = d <= N ? axes(A)[d] : OneTo(1) ``` may not be what you want: you may need to specialize it to return something other than `OneTo(1)` when `d > ndims(A)`. Likewise, in `Base` there is a dedicated function `indices1` which is equivalent -to `indices(A, 1)` but which avoids checking (at runtime) whether `ndims(A) > 0`. (This is purely +to `axes(A, 1)` but which avoids checking (at runtime) whether `ndims(A) > 0`. (This is purely a performance optimization.) It is defined as: ```julia indices1(A::AbstractArray{T,0}) where {T} = OneTo(1) -indices1(A::AbstractArray) = indices(A)[1] +indices1(A::AbstractArray) = axes(A)[1] ``` If the first of these (the zero-dimensional case) is problematic for your custom array type, be diff --git a/doc/src/manual/arrays.md b/doc/src/manual/arrays.md index 87d1883dbc8dee..8bbef72d07df6d 100644 --- a/doc/src/manual/arrays.md +++ b/doc/src/manual/arrays.md @@ -34,8 +34,8 @@ behavior, should take care to create a copy of inputs that it may modify. | [`ndims(A)`](@ref) | the number of dimensions of `A` | | [`size(A)`](@ref) | a tuple containing the dimensions of `A` | | [`size(A,n)`](@ref) | the size of `A` along dimension `n` | -| [`indices(A)`](@ref) | a tuple containing the valid indices of `A` | -| [`indices(A,n)`](@ref) | a range expressing the valid indices along dimension `n` | +| [`axes(A)`](@ref) | a tuple containing the valid indices of `A` | +| [`axes(A,n)`](@ref) | a range expressing the valid indices along dimension `n` | | [`eachindex(A)`](@ref) | an efficient iterator for visiting each position in `A` | | [`stride(A,k)`](@ref) | the stride (linear index distance between adjacent elements) along dimension `k` | | [`strides(A)`](@ref) | a tuple of the strides in each dimension | @@ -403,14 +403,14 @@ first `page` from `A` as a separate step). It can even be combined with a `:` to extract both diagonals from the two pages at the same time: ```jldoctest cartesianindex -julia> A[CartesianIndex.(indices(A, 1), indices(A, 2)), 1] +julia> A[CartesianIndex.(axes(A, 1), axes(A, 2)), 1] 4-element Array{Int64,1}: 1 6 11 16 -julia> A[CartesianIndex.(indices(A, 1), indices(A, 2)), :] +julia> A[CartesianIndex.(axes(A, 1), axes(A, 2)), :] 4×2 Array{Int64,2}: 1 17 6 22 diff --git a/doc/src/manual/interfaces.md b/doc/src/manual/interfaces.md index 1cb945400969a3..e8498d31a8e97d 100644 --- a/doc/src/manual/interfaces.md +++ b/doc/src/manual/interfaces.md @@ -228,7 +228,7 @@ ourselves, we can officially define it as a subtype of an [`AbstractArray`](@ref | `similar(A, dims::NTuple{Int})` | `similar(A, eltype(A), dims)` | Return a mutable array with the same element type and size *dims* | | `similar(A, ::Type{S}, dims::NTuple{Int})` | `Array{S}(uninitialized, dims)` | Return a mutable array with the specified element type and size | | **Non-traditional indices** | **Default definition** | **Brief description** | -| `indices(A)` | `map(OneTo, size(A))` | Return the `AbstractUnitRange` of valid indices | +| `axes(A)` | `map(OneTo, size(A))` | Return the `AbstractUnitRange` of valid indices | | `Base.similar(A, ::Type{S}, inds::NTuple{Ind})` | `similar(A, S, Base.to_shape(inds))` | Return a mutable array with the specified indices `inds` (see below) | | `Base.similar(T::Union{Type,Function}, inds)` | `T(Base.to_shape(inds))` | Return an array similar to `T` with the specified indices `inds` (see below) | @@ -399,7 +399,7 @@ perhaps range-types `Ind` of your own design. For more information, see [Arrays | `Base.broadcast_similar(f, ::DestStyle, ::Type{ElType}, inds, As...)` | Allocation of output container | | **Optional methods** | | | | `Base.BroadcastStyle(::Style1, ::Style2) = Style12()` | Precedence rules for mixing styles | -| `Base.broadcast_indices(::StyleA, A)` | Declaration of the indices of `A` for broadcasting purposes (for AbstractArrays, defaults to `indices(A)`) | +| `Base.broadcast_indices(::StyleA, A)` | Declaration of the indices of `A` for broadcasting purposes (for AbstractArrays, defaults to `axes(A)`) | | **Bypassing default machinery** | | | `broadcast(f, As...)` | Complete bypass of broadcasting machinery | | `broadcast(f, ::DestStyle, ::Void, ::Void, As...)` | Bypass after container type is computed | diff --git a/doc/src/manual/performance-tips.md b/doc/src/manual/performance-tips.md index 1b30724f3f7c49..6c666b51e83e92 100644 --- a/doc/src/manual/performance-tips.md +++ b/doc/src/manual/performance-tips.md @@ -844,7 +844,7 @@ do this in at least four ways (in addition to the recommended call to the built- ```julia function copy_cols(x::Vector{T}) where T - inds = indices(x, 1) + inds = axes(x, 1) out = similar(Array{T}, inds, inds) for i = inds out[:, i] = x @@ -853,7 +853,7 @@ function copy_cols(x::Vector{T}) where T end function copy_rows(x::Vector{T}) where T - inds = indices(x, 1) + inds = axes(x, 1) out = similar(Array{T}, inds, inds) for i = inds out[i, :] = x @@ -862,7 +862,7 @@ function copy_rows(x::Vector{T}) where T end function copy_col_row(x::Vector{T}) where T - inds = indices(x, 1) + inds = axes(x, 1) out = similar(Array{T}, inds, inds) for col = inds, row = inds out[row, col] = x[row] @@ -871,7 +871,7 @@ function copy_col_row(x::Vector{T}) where T end function copy_row_col(x::Vector{T}) where T - inds = indices(x, 1) + inds = axes(x, 1) out = similar(Array{T}, inds, inds) for row = inds, col = inds out[row, col] = x[col] diff --git a/doc/src/stdlib/arrays.md b/doc/src/stdlib/arrays.md index c39546121a7c9f..81d4d7d62e9f93 100644 --- a/doc/src/stdlib/arrays.md +++ b/doc/src/stdlib/arrays.md @@ -39,8 +39,8 @@ Base.Random.randsubseq! ```@docs Base.ndims Base.size -Base.indices(::Any) -Base.indices(::AbstractArray, ::Any) +Base.axes(::Any) +Base.axes(::AbstractArray, ::Any) Base.length(::AbstractArray) Base.eachindex Base.linearindices diff --git a/stdlib/DelimitedFiles/src/DelimitedFiles.jl b/stdlib/DelimitedFiles/src/DelimitedFiles.jl index e7535b93feb3c8..f78ac9b73488b2 100644 --- a/stdlib/DelimitedFiles/src/DelimitedFiles.jl +++ b/stdlib/DelimitedFiles/src/DelimitedFiles.jl @@ -742,9 +742,9 @@ function writedlm(io::IO, a::AbstractMatrix, dlm; opts...) optsd = val_opts(opts) quotes = get(optsd, :quotes, true) pb = PipeBuffer() - lastc = last(indices(a, 2)) - for i = indices(a, 1) - for j = indices(a, 2) + lastc = last(axes(a, 2)) + for i = axes(a, 1) + for j = axes(a, 2) writedlm_cell(pb, a[i, j], dlm, quotes) j == lastc ? write(pb,'\n') : print(pb,dlm) end diff --git a/stdlib/Test/src/Test.jl b/stdlib/Test/src/Test.jl index ad7917b335e5d5..d70a26d9d792ed 100644 --- a/stdlib/Test/src/Test.jl +++ b/stdlib/Test/src/Test.jl @@ -1220,9 +1220,9 @@ end # Raises an error if any columnwise vector norm exceeds err. Otherwise, returns # nothing. function test_approx_eq_modphase(a::StridedVecOrMat{S}, b::StridedVecOrMat{T}, - err = length(indices(a,1))^3*(eps(S)+eps(T))) where {S<:Real,T<:Real} - @test indices(a,1) == indices(b,1) && indices(a,2) == indices(b,2) - for i in indices(a,2) + err = length(axes(a,1))^3*(eps(S)+eps(T))) where {S<:Real,T<:Real} + @test axes(a,1) == axes(b,1) && axes(a,2) == axes(b,2) + for i in axes(a,2) v1, v2 = a[:, i], b[:, i] @test min(abs(norm(v1-v2)),abs(norm(v1+v2))) ≈ 0.0 atol=err end @@ -1452,7 +1452,7 @@ GenericArray{T}(args...) where {T} = GenericArray(Array{T}(args...)) GenericArray{T,N}(args...) where {T,N} = GenericArray(Array{T,N}(args...)) Base.keys(a::GenericArray) = keys(a.a) -Base.indices(a::GenericArray) = indices(a.a) +Base.axes(a::GenericArray) = axes(a.a) Base.length(a::GenericArray) = length(a.a) Base.size(a::GenericArray) = size(a.a) Base.getindex(a::GenericArray, i...) = a.a[i...] diff --git a/test/TestHelpers.jl b/test/TestHelpers.jl index f02c43275f3e7b..ef6d5610bc200c 100644 --- a/test/TestHelpers.jl +++ b/test/TestHelpers.jl @@ -159,17 +159,17 @@ parenttype(A::OffsetArray) = parenttype(typeof(A)) Base.parent(A::OffsetArray) = A.parent -errmsg(A) = error("size not supported for arrays with indices $(indices(A)); see https://docs.julialang.org/en/latest/devdocs/offset-arrays/") +errmsg(A) = error("size not supported for arrays with indices $(axes(A)); see https://docs.julialang.org/en/latest/devdocs/offset-arrays/") Base.size(A::OffsetArray) = errmsg(A) Base.size(A::OffsetArray, d) = errmsg(A) -Base.eachindex(::IndexCartesian, A::OffsetArray) = CartesianRange(indices(A)) -Base.eachindex(::IndexLinear, A::OffsetVector) = indices(A, 1) +Base.eachindex(::IndexCartesian, A::OffsetArray) = CartesianRange(axes(A)) +Base.eachindex(::IndexLinear, A::OffsetVector) = axes(A, 1) # Implementations of indices and indices1. Since bounds-checking is # performance-critical and relies on indices, these are usually worth # optimizing thoroughly. -@inline Base.indices(A::OffsetArray, d) = 1 <= d <= length(A.offsets) ? indices(parent(A))[d] .+ A.offsets[d] : (1:1) -@inline Base.indices(A::OffsetArray) = _indices(indices(parent(A)), A.offsets) # would rather use ntuple, but see #15276 +@inline Base.axes(A::OffsetArray, d) = 1 <= d <= length(A.offsets) ? axes(parent(A))[d] .+ A.offsets[d] : (1:1) +@inline Base.axes(A::OffsetArray) = _indices(axes(parent(A)), A.offsets) # would rather use ntuple, but see #15276 @inline _indices(inds, offsets) = (inds[1] .+ offsets[1], _indices(tail(inds), tail(offsets))...) _indices(::Tuple{}, ::Tuple{}) = () Base.indices1(A::OffsetArray{T,0}) where {T} = 1:1 # we only need to specialize this one diff --git a/test/abstractarray.jl b/test/abstractarray.jl index 2fbea6b17e0510..b74b8bc6b15fa2 100644 --- a/test/abstractarray.jl +++ b/test/abstractarray.jl @@ -702,11 +702,11 @@ A = TSlowNIndexes(rand(2,2)) @inferred size(rand(3,2,1), 2, 1) @inferred size(rand(3,2,1), 2, 1, 3) - @test @inferred(indices(rand(3,2))) == (1:3,1:2) - @test @inferred(indices(rand(3,2,1))) == (1:3,1:2,1:1) - @test @inferred(indices(rand(3,2), 1)) == 1:3 - @test @inferred(indices(rand(3,2), 2)) == 1:2 - @test @inferred(indices(rand(3,2), 3)) == 1:1 + @test @inferred(axes(rand(3,2))) == (1:3,1:2) + @test @inferred(axes(rand(3,2,1))) == (1:3,1:2,1:1) + @test @inferred(axes(rand(3,2), 1)) == 1:3 + @test @inferred(axes(rand(3,2), 2)) == 1:2 + @test @inferred(axes(rand(3,2), 3)) == 1:1 end @testset "#17088" begin diff --git a/test/arrayops.jl b/test/arrayops.jl index a4390866a96496..0db315e014aefd 100644 --- a/test/arrayops.jl +++ b/test/arrayops.jl @@ -1215,7 +1215,7 @@ end @testset "eachindexvalue" begin A14 = [11 13; 12 14] - R = CartesianRange(indices(A14)) + R = CartesianRange(axes(A14)) @test [a for (a,b) in pairs(IndexLinear(), A14)] == [1,2,3,4] @test [a for (a,b) in pairs(IndexCartesian(), A14)] == vec(collect(R)) @test [b for (a,b) in pairs(IndexLinear(), A14)] == [11,12,13,14] diff --git a/test/copy.jl b/test/copy.jl index b9ac472068b103..103ad6c849d81b 100644 --- a/test/copy.jl +++ b/test/copy.jl @@ -51,12 +51,12 @@ end @testset "with CartesianRange" begin let A = reshape(1:6, 3, 2), B = similar(A) - RA = CartesianRange(indices(A)) + RA = CartesianRange(axes(A)) copy!(B, RA, A, RA) @test B == A end let A = reshape(1:6, 3, 2), B = zeros(8,8) - RA = CartesianRange(indices(A)) + RA = CartesianRange(axes(A)) copy!(B, CartesianRange((5:7,2:3)), A, RA) @test B[5:7,2:3] == A B[5:7,2:3] = 0 diff --git a/test/inference.jl b/test/inference.jl index 471b14337b5e03..800f5228cbb969 100644 --- a/test/inference.jl +++ b/test/inference.jl @@ -657,7 +657,7 @@ end @test Base.return_types(i20343, ()) == [Int8] struct Foo20518 <: AbstractVector{Int}; end # issue #20518; inference assumed AbstractArrays Base.getindex(::Foo20518, ::Int) = "oops" # not to lie about their element type -Base.indices(::Foo20518) = (Base.OneTo(4),) +Base.axes(::Foo20518) = (Base.OneTo(4),) foo20518(xs::Any...) = -1 foo20518(xs::Int...) = [0] bar20518(xs) = sum(foo20518(xs...)) diff --git a/test/linalg/adjtrans.jl b/test/linalg/adjtrans.jl index b21c8ee31e529f..0439e8a7ecd0a5 100644 --- a/test/linalg/adjtrans.jl +++ b/test/linalg/adjtrans.jl @@ -98,10 +98,10 @@ end @test size(Transpose(intmat)) == reverse(size(intmat)) end @testset "indices methods" begin - @test indices(Adjoint(intvec)) == (Base.OneTo(1), Base.OneTo(length(intvec))) - @test indices(Adjoint(intmat)) == reverse(indices(intmat)) - @test indices(Transpose(intvec)) == (Base.OneTo(1), Base.OneTo(length(intvec))) - @test indices(Transpose(intmat)) == reverse(indices(intmat)) + @test axes(Adjoint(intvec)) == (Base.OneTo(1), Base.OneTo(length(intvec))) + @test axes(Adjoint(intmat)) == reverse(axes(intmat)) + @test axes(Transpose(intvec)) == (Base.OneTo(1), Base.OneTo(length(intvec))) + @test axes(Transpose(intmat)) == reverse(axes(intmat)) end @testset "IndexStyle methods" begin @test IndexStyle(Adjoint(intvec)) == IndexLinear() diff --git a/test/numbers.jl b/test/numbers.jl index 19f85623459f98..083fd6c19e65b7 100644 --- a/test/numbers.jl +++ b/test/numbers.jl @@ -2822,9 +2822,9 @@ end @test ndims(Integer) == 0 @test size(1,1) == 1 @test_throws BoundsError size(1,-1) - @test indices(1) == () - @test indices(1,1) == 1:1 - @test_throws BoundsError indices(1,-1) + @test axes(1) == () + @test axes(1,1) == 1:1 + @test_throws BoundsError axes(1,-1) @test isinteger(Integer(2)) == true @test !isinteger(π) @test size(1) == () diff --git a/test/offsetarray.jl b/test/offsetarray.jl index fc8682e93f7c0c..09943ef91ae14d 100644 --- a/test/offsetarray.jl +++ b/test/offsetarray.jl @@ -11,14 +11,14 @@ let v0 = rand(4) v = OffsetArray(v0, (-3,)) h = OffsetArray([-1,1,-2,2,0], (-3,)) -@test indices(v) == (-2:1,) +@test axes(v) == (-2:1,) @test_throws ErrorException size(v) @test_throws ErrorException size(v, 1) A0 = [1 3; 2 4] A = OffsetArray(A0, (-1,2)) # IndexLinear S = OffsetArray(view(A0, 1:2, 1:2), (-1,2)) # IndexCartesian -@test indices(A) == indices(S) == (0:1, 3:4) +@test axes(A) == axes(S) == (0:1, 3:4) @test_throws ErrorException size(A) @test_throws ErrorException size(A, 1) @@ -96,24 +96,24 @@ S = view(A, :, 3) @test S[0] == 1 @test S[1] == 2 @test_throws BoundsError S[2] -@test indices(S) === (0:1,) +@test axes(S) === (0:1,) S = view(A, 0, :) @test S == OffsetArray([1,3], (A.offsets[2],)) @test S[3] == 1 @test S[4] == 3 @test_throws BoundsError S[1] -@test indices(S) === (3:4,) +@test axes(S) === (3:4,) S = view(A, 0:0, 4) @test S == [3] @test S[1] == 3 @test_throws BoundsError S[0] -@test indices(S) === (Base.OneTo(1),) +@test axes(S) === (Base.OneTo(1),) S = view(A, 1, 3:4) @test S == [2,4] @test S[1] == 2 @test S[2] == 4 @test_throws BoundsError S[3] -@test indices(S) === (Base.OneTo(2),) +@test axes(S) === (Base.OneTo(2),) S = view(A, :, :) @test S == A @test S[0,3] == S[1] == 1 @@ -121,17 +121,17 @@ S = view(A, :, :) @test S[0,4] == S[3] == 3 @test S[1,4] == S[4] == 4 @test_throws BoundsError S[1,1] -@test indices(S) === (0:1, 3:4) +@test axes(S) === (0:1, 3:4) # https://github.com/JuliaArrays/OffsetArrays.jl/issues/27 g = OffsetArray(collect(-2:3), (-3,)) gv = view(g, -1:2) -@test indices(gv, 1) === Base.OneTo(4) +@test axes(gv, 1) === Base.OneTo(4) @test collect(gv) == collect(-1:2) gv = view(g, OffsetArray(-1:2, (-2,))) -@test indices(gv, 1) === -1:2 +@test axes(gv, 1) === -1:2 @test collect(gv) == collect(-1:2) gv = view(g, OffsetArray(-1:2, (-1,))) -@test indices(gv, 1) === 0:3 +@test axes(gv, 1) === 0:3 @test collect(gv) == collect(-1:2) # iteration @@ -201,33 +201,33 @@ PV = view(P, 2:3, :) # Similar B = similar(A, Float32) @test isa(B, OffsetArray{Float32,2}) -@test indices(B) === indices(A) +@test axes(B) === axes(A) B = similar(A, (3,4)) @test isa(B, Array{Int,2}) @test size(B) == (3,4) -@test indices(B) === (Base.OneTo(3), Base.OneTo(4)) +@test axes(B) === (Base.OneTo(3), Base.OneTo(4)) B = similar(A, (-3:3,1:4)) @test isa(B, OffsetArray{Int,2}) -@test indices(B) === (-3:3, 1:4) +@test axes(B) === (-3:3, 1:4) B = similar(parent(A), (-3:3,1:4)) @test isa(B, OffsetArray{Int,2}) -@test indices(B) === (-3:3, 1:4) +@test axes(B) === (-3:3, 1:4) # Indexing with OffsetArray indices i1 = OffsetArray([2,1], (-5,)) i1 = OffsetArray([2,1], -5) b = A0[i1, 1] -@test indices(b) === (-4:-3,) +@test axes(b) === (-4:-3,) @test b[-4] == 2 @test b[-3] == 1 b = A0[1,i1] -@test indices(b) === (-4:-3,) +@test axes(b) === (-4:-3,) @test b[-4] == 3 @test b[-3] == 1 v = view(A0, i1, 1) -@test indices(v) === (-4:-3,) +@test axes(v) === (-4:-3,) v = view(A0, 1:1, i1) -@test indices(v) === (Base.OneTo(1), -4:-3) +@test axes(v) === (Base.OneTo(1), -4:-3) # copy! and fill! a = OffsetArray{Int}(uninitialized, (-3:-1,)) @@ -314,10 +314,10 @@ a = OffsetArray(a0, (-1,2,3,4,5)) v = OffsetArray(v0, (-3,)) @test endof(v) == 1 @test v ≈ v -@test indices(v') === (Base.OneTo(1),-2:1) +@test axes(v') === (Base.OneTo(1),-2:1) @test parent(v) == collect(v) rv = reverse(v) -@test indices(rv) == indices(v) +@test axes(rv) == axes(v) @test rv[1] == v[-2] @test rv[0] == v[-1] @test rv[-1] == v[0] @@ -327,7 +327,7 @@ cv = copy(v) A = OffsetArray(rand(4,4), (-3,5)) @test A ≈ A -@test indices(A') === (6:9, -2:1) +@test axes(A') === (6:9, -2:1) @test parent(A') == parent(A)' @test collect(A) == parent(A) @test maximum(A) == maximum(parent(A)) diff --git a/test/reducedim.jl b/test/reducedim.jl index fbed7da08db6fb..6bbd491db2b873 100644 --- a/test/reducedim.jl +++ b/test/reducedim.jl @@ -20,7 +20,7 @@ for region in Any[ 1, 2, 3, 4, 5, (1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4), (1, 2, 3), (1, 3, 4), (2, 3, 4), (1, 2, 3, 4)] # println("region = $region") - r = fill(NaN, map(length, Base.reduced_indices(indices(Areduc), region))) + r = fill(NaN, map(length, Base.reduced_indices(axes(Areduc), region))) @test sum!(r, Areduc) ≈ safe_sum(Areduc, region) @test prod!(r, Areduc) ≈ safe_prod(Areduc, region) @test maximum!(r, Areduc) ≈ safe_maximum(Areduc, region) @@ -62,7 +62,7 @@ end # Test reduction along first dimension; this is special-cased for # size(A, 1) >= 16 Breduc = rand(64, 3) -r = fill(NaN, map(length, Base.reduced_indices(indices(Breduc), 1))) +r = fill(NaN, map(length, Base.reduced_indices(axes(Breduc), 1))) @test sum!(r, Breduc) ≈ safe_sum(Breduc, 1) @test sum!(abs, r, Breduc) ≈ safe_sumabs(Breduc, 1) @test sum!(abs2, r, Breduc) ≈ safe_sumabs2(Breduc, 1) diff --git a/test/sparse/higherorderfns.jl b/test/sparse/higherorderfns.jl index b8638ad1b2ba6c..e4dd960636ef6d 100644 --- a/test/sparse/higherorderfns.jl +++ b/test/sparse/higherorderfns.jl @@ -120,7 +120,7 @@ end # TODO strengthen this test, avoiding dependence on checking whether # check_broadcast_indices throws to determine whether sparse broadcast should throw try - Base.Broadcast.check_broadcast_indices(indices(Z), spzeros((shapeX .- 1)...)) + Base.Broadcast.check_broadcast_indices(axes(Z), spzeros((shapeX .- 1)...)) catch @test_throws DimensionMismatch broadcast!(sin, Z, spzeros((shapeX .- 1)...)) end @@ -144,7 +144,7 @@ end # TODO strengthen this test, avoiding dependence on checking whether # check_broadcast_indices throws to determine whether sparse broadcast should throw try - Base.Broadcast.check_broadcast_indices(indices(V), spzeros((shapeX .- 1)...)) + Base.Broadcast.check_broadcast_indices(axes(V), spzeros((shapeX .- 1)...)) catch @test_throws DimensionMismatch broadcast!(sin, V, spzeros((shapeX .- 1)...)) end @@ -202,7 +202,7 @@ end # TODO strengthen this test, avoiding dependence on checking whether # check_broadcast_indices throws to determine whether sparse broadcast should throw try - Base.Broadcast.check_broadcast_indices(indices(Z), spzeros((shapeX .- 1)...), Y) + Base.Broadcast.check_broadcast_indices(axes(Z), spzeros((shapeX .- 1)...), Y) catch @test_throws DimensionMismatch broadcast!(f, Z, spzeros((shapeX .- 1)...), Y) end @@ -259,7 +259,7 @@ end # TODO strengthen this test, avoiding dependence on checking whether # check_broadcast_indices throws to determine whether sparse broadcast should throw try - Base.Broadcast.check_broadcast_indices(indices(Q), spzeros((shapeX .- 1)...), Y, Z) + Base.Broadcast.check_broadcast_indices(axes(Q), spzeros((shapeX .- 1)...), Y, Z) catch @test_throws DimensionMismatch broadcast!(f, Q, spzeros((shapeX .- 1)...), Y, Z) end diff --git a/test/subarray.jl b/test/subarray.jl index 27112a6a32a8a7..cf9bf9af8d9199 100644 --- a/test/subarray.jl +++ b/test/subarray.jl @@ -352,7 +352,7 @@ sA = view(A, 2:2, 1:5, :) @test parentindexes(sA) == (2:2, 1:5, Base.Slice(1:8)) @test Base.parentdims(sA) == [1:3;] @test size(sA) == (1, 5, 8) -@test indices(sA) === (Base.OneTo(1), Base.OneTo(5), Base.OneTo(8)) +@test axes(sA) === (Base.OneTo(1), Base.OneTo(5), Base.OneTo(8)) @test sA[1, 2, 1:8][:] == [5:15:120;] sA[2:5:end] = -1 @test all(sA[2:5:end] .== -1) @@ -372,7 +372,7 @@ test_bounds(sA) sA = view(A, 1:3, 3:3, 2:5) @test Base.parentdims(sA) == [1:3;] @test size(sA) == (3,1,4) -@test indices(sA) === (Base.OneTo(3), Base.OneTo(1), Base.OneTo(4)) +@test axes(sA) === (Base.OneTo(3), Base.OneTo(1), Base.OneTo(4)) @test sA == A[1:3,3:3,2:5] @test sA[:] == A[1:3,3,2:5][:] test_bounds(sA) @@ -387,10 +387,10 @@ sA = view(A, 1:2:3, 1:3:5, 1:2:8) test_bounds(sA) sA = view(A, 1:1, 1:5, [1 3; 4 2]) @test ndims(sA) == 4 -@test indices(sA) === (Base.OneTo(1), Base.OneTo(5), Base.OneTo(2), Base.OneTo(2)) +@test axes(sA) === (Base.OneTo(1), Base.OneTo(5), Base.OneTo(2), Base.OneTo(2)) sA = view(A, 1:2, 3, [1 3; 4 2]) @test ndims(sA) == 3 -@test indices(sA) === (Base.OneTo(2), Base.OneTo(2), Base.OneTo(2)) +@test axes(sA) === (Base.OneTo(2), Base.OneTo(2), Base.OneTo(2)) # logical indexing #4763 A = view([1:10;], 5:8) @@ -408,7 +408,7 @@ sA = view(A, 2, :, 1:8) @test parentindexes(sA) == (2, Base.Slice(1:5), 1:8) @test Base.parentdims(sA) == [2:3;] @test size(sA) == (5, 8) -@test indices(sA) === (Base.OneTo(5), Base.OneTo(8)) +@test axes(sA) === (Base.OneTo(5), Base.OneTo(8)) @test strides(sA) == (3,15) @test sA[2, 1:8][:] == [5:15:120;] @test sA[:,1] == [2:3:14;] @@ -420,13 +420,13 @@ test_bounds(sA) sA = view(A, 1:3, 1:5, 5) @test Base.parentdims(sA) == [1:2;] @test size(sA) == (3,5) -@test indices(sA) === (Base.OneTo(3),Base.OneTo(5)) +@test axes(sA) === (Base.OneTo(3),Base.OneTo(5)) @test strides(sA) == (1,3) test_bounds(sA) sA = view(A, 1:2:3, 3, 1:2:8) @test Base.parentdims(sA) == [1,3] @test size(sA) == (2,4) -@test indices(sA) === (Base.OneTo(2), Base.OneTo(4)) +@test axes(sA) === (Base.OneTo(2), Base.OneTo(4)) @test strides(sA) == (2,30) @test sA[:] == A[sA.indexes...][:] test_bounds(sA)