Skip to content

Commit

Permalink
checker: disallow expr is Type if expr is Optional
Browse files Browse the repository at this point in the history
  • Loading branch information
Delta456 committed Jan 18, 2025
1 parent e2882ef commit 897257a
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 0 deletions.
4 changes: 4 additions & 0 deletions vlib/v/checker/infix.v
Original file line number Diff line number Diff line change
Expand Up @@ -781,6 +781,10 @@ fn (mut c Checker) infix_expr(mut node ast.InfixExpr) ast.Type {
if typ != ast.no_type {
typ_sym := c.table.sym(typ)
op := node.op.str()
if left_type.has_flag(.option) {
c.error('${node.left} is an Optional, it needs to be unwrapped first',
node.left.pos())
}
if typ_sym.kind == .placeholder {
c.error('${op}: type `${typ_sym.name}` does not exist', right_expr.pos())
}
Expand Down
7 changes: 7 additions & 0 deletions vlib/v/checker/tests/opt_is_op_check_err.out
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
vlib/v/checker/tests/opt_is_op_check_err.vv:13:7: error: t.a is an Optional, it needs to be unwrapped first
11 | a: s
12 | }
13 | if t.a is string {
| ^
14 | r(t.a)
15 | }
21 changes: 21 additions & 0 deletions vlib/v/checker/tests/opt_is_op_check_err.vv
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
type Foo = int | string

struct Struct {
a ?Foo
}

fn r(a string) {}

fn t(s ?Foo) {
mut t := Struct{
a: s
}
if t.a is string {
r(t.a)
}
}

fn main() {
s := ?Foo('hello')
t(s)
}
14 changes: 14 additions & 0 deletions vlib/v/checker/tests/orm_op_with_option_and_none.out
Original file line number Diff line number Diff line change
Expand Up @@ -47,3 +47,17 @@ vlib/v/checker/tests/orm_op_with_option_and_none.vv:45:30: warning: comparison w
| ~~
46 | }!
47 |
vlib/v/checker/tests/orm_op_with_option_and_none.vv:49:25: error: name is an Optional, it needs to be unwrapped first
47 |
48 | _ := sql db {
49 | select from Foo where name is none
| ~~~~
50 | }!
51 |
vlib/v/checker/tests/orm_op_with_option_and_none.vv:53:25: error: name is an Optional, it needs to be unwrapped first
51 |
52 | _ := sql db {
53 | select from Foo where name !is none
| ~~~~
54 | }!
55 | }

0 comments on commit 897257a

Please sign in to comment.