cgen: fix map clone (#7366)

pull/7371/head
Ned Palacios 2020-12-17 15:44:50 +08:00 committed by GitHub
parent 8addb31440
commit c164586fd5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 18 additions and 1 deletions

View File

@ -573,7 +573,7 @@ pub fn (d &DenseArray) clone() DenseArray {
} }
[unsafe] [unsafe]
pub fn (m map) clone() map { pub fn (m &map) clone() map {
metasize := int(sizeof(u32) * (m.cap + 2 + m.extra_metas)) metasize := int(sizeof(u32) * (m.cap + 2 + m.extra_metas))
res := map{ res := map{
key_bytes: m.key_bytes key_bytes: m.key_bytes

View File

@ -426,3 +426,17 @@ fn test_modify_map_value() {
assert m1['foo'] == 8 assert m1['foo'] == 8
assert m1['bar'] == 14 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
}

View File

@ -382,6 +382,9 @@ fn (mut g Gen) method_call(node ast.CallExpr) {
g.gen_str_for_type(node.receiver_type) g.gen_str_for_type(node.receiver_type)
} }
mut has_cast := false mut has_cast := false
if left_sym.kind == .map && node.name == 'clone' {
receiver_type_name = 'map'
}
// TODO performance, detect `array` method differently // TODO performance, detect `array` method differently
if left_sym.kind == .array && node.name in if left_sym.kind == .array && node.name in
['repeat', 'sort_with_compare', 'free', 'push_many', 'trim', 'first', 'last', 'pop', 'clone', 'reverse', 'slice'] { ['repeat', 'sort_with_compare', 'free', 'push_many', 'trim', 'first', 'last', 'pop', 'clone', 'reverse', 'slice'] {