From 549654aece7c549138180b110f1f0506231592a3 Mon Sep 17 00:00:00 2001 From: Swastik Baranwal Date: Sat, 16 Mar 2024 22:27:30 +0530 Subject: [PATCH] checker: disallow `Optional` and `Result` high val in a `for x in low..high {` loop (#21043) --- vlib/v/checker/for.v | 3 +++ .../tests/for_in_range_result_optional_err.out | 14 ++++++++++++++ .../tests/for_in_range_result_optional_err.vv | 16 ++++++++++++++++ 3 files changed, 33 insertions(+) create mode 100644 vlib/v/checker/tests/for_in_range_result_optional_err.out create mode 100644 vlib/v/checker/tests/for_in_range_result_optional_err.vv diff --git a/vlib/v/checker/for.v b/vlib/v/checker/for.v index 9f19d6d49..9184e784b 100644 --- a/vlib/v/checker/for.v +++ b/vlib/v/checker/for.v @@ -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 diff --git a/vlib/v/checker/tests/for_in_range_result_optional_err.out b/vlib/v/checker/tests/for_in_range_result_optional_err.out new file mode 100644 index 000000000..7c2bebeb4 --- /dev/null +++ b/vlib/v/checker/tests/for_in_range_result_optional_err.out @@ -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 | } diff --git a/vlib/v/checker/tests/for_in_range_result_optional_err.vv b/vlib/v/checker/tests/for_in_range_result_optional_err.vv new file mode 100644 index 000000000..73082b70f --- /dev/null +++ b/vlib/v/checker/tests/for_in_range_result_optional_err.vv @@ -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() { + } +} -- 2.39.5