Commit f2ddceb9

f2ddceb91fdbMerged

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

Description

fix(analyze,codegen): propagate is_a? narrow into return-type unify

Proposal A from the post-#463 type-inference plan, discovered while introducing bm_jekyll_lite / bm_poly_cells / bm_micro_lisp. A function body like

def render_one(v) if v.is_a?(String) return v end if v.is_a?(Integer) return v.to_s end "?" end

inferred its return type as poly even though every return arm yielded a string. collect_return_types' IfNode walker recursed into the then-arm without pushing the is_a?(C) narrow, so return v saw v as its poly param type, not as the narrowed String. The unify then mixed string with poly and surfaced poly.

Analyze fix: collect_return_types' IfNode arm now mirrors scan_new_calls' narrow push/pop pair around the then-body walk (parse_is_a_predicate + push_type_narrow + pop_type_narrow).

Codegen mirror: compile_return_stmt routes the returned expression through compile_expr_for_expected_type whenever the function's declared return type is concrete but infer_type still reports the expression as poly. That helper already emits the matching .v. unbox (the same path called sites already use when passing an is_a?-narrowed local into a concrete-typed param slot), so return lv_v in a const char * function now lowers to return lv_v.v.s cleanly.

Measurement on the three new benchmarks: bm_jekyll_lite: returns 0 / 15 (unchanged, already clean) bm_poly_cells: returns 1 / 9 (was 2; render_one now const char*) bm_micro_lisp: returns 5 / 20 (unchanged; remaining are genuine Lisp-value polyvariance)

Tests: 434 pass, bench 55/55 pass, bootstrap 4-way fixpoint OK.

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

Details

Commit
f2ddceb91fdb
Parent
40a82ad99bce

spinel_analyze.rbmodifiedView file

@@ -14446,10 +14446,28 @@
1444614446 return
1444714447 end
1444814448 if @nd_type[nid] == "IfNode"
14449+ # Push the is_a?(C) narrow before walking the then-arm so a
14450+ # `return v` inside contributes the narrowed type (string when
14451+ # `v.is_a?(String)`, etc.) to the return unify instead of the
14452+ # underlying poly param type. Mirrors scan_new_calls and
14453+ # scan_cls_method_calls — without this push, infer_body_return
14454+ # widens functions like `def render_one(v); if v.is_a?(String);
14455+ # return v; end; ...; end` to poly even when every return arm
14456+ # contributes a single concrete type.
14457+ pred = @nd_predicate[nid]
14458+ parsed = parse_is_a_predicate(pred)
14459+ narrow_var = parsed[0]
14460+ narrow_t = parsed[1]
14461+ if narrow_var != ""
14462+ push_type_narrow(narrow_var, narrow_t)
14463+ end
1444914464 body = @nd_body[nid]
1445014465 if body >= 0
1445114466 collect_return_types_nid(body, types)
1445214467 end
14468+ if narrow_var != ""
14469+ pop_type_narrow
14470+ end
1445314471 sub = @nd_subsequent[nid]
1445414472 if sub >= 0
1445514473 collect_return_types(sub, types)