Skip to content

Commit

Permalink
cgen: fix closure parameter judgment when var cross assign inside ano…
Browse files Browse the repository at this point in the history
…n fn(fix #19734) (#19736)
  • Loading branch information
shove70 committed Nov 3, 2023
1 parent 24befa0 commit 1a53a46
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
8 changes: 7 additions & 1 deletion vlib/v/gen/c/assign.v
Expand Up @@ -891,7 +891,13 @@ fn (mut g Gen) gen_cross_var_assign(node &ast.AssignStmt) {
ast.Ident {
left_typ := node.left_types[i]
left_sym := g.table.sym(left_typ)
anon_ctx := if g.anon_fn { '${closure_ctx}->' } else { '' }
mut anon_ctx := ''
if g.anon_fn {
obj := left.scope.find(left.name)
if obj is ast.Var && obj.is_inherited {
anon_ctx = '${closure_ctx}->'
}
}
if left_sym.kind == .function {
g.write_fn_ptr_decl(left_sym.info as ast.FnType, '_var_${left.pos.pos}')
g.writeln(' = ${anon_ctx}${c_name(left.name)};')
Expand Down
20 changes: 20 additions & 0 deletions vlib/v/tests/closure_test.v
Expand Up @@ -223,3 +223,23 @@ fn test_closure_over_variable_that_is_returned_from_a_multi_value_function() {
a()
println(two)
}

fn test_cross_var_assign_without_inherited() {
f := fn () {
mut left := 1
mut right := 2
left, right = right, left
assert left == 2 && right == 1
}
f()
}

fn test_cross_var_assign_with_inherited() {
mut left := 1
mut right := 2
f := fn [mut left, mut right] () {
left, right = right, left
assert left == 2 && right == 1
}
f()
}

0 comments on commit 1a53a46

Please sign in to comment.