Commit 2ddce70a

2ddce70a3d19Merged

Yukihiro "Matz" Matsumoto <[email protected]> · 5 months ago · 3 files · +2 added · ~1 modified

Description

codegen: keep the SymPolyHash arm in poly [] dispatch with a user-defined []

When any class defines an instance [], a [] send on a poly receiver falls out of the fast monomorphic path into the per-class cls_id switch (it must, to reach the user method). That switch carried builtin arms for an integer array index and for string-keyed hashes, but none for a symbol-keyed hash -- so indexing a Hash block param with a symbol (p[:name]) matched no case, fell through the switch, and yielded the pre-initialized nil. Defining one [] thus silently broke every arr.map { |p| p[:name] }.

Add the SP_BUILTIN_SYM_POLY_HASH arm (the sole symbol-keyed hash variant) to the [] / fetch dispatch, mirroring the existing string-keyed-hash arms: look the symbol key up via sp_SymPolyHash_get, unboxing to the result temp when the call site is typed narrower than poly.

Fixes #1437

Co-Authored-By: Claude Opus 4.8 (1M context) [email protected]

Details

Commit
2ddce70a3d19
Parent
5b1035c879cd

src/codegen_call.cmodifiedView file

@@ -5455,6 +5455,27 @@
54555455 buf_puts(b, "; break;");
54565456 }
54575457 }
5458+ /* a symbol-keyed hash (`{ name: ... }`) reaches here as SymPolyHash; add
5459+ its `[]` / `fetch` arm so a Hash receiver indexed by a symbol is not
5460+ dropped when a user class also defines an instance `[]` (#1437). */
5461+ if ((is_aref || is_fetch) && infer_type(c, argv[0]) == TY_SYMBOL) {
5462+ TyKind trt = is_scalar_ret(ret) ? ret : TY_INT;
5463+ char getx[200];
5464+ snprintf(getx, sizeof getx, "sp_SymPolyHash_get((sp_SymPolyHash *)_t%d.v.p, _t%d)", tv, atmp[0]);
5465+ buf_printf(b, " case SP_BUILTIN_SYM_POLY_HASH: _t%d = sp_SymPolyHash_has_key((sp_SymPolyHash *)_t%d.v.p, _t%d) ? ", tr, tv, atmp[0]);
5466+ if (ret == TY_POLY) buf_puts(b, getx);
5467+ else if (trt == TY_STRING) buf_printf(b, "sp_poly_to_s(%s)", getx);
5468+ else if (trt == TY_FLOAT) buf_printf(b, "sp_poly_to_f(%s)", getx);
5469+ else buf_printf(b, "sp_poly_to_i(%s)", getx);
5470+ buf_puts(b, " : ");
5471+ if (is_fetch && argc == 2) {
5472+ char dn[32]; snprintf(dn, sizeof dn, "_t%d", atmp[1]);
5473+ if (ret == TY_POLY) emit_boxed_text(c, infer_type(c, argv[1]), dn, b); else buf_puts(b, dn);
5474+ }
5475+ else if (is_fetch) { buf_puts(b, "(sp_raise_cls(\"KeyError\", \"key not found\"), "); buf_puts(b, ret == TY_POLY ? "sp_box_nil()" : default_value(trt)); buf_puts(b, ")"); }
5476+ else buf_puts(b, ret == TY_POLY ? "sp_box_nil()" : default_value(trt));
5477+ buf_puts(b, "; break;");
5478+ }
54585479 buf_printf(b, " } _t%d; })", tr);
54595480 free(atmp);
54605481 return;