checker: fix match expr type mismatch (#11220)

pull/11205/head
yuyi 2021-08-18 13:52:01 +08:00 committed by GitHub
parent 1dee4f25fd
commit c51f83efba
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 36 additions and 8 deletions

View File

@ -6091,7 +6091,8 @@ pub fn (mut c Checker) match_expr(mut node ast.MatchExpr) ast.Type {
} }
stmt.typ = expr_type stmt.typ = expr_type
} else if node.is_expr && ret_type != 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) ret_sym := c.table.get_type_symbol(ret_type)
if !(node.is_expr && ret_sym.kind == .sum_type) { if !(node.is_expr && ret_sym.kind == .sum_type) {
c.error('return type mismatch, it should be `$ret_sym.name`', c.error('return type mismatch, it should be `$ret_sym.name`',

View File

@ -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 24 | _ = match true {true {1} else {-1}} // OK
25 | match true {true {1} else {-1}} // result 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 | }

View File

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