From c164586fd54d49daf77b105e685cf14b14fe2d8c Mon Sep 17 00:00:00 2001 From: Ned Palacios Date: Thu, 17 Dec 2020 15:44:50 +0800 Subject: [PATCH] cgen: fix map clone (#7366) --- vlib/builtin/map.v | 2 +- vlib/builtin/map_test.v | 14 ++++++++++++++ vlib/v/gen/fn.v | 3 +++ 3 files changed, 18 insertions(+), 1 deletion(-) diff --git a/vlib/builtin/map.v b/vlib/builtin/map.v index eb24abdae7..ff4098ef67 100644 --- a/vlib/builtin/map.v +++ b/vlib/builtin/map.v @@ -573,7 +573,7 @@ pub fn (d &DenseArray) clone() DenseArray { } [unsafe] -pub fn (m map) clone() map { +pub fn (m &map) clone() map { metasize := int(sizeof(u32) * (m.cap + 2 + m.extra_metas)) res := map{ key_bytes: m.key_bytes diff --git a/vlib/builtin/map_test.v b/vlib/builtin/map_test.v index f1b3395ce9..49e9c59974 100644 --- a/vlib/builtin/map_test.v +++ b/vlib/builtin/map_test.v @@ -426,3 +426,17 @@ fn test_modify_map_value() { assert m1['foo'] == 8 assert m1['bar'] == 14 } + +fn test_map_clone() { + mut nums := { + 'foo': 1, + 'bar': 2 + } + mut nums2 := nums.clone() + nums2['foo']++ + nums2['bar'] *= 4 + assert nums['foo'] == 1 + assert nums['bar'] == 2 + assert nums2['foo'] == 2 + assert nums2['bar'] == 8 +} diff --git a/vlib/v/gen/fn.v b/vlib/v/gen/fn.v index 0300ea9fb8..a20b505320 100644 --- a/vlib/v/gen/fn.v +++ b/vlib/v/gen/fn.v @@ -382,6 +382,9 @@ fn (mut g Gen) method_call(node ast.CallExpr) { g.gen_str_for_type(node.receiver_type) } mut has_cast := false + if left_sym.kind == .map && node.name == 'clone' { + receiver_type_name = 'map' + } // TODO performance, detect `array` method differently if left_sym.kind == .array && node.name in ['repeat', 'sort_with_compare', 'free', 'push_many', 'trim', 'first', 'last', 'pop', 'clone', 'reverse', 'slice'] {