checker: add check preventing `if x:=non_optional() {}`

pull/6713/head
Delyan Angelov 2020-11-02 01:56:28 +02:00
parent a0bf796926
commit 3c0f4c46fa
3 changed files with 41 additions and 0 deletions

View File

@ -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 {

View File

@ -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 | }

View File

@ -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')
}
}