checker: check`match` types (#6149)
							parent
							
								
									dab639662f
								
							
						
					
					
						commit
						46b4e2a0cd
					
				|  | @ -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 | ||||
| 		} | ||||
| 	} | ||||
|  |  | |||
|  | @ -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 {} | ||||
|  | @ -0,0 +1,11 @@ | |||
| ch := `a` | ||||
| match ch { | ||||
|   'a' {} | ||||
|   else {} | ||||
| } | ||||
| 
 | ||||
| char := 123 | ||||
| match char { | ||||
|   'a' {} | ||||
|   else {} | ||||
| } | ||||
		Loading…
	
		Reference in New Issue