Skip to content

Commit 02634ee

Browse files
timholyKristofferC
authored andcommitted
Use only safe axis types for Broadcast.combine_axes
#30074 used the wrong notion of consistency since `OneTo(1)` is consistent (wrt broadcasting) with any range, but `OneTo` cannot handle `Slice(-1:1)`. (cherry picked from commit 1884cb4)
1 parent 375fc8b commit 02634ee

File tree

2 files changed

+8
-7
lines changed

2 files changed

+8
-7
lines changed

base/broadcast.jl

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -436,19 +436,16 @@ end
436436
_bcs1(a::Integer, b::Integer) = a == 1 ? b : (b == 1 ? a : (a == b ? a : throw(DimensionMismatch("arrays could not be broadcast to a common size"))))
437437
_bcs1(a::Integer, b) = a == 1 ? b : (first(b) == 1 && last(b) == a ? b : throw(DimensionMismatch("arrays could not be broadcast to a common size")))
438438
_bcs1(a, b::Integer) = _bcs1(b, a)
439-
_bcs1(a, b) = _bcsm(b, a) ? _sametype(b, a) : (_bcsm(a, b) ? _sametype(a, b) : throw(DimensionMismatch("arrays could not be broadcast to a common size")))
439+
_bcs1(a, b) = _bcsm(b, a) ? axistype(b, a) : (_bcsm(a, b) ? axistype(a, b) : throw(DimensionMismatch("arrays could not be broadcast to a common size")))
440440
# _bcsm tests whether the second index is consistent with the first
441441
_bcsm(a, b) = a == b || length(b) == 1
442442
_bcsm(a, b::Number) = b == 1
443443
_bcsm(a::Number, b::Number) = a == b || b == 1
444444
# Ensure inferrability when dealing with axes of different AbstractUnitRange types
445445
# (We may not want to define general promotion rules between, say, OneTo and Slice, but if
446-
# we get here we know the axes are at least consistent)
447-
_sametype(a::T, b::T) where T = a
448-
_sametype(a::OneTo, b::OneTo) = OneTo{Int}(a)
449-
_sametype(a::OneTo, b) = OneTo{Int}(a)
450-
_sametype(a, b::OneTo) = OneTo{Int}(a)
451-
_sametype(a, b) = UnitRange{Int}(a)
446+
# we get here we know the axes are at least consistent for the purposes of broadcasting)
447+
axistype(a::T, b::T) where T = a
448+
axistype(a, b) = UnitRange{Int}(a)
452449

453450
## Check that all arguments are broadcast compatible with shape
454451
# comparing one input against a shape

test/offsetarray.jl

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -472,6 +472,10 @@ A = OffsetArray(view(rand(4,4), 1:4, 4:-1:1), (-3,5))
472472
a = [1]
473473
b = OffsetArray(a, (0,))
474474
@test @inferred(a .+ b) == [2]
475+
a = OffsetArray([1, -2, 1], (-2,))
476+
@test a .* a' == OffsetArray([ 1 -2 1;
477+
-2 4 -2;
478+
1 -2 1], (-2,-2))
475479

476480
end # let
477481

0 commit comments

Comments
 (0)