From d649f5aff441d8012422899ee0c7605c17885aae Mon Sep 17 00:00:00 2001 From: yuyi Date: Mon, 5 Sep 2022 22:16:28 +0800 Subject: [PATCH] checker, cgen: fix go call fn using map value (#15665) --- vlib/v/checker/fn.v | 6 ++++++ vlib/v/gen/c/fn.v | 11 +++++++++++ vlib/v/tests/go_call_fn_using_map_value_test.v | 16 ++++++++++++++++ 3 files changed, 33 insertions(+) create mode 100644 vlib/v/tests/go_call_fn_using_map_value_test.v diff --git a/vlib/v/checker/fn.v b/vlib/v/checker/fn.v index 8a65f20d4..0806fa9fb 100644 --- a/vlib/v/checker/fn.v +++ b/vlib/v/checker/fn.v @@ -617,6 +617,8 @@ pub fn (mut c Checker) fn_call(mut node ast.CallExpr, mut continue_check &bool) if elem_sym.info is ast.FnType { func = elem_sym.info.func found = true + node.is_fn_var = true + node.fn_var_type = sym.info.elem_type } else { c.error('cannot call the element of the array, it is not a function', node.pos) @@ -626,6 +628,8 @@ pub fn (mut c Checker) fn_call(mut node ast.CallExpr, mut continue_check &bool) if value_sym.info is ast.FnType { func = value_sym.info.func found = true + node.is_fn_var = true + node.fn_var_type = sym.info.value_type } else { c.error('cannot call the value of the map, it is not a function', node.pos) } @@ -634,6 +638,8 @@ pub fn (mut c Checker) fn_call(mut node ast.CallExpr, mut continue_check &bool) if elem_sym.info is ast.FnType { func = elem_sym.info.func found = true + node.is_fn_var = true + node.fn_var_type = sym.info.elem_type } else { c.error('cannot call the element of the array, it is not a function', node.pos) diff --git a/vlib/v/gen/c/fn.v b/vlib/v/gen/c/fn.v index 51395438e..e59009ec0 100644 --- a/vlib/v/gen/c/fn.v +++ b/vlib/v/gen/c/fn.v @@ -1722,6 +1722,17 @@ fn (mut g Gen) go_expr(node ast.GoExpr) { g.gen_anon_fn_decl(mut expr.left) name = expr.left.decl.name } + } else if expr.left is ast.IndexExpr { + if expr.is_fn_var { + fn_sym := g.table.sym(expr.fn_var_type) + func := (fn_sym.info as ast.FnType).func + fn_var := g.fn_var_signature(func.return_type, func.params.map(it.typ), tmp_fn) + g.write('\t$fn_var = ') + g.expr(expr.left) + g.writeln(';') + name = fn_sym.cname + use_tmp_fn_var = true + } } name = util.no_dots(name) if g.pref.obfuscate && g.cur_mod.name == 'main' && name.starts_with('main__') { diff --git a/vlib/v/tests/go_call_fn_using_map_value_test.v b/vlib/v/tests/go_call_fn_using_map_value_test.v new file mode 100644 index 000000000..63c3ad8b3 --- /dev/null +++ b/vlib/v/tests/go_call_fn_using_map_value_test.v @@ -0,0 +1,16 @@ +module main + +fn test_go_call_fn_using_map_value() { + sum := fn (x int, y int) int { + return x + y + } + + mut fns := map[string]fn (int, int) int{} + fns['sum'] = sum + + g := go fns['sum'](2, 3) + x := g.wait() + + println('$x') + assert x == 5 +} -- 2.30.2