Commit aadd3c66
aadd3c6627abMerged
Yukihiro "Matz" Matsumoto <[email protected]> · 6 months ago · 3 files · +2 added · ~1 modified
Description
fix(codegen): nullable-obj != nil emits runtime check, not constant TRUE (#423)
if c != nil and while c != nil on a nullable user-class
local emitted the body unconditionally -- the != nil
comparison constant-folded to TRUE, the surrounding if
collapsed via compile_if_stmt's static-TRUE fold, and the body
ran even when c was NULL. Found in tep's route dispatch loop:
while route != nil && !served entered with route = NULL after
a no-match POST and segfaulted.
Root cause: compile_eq's cross-type-prim-vs-obj fold treated
obj_<C>? == nil and != nil as type-strict pairs (LHS is obj,
RHS is nil-typed; the fold returned FALSE/TRUE because "obj and
nil are different types, always unequal"). Correct for a
non-nullable obj_<C> -- the C pointer is never NULL by design
-- but wrong for obj_<C>? where NULL is the runtime nil
sentinel.
Fix: in the cross-type prim-vs-obj branch, when other_t ==
"nil", check is_nullable_type on the obj side. If nullable,
emit the actual pointer comparison (obj == NULL / obj != NULL) instead of folding. Non-nullable obj types still fold;
those pointers are never NULL so the answer is statically known.
Test nullable_obj_nil_compare.rb covers the nil and non-nil
branches across if c != nil, plain truthy if c, and if !c.nil? (all three agree), the while c != nil shape (loop
terminates), and a non-nullable obj as a regression guard for
the static fold.
Closes #423
Co-Authored-By: Claude Opus 4.7 (1M context) [email protected]
Details
- Commit
- aadd3c6627ab
- Parent
- 22dbee2d65de
spinel_codegen.rbmodifiedView file
rhs_obj = is_obj_type(at) if lhs_obj != rhs_obj other_t = lhs_obj == 1 ? at : lt # Issue #423: `obj == nil` / `obj != nil` on a nullable obj # type can't constant-fold -- the runtime pointer is allowed # to be NULL (the type is obj_<C>?), and the body's behavior # depends on the actual value. Fall through to the pointer # comparison emit below. Non-nullable obj types still fold # because the pointer is never NULL by design (locals are # only typed `obj_<C>` after the type-tracker proved every # assigned write is non-nil). if other_t == "nil" obj_side_t = lhs_obj == 1 ? lt : at if is_nullable_type(obj_side_t) == 1 obj_expr_nilcmp = lhs_obj == 1 ? compile_expr(recv) : compile_expr(arg_id) if op == "==" return "(" + obj_expr_nilcmp + " == NULL)" end return "(" + obj_expr_nilcmp + " != NULL)" end end if lhs_obj == 0 && (other_t == "int" || other_t == "float") cname = at[4, at.length - 4] ci = find_class_idx(cname)test/nullable_obj_nil_compare.rbaddedView file
Loading diff…
test/nullable_obj_nil_compare.rb.expectedaddedView file
Loading diff…