checker: fix option mismatch checking on array initializations (fix #20409) (#20415)

This commit is contained in:
shove 2024-01-07 04:31:47 +08:00 committed by GitHub
parent 1303c244e2
commit 2d97f16a3d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 47 additions and 0 deletions

View File

@ -212,6 +212,20 @@ fn (mut c Checker) array_init(mut node ast.ArrayInit) ast.Type {
c.check_expected(typ, elem_type) or {
c.error('invalid array element: ${err.msg()}', expr.pos())
}
if !elem_type.has_flag(.option)
&& (typ.has_flag(.option) || typ.idx() == ast.none_type_idx) {
typ_str, elem_type_str := c.get_string_names_of(typ, elem_type)
if typ.idx() == ast.none_type_idx {
c.error('cannot use `${typ_str}` as `${elem_type_str}`', expr.pos())
} else {
c.error('cannot use `${typ_str}` as `${elem_type_str}`, it must be unwrapped first',
expr.pos())
}
} else if elem_type.has_flag(.option) && !typ.has_flag(.option)
&& typ.idx() != ast.none_type_idx && !expr.is_pure_literal() {
typ_str, elem_type_str := c.get_string_names_of(typ, elem_type)
c.error('cannot use `${typ_str}` as `${elem_type_str}`', expr.pos())
}
}
}
if node.is_fixed {

View File

@ -0,0 +1,20 @@
vlib/v/checker/tests/array_init_element_option_mismatch_err.vv:8:11: error: cannot use `?string` as `string`, it must be unwrapped first
6 | fn main() {
7 | str := ?string(none)
8 | _ = ['', str]
| ~~~
9 |
10 | foo := Foo{}
vlib/v/checker/tests/array_init_element_option_mismatch_err.vv:11:18: error: cannot use `?string` as `string`, it must be unwrapped first
9 |
10 | foo := Foo{}
11 | _ = [foo.a, foo.b]
| ^
12 | _ = [foo.b, foo.a]
13 | }
vlib/v/checker/tests/array_init_element_option_mismatch_err.vv:12:18: error: cannot use `string` as `?string`
10 | foo := Foo{}
11 | _ = [foo.a, foo.b]
12 | _ = [foo.b, foo.a]
| ^
13 | }

View File

@ -0,0 +1,13 @@
struct Foo {
a string
b ?string
}
fn main() {
str := ?string(none)
_ = ['', str]
foo := Foo{}
_ = [foo.a, foo.b]
_ = [foo.b, foo.a]
}