Commit 840f5573

840f557379e4Merged

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

Description

fix(codegen): #207 — is_a? type narrowing + dead-arm elimination

Closes the symbolize_keys recursion piece of #207. The Rails-style Parameters wrapper

def symbolize_keys(input) out = {} input.each do |k, v| out[sym] = v.is_a?(Hash) ? symbolize_keys(v) : v end end

failed to compile because spinel emitted both ternary arms in C — the dead symbolize_keys(v) recursion call passed a const char * to an sp_SymStrHash * parameter even though v.is_a?(Hash) was statically FALSE for v of type string.

Two complementary mechanisms:

  1. is_a? type narrowing infrastructure

    • new @type_narrow_names / @type_narrow_types stack consulted by find_var_type before the regular scope walk.
    • parse_is_a_predicate decodes <expr>.is_a?(<Class>) / .kind_of?(<Class>) into (var_name, narrow_type).
    • narrow_type_for_class maps Symbol/Integer/Float/String/Bool/ NilClass/Proc/Range/ to spinel's static tags. Hash and Array intentionally NOT narrowed: spinel has no single "any hash"/"any array" type that supports iteration, so widening callee params via unify_call_types would degrade them to "poly" and drop the .each dispatch.
    • scan_new_calls and scan_cls_method_calls grow IfNode dispatch that pushes the narrow before walking the then-arm.
  2. Static is_a? FALSE/TRUE dead-arm elimination

    The narrow path can't fix Hash/Array narrowing for the reason above, but the symbolize_keys repro doesn't actually need the narrow — v's static type is already "string", so v.is_a?(Hash) is statically FALSE and the then-arm is dead. New static_is_a_value / is_a_static_eval helpers compute the answer when the receiver's type is concrete; the IfNode emit path in box_expr_to_poly gates on the result and emits only the live arm. C never sees the dead recursion call.

Both pieces stay narrow in scope: the narrow stack is consulted at find_var_type only, the static eval gates only one IfNode emit site (the box_expr_to_poly ternary that triggers the repro). Other IfNode emit sites can adopt the same pattern incrementally as real-world failures surface.

Closes #207

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

Details

Commit
840f557379e4
Parent
eaad8a4edb93

spinel_codegen.rbmodifiedView file

