Commit c38448ce

c38448ced0e7Merged

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

Description

fix(codegen): cross-type case-when emits literal 0 not strcmp/== mismatch

case <string> when :sym_literal lowered to strcmp(str, SPS_<sym>) == 0 — passing an sp_sym (long long) to a const char * parameter, C type error on every such arm. The symmetric case <symbol> when "string_literal" had the same shape with mrb_int == const char *.

CRuby semantics: :sym === "str" and "str" === :sym are both false (Symbol#=== / String#=== only match same-type receivers), so the correct lowering for these cross-type when arms is a literal 0 — the C compiles, the runtime correctly falls through to the next arm or to the else clause.

Fix in compile_when_conds (used by both compile_case_stmt and compile_case_return): special-case the (string-pred, SymbolNode- arm) and (symbol-pred, StringNode-arm) shapes to emit 0 directly rather than dispatching through compile_expr(cid).

Fixes #378

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

Details

Commit
c38448ced0e7
Parent
c4fcd37e5799

spinel_codegen.rbmodifiedView file

@@ -32038,9 +32038,27 @@
3203832038 end
3203932039 else
3204032040 if pred_type == "string"
32041- result = result + "strcmp(" + tmp + ", " + compile_expr(cid) + ") == 0"
32041+ # `case <string> when :sym_literal` — CRuby's
32042+ # `:sym === "str"` is always false (Symbol#=== returns
32043+ # false for non-Symbol receivers), so emit a literal
32044+ # 0 for this arm. Without the special-case
32045+ # compile_expr(cid) returns `SPS_<sym>` (an sp_sym aka
32046+ # long long) and strcmp would reject it.
32047+ if @nd_type[cid] == "SymbolNode"
32048+ result = result + "0"
32049+ else
32050+ result = result + "strcmp(" + tmp + ", " + compile_expr(cid) + ") == 0"
32051+ end
3204232052 else
32043- result = result + tmp + " == " + compile_expr(cid)
32053+ # Symmetric case: `case <sym> when "literal_str"` is
32054+ # also always false in CRuby (String#=== returns false
32055+ # for a Symbol). Emit 0 to avoid a `mrb_int == const
32056+ # char *` type mismatch in the generated C.
32057+ if pred_type == "symbol" && @nd_type[cid] == "StringNode"
32058+ result = result + "0"
32059+ else
32060+ result = result + tmp + " == " + compile_expr(cid)
32061+ end
3204432062 end
3204532063 end
3204632064 k = k + 1