StaticArrays.jl icon indicating copy to clipboard operation
StaticArrays.jl copied to clipboard

Failure to reinterpret SMatrix

Open kbarros opened this issue 2 years ago • 5 comments

Is this expected behavior? Tested on [email protected].

using StaticArrays

# This gives a surprising error:
A = zeros(SMatrix{3,3,Float64}, 2, 3)
reinterpret(reshape, Float64, A) # ERROR: ArgumentError: cannot reinterpret `SMatrix{3, 3, Float64}` as `Float64`, type `SMatrix{3, 3, Float64}` is not a bits type

# However, it seems like `SMatrix{3, 3, Float64}` is indeed `isbits`
@assert isbits(A[1,1])

# And reinterpreting an `SVector` is fine
B = zeros(SVector{3,Float64}, 4)
reinterpret(reshape, Float64, B)

kbarros avatar Sep 22 '23 14:09 kbarros

It works if you provide all arguments to SMatrix (which is strongly suggested):

A = zeros(SMatrix{3,3,Float64,9}, 2, 3)

Note that without ,9:

julia> isbitstype(eltype(A))
false

mateuszbaran avatar Sep 22 '23 14:09 mateuszbaran

Thanks! I agree this is user error, feel free to close the issue.

I wonder, however, if there is some way to print a more informative error message? Something along the lines of "missing 4th type parameter".

kbarros avatar Sep 22 '23 14:09 kbarros

I guess we could use Base.Experimental.register_error_hint but I'm not sure if that's the right thing to do. This error, actually, is far from the worst errors that I've seen and I haven't seen that much usage of register_error_hint across the ecosystem.

mateuszbaran avatar Sep 22 '23 14:09 mateuszbaran

Thanks. Is there a valid use case for SMatrix{3,3,Float64} without the final fourth type parameter? If not, perhaps Julia could error if an object with such a type is being constructed? Besides this, I have no further comments.

kbarros avatar Sep 22 '23 15:09 kbarros

You can use the three-parameter variant for constructing SMatrix objects, and the fourth one will be automatically added:

julia> SMatrix{2,2,Float64}(1, 2, 3, 4)
2×2 SMatrix{2, 2, Float64, 4} with indices SOneTo(2)×SOneTo(2):
 1.0  3.0
 2.0  4.0

Here we have an issue of zeros not trying to narrow down given eltype, but that's somewhat intentional (it's useful in different situations).

mateuszbaran avatar Sep 22 '23 15:09 mateuszbaran