Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 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
24 changes: 11 additions & 13 deletions base/broadcast.jl
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,17 @@ Base.LinearIndices(bc::Broadcasted{<:Any,<:Tuple{Any}}) = LinearIndices(axes(bc)

Base.ndims(bc::Broadcasted) = ndims(typeof(bc))
Base.ndims(::Type{<:Broadcasted{<:Any,<:NTuple{N,Any}}}) where {N} = N
Base.ndims(BC::Type{<:Broadcasted{<:Any,Nothing}}) = _maxndims(fieldtype(BC, 2))
function Base.ndims(BC::Type{<:Broadcasted{<:AbstractArrayStyle{N},Nothing}}) where {N}
N isa Int ? N : _maxndims(fieldtype(BC, 2))
end

_maxndims(::Type{Tuple{}}) = 0
_maxndims(::Type{Tuple{T}}) where {T} = T <: Tuple ? 1 : Int(ndims(T))::Int
function _maxndims(Args::Type{<:Tuple{T,Vararg{Any}}}) where {T}
Argstail = Tuple{ntuple(i -> fieldtype(Args, i + 1), fieldcount(Args) - 1)...}
max(_maxndims(Tuple{T}), _maxndims(Argstail))
end

Base.size(bc::Broadcasted) = map(length, axes(bc))
Base.length(bc::Broadcasted) = prod(size(bc))
Expand All @@ -262,19 +273,6 @@ Base.@propagate_inbounds function Base.iterate(bc::Broadcasted, s)
end

Base.IteratorSize(::Type{T}) where {T<:Broadcasted} = Base.HasShape{ndims(T)}()
Base.ndims(BC::Type{<:Broadcasted{<:Any,Nothing}}) = _maxndims(fieldtype(BC, 2))
Base.ndims(::Type{<:Broadcasted{<:AbstractArrayStyle{N},Nothing}}) where {N<:Integer} = N

_maxndims(T::Type{<:Tuple}) = reduce(max, (ntuple(n -> _ndims(fieldtype(T, n)), Base._counttuple(T))))
_maxndims(::Type{<:Tuple{T}}) where {T} = ndims(T)
_maxndims(::Type{<:Tuple{T}}) where {T<:Tuple} = _ndims(T)
function _maxndims(::Type{<:Tuple{T, S}}) where {T, S}
return T<:Tuple || S<:Tuple ? max(_ndims(T), _ndims(S)) : max(ndims(T), ndims(S))
end

_ndims(x) = ndims(x)
_ndims(::Type{<:Tuple}) = 1

Base.IteratorEltype(::Type{<:Broadcasted}) = Base.EltypeUnknown()

## Instantiation fills in the "missing" fields in Broadcasted.
Expand Down
11 changes: 7 additions & 4 deletions test/broadcast.jl
Original file line number Diff line number Diff line change
Expand Up @@ -882,11 +882,14 @@ let

@test @inferred(Base.IteratorSize(Broadcast.broadcasted((1,2,3),a1,zeros(3,3,3)))) === Base.HasShape{3}()

@test @inferred(Base.IteratorSize(Base.broadcasted(randn))) === Base.HasShape{0}()

# inference on nested
bc = Base.broadcasted(+, AD1(randn(3)), AD1(randn(3)))
bc_nest = Base.broadcasted(+, bc , bc)
@test @inferred(Base.IteratorSize(bc_nest)) === Base.HasShape{1}()
end
bc = Base.broadcasted(+, AD1(randn(3)), AD1(randn(3)), AD1(randn(3)))
bc_nest = Base.broadcasted(*, bc, bc, bc, bc, AD1(randn(3)))
bc_nest2 = Base.broadcasted(-, bc_nest, bc_nest)
@test @inferred(Base.IteratorSize(bc_nest2)) === Base.HasShape{1}()
end

# issue #31295
let a = rand(5), b = rand(5), c = copy(a)
Expand Down