Skip to content

Commit bf019ca

Browse files
committed
Add helpful error message when users specify loops of invalid type.
1 parent 3b8b1df commit bf019ca

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

src/modeling/graphs.jl

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -894,6 +894,26 @@ end
894894
@inline canonicalize_range(r::CartesianIndices) = CartesianIndices(map(canonicalize_range, r.indices))
895895
@inline canonicalize_range(r::Base.OneTo{U}) where {U <: Unsigned} = One():last(r)
896896

897+
function canonicalize_range(x)
898+
throw(ArgumentError("""
899+
`@turbo` only supports loops iterating over ranges, and not objects of type `$(typeof(x))`.
900+
It is recommended to instead iterate over `eachindex(...)` and then index the object in the loop.
901+
For example, rewrite
902+
```julia
903+
@turbo for xᵢ in x
904+
...
905+
end
906+
```
907+
as
908+
```julia
909+
@turbo for i in eachindex(x)
910+
xᵢ = x[i]
911+
...
912+
end
913+
```
914+
"""))
915+
end
916+
897917
function misc_loop!(ls::LoopSet, r::Union{Expr,Symbol}, itersym::Symbol, staticstepone::Bool)::Loop
898918
rangename = gensym!(ls, "looprange" * string(itersym)); lenname = gensym!(ls, "looplen" * string(itersym));
899919
pushprepreamble!(ls, Expr(:(=), rangename, Expr(:call, lv(:canonicalize_range), :(@inbounds $(static_literals!(r))))))

test/miscellaneous.jl

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1419,6 +1419,15 @@ end
14191419
@test issue_257!(A0,G) issue_257_avx!(A1,G)
14201420
end
14211421

1422+
function sum_range(x)
1423+
s = zero(eltype(x))
1424+
@turbo for xᵢ x
1425+
s += xᵢ
1426+
end
1427+
s
1428+
end
1429+
@test sum_range(-3:8) == sum(-3:8)
1430+
@test_throws ArgumentError sum_range(Int[1,2])
14221431
end
14231432

14241433

0 commit comments

Comments
 (0)