Skip to content

Commit

Permalink
Replace some occurrences of iteration over 1:length with more idiomat…
Browse files Browse the repository at this point in the history
…ic structures (mostly eachindex) (#55137)

Base should be a model for the ecosystem, and `eachindex(x)` is better
than `1:length(x)` in almost all cases. I've updated many, but certainly
not all examples. This is mostly a NFC, but also fixes #55136.
  • Loading branch information
LilithHafner authored Jul 16, 2024
1 parent 742e7d9 commit 0945b9d
Show file tree
Hide file tree
Showing 9 changed files with 25 additions and 26 deletions.
8 changes: 4 additions & 4 deletions base/abstractarray.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1659,10 +1659,10 @@ typed_vcat(::Type{T}) where {T} = Vector{T}()
typed_hcat(::Type{T}) where {T} = Vector{T}()

## cat: special cases
vcat(X::T...) where {T} = T[ X[i] for i=1:length(X) ]
vcat(X::T...) where {T<:Number} = T[ X[i] for i=1:length(X) ]
hcat(X::T...) where {T} = T[ X[j] for i=1:1, j=1:length(X) ]
hcat(X::T...) where {T<:Number} = T[ X[j] for i=1:1, j=1:length(X) ]
vcat(X::T...) where {T} = T[ X[i] for i=eachindex(X) ]
vcat(X::T...) where {T<:Number} = T[ X[i] for i=eachindex(X) ]
hcat(X::T...) where {T} = T[ X[j] for i=1:1, j=eachindex(X) ]
hcat(X::T...) where {T<:Number} = T[ X[j] for i=1:1, j=eachindex(X) ]

vcat(X::Number...) = hvcat_fill!(Vector{promote_typeof(X...)}(undef, length(X)), X)
hcat(X::Number...) = hvcat_fill!(Matrix{promote_typeof(X...)}(undef, 1,length(X)), X)
Expand Down
10 changes: 5 additions & 5 deletions base/errorshow.jl
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ function showerror(io::IO, ex::CanonicalIndexError)
print(io, "CanonicalIndexError: ", ex.func, " not defined for ", ex.type)
end

typesof(@nospecialize args...) = Tuple{Any[ Core.Typeof(args[i]) for i in 1:length(args) ]...}
typesof(@nospecialize args...) = Tuple{Any[Core.Typeof(arg) for arg in args]...}

function print_with_compare(io::IO, @nospecialize(a::DataType), @nospecialize(b::DataType), color::Symbol)
if a.name === b.name
Expand Down Expand Up @@ -273,7 +273,7 @@ function showerror(io::IO, ex::MethodError)
arg_types_param = arg_types_param[3:end]
san_arg_types_param = san_arg_types_param[3:end]
keys = kwt.parameters[1]::Tuple
kwargs = Any[(keys[i], fieldtype(kwt, i)) for i in 1:length(keys)]
kwargs = Any[(keys[i], fieldtype(kwt, i)) for i in eachindex(keys)]
arg_types = rewrap_unionall(Tuple{arg_types_param...}, arg_types)
end
if f === Base.convert && length(arg_types_param) == 2 && !is_arg_types
Expand Down Expand Up @@ -694,7 +694,7 @@ function show_reduced_backtrace(io::IO, t::Vector)

push!(repeated_cycle, (0,0,0)) # repeated_cycle is never empty
frame_counter = 1
for i in 1:length(displayed_stackframes)
for i in eachindex(displayed_stackframes)
(frame, n) = displayed_stackframes[i]

print_stackframe(io, frame_counter, frame, n, ndigits_max, STACKTRACE_FIXEDCOLORS, STACKTRACE_MODULECOLORS)
Expand Down Expand Up @@ -871,7 +871,7 @@ end
function _collapse_repeated_frames(trace)
kept_frames = trues(length(trace))
last_frame = nothing
for i in 1:length(trace)
for i in eachindex(trace)
frame::StackFrame, _ = trace[i]
if last_frame !== nothing && frame.file == last_frame.file && frame.line == last_frame.line
#=
Expand Down Expand Up @@ -916,7 +916,7 @@ function _collapse_repeated_frames(trace)
end
if length(last_params) > length(params)
issame = true
for i = 1:length(params)
for i = eachindex(params)
issame &= params[i] == last_params[i]
end
if issame
Expand Down
2 changes: 1 addition & 1 deletion base/expr.jl
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ function copy_exprs(@nospecialize(x))
end
return x
end
copy_exprargs(x::Array{Any,1}) = Any[copy_exprs(@inbounds x[i]) for i in 1:length(x)]
copy_exprargs(x::Array{Any,1}) = Any[copy_exprs(@inbounds x[i]) for i in eachindex(x)]

@eval exprarray(head::Symbol, arg::Array{Any,1}) = $(Expr(:new, :Expr, :head, :arg))

Expand Down
2 changes: 1 addition & 1 deletion base/intfuncs.jl
Original file line number Diff line number Diff line change
Expand Up @@ -978,7 +978,7 @@ end
Return an array with element type `T` (default `Int`) of the digits of `n` in the given
base, optionally padded with zeros to a specified size. More significant digits are at
higher indices, such that `n == sum(digits[k]*base^(k-1) for k=1:length(digits))`.
higher indices, such that `n == sum(digits[k]*base^(k-1) for k in eachindex(digits))`.
See also [`ndigits`](@ref), [`digits!`](@ref),
and for base 2 also [`bitstring`](@ref), [`count_ones`](@ref).
Expand Down
9 changes: 4 additions & 5 deletions base/loading.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1214,7 +1214,7 @@ function _include_from_serialized(pkg::PkgId, path::String, ocachepath::Union{No
t_comp_before = cumulative_compile_time_ns()
end

for i in 1:length(depmods)
for i in eachindex(depmods)
dep = depmods[i]
dep isa Module && continue
_, depkey, depbuild_id = dep::Tuple{String, PkgId, UInt128}
Expand Down Expand Up @@ -1706,8 +1706,7 @@ function compilecache_path(pkg::PkgId;
end
staledeps, _, _ = staledeps::Tuple{Vector{Any}, Union{Nothing, String}, UInt128}
# finish checking staledeps module graph
for i in 1:length(staledeps)
dep = staledeps[i]
for dep in staledeps
dep isa Module && continue
modpath, modkey, modbuild_id = dep::Tuple{String, PkgId, UInt128}
modpaths = find_all_in_cache_path(modkey)
Expand Down Expand Up @@ -1897,7 +1896,7 @@ end
try
staledeps, ocachefile, newbuild_id = staledeps::Tuple{Vector{Any}, Union{Nothing, String}, UInt128}
# finish checking staledeps module graph
for i in 1:length(staledeps)
for i in eachindex(staledeps)
dep = staledeps[i]
dep isa Module && continue
modpath, modkey, modbuild_id = dep::Tuple{String, PkgId, UInt128}
Expand Down Expand Up @@ -1929,7 +1928,7 @@ end
end
# finish loading module graph into staledeps
# TODO: call all start_loading calls (in reverse order) before calling any _include_from_serialized, since start_loading will drop the loading lock
for i in 1:length(staledeps)
for i in eachindex(staledeps)
dep = staledeps[i]
dep isa Module && continue
modpath, modkey, modbuild_id, modcachepath, modstaledeps, modocachepath = dep::Tuple{String, PkgId, UInt128, String, Vector{Any}, Union{Nothing, String}}
Expand Down
2 changes: 1 addition & 1 deletion base/multidimensional.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1674,7 +1674,7 @@ function checkdims_perm(P::AbstractArray{TP,N}, B::AbstractArray{TB,N}, perm) wh
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 = axes(P)
for i = 1:length(perm)
for i in eachindex(perm)
indsP[i] == indsB[perm[i]] || throw(DimensionMismatch("destination tensor of incorrect size"))
end
nothing
Expand Down
2 changes: 1 addition & 1 deletion base/reflection.jl
Original file line number Diff line number Diff line change
Expand Up @@ -2425,7 +2425,7 @@ function hasmethod(f, t, kwnames::Tuple{Vararg{Symbol}}; world::UInt=get_world_c
for kw in kws
endswith(String(kw), "...") && return true
end
kwnames = Symbol[kwnames[i] for i in 1:length(kwnames)]
kwnames = collect(kwnames)
return issubset(kwnames, kws)
end

Expand Down
10 changes: 5 additions & 5 deletions base/show.jl
Original file line number Diff line number Diff line change
Expand Up @@ -681,7 +681,7 @@ function show_can_elide(p::TypeVar, wheres::Vector, elide::Int, env::SimpleVecto
has_typevar(v.lb, p) && return false
has_typevar(v.ub, p) && return false
end
for i = 1:length(env)
for i = eachindex(env)
i == skip && continue
has_typevar(env[i], p) && return false
end
Expand Down Expand Up @@ -1188,7 +1188,7 @@ end

function show_at_namedtuple(io::IO, syms::Tuple, types::DataType)
first = true
for i in 1:length(syms)
for i in eachindex(syms)
if !first
print(io, ", ")
end
Expand Down Expand Up @@ -2382,7 +2382,7 @@ function show_unquoted(io::IO, ex::Expr, indent::Int, prec::Int, quote_level::In
if get(io, beginsym, false)
print(io, '(')
ind = indent + indent_width
for i = 1:length(ex.args)
for i = eachindex(ex.args)
if i > 1
# if there was only a comment before the first semicolon, the expression would get parsed as a NamedTuple
if !(i == 2 && ex.args[1] isa LineNumberNode)
Expand Down Expand Up @@ -2904,7 +2904,7 @@ function dump(io::IOContext, x::SimpleVector, n::Int, indent)
end
print(io, "SimpleVector")
if n > 0
for i = 1:length(x)
for i in eachindex(x)
println(io)
print(io, indent, " ", i, ": ")
if isassigned(x,i)
Expand Down Expand Up @@ -3021,7 +3021,7 @@ function dump(io::IOContext, x::DataType, n::Int, indent)
end
fields = fieldnames(x)
fieldtypes = datatype_fieldtypes(x)
for idx in 1:length(fields)
for idx in eachindex(fields)
println(io)
print(io, indent, " ")
is_mut && isconst(x, idx) && print(io, "const ")
Expand Down
6 changes: 3 additions & 3 deletions base/tuple.jl
Original file line number Diff line number Diff line change
Expand Up @@ -503,7 +503,7 @@ end
_findfirst_rec(f, i::Int, ::Tuple{}) = nothing
_findfirst_rec(f, i::Int, t::Tuple) = (@inline; f(first(t)) ? i : _findfirst_rec(f, i+1, tail(t)))
function _findfirst_loop(f::Function, t)
for i in 1:length(t)
for i in eachindex(t)
f(t[i]) && return i
end
return nothing
Expand Down Expand Up @@ -537,7 +537,7 @@ function _isequal(t1::Tuple{Any,Vararg{Any}}, t2::Tuple{Any,Vararg{Any}})
return isequal(t1[1], t2[1]) && _isequal(tail(t1), tail(t2))
end
function _isequal(t1::Any32, t2::Any32)
for i = 1:length(t1)
for i in eachindex(t1, t2)
if !isequal(t1[i], t2[i])
return false
end
Expand Down Expand Up @@ -568,7 +568,7 @@ function _eq_missing(t1::Tuple, t2::Tuple)
end
function _eq(t1::Any32, t2::Any32)
anymissing = false
for i = 1:length(t1)
for i in eachindex(t1, t2)
eq = (t1[i] == t2[i])
if ismissing(eq)
anymissing = true
Expand Down

0 comments on commit 0945b9d

Please sign in to comment.