Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

checker: disallow expr is Type if expr is Optional #23510

Merged
merged 7 commits into from
Jan 25, 2025
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 | }
Delta456 marked this conversation as resolved.
Show resolved Hide resolved
Loading