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

@@ -16905,6 +16905,24 @@
1690516905 rhs_obj = is_obj_type(at)
1690616906 if lhs_obj != rhs_obj
1690716907 other_t = lhs_obj == 1 ? at : lt
16908+ # Issue #423: `obj == nil` / `obj != nil` on a nullable obj
16909+ # type can't constant-fold -- the runtime pointer is allowed
16910+ # to be NULL (the type is obj_<C>?), and the body's behavior
16911+ # depends on the actual value. Fall through to the pointer
16912+ # comparison emit below. Non-nullable obj types still fold
16913+ # because the pointer is never NULL by design (locals are
16914+ # only typed `obj_<C>` after the type-tracker proved every
16915+ # assigned write is non-nil).
16916+ if other_t == "nil"
16917+ obj_side_t = lhs_obj == 1 ? lt : at
16918+ if is_nullable_type(obj_side_t) == 1
16919+ obj_expr_nilcmp = lhs_obj == 1 ? compile_expr(recv) : compile_expr(arg_id)
16920+ if op == "=="
16921+ return "(" + obj_expr_nilcmp + " == NULL)"
16922+ end
16923+ return "(" + obj_expr_nilcmp + " != NULL)"
16924+ end
16925+ end
1690816926 if lhs_obj == 0 && (other_t == "int" || other_t == "float")
1690916927 cname = at[4, at.length - 4]
1691016928 ci = find_class_idx(cname)