checker: disallow non_opt_array << optvalue (#20573)

This commit is contained in:
Swastik Baranwal 2024-01-19 23:06:06 +05:30 committed by GitHub
parent a2443cc378
commit d744314ba1
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 38 additions and 0 deletions

View File

@ -529,6 +529,10 @@ fn (mut c Checker) infix_expr(mut node ast.InfixExpr) ast.Type {
node.auto_locked, _ = c.fail_if_immutable(mut node.left) node.auto_locked, _ = c.fail_if_immutable(mut node.left)
left_value_type := c.table.value_type(c.unwrap_generic(left_type)) left_value_type := c.table.value_type(c.unwrap_generic(left_type))
left_value_sym := c.table.sym(c.unwrap_generic(left_value_type)) left_value_sym := c.table.sym(c.unwrap_generic(left_value_type))
if !left_value_type.has_flag(.option) && right_type.has_flag(.option) {
c.error('unwrapped Option cannot be used in an infix expression',
node.pos)
}
if left_value_sym.kind == .interface_ { if left_value_sym.kind == .interface_ {
if right_final_sym.kind != .array { if right_final_sym.kind != .array {
// []Animal << Cat // []Animal << Cat

View File

@ -0,0 +1,13 @@
vlib/v/checker/tests/non_optional_array_append_optional_type_err.vv:12:10: error: unwrapped Option cannot be used in an infix expression
10 | fn main() {
11 | mut foobars := []Foobar{}
12 | foobars << ?Foobar(.foo)
| ~~
13 | foobars << get_foo_or_none(true)
14 | }
vlib/v/checker/tests/non_optional_array_append_optional_type_err.vv:13:10: error: unwrapped Option cannot be used in an infix expression
11 | mut foobars := []Foobar{}
12 | foobars << ?Foobar(.foo)
13 | foobars << get_foo_or_none(true)
| ~~
14 | }

View File

@ -0,0 +1,14 @@
pub enum Foobar {
foo
bar
}
fn get_foo_or_none(fail bool) ?Foobar {
return if fail {none} else {.foo}
}
fn main() {
mut foobars := []Foobar{}
foobars << ?Foobar(.foo)
foobars << get_foo_or_none(true)
}

View File

@ -40,6 +40,13 @@ vlib/v/checker/tests/option_fn_err.vv:49:6: error: cannot use `?int` as `int`, i
| ~~~~~~ | ~~~~~~
50 | 50 |
51 | // array 51 | // array
vlib/v/checker/tests/option_fn_err.vv:53:6: error: unwrapped Option cannot be used in an infix expression
51 | // array
52 | mut arr := [1, 2]
53 | arr << bar(0)
| ~~
54 | // init
55 | _ := [bar(0)]
vlib/v/checker/tests/option_fn_err.vv:56:27: error: cannot use unwrapped Option as initializer vlib/v/checker/tests/option_fn_err.vv:56:27: error: cannot use unwrapped Option as initializer
54 | // init 54 | // init
55 | _ := [bar(0)] 55 | _ := [bar(0)]