Commit 2fd67094

2fd670948d89Merged

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

Description

fix(codegen): puts mixed-type ternary routes through sp_poly_puts

puts cond ? :sym : int mis-dispatched: unify_return_type collapsed [int, symbol] to "symbol" via its int-as-default heuristic, so the else arm's int went through sp_sym_to_s and printed garbage. The reporter (#640) hit this on puts a%2>0 ? :odd : a printing blank instead of "2".

compile_puts now peeks an IfNode arg's then/else base types; if they differ and neither arm is nil/void (the implicit if cond; X; end shape, which strings already handle via str_or_nil), box the arg to poly and dispatch through sp_poly_puts so each arm's runtime tag drives the right printer.

Closes #640.

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

Details

Commit
2fd670948d89
Parent
087d01fd3171

spinel_codegen.rbmodifiedView file

@@ -31732,6 +31732,50 @@
3173231732 while k < arg_ids.length
3173331733 aid = arg_ids[k]
3173431734 at = infer_type(aid)
31735+ # Issue #640: `puts cond ? :sym : int` ternary's unify_return_type
31736+ # picks one arm's type (e.g. "symbol") and the other arm's emit
31737+ # gets dispatched through the wrong puts variant — `sp_sym_to_s
31738+ # (an_int)` prints garbage. Detect the mixed-type ternary at the
31739+ # puts boundary and route through sp_poly_puts so each arm's
31740+ # value is boxed to its real tag.
31741+ mixed_ternary = 0
31742+ if at != "poly" && aid >= 0 && @nd_type[aid] == "IfNode"
31743+ if_then_t_pt = "nil"
31744+ if_body_pt = @nd_body[aid]
31745+ if if_body_pt >= 0
31746+ if_stmts_pt = get_stmts(if_body_pt)
31747+ if if_stmts_pt.length > 0
31748+ if_then_t_pt = base_type(infer_type(if_stmts_pt.last))
31749+ end
31750+ end
31751+ if_else_t_pt = "nil"
31752+ if_sub_pt = @nd_subsequent[aid]
31753+ if if_sub_pt >= 0 && @nd_type[if_sub_pt] == "ElseNode"
31754+ eb_pt = @nd_body[if_sub_pt]
31755+ if eb_pt >= 0
31756+ es_pt = get_stmts(eb_pt)
31757+ if es_pt.length > 0
31758+ if_else_t_pt = base_type(infer_type(es_pt.last))
31759+ end
31760+ end
31761+ end
31762+ if if_then_t_pt != if_else_t_pt
31763+ # Only fire when both arms have a concrete type. nil-arms are
31764+ # the implicit `if cond; X; end` (no else) shape — leaving them
31765+ # alone preserves the existing puts dispatch (`nil` on the
31766+ # missing branch goes through the int/string fallback path).
31767+ if if_then_t_pt != "nil" && if_else_t_pt != "nil" &&
31768+ if_then_t_pt != "void" && if_else_t_pt != "void"
31769+ mixed_ternary = 1
31770+ end
31771+ end
31772+ end
31773+ if mixed_ternary == 1
31774+ @needs_rb_value = 1
31775+ emit(" sp_poly_puts(" + box_expr_to_poly(aid) + ");")
31776+ k = k + 1
31777+ next
31778+ end
3173531779 val = compile_expr(aid)
3173631780 if at == "poly"
3173731781 @needs_rb_value = 1