From 51f2eb81f4bd7bdda6133482b946c3213257124f Mon Sep 17 00:00:00 2001 From: Ruofan XU <47302112+SleepyRoy@users.noreply.github.com> Date: Tue, 2 Feb 2021 03:10:24 +0800 Subject: [PATCH] checker/cgen: fix mut array of fn as argument (#8469) --- vlib/v/checker/check_types.v | 2 +- vlib/v/gen/cgen.v | 3 +++ vlib/v/tests/map_and_array_with_fns_test.v | 20 ++++++++++++++++++++ 3 files changed, 24 insertions(+), 1 deletion(-) diff --git a/vlib/v/checker/check_types.v b/vlib/v/checker/check_types.v index 0bc1f3a6c8..977fee4560 100644 --- a/vlib/v/checker/check_types.v +++ b/vlib/v/checker/check_types.v @@ -87,7 +87,7 @@ pub fn (mut c Checker) check_basic(got table.Type, expected table.Type) bool { } // array fn if got_type_sym.kind == .array && exp_type_sym.kind == .array { - if c.table.type_to_str(got) == c.table.type_to_str(expected) { + if c.table.type_to_str(got) == c.table.type_to_str(expected).trim('&') { return true } } diff --git a/vlib/v/gen/cgen.v b/vlib/v/gen/cgen.v index 1f7d9b03d3..63c06b9d4e 100644 --- a/vlib/v/gen/cgen.v +++ b/vlib/v/gen/cgen.v @@ -4138,6 +4138,9 @@ fn (mut g Gen) index_expr(node ast.IndexExpr) { g.write_fn_ptr_decl(&elem_typ.info, '') g.write(')(*($array_ptr_type_str)/*ee elem_typ */array_get(') } + if left_is_ptr && !node.left_type.has_flag(.shared_f) { + g.write('*') + } } else if is_direct_array_access { g.write('(($array_ptr_type_str)') } else { diff --git a/vlib/v/tests/map_and_array_with_fns_test.v b/vlib/v/tests/map_and_array_with_fns_test.v index 815d229fdc..a7841f19a5 100644 --- a/vlib/v/tests/map_and_array_with_fns_test.v +++ b/vlib/v/tests/map_and_array_with_fns_test.v @@ -62,6 +62,10 @@ fn foo3(a string) int { return 10 + a.len } +fn foo4(a string) int { + return 20 + a.len +} + fn test_map_and_array_with_fns_typeof_and_direct_call() { a := [foo3] assert typeof(a).name == '[]fn (string) int' @@ -71,3 +75,19 @@ fn test_map_and_array_with_fns_typeof_and_direct_call() { // TODO: enable this // assert b['one']('hi') == 12 } + +fn bar1(mut a []fn (string) int) int { + a[0] = foo4 + return a[0]('hello') +} + +fn bar2(a []fn (string) int) int { + return a[0]('hello') +} + +fn test_array_of_fns_as_argument() { + mut a1 := [foo3] + assert bar1(mut a1) == 25 + a2 := [foo3] + assert bar2(a2) == 15 +}