checker: check match return mismatch type (fix #6826) (#7109)

pull/7118/head
yuyi 2020-12-04 03:14:23 +08:00 committed by GitHub
parent d590ce7675
commit 9b6a1552e9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 25 additions and 9 deletions

View File

@ -3434,8 +3434,13 @@ pub fn (mut c Checker) match_expr(mut node ast.MatchExpr) table.Type {
mut stmt := branch.stmts[branch.stmts.len - 1]
match mut stmt {
ast.ExprStmt {
ret_type = c.expr(stmt.expr)
stmt.typ = ret_type
if ret_type == table.void_type {
ret_type = c.expr(stmt.expr)
stmt.typ = ret_type
} else if node.is_expr && ret_type != c.expr(stmt.expr) {
sym := c.table.get_type_symbol(ret_type)
c.error('return type mismatch, it should be `$sym.name`', stmt.expr.position())
}
}
else {
// TODO: ask alex about this
@ -4009,14 +4014,11 @@ pub fn (mut c Checker) if_expr(mut node ast.IfExpr) table.Type {
} else if node.typ == table.any_flt_type {
node.typ = table.f64_type
}
if expr_required {
if !node.has_else {
d := if node.is_comptime { '$' } else { '' }
c.error('`$if_kind` expression needs `${d}else` clause', node.pos)
}
return node.typ
if expr_required && !node.has_else {
d := if node.is_comptime { '$' } else { '' }
c.error('`$if_kind` expression needs `${d}else` clause', node.pos)
}
return table.bool_type
return node.typ
}
// comp_if_branch checks the condition of a compile-time `if` branch. It returns a `bool` that

View File

@ -0,0 +1,7 @@
vlib/v/checker/tests/match_return_mismatch_type_err.vv:4:10: error: return type mismatch, it should be `string`
2 | a := match 1 {
3 | 1 { 'aa' }
4 | else { 22 }
| ~~
5 | }
6 | println(a)

View File

@ -0,0 +1,7 @@
fn main() {
a := match 1 {
1 { 'aa' }
else { 22 }
}
println(a)
}