Skip to content

Commit

Permalink
checker: disallow Optional and Result high val in a `for x in lo…
Browse files Browse the repository at this point in the history
…w..high {` loop (#21043)
  • Loading branch information
Delta456 authored Mar 16, 2024
1 parent a1c6377 commit 549654a
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 0 deletions.
3 changes: 3 additions & 0 deletions vlib/v/checker/for.v
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,9 @@ fn (mut c Checker) for_in_stmt(mut node ast.ForInStmt) {
node.cond.pos().extend(node.high.pos()))
} else if typ_idx !in ast.integer_type_idxs {
c.error('range type can only be an integer type', node.cond.pos().extend(node.high.pos()))
} else if high_type.has_option_or_result() {
c.error('the `high` value in a `for x in low..high {` loop, cannot be Result or Option',
node.high.pos())
}
if high_type in [ast.int_type, ast.int_literal_type] {
node.val_type = typ
Expand Down
14 changes: 14 additions & 0 deletions vlib/v/checker/tests/for_in_range_result_optional_err.out
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
vlib/v/checker/tests/for_in_range_result_optional_err.vv:11:23: error: the `high` value in a `for x in low..high {` loop, cannot be Result or Option
9 | fn main() {
10 | arr := [1, 2, 3, 4, 5, 6, 7, 8, 9]
11 | for _ in 0 .. arrays.idx_min(arr) {
| ~~~~~~~~~~~~
12 | }
13 |
vlib/v/checker/tests/for_in_range_result_optional_err.vv:14:16: error: the `high` value in a `for x in low..high {` loop, cannot be Result or Option
12 | }
13 |
14 | for _ in 0 .. foo() {
| ~~~~~
15 | }
16 | }
16 changes: 16 additions & 0 deletions vlib/v/checker/tests/for_in_range_result_optional_err.vv
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
module main

import arrays

fn foo() ?int {
return 12
}

fn main() {
arr := [1, 2, 3, 4, 5, 6, 7, 8, 9]
for _ in 0 .. arrays.idx_min(arr) {
}

for _ in 0 .. foo() {
}
}

0 comments on commit 549654a

Please sign in to comment.