@@ -159,6 +159,15 @@
159159 @scope_names = "".split(",")
160160 @scope_types = "".split(",")
161161
162+ # Issue #207: type narrowing introduced by `is_a?`/`kind_of?`
163+ # guards. While walking the then-arm of `if v.is_a?(Hash)` or
164+ # the truthy branch of `v.is_a?(Hash) ? a : b`, we push the
165+ # narrowed `(var_name, narrowed_type)` here; find_var_type's
166+ # top-down lookup picks it up and infer_type / scan / codegen
167+ # see the narrowed type without per-pass plumbing.
168+ @type_narrow_names = "".split(",")
169+ @type_narrow_types = "".split(",")
170+
162171 @current_class_idx = -1
163172 @current_method_name = ""
164173 @current_lexical_scope = ""
@@ -1106,6 +1115,16 @@
11061115 end
11071116
11081117 def find_var_type(name)
1118+ # Type-narrow override (issue #207): walk top-down so the
1119+ # innermost is_a? guard wins. Skipped for the unscoped global
1120+ # call (e.g. ivar lookups) — narrows are about local var typing.
1121+ i = @type_narrow_names.length - 1
1122+ while i >= 0
1123+ if @type_narrow_names[i] == name
1124+ return @type_narrow_types[i]
1125+ end
1126+ i = i - 1
1127+ end
11091128 i = @scope_names.length - 1
11101129 while i >= 0
11111130 if @scope_names[i] == name
@@ -1116,6 +1135,256 @@
11161135 ""
11171136 end
11181137
1138+ # ---- is_a? type narrowing ----
1139+ # Issue #207: `<expr>.is_a?(<Class>)` (or kind_of?) used as the
1140+ # predicate of an if / ternary lets us treat <expr> as <Class>'s
1141+ # type inside the then-arm. The four entry points (push, pop,
1142+ # narrow_type_for_class, parse_is_a_predicate) are called from
1143+ # both inference and codegen sides — keep the API tiny so the
1144+ # narrow context can be plumbed through without leaking state.
1145+
1146+ def push_type_narrow(var_name, narrow_type)
1147+ @type_narrow_names.push(var_name)
1148+ @type_narrow_types.push(narrow_type)
1149+ end
1150+
1151+ def pop_type_narrow
1152+ @type_narrow_names.pop
1153+ @type_narrow_types.pop
1154+ end
1155+
1156+ # Map a Ruby class name to spinel's static type tag for narrowing.
1157+ # Returns "" when the class doesn't have a concrete spinel type
1158+ # we can narrow to (and the call site should leave the var type
1159+ # alone). The first set is concrete primitives — narrow gives a
1160+ # real type win. The Hash / Array group widens to the catch-all
1161+ # poly_* variant since spinel doesn't track a single "any hash"
1162+ # type, but `poly_hash` / `poly_array` reaches every receiver-
1163+ # method dispatch the narrowed var participates in.
1164+ def narrow_type_for_class(cname)
1165+ if cname == "Symbol"
1166+ return "symbol"
1167+ end
1168+ if cname == "Integer" || cname == "Numeric"
1169+ return "int"
1170+ end
1171+ if cname == "Float"
1172+ return "float"
1173+ end
1174+ if cname == "String"
1175+ return "string"
1176+ end
1177+ if cname == "TrueClass" || cname == "FalseClass"
1178+ return "bool"
1179+ end
1180+ if cname == "NilClass"
1181+ return "nil"
1182+ end
1183+ # Hash / Array narrow intentionally omitted: spinel has many
1184+ # concrete hash/array variants (sym_int_hash, str_str_hash,
1185+ # int_array, ...) and no single "any hash" type that supports
1186+ # iteration. Narrowing to a generic "poly_hash" widens callee
1187+ # params via unify_call_types to "poly", which makes the body's
1188+ # `each` loop drop out (no overload for poly recv). The
1189+ # symbolize_keys-style recursive repro in #207 hits this: better
1190+ # to leave the C compile error visible than emit a silently-
1191+ # empty body. Concrete-class narrow (Symbol, Integer, ...)
1192+ # below is unaffected.
1193+ if cname == "Proc"
1194+ return "proc"
1195+ end
1196+ if cname == "Range"
1197+ return "range"
1198+ end
1199+ # User-defined class: narrow to obj_<C> when the class is
1200+ # registered. Otherwise return "" — narrow is a no-op.
1201+ if find_class_idx(cname) >= 0
1202+ return "obj_" + cname
1203+ end
1204+ ""
1205+ end
1206+
1207+ # Issue #207: static evaluation of `<expr>.is_a?(<Class>)` /
1208+ # `.kind_of?(<Class>)` when expr's static type already proves the
1209+ # answer. Returns "TRUE" / "FALSE" / "" (= dynamic). Used at
1210+ # IfNode emit sites to skip the dead arm so the C compiler doesn't
1211+ # type-check a recursion call whose argument types don't match.
1212+ def static_is_a_value(pred_id)
1213+ if pred_id < 0
1214+ return ""
1215+ end
1216+ if @nd_type[pred_id] != "CallNode"
1217+ return ""
1218+ end
1219+ pname = @nd_name[pred_id]
1220+ if pname != "is_a?" && pname != "kind_of?"
1221+ return ""
1222+ end
1223+ expr = @nd_receiver[pred_id]
1224+ if expr < 0
1225+ return ""
1226+ end
1227+ args = @nd_arguments[pred_id]
1228+ if args < 0
1229+ return ""
1230+ end
1231+ arg_ids = get_args(args)
1232+ if arg_ids.length < 1
1233+ return ""
1234+ end
1235+ arg0 = arg_ids[0]
1236+ cname = ""
1237+ if @nd_type[arg0] == "ConstantReadNode"
1238+ cname = @nd_name[arg0]
1239+ elsif @nd_type[arg0] == "ConstantPathNode"
1240+ cname = resolve_const_ref_name(arg0)
1241+ end
1242+ if cname == ""
1243+ return ""
1244+ end
1245+ expr_t = infer_type(expr)
1246+ is_a_static_eval(expr_t, cname)
1247+ end
1248+
1249+ def is_a_static_eval(expr_t, cname)
1250+ eb = base_type(expr_t)
1251+ if eb == "poly"
1252+ return ""
1253+ end
1254+ # Concrete primitives: positive answer wins, otherwise narrow
1255+ # to the right tag.
1256+ if cname == "Symbol"
1257+ if eb == "symbol"
1258+ return "TRUE"
1259+ end
1260+ return is_a_static_negative(eb)
1261+ end
1262+ if cname == "String"
1263+ if eb == "string" || eb == "mutable_str"
1264+ return "TRUE"
1265+ end
1266+ return is_a_static_negative(eb)
1267+ end
1268+ if cname == "Integer" || cname == "Numeric"
1269+ if eb == "int"
1270+ return "TRUE"
1271+ end
1272+ if cname == "Numeric" && eb == "float"
1273+ return "TRUE"
1274+ end
1275+ return is_a_static_negative(eb)
1276+ end
1277+ if cname == "Float"
1278+ if eb == "float"
1279+ return "TRUE"
1280+ end
1281+ return is_a_static_negative(eb)
1282+ end
1283+ if cname == "TrueClass" || cname == "FalseClass"
1284+ if eb == "bool"
1285+ return "" # value-dependent, leave dynamic
1286+ end
1287+ return is_a_static_negative(eb)
1288+ end
1289+ if cname == "NilClass"
1290+ if eb == "nil"
1291+ return "TRUE"
1292+ end
1293+ return is_a_static_negative(eb)
1294+ end
1295+ if cname == "Hash"
1296+ if is_hash_type(eb) == 1
1297+ return "TRUE"
1298+ end
1299+ return is_a_static_negative(eb)
1300+ end
1301+ if cname == "Array"
1302+ if is_array_type(eb) == 1
1303+ return "TRUE"
1304+ end
1305+ return is_a_static_negative(eb)
1306+ end
1307+ if cname == "Proc"
1308+ if eb == "proc" || eb == "lambda"
1309+ return "TRUE"
1310+ end
1311+ return is_a_static_negative(eb)
1312+ end
1313+ if cname == "Range"
1314+ if eb == "range"
1315+ return "TRUE"
1316+ end
1317+ return is_a_static_negative(eb)
1318+ end
1319+ # User-defined class
1320+ if find_class_idx(cname) >= 0
1321+ if is_obj_type(eb) == 1
1322+ ecname = eb[4, eb.length - 4]
1323+ if is_class_or_ancestor(ecname, cname) == 1
1324+ return "TRUE"
1325+ end
1326+ return "FALSE"
1327+ end
1328+ return is_a_static_negative(eb)
1329+ end
1330+ ""
1331+ end
1332+
1333+ # When the receiver's static type is a non-poly concrete tag, we
1334+ # can safely declare any non-matching is_a? as FALSE. Used by the
1335+ # primitive class branches above.
1336+ def is_a_static_negative(eb)
1337+ if eb == "poly" || eb == ""
1338+ return ""
1339+ end
1340+ "FALSE"
1341+ end
1342+
1343+ # Decode `<expr>.is_a?(<Class>)` / `.kind_of?(<Class>)` into
1344+ # `(var_name, narrow_type)` when expr is a LocalVariableReadNode
1345+ # and the argument is a constant naming a known class. Returns
1346+ # `["", ""]` if the predicate isn't a narrowable shape (the empty
1347+ # var name is the sentinel; the caller skips the push).
1348+ def parse_is_a_predicate(pred_id)
1349+ if pred_id < 0
1350+ return ["", ""]
1351+ end
1352+ if @nd_type[pred_id] != "CallNode"
1353+ return ["", ""]
1354+ end
1355+ pname = @nd_name[pred_id]
1356+ if pname != "is_a?" && pname != "kind_of?"
1357+ return ["", ""]
1358+ end
1359+ expr = @nd_receiver[pred_id]
1360+ if expr < 0 || @nd_type[expr] != "LocalVariableReadNode"
1361+ return ["", ""]
1362+ end
1363+ args = @nd_arguments[pred_id]
1364+ if args < 0
1365+ return ["", ""]
1366+ end
1367+ arg_ids = get_args(args)
1368+ if arg_ids.length < 1
1369+ return ["", ""]
1370+ end
1371+ arg0 = arg_ids[0]
1372+ cname = ""
1373+ if @nd_type[arg0] == "ConstantReadNode"
1374+ cname = @nd_name[arg0]
1375+ elsif @nd_type[arg0] == "ConstantPathNode"
1376+ cname = resolve_const_ref_name(arg0)
1377+ end
1378+ if cname == ""
1379+ return ["", ""]
1380+ end
1381+ nt = narrow_type_for_class(cname)
1382+ if nt == ""
1383+ return ["", ""]
1384+ end
1385+ [@nd_name[expr], nt]
1386+ end
1387+
11191388 def set_var_type(name, vtype)
11201389 i = @scope_names.length - 1
11211390 while i >= 0
@@ -7034,6 +7303,40 @@
70347303 @current_lexical_scope = saved_scope2
70357304 return
70367305 end
7306+ # Issue #207: IfNode (incl. ternary). When the predicate is
7307+ # `var.is_a?(C)` / `kind_of?(C)`, push a narrow on `var` while
7308+ # walking the then-arm so a recursive call inside the arm sees
7309+ # the narrowed type and unify_call_types widens the callee's
7310+ # param accordingly. The else-arm walks unchanged (we don't
7311+ # currently model "type minus C").
7312+ if @nd_type[nid] == "IfNode"
7313+ pred = @nd_predicate[nid]
7314+ if pred >= 0
7315+ scan_new_calls(pred)
7316+ end
7317+ parsed = parse_is_a_predicate(pred)
7318+ narrow_var = parsed[0]
7319+ narrow_t = parsed[1]
7320+ if narrow_var != ""
7321+ push_type_narrow(narrow_var, narrow_t)
7322+ end
7323+ then_body = @nd_body[nid]
7324+ if then_body >= 0
7325+ scan_new_calls(then_body)
7326+ end
7327+ if narrow_var != ""
7328+ pop_type_narrow
7329+ end
7330+ sub = @nd_subsequent[nid]
7331+ if sub >= 0
7332+ scan_new_calls(sub)
7333+ end
7334+ else_body = @nd_else_clause[nid]
7335+ if else_body >= 0
7336+ scan_new_calls(else_body)
7337+ end
7338+ return
7339+ end
70377340 if @nd_type[nid] == "CallNode"
70387341 # Also infer top-level method param types from call sites
70397342 mname = @nd_name[nid]
@@ -10519,6 +10822,36 @@
1051910822 if nid < 0
1052010823 return
1052110824 end
10825+ # Issue #207: same is_a? narrow as scan_new_calls so a self
10826+ # call inside the then-arm sees the narrowed receiver type.
10827+ if @nd_type[nid] == "IfNode"
10828+ pred = @nd_predicate[nid]
10829+ if pred >= 0
10830+ scan_cls_method_calls(ci, pred)
10831+ end
10832+ parsed = parse_is_a_predicate(pred)
10833+ narrow_var = parsed[0]
10834+ narrow_t = parsed[1]
10835+ if narrow_var != ""
10836+ push_type_narrow(narrow_var, narrow_t)
10837+ end
10838+ then_body = @nd_body[nid]
10839+ if then_body >= 0
10840+ scan_cls_method_calls(ci, then_body)
10841+ end
10842+ if narrow_var != ""
10843+ pop_type_narrow
10844+ end
10845+ sub = @nd_subsequent[nid]
10846+ if sub >= 0
10847+ scan_cls_method_calls(ci, sub)
10848+ end
10849+ else_body = @nd_else_clause[nid]
10850+ if else_body >= 0
10851+ scan_cls_method_calls(ci, else_body)
10852+ end
10853+ return
10854+ end
1052210855 if @nd_type[nid] == "CallNode"
1052310856 mname = @nd_name[nid]
1052410857 # Handle implicit self calls (no receiver) to same-class methods
@@ -20714,6 +21047,41 @@
2071421047 # gate misses it. The pre-#131 emit then `sp_box_str`'d the entire
2071521048 # raw ternary, which is the same UB.
2071621049 if nid >= 0 && @nd_type[nid] == "IfNode"
21050+ # Issue #207: if the predicate is a statically-decidable
21051+ # is_a? / kind_of? on an already-typed expression, emit only
21052+ # the live arm. The dead arm may contain a recursion call
21053+ # whose argument types don't match the function's signature
21054+ # (e.g. `v.is_a?(Hash) ? recurse(v) : v` where v is statically
21055+ # a string) — generating it would land as a C type error
21056+ # even though the branch is unreachable at runtime.
21057+ sv = static_is_a_value(@nd_predicate[nid])
21058+ if sv == "TRUE"
21059+ body = @nd_body[nid]
21060+ if body >= 0
21061+ ts = get_stmts(body)
21062+ if ts.length > 0
21063+ return box_expr_to_poly(ts.last)
21064+ end
21065+ end
21066+ return "sp_box_nil()"
21067+ end
21068+ if sv == "FALSE"
21069+ sub = @nd_subsequent[nid]
21070+ if sub >= 0
21071+ if @nd_type[sub] == "ElseNode"
21072+ eb = @nd_body[sub]
21073+ if eb >= 0
21074+ es = get_stmts(eb)
21075+ if es.length > 0
21076+ return box_expr_to_poly(es.last)
21077+ end
21078+ end
21079+ else
21080+ return box_expr_to_poly(sub)
21081+ end
21082+ end
21083+ return "sp_box_nil()"
21084+ end
2071721085 cond = compile_cond_expr(@nd_predicate[nid])
2071821086 then_v = "sp_box_nil()"
2071921087 body = @nd_body[nid]