rafaqz / DimensionalData.jl

Named dimensions and indexing for julia arrays and other data
https://rafaqz.github.io/DimensionalData.jl/stable/
MIT License
282 stars 42 forks source link

Type piracy on `similar` with `Union`s #857

Open kapple19 opened 6 days ago

kapple19 commented 6 days ago

During development of #852, a new method defined as

function DimArray(gen::Base.Generator, argdims=nothing; dims=nothing, kw...) 
    A = collect(gen)
    ds = isnothing(dims) ? argdims : dims
    if isnothing(ds)
        A isa DimArray || throw(ArgumentError("No dims. Use Dimensions wrappers in the generator or pass `dims` as a keyword or second argument."))
        rebuild(A; kw...)
    else
        rebuild(A; dims=ds, kw...)
    end
end

triggers the following error

ERROR: MethodError: similar(::Type{Matrix{Int64}}, ::Tuple{Base.OneTo{Int64}, Base.OneTo{Int64}}) is ambiguous.

when the following generator example (which has no DimArray involvement) is run

(x + y for x in 1:5, y in 1:3)

Full error message:

ERROR: MethodError: similar(::Type{Matrix{Int64}}, ::Tuple{Base.OneTo{Int64}, Base.OneTo{Int64}}) is ambiguous.

Candidates:
  similar(T::Type{<:AbstractArray}, shape::Tuple{Union{Integer, Base.OneTo, DimensionalData.Dimensions.DimUnitRange}, Union{Integer, Base.OneTo, DimensionalData.Dimensions.DimUnitRange}, Vararg{Union{Integer, Base.OneTo, DimensionalData.Dimensions.DimUnitRange}}}; kw...)
    @ DimensionalData C:\Users\Aaron\.julia\dev\DimensionalData\src\array\array.jl:208
  similar(::Type{T}, shape::Tuple{Union{Integer, Base.OneTo}, Vararg{Union{Integer, Base.OneTo}}}) where T<:AbstractArray
    @ Base abstractarray.jl:867

Possible fix, define
  similar(::Type{T}, ::Tuple{Union{…}, Union{…}, Vararg{…}}) where T<:AbstractArray

Stacktrace:
 [1] _similar(::Type{…}, shape::Tuple{…}; kw::@Kwargs{})
   @ DimensionalData C:\Users\Aaron\.julia\dev\DimensionalData\src\array\array.jl:252
 [2] _similar(::Type{…}, shape::Tuple{…})
   @ DimensionalData C:\Users\Aaron\.julia\dev\DimensionalData\src\array\array.jl:251
 [3] similar(T::Type{…}, shape::Tuple{…}; kw::@Kwargs{})
   @ DimensionalData C:\Users\Aaron\.julia\dev\DimensionalData\src\array\array.jl:211
 [4] similar(T::Type{…}, shape::Tuple{…})
   @ DimensionalData C:\Users\Aaron\.julia\dev\DimensionalData\src\array\array.jl:208
 [5] _array_for(::Type{…}, ::Base.HasShape{…}, axs::Tuple{…})
   @ Base .\array.jl:665
 [6] collect(itr::Base.Generator{Base.Iterators.ProductIterator{Tuple{Dim{…}, Dim{…}}}, var"#15#16"})
   @ Base .\array.jl:0
 [7] DimArray(gen::Base.Generator{Base.Iterators.ProductIterator{Tuple{…}}, var"#15#16"}; dims::Nothing, kw::@Kwargs{})
   @ DimensionalData C:\Users\Aaron\.julia\dev\DimensionalData\src\array\array.jl:492
 [8] DimArray(gen::Base.Generator{Base.Iterators.ProductIterator{Tuple{Dim{…}, Dim{…}}}, var"#15#16"})
   @ DimensionalData C:\Users\Aaron\.julia\dev\DimensionalData\src\array\array.jl:491
 [9] top-level scope
   @ REPL[5]:1