Skip to content

Commit b5c4e63

Browse files
authored
fix #33020, check axes for broadcasted assignment from tuples (#33080)
We avoid computing axes for tuples -- which is a valuable optimization -- but when we explicitly construct a tuple broadcast with axes pre-set (for, e.g., broadcasted assignment), we need to check that those axes are compatible with the ones inside the broadcasted expression before accepting them.
1 parent 9725fb4 commit b5c4e63

File tree

2 files changed

+26
-2
lines changed

2 files changed

+26
-2
lines changed

base/broadcast.jl

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -260,8 +260,13 @@ of the `Broadcasted` object empty (populated with [`nothing`](@ref)).
260260
end
261261
return Broadcasted{Style}(bc.f, bc.args, axes)
262262
end
263-
instantiate(bc::Broadcasted{<:Union{AbstractArrayStyle{0}, Style{Tuple}}}) = bc
264-
263+
instantiate(bc::Broadcasted{<:AbstractArrayStyle{0}}) = bc
264+
# Tuples don't need axes, but when they have axes (for .= assignment), we need to check them (#33020)
265+
instantiate(bc::Broadcasted{Style{Tuple}, Nothing}) = bc
266+
function instantiate(bc::Broadcasted{Style{Tuple}})
267+
check_broadcast_axes(bc.axes, bc.args...)
268+
return bc
269+
end
265270
## Flattening
266271

267272
"""

test/broadcast.jl

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -663,6 +663,25 @@ end
663663
@test_throws DimensionMismatch (1, 2) .+ (1, 2, 3)
664664
end
665665

666+
@testset "broadcasted assignment from tuples and tuple styles (#33020)" begin
667+
a = zeros(3)
668+
@test_throws DimensionMismatch a .= (1,2)
669+
@test_throws DimensionMismatch a .= sqrt.((1,2))
670+
a .= (1,)
671+
@test all(==(1), a)
672+
a .= sqrt.((2,))
673+
@test all(==(2), a)
674+
a = zeros(3, 2)
675+
@test_throws DimensionMismatch a .= (1,2)
676+
@test_throws DimensionMismatch a .= sqrt.((1,2))
677+
a .= (1,)
678+
@test all(==(1), a)
679+
a .= sqrt.((2,))
680+
@test all(==(2), a)
681+
a .= (1,2,3)
682+
@test a == [1 1; 2 2; 3 3]
683+
end
684+
666685
@testset "scalar .=" begin
667686
A = [[1,2,3],4:5,6]
668687
A[1] .= 0

0 commit comments

Comments
 (0)