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

checker: correct type check for generic function with ternary if return (#9296)

This commit is contained in:
StunxFS 2021-03-14 13:01:32 -04:00 committed by GitHub
parent 906d28e9e4
commit 92e95f127a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 26 additions and 11 deletions

View File

@ -5027,6 +5027,13 @@ pub fn (mut c Checker) if_expr(mut node ast.IfExpr) table.Type {
} }
continue continue
} }
if c.expected_type.has_flag(.generic) {
if node.typ == table.void_type {
node.is_expr = true
node.typ = c.unwrap_generic(c.expected_type)
}
continue
}
last_expr.typ = c.expr(last_expr.expr) last_expr.typ = c.expr(last_expr.expr)
if !c.check_types(last_expr.typ, node.typ) { if !c.check_types(last_expr.typ, node.typ) {
if node.typ == table.void_type { if node.typ == table.void_type {

View File

@ -22,11 +22,7 @@ fn test_if_expression_with_stmts() {
} }
assert a == 1 assert a == 1
mut b := 0 mut b := 0
b = if false { b = if false { 42 } else { 24 }
42
} else {
24
}
assert b == 24 assert b == 24
} }
@ -164,18 +160,22 @@ fn test_if_expr_with_infix() {
} }
fn test_multi_if_expr_with_infix() { fn test_multi_if_expr_with_infix() {
a := if 1 == 0 { 1 } else if 1 == 0 { 2 } else { 3 } + 4 a := if 1 == 0 {
1
} else if 1 == 0 {
2
} else {
3
} + 4
assert a == 7 assert a == 7
} }
fn test_if_expr_with_array_map() { fn test_if_expr_with_array_map() {
num_string := '2 3' num_string := '2 3'
assigned := if num_string.len > 1 { assigned := if num_string.len > 1 { num_string.split(' ').map(it.int()) } else { [
num_string.split(' ').map(it.int()) 789,
} else { ] }
[789]
}
println(assigned) println(assigned)
assert assigned == [2, 3] assert assigned == [2, 3]
@ -191,3 +191,11 @@ fn test_if_epxr_with_array_conditions() {
assert false assert false
} }
} }
fn min<T>(a T, b T) T {
return if a < b { a } else { b }
}
fn test_if_expr_with_fn_generic() {
assert min(42, 13) == 13
}