From 9b6a1552e90547df1a42eeb5dca9394c72d2cef1 Mon Sep 17 00:00:00 2001 From: yuyi Date: Fri, 4 Dec 2020 03:14:23 +0800 Subject: [PATCH] checker: check match return mismatch type (fix #6826) (#7109) --- vlib/v/checker/checker.v | 20 ++++++++++--------- .../tests/match_return_mismatch_type_err.out | 7 +++++++ .../tests/match_return_mismatch_type_err.vv | 7 +++++++ 3 files changed, 25 insertions(+), 9 deletions(-) create mode 100644 vlib/v/checker/tests/match_return_mismatch_type_err.out create mode 100644 vlib/v/checker/tests/match_return_mismatch_type_err.vv diff --git a/vlib/v/checker/checker.v b/vlib/v/checker/checker.v index bf1ccb7e9e..d51a57f067 100644 --- a/vlib/v/checker/checker.v +++ b/vlib/v/checker/checker.v @@ -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 diff --git a/vlib/v/checker/tests/match_return_mismatch_type_err.out b/vlib/v/checker/tests/match_return_mismatch_type_err.out new file mode 100644 index 0000000000..3a8e8fe15c --- /dev/null +++ b/vlib/v/checker/tests/match_return_mismatch_type_err.out @@ -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) diff --git a/vlib/v/checker/tests/match_return_mismatch_type_err.vv b/vlib/v/checker/tests/match_return_mismatch_type_err.vv new file mode 100644 index 0000000000..c422126014 --- /dev/null +++ b/vlib/v/checker/tests/match_return_mismatch_type_err.vv @@ -0,0 +1,7 @@ +fn main() { + a := match 1 { + 1 { 'aa' } + else { 22 } + } + println(a) +}