Commit 8e19a795

8e19a79517b4Merged

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

Description

fix(analyze,codegen): case fallthrough returns nil + ! is Ruby-truthy

#707: case x when 1; "one"; end without else returns nil in Ruby. Two changes:

  1. infer_type's CaseNode arm: when no else clause, push "nil" into the type-unify so a string-returning arm widens to string, an int arm widens to int? (matching the existing nullable-pointer widening for the else-present case).
  2. unify_return_type: int + nil widens to int? (sentinel-based, already used by Hash#fetch(k, nil) on int- leaf hashes). Lets r = case v when Range then 1 end produce int? slot for r and the function-return type for the enclosing method.
  3. compile_puts + compile_puts_single: add an int? arm that emits if (sp_int_is_nil(v)) putchar('\n'); else printf("%lld\n", v); so puts r outputs an empty line for the SP_INT_NIL sentinel instead of dumping INT64_MIN's decimal representation.

#703: !val on int / symbol / other concrete types used C's ! directly. !0 in C is true, but in Ruby 0 is truthy and !0 is false. Same shape for !:sym (symbols are always truthy in Ruby). Route the ! codegen through truthy_c_expr so each type's Ruby-correct truthy semantic flows in:

  • int / symbol / float / value-types → always-truthy fallback ((val), TRUE), so !val becomes !TRUE = FALSE
  • nil → FALSE, so !nil = TRUE
  • bool → expr, so !true = FALSE
  • nullable pointer → val != NULL, so !nil_ptr = TRUE
  • poly → sp_poly_truthy (already handled)

Tests:

  • test/case_fallthrough_returns_nil.rb (string + int when arms, both with and without else)
  • existing test/case_when_poly_scrutinee_bound_to_local.rb's "no when match -> 0" expected updated to empty line (Ruby semantic for nil)

450 -> 451 tests pass, optcarrot 59662 holds.

Fixes #707 Fixes #703

Co-Authored-By: Claude Opus 4.7 [email protected]

Details

Commit
8e19a79517b4
Parent
255307cef2c6

spinel_analyze.rbmodifiedView file

@@ -2395,6 +2395,12 @@
23952395 types.push(infer_type(es.last))
23962396 end
23972397 end
2398+ else
2399+ # No `else` clause: Ruby returns nil on fallthrough. Push "nil"
2400+ # into the unify so a `string`-returning when-arm widens to
2401+ # `string?`, an int-returning arm widens to `int?`, etc.
2402+ # Issue #707.
2403+ types.push("nil")
23982404 end
23992405 if types.length > 0
24002406 return unify_return_type(types)
@@ -18837,6 +18843,14 @@
1883718843 result = result + "?"
1883818844 end
1883918845 end
18846+ # `int` + `nil` widens to `int?` (scalar-nullable, SP_INT_NIL
18847+ # sentinel). Hash#fetch(k, nil) already returns int? for the
18848+ # int-leaf shape; this extends the same widening to `case`-
18849+ # without-else and similar fallthrough returns of int-valued
18850+ # arms. Issue #707.
18851+ if result == "int"
18852+ result = "int?"
18853+ end
1884018854 end
1884118855 result
1884218856 end