Skip to content

Commit

Permalink
checker: fix option mismatch checking on array initializations (fix #…
Browse files Browse the repository at this point in the history
  • Loading branch information
shove70 committed Jan 6, 2024
1 parent 1303c24 commit 2d97f16
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 0 deletions.
14 changes: 14 additions & 0 deletions vlib/v/checker/containers.v
Expand Up @@ -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 {
Expand Down
20 changes: 20 additions & 0 deletions vlib/v/checker/tests/array_init_element_option_mismatch_err.out
@@ -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 | }
13 changes: 13 additions & 0 deletions vlib/v/checker/tests/array_init_element_option_mismatch_err.vv
@@ -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]
}

0 comments on commit 2d97f16

Please sign in to comment.