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

Draft
wants to merge 4 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all 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.inside_sql {
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)
}
Loading