Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make (1:3:4)[6148914691236517207] throw #50118

Merged
merged 2 commits into from
Jul 7, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 10 additions & 6 deletions base/range.jl
Original file line number Diff line number Diff line change
Expand Up @@ -934,12 +934,16 @@ end
function getindex(v::AbstractRange{T}, i::Integer) where T
@inline
i isa Bool && throw(ArgumentError("invalid index: $i of type Bool"))
ret = convert(T, first(v) + (i - oneunit(i))*step_hp(v))
ok = ifelse(step(v) > zero(step(v)),
(ret <= last(v)) & (ret >= first(v)),
(ret <= first(v)) & (ret >= last(v)))
@boundscheck ((i > 0) & ok) || throw_boundserror(v, i)
ret
@boundscheck checkbounds(v, i)
convert(T, first(v) + (i - oneunit(i))*step_hp(v))
end

let BitInteger64 = Union{Int8,Int16,Int32,Int64,UInt8,UInt16,UInt32,UInt64} # for bootstrapping
function checkbounds(::Type{Bool}, v::StepRange{<:BitInteger64, <:BitInteger64}, i::BitInteger64)
@inline
res = widemul(step(v), i-oneunit(i)) + first(v)
(0 < i) & ifelse(0 < step(v), res <= last(v), res >= last(v))
end
end

function getindex(r::Union{StepRangeLen,LinRange}, i::Integer)
Expand Down
8 changes: 8 additions & 0 deletions test/ranges.jl
Original file line number Diff line number Diff line change
Expand Up @@ -2487,3 +2487,11 @@ function check_ranges(rx, ry)
end
@test Core.Compiler.is_foldable(Base.infer_effects(check_ranges, (UnitRange{Int},UnitRange{Int})))
# TODO JET.@test_opt check_ranges(1:2, 3:4)

@testset "checkbounds overflow (#26623)" begin
# the reported issue:
@test_throws BoundsError (1:3:4)[typemax(Int)÷3*2+3]

# a case that using mul_with_overflow & add_with_overflow might get wrong:
@test (-10:2:typemax(Int))[typemax(Int)÷2+2] == typemax(Int)-9
end