From d9cca53bd0276c5e15bba1c918379f6ed751904d Mon Sep 17 00:00:00 2001 From: yuyi Date: Mon, 21 Mar 2022 16:17:57 +0800 Subject: [PATCH] checker: check error for index of optional (#13785) --- vlib/v/checker/checker.v | 3 +++ vlib/v/checker/tests/index_of_optional_err.out | 7 +++++++ vlib/v/checker/tests/index_of_optional_err.vv | 8 ++++++++ 3 files changed, 18 insertions(+) create mode 100644 vlib/v/checker/tests/index_of_optional_err.out create mode 100644 vlib/v/checker/tests/index_of_optional_err.vv diff --git a/vlib/v/checker/checker.v b/vlib/v/checker/checker.v index 0b29b56de3..765d5e4e4a 100644 --- a/vlib/v/checker/checker.v +++ b/vlib/v/checker/checker.v @@ -3775,6 +3775,9 @@ pub fn (mut c Checker) index_expr(mut node ast.IndexExpr) ast.Type { && typ !in [ast.byteptr_type, ast.charptr_type] && !typ.has_flag(.variadic) { c.error('type `$typ_sym.name` does not support indexing', node.pos) } + if typ.has_flag(.optional) { + c.error('type `?$typ_sym.name` is optional, it does not support indexing', node.left.pos()) + } if typ_sym.kind == .string && !typ.is_ptr() && node.is_setter { c.error('cannot assign to s[i] since V strings are immutable\n' + '(note, that variables may be mutable but string values are always immutable, like in Go and Java)', diff --git a/vlib/v/checker/tests/index_of_optional_err.out b/vlib/v/checker/tests/index_of_optional_err.out new file mode 100644 index 0000000000..a3628501d8 --- /dev/null +++ b/vlib/v/checker/tests/index_of_optional_err.out @@ -0,0 +1,7 @@ +vlib/v/checker/tests/index_of_optional_err.vv:6:7: error: type `?[]int` is optional, it does not support indexing + 4 | + 5 | fn main() { + 6 | a := abc()[0] or { 5 } + | ~~~~~ + 7 | dump(a) + 8 | } diff --git a/vlib/v/checker/tests/index_of_optional_err.vv b/vlib/v/checker/tests/index_of_optional_err.vv new file mode 100644 index 0000000000..06bc943aae --- /dev/null +++ b/vlib/v/checker/tests/index_of_optional_err.vv @@ -0,0 +1,8 @@ +fn abc() ?[]int { + return [1, 2, 3] +} + +fn main() { + a := abc()[0] or { 5 } + dump(a) +}