Commit a44faa17

a44faa176822Merged

Yasuhiro Matsumoto <[email protected]> · 5 months ago · 1 file · ~1 modified

Description

analyze: widen a hash literal's type to its destination variable

{ begin: ... } infers SymPolyHash, but dic is promoted to POLY_POLY_HASH by a later mixed-key write. Codegen emitted the literal from its own type, so sp_SymPolyHash_new was assigned to a sp_PolyPolyHash * -- corrupting the hash at runtime. Reconcile after the fixpoint so the literal uses the variable's type.

Details

Commit
a44faa176822
Parent
5914c9e1bef6

src/analyze.cmodifiedView file

@@ -2327,5 +2327,48 @@
23272327 TyKind lt = comp_ntype(c, st[n - 1]);
23282328 if (ty_is_object(lt)) { int q = ty_object_class(lt); if (q >= 0 && q < c->nclasses) c->classes[q].is_value_type = 0; }
23292329 }
2330+
2331+ /* Reconcile a hash literal's node type with the variable it initializes.
2332+ A literal like `{ begin: ... }` infers a narrow variant (SYM_POLY_HASH)
2333+ from its own keys, but the variable may later be promoted to a wider hash
2334+ (e.g. POLY_POLY_HASH from a mixed-key `dic[sym_or_int] = ...`). Codegen
2335+ emits the literal from its own node type, so without this the constructor
2336+ (sp_SymPolyHash_new) disagrees with the variable's declared C type
2337+ (sp_PolyPolyHash *) -- an incompatible-pointer assignment that corrupts
2338+ the hash at runtime. Align the literal to the variable's type so the right
2339+ constructor and key/value boxing are emitted. Widen only (the variable
2340+ type is the union over all writes, so it is never narrower). */
2341+ for (int id = 0; id < c->nt->count; id++) {
2342+ const char *ty = nt_type(c->nt, id);
2343+ if (!ty) continue;
2344+ int is_lv = !strcmp(ty, "LocalVariableWriteNode");
2345+ int is_iv = !strcmp(ty, "InstanceVariableWriteNode");
2346+ if (!is_lv && !is_iv) continue;
2347+ int v = nt_ref(c->nt, id, "value");
2348+ if (v < 0) continue;
2349+ const char *vty = nt_type(c->nt, v);
2350+ if (!vty || (strcmp(vty, "HashNode") && strcmp(vty, "KeywordHashNode"))) continue;
2351+ TyKind litt = c->ntype[v];
2352+ if (!ty_is_hash(litt)) continue;
2353+ const char *nm = nt_str(c->nt, id, "name");
2354+ if (!nm) continue;
2355+ TyKind dstt = TY_UNKNOWN;
2356+ if (is_lv) {
2357+ Scope *s = comp_scope_of(c, id);
2358+ LocalVar *lv = s ? scope_local(s, nm) : NULL;
2359+ if (lv) dstt = lv->type;
2360+ } else {
2361+ Scope *s = comp_scope_of(c, id);
2362+ if (s && s->class_id >= 0) {
2363+ int iv = comp_ivar_index(&c->classes[s->class_id], nm);
2364+ if (iv >= 0) dstt = c->classes[s->class_id].ivar_types[iv];
2365+ }
2366+ }
2367+ /* Only widen toward POLY_POLY_HASH, the universally-boxed variant whose
2368+ constructor accepts any keys/values -- a safe target for any narrower
2369+ literal. Other cross-variant widenings are left alone. */
2370+ if (dstt == TY_POLY_POLY_HASH && litt != TY_POLY_POLY_HASH)
2371+ c->ntype[v] = dstt;
2372+ }
23302373 }
23312374