1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

checker: checkmatch types (#6149)

This commit is contained in:
Swastik Baranwal 2020-08-17 23:49:21 +05:30 committed by GitHub
parent dab639662f
commit 46b4e2a0cd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 34 additions and 1 deletions

View File

@ -2694,6 +2694,9 @@ pub fn (mut c Checker) match_expr(mut node ast.MatchExpr) table.Type {
node.is_expr = c.expected_type != table.void_type
node.expected_type = c.expected_type
cond_type := c.expr(node.cond)
// we setting this here rather than at the end of the method
// since it is used in c.match_exprs() it saves checking twice
node.cond_type = cond_type
if cond_type == 0 {
c.error('match 0 cond type', node.pos)
}
@ -2761,7 +2764,6 @@ pub fn (mut c Checker) match_expr(mut node ast.MatchExpr) table.Type {
// node.expected_type = c.expected_type
// }
node.return_type = ret_type
node.cond_type = cond_type
// println('!m $expr_type')
return ret_type
}
@ -2816,6 +2818,13 @@ fn (mut c Checker) match_exprs(mut node ast.MatchExpr, type_sym table.TypeSymbol
if val == 1 {
c.error('match case `$key` is handled more than once', branch.pos)
}
c.expected_type = node.cond_type
expr_type := c.expr(expr)
if !c.check_types(expr_type, c.expected_type) {
expr_str := c.table.type_to_str(expr_type)
expect_str := c.table.type_to_str(c.expected_type)
c.error('cannot use type `$expect_str` as type `$expr_str`', node.pos)
}
branch_exprs[key] = val + 1
}
}

View File

@ -0,0 +1,13 @@
vlib/v/checker/tests/match_expr_and_expected_type_error.v:2:1: error: cannot use type `byte` as type `string`
1 | ch := `a`
2 | match ch {
| ~~~~~~~~~~
3 | 'a' {}
4 | else {}
vlib/v/checker/tests/match_expr_and_expected_type_error.v:8:1: error: cannot use type `int` as type `string`
6 |
7 | char := 123
8 | match char {
| ~~~~~~~~~~~~
9 | 'a' {}
10 | else {}

View File

@ -0,0 +1,11 @@
ch := `a`
match ch {
'a' {}
else {}
}
char := 123
match char {
'a' {}
else {}
}