checker: error on ternary if type mismatch
							parent
							
								
									54d1a29267
								
							
						
					
					
						commit
						f6d74c8a37
					
				|  | @ -157,7 +157,7 @@ fn (d mut DenseArray) zeros_to_end() { | |||
| 	} | ||||
| 	d.deletes = 0 | ||||
| 	d.size = count | ||||
| 	d.cap = if count < 8 { 8 } else { count } | ||||
| 	d.cap = if count < 8 { u32(8) } else { count } | ||||
| 	d.data = &KeyValue(C.realloc(d.data, sizeof(KeyValue) * d.cap)) | ||||
| } | ||||
| 
 | ||||
|  |  | |||
|  | @ -1827,6 +1827,8 @@ pub fn (mut c Checker) if_expr(node mut ast.IfExpr) table.Type { | |||
| 		node.is_expr = true | ||||
| 	} | ||||
| 	node.typ = table.void_type | ||||
| 	mut first_typ := 0 | ||||
| 	is_ternary := node.is_expr && node.branches.len >= 2 && node.has_else | ||||
| 	for i, branch in node.branches { | ||||
| 		if branch.cond is ast.ParExpr { | ||||
| 			c.error('unnecessary `()` in an if condition. use `if expr {` instead of `if (expr) {`.', | ||||
|  | @ -1840,6 +1842,13 @@ pub fn (mut c Checker) if_expr(node mut ast.IfExpr) table.Type { | |||
| 				c.error('non-bool (`$typ_sym.name`) used as if condition', node.pos) | ||||
| 			} | ||||
| 		} | ||||
| 		if is_ternary && i < node.branches.len - 1 && branch.stmts.len > 0 { | ||||
| 			last_stmt := branch.stmts[branch.stmts.len - 1] | ||||
| 			if last_stmt is ast.ExprStmt { | ||||
| 				last_expr := last_stmt as ast.ExprStmt | ||||
| 				first_typ = c.expr(last_expr.expr) | ||||
| 			} | ||||
| 		} | ||||
| 		c.stmts(branch.stmts) | ||||
| 	} | ||||
| 	if node.has_else && node.is_expr { | ||||
|  | @ -1850,6 +1859,9 @@ pub fn (mut c Checker) if_expr(node mut ast.IfExpr) table.Type { | |||
| 					// type_sym := p.table.get_type_symbol(it.typ)
 | ||||
| 					// p.warn('if expr ret $type_sym.name')
 | ||||
| 					t := c.expr(it.expr) | ||||
| 					if is_ternary && t != first_typ { | ||||
| 						c.error('mismatched types `${c.table.type_to_str(first_typ)}` and `${c.table.type_to_str(t)}`', node.pos) | ||||
| 					}					 | ||||
| 					node.typ = t | ||||
| 					return t | ||||
| 				} | ||||
|  |  | |||
|  | @ -0,0 +1,6 @@ | |||
| vlib/v/checker/tests/ternary_mismatch.v:2:7: error: mismatched types `string` and `int`  | ||||
|     1| fn main() { | ||||
|     2|     s := if true { '12' } else { 12 } | ||||
|                 ~~ | ||||
|     3|     println(s) | ||||
|     4| } | ||||
|  | @ -0,0 +1,4 @@ | |||
| fn main() { | ||||
| 	s := if true { '12' } else { 12 } | ||||
| 	println(s) | ||||
| } | ||||
		Loading…
	
		Reference in New Issue