Skip to content

Commit d744314

Browse files
authored
checker: disallow non_opt_array << optvalue (#20573)
1 parent a2443cc commit d744314

File tree

4 files changed

+38
-0
lines changed

4 files changed

+38
-0
lines changed

vlib/v/checker/infix.v

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -529,6 +529,10 @@ fn (mut c Checker) infix_expr(mut node ast.InfixExpr) ast.Type {
529529
node.auto_locked, _ = c.fail_if_immutable(mut node.left)
530530
left_value_type := c.table.value_type(c.unwrap_generic(left_type))
531531
left_value_sym := c.table.sym(c.unwrap_generic(left_value_type))
532+
if !left_value_type.has_flag(.option) && right_type.has_flag(.option) {
533+
c.error('unwrapped Option cannot be used in an infix expression',
534+
node.pos)
535+
}
532536
if left_value_sym.kind == .interface_ {
533537
if right_final_sym.kind != .array {
534538
// []Animal << Cat
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
vlib/v/checker/tests/non_optional_array_append_optional_type_err.vv:12:10: error: unwrapped Option cannot be used in an infix expression
2+
10 | fn main() {
3+
11 | mut foobars := []Foobar{}
4+
12 | foobars << ?Foobar(.foo)
5+
| ~~
6+
13 | foobars << get_foo_or_none(true)
7+
14 | }
8+
vlib/v/checker/tests/non_optional_array_append_optional_type_err.vv:13:10: error: unwrapped Option cannot be used in an infix expression
9+
11 | mut foobars := []Foobar{}
10+
12 | foobars << ?Foobar(.foo)
11+
13 | foobars << get_foo_or_none(true)
12+
| ~~
13+
14 | }
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
pub enum Foobar {
2+
foo
3+
bar
4+
}
5+
6+
fn get_foo_or_none(fail bool) ?Foobar {
7+
return if fail {none} else {.foo}
8+
}
9+
10+
fn main() {
11+
mut foobars := []Foobar{}
12+
foobars << ?Foobar(.foo)
13+
foobars << get_foo_or_none(true)
14+
}

vlib/v/checker/tests/option_fn_err.out

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,13 @@ vlib/v/checker/tests/option_fn_err.vv:49:6: error: cannot use `?int` as `int`, i
4040
| ~~~~~~
4141
50 |
4242
51 | // array
43+
vlib/v/checker/tests/option_fn_err.vv:53:6: error: unwrapped Option cannot be used in an infix expression
44+
51 | // array
45+
52 | mut arr := [1, 2]
46+
53 | arr << bar(0)
47+
| ~~
48+
54 | // init
49+
55 | _ := [bar(0)]
4350
vlib/v/checker/tests/option_fn_err.vv:56:27: error: cannot use unwrapped Option as initializer
4451
54 | // init
4552
55 | _ := [bar(0)]

0 commit comments

Comments
 (0)