Skip to content

relax dispatch for the IteratorSize method for Generator #58110

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

Merged
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
2 changes: 1 addition & 1 deletion base/generator.jl
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ IteratorSize(::Type{Any}) = SizeUnknown()

IteratorSize(::Type{<:Tuple}) = HasLength()
IteratorSize(::Type{<:AbstractArray{<:Any,N}}) where {N} = HasShape{N}()
IteratorSize(::Type{Generator{I,F}}) where {I,F} = IteratorSize(I)
IteratorSize(::Type{<:Generator{I}}) where {I} = (@isdefined I) ? IteratorSize(I) : SizeUnknown()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Apologies for the dumb question, but in which scenario would @isdefined I return false ?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The bottom type does it:

julia> struct S{P} end
 
julia> f(::Type{<:S}) = "fallback"
f (generic function with 1 method)
 
julia> f(::Type{<:S{P}}) where {P} = (@isdefined P) ? "is defined" : "is not defined"
f (generic function with 2 methods)
 
julia> f(Union{})
"is not defined"

@isdefined is often used like that in eltype method definitions.


haslength(iter) = IteratorSize(iter) isa Union{HasShape, HasLength}

Expand Down
6 changes: 6 additions & 0 deletions test/iterators.jl
Original file line number Diff line number Diff line change
Expand Up @@ -988,6 +988,12 @@ end
@test accumulate(+, (x^2 for x in 1:3); init=100) == [101, 105, 114]
end

@testset "issue #58109" begin
i = Iterators.map(identity, 3)
j = Iterators.map(sqrt, 7)
@test (@inferred Base.IteratorSize(i)) === @inferred Base.IteratorSize(eltype([i, j]))
end

@testset "IteratorSize trait for zip" begin
@test (@inferred Base.IteratorSize(zip())) == Base.IsInfinite() # for zip of empty tuple
@test (@inferred Base.IteratorSize(zip((1,2,3), repeated(0)))) == Base.HasLength() # for zip of ::HasLength and ::IsInfinite
Expand Down