From c51f83efba2d0c3c60d165672b6a3f217311e5c8 Mon Sep 17 00:00:00 2001 From: yuyi Date: Wed, 18 Aug 2021 13:52:01 +0800 Subject: [PATCH] checker: fix match expr type mismatch (#11220) --- vlib/v/checker/checker.v | 3 +- vlib/v/checker/tests/if_match_expr.out | 7 ---- .../match_expr_with_promote_number_test.v | 34 +++++++++++++++++++ 3 files changed, 36 insertions(+), 8 deletions(-) create mode 100644 vlib/v/tests/match_expr_with_promote_number_test.v diff --git a/vlib/v/checker/checker.v b/vlib/v/checker/checker.v index 881bcb694a..1e3eb79caf 100644 --- a/vlib/v/checker/checker.v +++ b/vlib/v/checker/checker.v @@ -6091,7 +6091,8 @@ pub fn (mut c Checker) match_expr(mut node ast.MatchExpr) ast.Type { } stmt.typ = expr_type } else if node.is_expr && ret_type != expr_type { - if !c.check_types(ret_type, expr_type) { + if !c.check_types(ret_type, expr_type) + && !c.check_types(expr_type, ret_type) { ret_sym := c.table.get_type_symbol(ret_type) if !(node.is_expr && ret_sym.kind == .sum_type) { c.error('return type mismatch, it should be `$ret_sym.name`', diff --git a/vlib/v/checker/tests/if_match_expr.out b/vlib/v/checker/tests/if_match_expr.out index 9c6597646b..81c13a7f69 100644 --- a/vlib/v/checker/tests/if_match_expr.out +++ b/vlib/v/checker/tests/if_match_expr.out @@ -40,10 +40,3 @@ vlib/v/checker/tests/if_match_expr.vv:23:3: error: `match` expression branch has | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 24 | _ = match true {true {1} else {-1}} // OK 25 | match true {true {1} else {-1}} // result -vlib/v/checker/tests/if_match_expr.vv:25:3: error: return type mismatch, it should be `int` - 23 | match true {true {} else {}} // statement not expression - 24 | _ = match true {true {1} else {-1}} // OK - 25 | match true {true {1} else {-1}} // result - | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - 26 | } - 27 | } diff --git a/vlib/v/tests/match_expr_with_promote_number_test.v b/vlib/v/tests/match_expr_with_promote_number_test.v new file mode 100644 index 0000000000..572cd6d863 --- /dev/null +++ b/vlib/v/tests/match_expr_with_promote_number_test.v @@ -0,0 +1,34 @@ +struct Data { + x f64 + y f64 +} + +fn (d Data) test(n int) f64 { + return match n { + 0 { d.x } + 1 { d.y } + else { 0 } + } +} + +fn test1(n int) f64 { + return match n { + 0 { 1 } + 1 { 2 } + else { 0 } + } +} + +fn test_match_expr_with_promote_number() { + d := Data{ + x: 1 + y: 2 + } + ret1 := d.test(2) + println(ret1) + assert ret1 == 0 + + ret2 := test1(2) + println(ret2) + assert ret2 == 0 +}