checker: add check preventing `if x:=non_optional() {}`
parent
a0bf796926
commit
3c0f4c46fa
|
@ -2809,6 +2809,9 @@ pub fn (mut c Checker) expr(node ast.Expr) table.Type {
|
|||
}
|
||||
ast.IfGuardExpr {
|
||||
node.expr_type = c.expr(node.expr)
|
||||
if !node.expr_type.has_flag(.optional) {
|
||||
c.error('expression should return an option', node.expr.position())
|
||||
}
|
||||
return table.bool_type
|
||||
}
|
||||
ast.IndexExpr {
|
||||
|
|
|
@ -0,0 +1,7 @@
|
|||
vlib/v/checker/tests/expression_should_return_an_option.vv:28:10: error: expression should return an option
|
||||
26 | }
|
||||
27 | // should be an checker error:
|
||||
28 | if x := return_string() {
|
||||
| ~~~~~~~~~~~~~~~
|
||||
29 | println('x: $x')
|
||||
30 | }
|
|
@ -0,0 +1,31 @@
|
|||
fn return_optional(fail bool) ?string {
|
||||
if fail {
|
||||
return error('nope')
|
||||
}
|
||||
return 'foo'
|
||||
}
|
||||
|
||||
fn return_string() string {
|
||||
return 'foo'
|
||||
}
|
||||
|
||||
fn main() {
|
||||
// works
|
||||
if r := return_optional(false) {
|
||||
println(r)
|
||||
}
|
||||
// works
|
||||
if r := return_optional(false) {
|
||||
println(r)
|
||||
} else {
|
||||
println(err)
|
||||
}
|
||||
// works
|
||||
return_optional(true) or {
|
||||
println(err)
|
||||
}
|
||||
// should be an checker error:
|
||||
if x := return_string() {
|
||||
println('x: $x')
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue