Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

checker: fix generic comparison for conditional assignment (fix #19398) #19401

Merged
merged 1 commit into from
Sep 21, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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]
}
Loading