From e40e1500a866cef6180492df024a7bc7990fa98b Mon Sep 17 00:00:00 2001 From: yuyi Date: Tue, 15 Dec 2020 23:07:24 +0800 Subject: [PATCH] cgen: fix map['xxx']() error (#7342) --- vlib/v/gen/cgen.v | 18 +++++++++++++----- ...call_test.v => fn_index_direct_call_test.v} | 12 ++++++++++++ 2 files changed, 25 insertions(+), 5 deletions(-) rename vlib/v/tests/{fn_array_direct_call_test.v => fn_index_direct_call_test.v} (54%) diff --git a/vlib/v/gen/cgen.v b/vlib/v/gen/cgen.v index b6d08ae62b..1e17a1883a 100644 --- a/vlib/v/gen/cgen.v +++ b/vlib/v/gen/cgen.v @@ -3765,14 +3765,14 @@ fn (mut g Gen) index_expr(node ast.IndexExpr) { if needs_clone { g.write('/*2*/string_clone(') } - if is_direct_array_access { - g.write('(($array_ptr_type_str)') - } else if g.is_fn_index_call { + if g.is_fn_index_call { if elem_typ.info is table.FnType { g.write('((') g.write_fn_ptr_decl(&elem_typ.info, '') g.write(')(*($array_ptr_type_str)/*ee elem_typ */array_get(') } + } else if is_direct_array_access { + g.write('(($array_ptr_type_str)') } else { g.write('(*($array_ptr_type_str)/*ee elem_typ */array_get(') if left_is_ptr && !node.left_type.has_flag(.shared_f) { @@ -3857,7 +3857,13 @@ fn (mut g Gen) index_expr(node ast.IndexExpr) { g.write(', &($elem_type_str[]){ $zero }))') } else { zero := g.type_default(info.value_type) - if elem_typ.kind == .function { + if g.is_fn_index_call { + if elem_typ.info is table.FnType { + g.write('((') + g.write_fn_ptr_decl(&elem_typ.info, '') + g.write(')(*(voidptr*)map_get(') + } + } else if elem_typ.kind == .function { g.write('(*(voidptr*)map_get(') } else { g.write('(*($elem_type_str*)map_get(') @@ -3875,7 +3881,9 @@ fn (mut g Gen) index_expr(node ast.IndexExpr) { } g.write(', ') g.expr(node.index) - if elem_typ.kind == .function { + if g.is_fn_index_call { + g.write(', &(voidptr[]){ $zero })))') + } else if elem_typ.kind == .function { g.write(', &(voidptr[]){ $zero }))') } else { g.write(', &($elem_type_str[]){ $zero }))') diff --git a/vlib/v/tests/fn_array_direct_call_test.v b/vlib/v/tests/fn_index_direct_call_test.v similarity index 54% rename from vlib/v/tests/fn_array_direct_call_test.v rename to vlib/v/tests/fn_index_direct_call_test.v index 501167ec4f..ab0b26f8d5 100644 --- a/vlib/v/tests/fn_array_direct_call_test.v +++ b/vlib/v/tests/fn_index_direct_call_test.v @@ -13,5 +13,17 @@ fn test_fn_array_direct_call() { return false } + println(fs.array_of_fn[0](1, &Placeholder{name: 'Bob'}, 'Builder')) assert fs.array_of_fn[0](1, &Placeholder{name: 'Bob'}, 'Builder') == false } + +fn test_fn_map_direct_call() { + a := { + 'aaa': fn()string {return 'aaa'}, + 'bbb': fn()string {return 'bbb'}, + } + println(a['aaa']()) + println(a['bbb']()) + assert a['aaa']() == 'aaa' + assert a['bbb']() == 'bbb' +}