From c18bf48833d389945b6acae801f9aaed4ab0bbb2 Mon Sep 17 00:00:00 2001 From: yuyi Date: Sun, 19 Mar 2023 16:11:11 +0800 Subject: [PATCH] cgen: fix closure with fixed array variable (#17707) --- vlib/v/gen/c/fn.v | 22 +++++++++++++++++-- .../tests/closure_with_fixed_array_var_test.v | 16 ++++++++++++++ 2 files changed, 36 insertions(+), 2 deletions(-) create mode 100644 vlib/v/tests/closure_with_fixed_array_var_test.v diff --git a/vlib/v/gen/c/fn.v b/vlib/v/gen/c/fn.v index 53759cb99f..8e32578610 100644 --- a/vlib/v/gen/c/fn.v +++ b/vlib/v/gen/c/fn.v @@ -487,12 +487,30 @@ fn (mut g Gen) gen_anon_fn(mut node ast.AnonFn) { if obj is ast.Var { if obj.has_inherited { has_inherited = true - g.writeln('.${var.name} = ${c.closure_ctx}->${var.name},') + var_sym := g.table.sym(var.typ) + if var_sym.info is ast.ArrayFixed { + g.write('.${var.name} = {') + for i in 0 .. var_sym.info.size { + g.write('${c.closure_ctx}->${var.name}[${i}],') + } + g.writeln('},') + } else { + g.writeln('.${var.name} = ${c.closure_ctx}->${var.name},') + } } } } if !has_inherited { - g.writeln('.${var.name} = ${var.name},') + var_sym := g.table.sym(var.typ) + if var_sym.info is ast.ArrayFixed { + g.write('.${var.name} = {') + for i in 0 .. var_sym.info.size { + g.write('${var.name}[${i}],') + } + g.writeln('},') + } else { + g.writeln('.${var.name} = ${var.name},') + } } } g.indent-- diff --git a/vlib/v/tests/closure_with_fixed_array_var_test.v b/vlib/v/tests/closure_with_fixed_array_var_test.v new file mode 100644 index 0000000000..c809cc1645 --- /dev/null +++ b/vlib/v/tests/closure_with_fixed_array_var_test.v @@ -0,0 +1,16 @@ +struct Crasher { + value int +} + +fn crash(c [1]Crasher) fn () int { + return fn [c] () int { + println(c[0].value) + return c[0].value + } +} + +fn test_closure_with_fixed_array_var() { + crash_fn := crash([Crasher{1}]!) + ret := crash_fn() + assert ret == 1 +}