From cd5c5561db280ca76fe74fec8162d9a3efc3e37f Mon Sep 17 00:00:00 2001 From: yuyi Date: Tue, 7 Nov 2023 20:29:03 +0800 Subject: [PATCH] cgen: fix closure variable in smartcast (#19796) --- vlib/v/gen/c/fn.v | 6 ++++- .../closure_variable_in_smartcast_test.v | 25 +++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) create mode 100644 vlib/v/tests/closure_variable_in_smartcast_test.v diff --git a/vlib/v/gen/c/fn.v b/vlib/v/gen/c/fn.v index 734dc2f6aded7b..2d3879ea32267a 100644 --- a/vlib/v/gen/c/fn.v +++ b/vlib/v/gen/c/fn.v @@ -1777,7 +1777,11 @@ fn (mut g Gen) fn_call(node ast.CallExpr) { cast_sym := g.table.sym(g.unwrap_generic(typ)) mut is_ptr := false if i == 0 { - g.write(node.name) + if obj.is_inherited { + g.write(c.closure_ctx + '->' + node.name) + } else { + g.write(node.name) + } if obj.orig_type.is_ptr() { is_ptr = true } diff --git a/vlib/v/tests/closure_variable_in_smartcast_test.v b/vlib/v/tests/closure_variable_in_smartcast_test.v new file mode 100644 index 00000000000000..39feebf579c959 --- /dev/null +++ b/vlib/v/tests/closure_variable_in_smartcast_test.v @@ -0,0 +1,25 @@ +pub type MyCallback = fn () | fn (ctx voidptr) + +fn my_lower_level_func(func fn (ctx voidptr), ctx voidptr) { + println('Bar') +} + +fn my_func(cb MyCallback, ctx voidptr) { + my_lower_level_func(fn [cb] (ctx voidptr) { + match cb { + fn () { + cb() + } + fn (ctx voidptr) { + cb(ctx) + } + } + }, ctx) +} + +fn test_closure_variable_in_smartcast() { + my_func(fn () { + println('Foo') + }, unsafe { nil }) + assert true +}