Commit 3ef414b9

3ef414b9109fMerged

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

Description

analyze: fix array-param type inference when [] read causes premature hash promotion

Three related fixes for the case where a local variable x = [] is passed to a method param buf, the body uses buf.push(v), but x[i] (read) appears in the caller -- the body-usage pass promotes x to TY_POLY_POLY_HASH before the push can narrow it to an array.

  1. infer_array_params: fire even when the param already has a hash type (push wins over [] read promotion).

  2. Backstop for empty-array locals: also reset hash-typed locals to TY_POLY_ARRAY when their only write is an empty array literal.

  3. Post-fixpoint mini-loop: include infer_write_types so locals whose types derive from function return types get updated after param promotion.

Co-Authored-By: Claude Sonnet 4.6 [email protected]

Details

Commit
3ef414b9109f
Parent
d426578de4e9

src/analyze.cmodifiedView file

@@ -3181,7 +3181,9 @@
31813181 if (!rty || strcmp(rty, "LocalVariableReadNode")) continue;
31823182 Scope *s = comp_scope_of(c, id);
31833183 LocalVar *lv = scope_local(s, nt_str(nt, recv, "name"));
3184- if (lv && lv->is_param && lv->type == TY_UNKNOWN) { lv->type = TY_POLY_ARRAY; changed = 1; }
3184+ /* If caller-side [] read already widened this param to a hash type,
3185+ push wins: a param that receives push() is an array, not a hash. */
3186+ if (lv && lv->is_param && (lv->type == TY_UNKNOWN || ty_is_hash(lv->type))) { lv->type = TY_POLY_ARRAY; changed = 1; }
31853187 }
31863188 return changed;
31873189 }
@@ -4415,7 +4417,10 @@
44154417 const char *nm = nt_str(c->nt, id, "name");
44164418 Scope *s = comp_scope_of(c, id);
44174419 LocalVar *lv = nm ? scope_local(s, nm) : NULL;
4418- if (lv && lv->type == TY_UNKNOWN) lv->type = TY_POLY_ARRAY;
4420+ /* Also reset any hash type that crept in via premature [] read
4421+ promotion: a variable whose only write is an empty array literal
4422+ is definitively an array, not a hash. */
4423+ if (lv && (lv->type == TY_UNKNOWN || ty_is_hash(lv->type))) lv->type = TY_POLY_ARRAY;
44194424 }
44204425 /* A read-only ivar (referenced but never assigned a typed value) stays
44214426 TY_UNKNOWN -> it has no C type. Such a slot always reads nil at runtime;
@@ -4441,6 +4446,10 @@
44414446 int ch = 0;
44424447 ch |= infer_param_types(c);
44434448 ch |= infer_return_types(c);
4449+ /* Re-run write-type inference so locals whose types derive from
4450+ function return types (e.g. `x = f([])` after `f`'s param was
4451+ promoted from UNKNOWN to POLY_ARRAY) get updated. */
4452+ ch |= infer_write_types(c);
44444453 if (!ch) break;
44454454 }
44464455 }