Skip to content

Commit a3793e3

Browse files
authored
checker: fix generic inference in if expressions used in assignments (#21781)
1 parent 0682500 commit a3793e3

File tree

3 files changed

+20
-0
lines changed

3 files changed

+20
-0
lines changed

vlib/v/checker/assign.v

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,14 @@ fn (mut c Checker) assign_stmt(mut node ast.AssignStmt) {
5353
right_len = node.right_types.len
5454
} else if right_type == ast.void_type {
5555
right_len = 0
56+
if mut right is ast.IfExpr {
57+
last_branch := right.branches.last()
58+
last_stmts := last_branch.stmts.filter(it is ast.ExprStmt)
59+
if last_stmts.any((it as ast.ExprStmt).typ.has_flag(.generic)) {
60+
right_len = last_branch.stmts.len
61+
node.right_types = last_stmts.map((it as ast.ExprStmt).typ)
62+
}
63+
}
5664
}
5765
}
5866
if mut right is ast.InfixExpr {

vlib/v/checker/if.v

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -473,6 +473,10 @@ fn (mut c Checker) if_expr(mut node ast.IfExpr) ast.Type {
473473
c.error('mismatched types `${c.table.type_to_str(node.typ)}` and `${c.table.type_to_str(stmt.typ)}`',
474474
node.pos)
475475
} else {
476+
if node.is_expr == false && c.comptime.is_generic_param_var(stmt.expr) {
477+
// generic variable no yet type bounded
478+
node.is_expr = true
479+
}
476480
if c.inside_assign && node.is_expr && !node.typ.has_flag(.shared_f)
477481
&& stmt.typ != ast.voidptr_type {
478482
if stmt.typ.is_ptr() != node.typ.is_ptr() {

vlib/v/tests/generic_if_ret_test.v

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
fn clamp[T](a T, x T, b T) T {
2+
min := if x < b { x } else { b }
3+
return if min < a { a } else { min }
4+
}
5+
6+
fn test_main() {
7+
assert dump(clamp(1, 2, 3)) == 2
8+
}

0 commit comments

Comments
 (0)