Skip to content

Commit 47c06fc

Browse files
authored
Add type-assertions to length to help with inference (#958)
* Add type-assertion to length * Add assertion to method with types * Add tests
1 parent f59bceb commit 47c06fc

File tree

2 files changed

+16
-6
lines changed

2 files changed

+16
-6
lines changed

src/abstractarray.jl

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
length(a::StaticArrayLike) = prod(Size(a))
2-
length(a::Type{SA}) where {SA <: StaticArrayLike} = prod(Size(SA))
1+
length(a::StaticArrayLike) = prod(Size(a))::Int
2+
length(a::Type{SA}) where {SA <: StaticArrayLike} = prod(Size(SA))::Int
33

44
@pure size(::Type{SA}) where {SA <: StaticArrayLike} = Tuple(Size(SA))
55
@inline function size(t::Type{<:StaticArrayLike}, d::Int)

test/abstractarray.jl

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -203,7 +203,7 @@ using StaticArrays, Test, LinearAlgebra
203203
@test @inferred(convert(AbstractArray{Float64}, diag)) isa Diagonal{Float64,SVector{2,Float64}}
204204
@test convert(AbstractArray{Float64}, diag) == diag
205205
# The following cases currently convert the SMatrix into an MMatrix, because
206-
# the constructor in Base invokes `similar`, rather than `convert`, on the static
206+
# the constructor in Base invokes `similar`, rather than `convert`, on the static
207207
# array. This was fixed in https://github.com/JuliaLang/julia/pull/40831; so should
208208
# work from Julia v1.8.0-DEV.55
209209
trans = Transpose(SVector(1,2))
@@ -219,6 +219,16 @@ using StaticArrays, Test, LinearAlgebra
219219
unitlotri = UnitLowerTriangular(SA[1 0; 2 1])
220220
@test_was_once_broken v"1.8.0-DEV.55" @inferred(convert(AbstractArray{Float64}, unitlotri)) isa UnitLowerTriangular{Float64,SMatrix{2,2,Float64,4}}
221221
end
222+
223+
@testset "type inference in length" begin
224+
s1 = SA[1,2];
225+
s2 = SA[1,2,3];
226+
v = [s1, s2];
227+
f(v, i) = length(v[i]);
228+
for i in 1:2
229+
@test (@inferred f(v, i)) == length(v[i])
230+
end
231+
end
222232
end
223233

224234
@testset "permutedims" begin
@@ -318,7 +328,7 @@ end
318328
@test Base.rest(x) == x
319329
a, b... = x
320330
@test b == SA[2, 3]
321-
331+
322332
x = SA[1 2; 3 4]
323333
@test Base.rest(x) == vec(x)
324334
a, b... = x
@@ -327,14 +337,14 @@ end
327337
a, b... = SA[1]
328338
@test b == []
329339
@test b isa SVector{0}
330-
340+
331341
for (Vec, Mat) in [(MVector, MMatrix), (SizedVector, SizedMatrix)]
332342
x = Vec(1, 2, 3)
333343
@test Base.rest(x) == x
334344
@test pointer(Base.rest(x)) != pointer(x)
335345
a, b... = x
336346
@test b == Vec(2, 3)
337-
347+
338348
x = Mat{2,2}(1, 2, 3, 4)
339349
@test Base.rest(x) == vec(x)
340350
@test pointer(Base.rest(x)) != pointer(x)

0 commit comments

Comments
 (0)