Commit 649feee0

649feee0e99fMerged

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

Description

fix(analyze,codegen): raise ... unless x.is_a?(C) narrows x for rest of scope

Sam Ruby's #493 proposal: raise ... unless x.is_a?(C) and the equivalent if !x.is_a?(C); raise ...; end are definite-throw type assertions. After such a statement, control only flows when the predicate held, so x is provably of class C for the rest of the enclosing scope. Spinel previously emitted the runtime check correctly but didn't carry the narrow forward -- field access on x after the guard fell into the full cls_id-switch over every class that declared the same field name, inflating binary size and producing dispatch noise that breaks under unrelated additions elsewhere in the program.

This change makes the narrow stack sibling-scoped for raise-guard statements: pushed at the statement that contains the guard, popped at the end of the enclosing StatementsNode. The push/pop asymmetry vs. the existing if-arm narrows (matched per-arm) is the non-trivial part.

Implementation:

  • spinel_analyze.rb: new helpers body_definitely_raises? and parse_raise_guard_narrow recognize UnlessNode whose body raises and IfNode whose negated !is_a? predicate gates a raising body. Three body-walker call sites (scan_new_calls, collect_return_types_nid, scan_cls_method_calls) push the narrow at each guard stmt in their stmts loop and pop them all after the loop. Callee param widening from post-guard sibling calls now sees x as the narrowed type via the existing find_var_type narrow- first lookup.

  • spinel_codegen.rb: copies the same helpers (narrow_type_for_class / parse_is_a_predicate / body_definitely_raises? / parse_raise_guard_narrow) plus the missing push_type_narrow / pop_type_narrow wrappers (codegen had the narrow stack but no public push/pop). compile_body_return now wraps an inner _inner implementation with a baseline-and-cleanup pattern so the inner's many early-return paths leave the stack consistent without per- return pop calls. compile_call_expr casts the recv expr through .v.p when the receiver is a LocalVariableReadNode whose narrowed type is obj_<C> but declared type is poly -- the underlying storage is still sp_RbVal so the call site has to unbox before reading struct fields. infer_type adds a pre-cache narrow-aware arm that resolves LV(narrowed).attr_reader_name directly to the narrowed class's ivar type, bypassing the stale @nd_inferred_type cache that was filled by analyze before the narrow was active.

Scope notes:

  • Only is_a? / kind_of? predicates are recognized (the existing parse_is_a_predicate handles both). nil?-based guards (raise ... if x.nil?) follow the same shape but aren't part of this change.
  • The body must terminate in a raise call. Bodies that raise inside nested control flow (unless cond; if other; raise; end; end) leave the narrow stack alone -- conservative.
  • IfNode guards require no else / elsif chain; an else branch means fall-through doesn't imply the predicate held.

Test (test/raise_unless_isa_narrow.rb): exercises both spellings plus a two-guard sequence that accumulates narrows. Verified the emit shape (single cls_id arm, direct struct-field access) matches the issue's "desired output" via spinel ... -S.

Closes #493

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

Details

Commit
649feee0e99f
Parent
880d7270f2c0

spinel_analyze.rbmodifiedView file

