checker: check error for index of optional (#13785)

pull/13788/head
yuyi 2022-03-21 16:17:57 +08:00 committed by GitHub
parent 21e9b1deb0
commit d9cca53bd0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 18 additions and 0 deletions

View File

@ -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)',

View File

@ -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 | }

View File

@ -0,0 +1,8 @@
fn abc() ?[]int {
return [1, 2, 3]
}
fn main() {
a := abc()[0] or { 5 }
dump(a)
}