Commit 48a64b36

48a64b36ca62Merged

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

Description

Add M19: empty-array element-type promotion from usage

An empty [] literal no longer pins a poly type; instead the variable's element type is inferred from a << x / a.push(x) / a[i] = x usage (folded into the write-inference recompute frame so it survives the fixpoint reset). a = [] then emits sp_Array_new() for the resolved element type. Guarded so a string local's << (append) doesn't get misread as array push.

make test: 19 (no regression; unblocks the common build-empty-then-push pattern).

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

Details

Commit
48a64b36ca62
Parent
cb3f6762fc1f

src/analyze.cmodifiedView file

@@ -303,7 +303,7 @@
303303 if (!strcmp(ty, "ArrayNode")) {
304304 int n = 0;
305305 const int *els = nt_arr(nt, id, "elements", &n);
306- if (n == 0) return TY_POLY_ARRAY;
306+ if (n == 0) return TY_UNKNOWN; /* empty: element type comes from usage */
307307 TyKind e = TY_UNKNOWN;
308308 for (int k = 0; k < n; k++) e = ty_unify(e, infer_type(c, els[k]));
309309 return ty_array_of(e);
@@ -628,6 +628,34 @@
628628 lv->type = ty_unify(lv->type, newt);
629629 }
630630
631+ /* Fold container usage into the local type: `a << x` / `a.push(x)` /
632+ `a[i] = x` on a local `a` promotes it to an array of x's type (this is
633+ how an empty `[]` gets its element type). Part of the same recompute
634+ frame so it survives the reset and the change check stays consistent. */
635+ for (int id = 0; id < nt->count; id++) {
636+ const char *ty = nt_type(nt, id);
637+ if (!ty || strcmp(ty, "CallNode")) continue;
638+ int recv = nt_ref(nt, id, "receiver");
639+ if (recv < 0 || strcmp(nt_type(nt, recv) ? nt_type(nt, recv) : "", "LocalVariableReadNode")) continue;
640+ const char *name = nt_str(nt, id, "name");
641+ if (!name) continue;
642+ int args = nt_ref(nt, id, "arguments");
643+ int an = 0;
644+ const int *argv = args >= 0 ? nt_arr(nt, args, "arguments", &an) : NULL;
645+ TyKind elem = TY_UNKNOWN;
646+ if ((!strcmp(name, "push") || !strcmp(name, "<<")) && an == 1) elem = infer_type(c, argv[0]);
647+ else if (!strcmp(name, "[]=") && an == 2) elem = infer_type(c, argv[1]);
648+ else continue;
649+ if (elem == TY_UNKNOWN) continue;
650+ const char *rnm = nt_str(nt, recv, "name");
651+ LocalVar *lv = rnm ? scope_local(comp_scope_of(c, recv), rnm) : NULL;
652+ if (!lv || lv->is_param || lv->is_block_param) continue;
653+ /* only promote a container local: a known string uses `<<` for append,
654+ not array push -- don't pollute it */
655+ if (lv->type != TY_UNKNOWN && !ty_is_array(lv->type)) continue;
656+ lv->type = ty_unify(lv->type, ty_array_of(elem));
657+ }
658+
631659 /* detect change vs the stashed old types */
632660 for (int s = 0; s < c->nscopes; s++)
633661 for (int i = 0; i < c->scopes[s].nlocals; i++) {