Commit b047f1a8

b047f1a8c88cMerged

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

Description

fix(analyze,codegen): narrow int|nil locals to int after return-on-nil guard

Mirror of d3ee2b2 (#493) for the nil-vs-not case. After return X if h.nil? (or raise X if h.nil?), the rest of the enclosing scope sees h as non-nil. For a local whose most recent writer was a known int-or-nil source (String#index, rindex, find_index), the non-nil arm is mrb_int; pin the narrow type to int.

Triggered by the 0210389 String#index return-type change. Tep collected ~18 s.index(needle) callsites that all started widening downstream locals to sp_RbVal; Ori Pekelman's workaround was a pure-int Tep.str_find helper. The narrow restores the idiomatic shape:

def find_or_neg(s, needle) h = s.index(needle) return -1 if h.nil? h + 1 end

Pre-fix: find_or_neg returns sp_RbVal; h + 1 lowers via sp_poly_add and boxes the result.

Post-fix: find_or_neg returns mrb_int; h + 1 lowers as (lv_h).v.i + 1LL (the narrow detects the declared-poly / narrow-int mismatch at the LocalVariableReadNode emit and inserts an explicit unbox).

Three pieces:

  1. parse_nil_guard_var (analyze + codegen) recognizes return X if h.nil? / raise X if h.nil? and returns the LV name; scan_back_writer_narrow_for walks the preceding statements to find h's writer and infer the narrow type from the writer's source call.

  2. The 3 analyze body-walker call sites (scan_new_calls, collect_return_types_nid, scan_cls_method_calls) plus infer_body_return push the narrow after each guard, so callee param widening AND implicit-return inference both see the narrowed type.

  3. compile_expr's LocalVariableReadNode emit (codegen) unboxes via .v.i when the declared C type is sp_RbVal but the active narrow says int. Existing #493 obj_ narrows over poly locals are unaffected (they route through the dispatch-level paths).

The two helpers (parse_nil_guard_var + scan_back_writer_narrow_for) return scalars instead of one combined [var, narrow_type] array on purpose: spinel-self's iterative inference widens an array-return into poly_array at some iteration order, and the cascade reaches push_type_narrow's param signature; once widened, sp_StrArray_push inside push_type_narrow's body fails to compile because it expects const char *. Keeping the helpers scalar avoids the array-element widening path.

Closes #550

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

Details

Commit
b047f1a8c88c
Parent
483fd088b459

spinel_analyze.rbmodifiedView file

@@ -1416,6 +1416,112 @@
14161416 ["", ""]
14171417 end
14181418
1419+ # `<lv>.nil?` predicate. Returns the LV name; otherwise "".
1420+ def parse_nil_predicate(pred_id)
1421+ if pred_id < 0
1422+ return ""
1423+ end
1424+ if @nd_type[pred_id] != "CallNode"
1425+ return ""
1426+ end
1427+ if @nd_name[pred_id] != "nil?"
1428+ return ""
1429+ end
1430+ recv = @nd_receiver[pred_id]
1431+ if recv < 0 || @nd_type[recv] != "LocalVariableReadNode"
1432+ return ""
1433+ end
1434+ @nd_name[recv]
1435+ end
1436+
1437+ # Body is a single `return ...` or single `raise ...`. Used by
1438+ # the nil-guard narrow (issue #550) to identify scope-exiting
1439+ # bodies that mirror the raise-guard shape.
1440+ def body_definitely_exits?(body_id)
1441+ if body_id < 0
1442+ return 0
1443+ end
1444+ stmts_r = get_stmts(body_id)
1445+ if stmts_r.length == 0
1446+ return 0
1447+ end
1448+ last = stmts_r[stmts_r.length - 1]
1449+ if @nd_type[last] == "ReturnNode"
1450+ return 1
1451+ end
1452+ if @nd_type[last] == "CallNode" && @nd_name[last] == "raise"
1453+ return 1
1454+ end
1455+ 0
1456+ end
1457+
1458+ # Given the rhs of the most recent write to a local variable
1459+ # whose nil? was just checked, return the type the variable
1460+ # narrows to after the nil-exit. Currently recognizes
1461+ # `<string>.index(needle)` (and rindex / find_index) returning
1462+ # int-or-nil; the non-nil arm is mrb_int. Returns "" when the
1463+ # writer's shape isn't a known int-or-nil source so the caller
1464+ # leaves the type alone. Issue #550.
1465+ def infer_nil_guard_narrow_type(expr_id)
1466+ if expr_id < 0
1467+ return ""
1468+ end
1469+ if @nd_type[expr_id] != "CallNode"
1470+ return ""
1471+ end
1472+ mname_eg = @nd_name[expr_id]
1473+ if mname_eg != "index" && mname_eg != "rindex" && mname_eg != "find_index"
1474+ return ""
1475+ end
1476+ recv_eg = @nd_receiver[expr_id]
1477+ if recv_eg < 0
1478+ return ""
1479+ end
1480+ rt_eg = infer_type(recv_eg)
1481+ if rt_eg == "string" || rt_eg == "mutable_str"
1482+ return "int"
1483+ end
1484+ ""
1485+ end
1486+
1487+ # Recognize `return X if h.nil?` shape; return the LV name or
1488+ # "". Caller threads the stmt list separately into
1489+ # scan_back_writer_narrow_for to derive the narrow type. (Two
1490+ # separate calls instead of one [var, type] return because
1491+ # spinel-self's inference widens an array-return into poly,
1492+ # cascading into push_type_narrow's param signature.)
1493+ # Issue #550.
1494+ def parse_nil_guard_var(nid)
1495+ if nid < 0
1496+ return ""
1497+ end
1498+ if @nd_type[nid] != "IfNode"
1499+ return ""
1500+ end
1501+ body_i = @nd_body[nid]
1502+ if body_definitely_exits?(body_i) == 0
1503+ return ""
1504+ end
1505+ sub_i = @nd_subsequent[nid]
1506+ else_i = @nd_else_clause[nid]
1507+ if sub_i >= 0 || else_i >= 0
1508+ return ""
1509+ end
1510+ parse_nil_predicate(@nd_predicate[nid])
1511+ end
1512+
1513+ def scan_back_writer_narrow_for(stmts_list, before_idx, varname)
1514+ j = before_idx - 1
1515+ while j >= 0
1516+ stmt = stmts_list[j]
1517+ if @nd_type[stmt] == "LocalVariableWriteNode" && @nd_name[stmt] == varname
1518+ return infer_nil_guard_narrow_type(@nd_expression[stmt])
1519+ end
1520+ j = j - 1
1521+ end
1522+ ""
1523+ end
1524+
14191525 def parse_is_a_predicate(pred_id)
14201526 if pred_id < 0
14211527 return ["", ""]
@@ -11287,6 +11393,14 @@
1128711393 push_type_narrow(rg_p[0], rg_p[1])
1128811394 pushed_raise_guards_snc = pushed_raise_guards_snc + 1
1128911395 end
11396+ ng_var_snc = parse_nil_guard_var(stmts[k])
11397+ if ng_var_snc != ""
11398+ ng_narrow_snc = scan_back_writer_narrow_for(stmts, k, ng_var_snc)
11399+ if ng_narrow_snc != ""
11400+ push_type_narrow(ng_var_snc, ng_narrow_snc)
11401+ pushed_raise_guards_snc = pushed_raise_guards_snc + 1
11402+ end
11403+ end
1129011404 k = k + 1
1129111405 end
1129211406 while pushed_raise_guards_snc > 0
@@ -16018,6 +16132,29 @@
1601816132 # Collect all explicit return types
1601916133 types = "".split(",")
1602016134 collect_return_types_nid(body_id, types)
16135+ # Push sibling-scope narrows from preceding guards so the
16136+ # implicit-return type sees the narrowed local types. Without
16137+ # this, `def f; h = s.index(...); return -1 if h.nil?; h+1; end`
16138+ # infers `h+1` against h's poly source type, widening f's
16139+ # return to poly. Issues #493 / #550.
16140+ pushed_guards_ibr = 0
16141+ kk_ibr = 0
16142+ while kk_ibr < stmts.length - 1
16143+ rg_p_ibr = parse_raise_guard_narrow(stmts[kk_ibr])
16144+ if rg_p_ibr[0] != ""
16145+ push_type_narrow(rg_p_ibr[0], rg_p_ibr[1])
16146+ pushed_guards_ibr = pushed_guards_ibr + 1
16147+ end
16148+ ng_var_ibr = parse_nil_guard_var(stmts[kk_ibr])
16149+ if ng_var_ibr != ""
16150+ ng_narrow_ibr = scan_back_writer_narrow_for(stmts, kk_ibr, ng_var_ibr)
16151+ if ng_narrow_ibr != ""
16152+ push_type_narrow(ng_var_ibr, ng_narrow_ibr)
16153+ pushed_guards_ibr = pushed_guards_ibr + 1
16154+ end
16155+ end
16156+ kk_ibr = kk_ibr + 1
16157+ end
1602116158 # Add implicit return (last expression). When the implicit return
1602216159 # is a bare LocalVariableReadNode of an "int_array"-typed local
1602316160 # (the empty-`[]` default), look at the body's push observations
@@ -16036,6 +16173,10 @@
1603616173 end
1603716174 end
1603816175 types.push(last_type)
16176+ while pushed_guards_ibr > 0
16177+ pop_type_narrow
16178+ pushed_guards_ibr = pushed_guards_ibr - 1
16179+ end
1603916180 # Unify all return path types
1604016181 unify_return_type(types)
1604116182 end
@@ -16055,6 +16196,14 @@
1605516196 push_type_narrow(rg_p[0], rg_p[1])
1605616197 pushed_raise_guards_crt = pushed_raise_guards_crt + 1
1605716198 end
16199+ ng_var_crt = parse_nil_guard_var(stmts[k])
16200+ if ng_var_crt != ""
16201+ ng_narrow_crt = scan_back_writer_narrow_for(stmts, k, ng_var_crt)
16202+ if ng_narrow_crt != ""
16203+ push_type_narrow(ng_var_crt, ng_narrow_crt)
16204+ pushed_raise_guards_crt = pushed_raise_guards_crt + 1
16205+ end
16206+ end
1605816207 k = k + 1
1605916208 end
1606016209 while pushed_raise_guards_crt > 0
@@ -18018,6 +18167,14 @@
1801818167 push_type_narrow(rg_p[0], rg_p[1])
1801918168 pushed_raise_guards_scm = pushed_raise_guards_scm + 1
1802018169 end
18170+ ng_var_scm = parse_nil_guard_var(stmts[k])
18171+ if ng_var_scm != ""
18172+ ng_narrow_scm = scan_back_writer_narrow_for(stmts, k, ng_var_scm)
18173+ if ng_narrow_scm != ""
18174+ push_type_narrow(ng_var_scm, ng_narrow_scm)
18175+ pushed_raise_guards_scm = pushed_raise_guards_scm + 1
18176+ end
18177+ end
1802118178 k = k + 1
1802218179 end
1802318180 while pushed_raise_guards_scm > 0