Commit 5253b803
5253b8031cf9Merged
Yukihiro "Matz" Matsumoto <[email protected]> · 5 months ago · 1 file · ~1 modified
Description
Make Array#dup / #clone copy instead of aliasing
The identity-method shortcut returned the receiver itself for dup/clone
on arrays, so b = a.dup; b << x mutated a too. The bug was masked
whenever the destination had a different array type (the type-converting
assignment copied), but a same-type dup aliased.
Exclude arrays (like hashes and strings) from the identity shortcut and add a real sp_*Array_dup arm for typed arrays in the array-method path.
make test 845, make bench 57, optcarrot checksum 59662 (fps unchanged).
Co-Authored-By: Claude Opus 4.8 (1M context) [email protected]
Details
- Commit
- 5253b8031cf9
- Parent
- cc697a74142a
src/codegen_call.cmodifiedView file
@@ -1593,10 +1593,13 @@
15931593
!strcmp(name, "dup") || !strcmp(name, "clone"))) {15941594
int args = nt_ref(nt, id, "arguments");15951595
int argc0 = 0; if (args >= 0) nt_arr(nt, args, "arguments", &argc0);1596-
/* hash and string dup/clone require deep copies -- skip the identity shortcut for them */1596+
/* hash, string, and array dup/clone require real copies (they are mutable1597+
reference types) -- skip the identity shortcut for them so the dedicated1598+
sp_*_dup paths run. freeze/itself on any value stay identity. */15971599
TyKind recv_t = recv >= 0 ? comp_ntype(c, recv) : TY_UNKNOWN;15981600
int is_dup_clone = !strcmp(name, "dup") || !strcmp(name, "clone");1599-
if (argc0 == 0 && !ty_is_hash(recv_t) && !(recv_t == TY_STRING && is_dup_clone)) {1601+
if (argc0 == 0 && !ty_is_hash(recv_t) &&1602+
!(is_dup_clone && (recv_t == TY_STRING || ty_is_array(recv_t)))) {16001603
emit_expr(c, recv, b); return;16011604
}16021605
if (argc0 == 0 && recv_t == TY_STRING && is_dup_clone) {@@ -6264,6 +6267,11 @@
62646267
return;62656268
}62666269
}6270+
if ((!strcmp(name, "dup") || !strcmp(name, "clone")) && argc == 0) {6271+
/* a real copy: arrays are mutable, so dup/clone must not alias. */6272+
buf_printf(b, "sp_%sArray_dup(", k); emit_expr(c, recv, b); buf_puts(b, ")");6273+
return;6274+
}62676275
if (!strcmp(name, "reverse") && argc == 0) {62686276
/* copy + reverse in place; sp_*Array_dup exists for Int/Str/Float/Poly */62696277
int t = ++g_tmp;