Skip to content

Commit

Permalink
checker: fix generic comparison for conditional assignment (vlang#19401)
Browse files Browse the repository at this point in the history
  • Loading branch information
yuyi98 authored and Wertzui123 committed Oct 8, 2023
1 parent 6fb7266 commit 569ad61
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
15 changes: 15 additions & 0 deletions vlib/v/checker/infix.v
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,21 @@ fn (mut c Checker) infix_expr(mut node ast.InfixExpr) ast.Type {
if node.op == .key_is {
c.inside_x_is_type = true
}
// `arr << if n > 0 { 10 } else { 11 }` set the right c.expected_type
if node.op == .left_shift && c.table.sym(left_type).kind == .array {
if mut node.right is ast.IfExpr {
if node.right.is_expr && node.right.branches.len > 0 {
mut last_stmt := node.right.branches[0].stmts.last()
if mut last_stmt is ast.ExprStmt {
expr_typ := c.expr(mut last_stmt.expr)
info := c.table.sym(left_type).array_info()
if expr_typ == info.elem_type {
c.expected_type = info.elem_type
}
}
}
}
}
mut right_type := c.expr(mut node.right)
if node.op == .key_is {
c.inside_x_is_type = false
Expand Down
21 changes: 21 additions & 0 deletions vlib/v/tests/generic_comparison_for_conditional_assign_test.v
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
fn clip[N](x []N, min N, max N) []N {
mut result := []N{cap: x.len}
for value in x {
result << if value < min {
min
} else if value > max {
max
} else {
value
}
}
return result
}

fn test_generic_comparison_for_conditional_assign() {
a := [1, 2, 3, 4, 5]
dump(a)
b := clip(a, 2, 4)
dump(b)
assert b == [2, 2, 3, 4, 4]
}

0 comments on commit 569ad61

Please sign in to comment.