@@ -1336,6 +1336,87 @@
13361336 # and the argument is a constant naming a known class. Returns
13371337 # `["", ""]` if the predicate isn't a narrowable shape (the empty
13381338 # var name is the sentinel; the caller skips the push).
1339+ # Returns 1 if `body_id` is a body whose statements always raise
1340+ # (every reachable tail is a `raise ...` call). The simple form
1341+ # is a single-statement body whose statement is `raise ...`;
1342+ # we treat that as the canonical "definite throw" shape and
1343+ # leave more complex shapes (raise inside nested if/case) to a
1344+ # future extension. Issue #493.
1345+ def body_definitely_raises?(body_id)
1346+ if body_id < 0
1347+ return 0
1348+ end
1349+ stmts_r = get_stmts(body_id)
1350+ if stmts_r.length == 0
1351+ return 0
1352+ end
1353+ # Multi-statement bodies: check the LAST stmt for the raise.
1354+ # CRuby's semantics treat the body as definitely-throwing iff
1355+ # the tail throws; earlier statements may do bookkeeping
1356+ # before the raise (logger.error, etc.).
1357+ last = stmts_r[stmts_r.length - 1]
1358+ if @nd_type[last] != "CallNode"
1359+ return 0
1360+ end
1361+ if @nd_name[last] != "raise"
1362+ return 0
1363+ end
1364+ 1
1365+ end
1366+
1367+ # Decode `raise ... unless x.is_a?(C)` / `if !x.is_a?(C); raise; end`
1368+ # / `raise ... if !x.is_a?(C)` into `(var_name, narrow_type)`. After
1369+ # such a guard, the rest of the enclosing scope can assume `x` is
1370+ # of class `C` (the raise eliminated the other path). Returns
1371+ # `["", ""]` for non-guard statements. Used by the body-walker
1372+ # in scan_new_calls / collect_return_types_nid /
1373+ # scan_cls_method_calls (and the codegen-side body walkers) to
1374+ # push a sibling-scope narrow for the statements that follow.
1375+ # Issue #493.
1376+ def parse_raise_guard_narrow(nid)
1377+ if nid < 0
1378+ return ["", ""]
1379+ end
1380+ t = @nd_type[nid]
1381+ if t == "UnlessNode"
1382+ # `raise ... unless x.is_a?(C)`: body fires when predicate is
1383+ # false. Fall-through assumes `x.is_a?(C)` is true.
1384+ body_u = @nd_body[nid]
1385+ if body_definitely_raises?(body_u) == 0
1386+ return ["", ""]
1387+ end
1388+ return parse_is_a_predicate(@nd_predicate[nid])
1389+ end
1390+ if t == "IfNode"
1391+ # `raise ... if !x.is_a?(C)` and `if !x.is_a?(C); raise; end`:
1392+ # body fires when the negated predicate is true (so x is NOT
1393+ # of class C). Fall-through assumes x IS of class C. Peel one
1394+ # level of `!` off the predicate before reusing
1395+ # parse_is_a_predicate.
1396+ pred_i = @nd_predicate[nid]
1397+ if pred_i < 0 || @nd_type[pred_i] != "CallNode" || @nd_name[pred_i] != "!"
1398+ return ["", ""]
1399+ end
1400+ inner_i = @nd_receiver[pred_i]
1401+ if inner_i < 0
1402+ return ["", ""]
1403+ end
1404+ body_i = @nd_body[nid]
1405+ if body_definitely_raises?(body_i) == 0
1406+ return ["", ""]
1407+ end
1408+ sub_i = @nd_subsequent[nid]
1409+ else_i = @nd_else_clause[nid]
1410+ if sub_i >= 0 || else_i >= 0
1411+ # Has an else clause — falling through doesn't necessarily
1412+ # mean the predicate was true (the else might run). Skip.
1413+ return ["", ""]
1414+ end
1415+ return parse_is_a_predicate(inner_i)
1416+ end
1417+ ["", ""]
1418+ end
1419+
13391420 def parse_is_a_predicate(pred_id)
13401421 if pred_id < 0
13411422 return ["", ""]
@@ -11155,11 +11236,28 @@
1115511236 scan_new_calls(@nd_body[nid])
1115611237 end
1115711238 stmts = parse_id_list(@nd_stmts[nid])
11239+ # Sibling-scope narrow for `raise ... unless x.is_a?(C)` guards.
11240+ # When stmts[k] is a definite-throw guard, push the narrow
11241+ # before walking siblings k+1..N so any recursive call inside
11242+ # those siblings sees `x` as the narrowed type (and
11243+ # unify_call_types widens the callee's param accordingly).
11244+ # The narrow is asymmetric vs. the if-arm shape: pushed at
11245+ # stmts[k], popped at end-of-StatementsNode. Issue #493.
11246+ pushed_raise_guards_snc = 0
1115811247 k = 0
1115911248 while k < stmts.length
1116011249 scan_new_calls(stmts[k])
11250+ rg_p = parse_raise_guard_narrow(stmts[k])
11251+ if rg_p[0] != ""
11252+ push_type_narrow(rg_p[0], rg_p[1])
11253+ pushed_raise_guards_snc = pushed_raise_guards_snc + 1
11254+ end
1116111255 k = k + 1
1116211256 end
11257+ while pushed_raise_guards_snc > 0
11258+ pop_type_narrow
11259+ pushed_raise_guards_snc = pushed_raise_guards_snc - 1
11260+ end
1116311261 if @nd_receiver[nid] >= 0
1116411262 scan_new_calls(@nd_receiver[nid])
1116511263 end
@@ -15562,11 +15660,25 @@
1556215660
1556315661 def collect_return_types_nid(nid, types)
1556415662 stmts = get_stmts(nid)
15663+ # Sibling-scope narrow for `raise unless x.is_a?(C)` guards, so
15664+ # a `return v` inside a sibling sees the narrowed type and the
15665+ # return-unify uses the narrow instead of the wider underlying
15666+ # poly param. Mirrors scan_new_calls' stmts loop. Issue #493.
15667+ pushed_raise_guards_crt = 0
1556515668 k = 0
1556615669 while k < stmts.length
1556715670 collect_return_types(stmts[k], types)
15671+ rg_p = parse_raise_guard_narrow(stmts[k])
15672+ if rg_p[0] != ""
15673+ push_type_narrow(rg_p[0], rg_p[1])
15674+ pushed_raise_guards_crt = pushed_raise_guards_crt + 1
15675+ end
1556815676 k = k + 1
1556915677 end
15678+ while pushed_raise_guards_crt > 0
15679+ pop_type_narrow
15680+ pushed_raise_guards_crt = pushed_raise_guards_crt - 1
15681+ end
1557015682 end
1557115683
1557215684 def collect_return_types(nid, types)
@@ -17513,11 +17625,23 @@
1751317625 scan_cls_method_calls(ci, @nd_body[nid])
1751417626 end
1751517627 stmts = parse_id_list(@nd_stmts[nid])
17628+ # Sibling-scope narrow for `raise unless x.is_a?(C)` guards.
17629+ # Same shape as scan_new_calls' stmts loop. Issue #493.
17630+ pushed_raise_guards_scm = 0
1751617631 k = 0
1751717632 while k < stmts.length
1751817633 scan_cls_method_calls(ci, stmts[k])
17634+ rg_p = parse_raise_guard_narrow(stmts[k])
17635+ if rg_p[0] != ""
17636+ push_type_narrow(rg_p[0], rg_p[1])
17637+ pushed_raise_guards_scm = pushed_raise_guards_scm + 1
17638+ end
1751917639 k = k + 1
1752017640 end
17641+ while pushed_raise_guards_scm > 0
17642+ pop_type_narrow
17643+ pushed_raise_guards_scm = pushed_raise_guards_scm - 1
17644+ end
1752117645 if @nd_receiver[nid] >= 0
1752217646 scan_cls_method_calls(ci, @nd_receiver[nid])
1752317647 end