Commit d20b4715

d20b4715d1e6Merged

Yusuke Endoh <[email protected]> · 6 months ago · 3 files · +2 added · ~1 modified

Description

fix(codegen): skip body emission when if/unless predicate folds to static FALSE/TRUE

compile_cond_expr already returns the literal "FALSE" string when the predicate is statically nil (e.g. an attr_reader for an ivar whose only init is = nil) — same for "TRUE" on a statically-truthy predicate. Today the if/unless emit always wraps the body in if (cond) { ... }, so a if @stackprof_mode where @stackprof_mode is statically nil emits

if (FALSE) { lv_out = sp_str_sub(_t, "MODE", iv_stackprof_mode); }

with iv_stackprof_mode defaulted to mrb_int (the only assignment visible was = nil). The body is unreachable but still passes through the C compiler and trips -Wint-conversion.

Drop the body entirely when cond is statically FALSE; for the else side, emit it at the surrounding scope. Symmetric handling in compile_unless_stmt. Behavior is preserved (the dead body was already unreachable at runtime); the only change is that type errors hidden inside the dead branch no longer reach gcc.

Details

Commit
d20b4715d1e6
Parent
59f48e594a9d

spinel_codegen.rbmodifiedView file

@@ -30568,6 +30568,28 @@
3056830568
3056930569 def compile_if_stmt(nid)
3057030570 cond = compile_cond_expr(@nd_predicate[nid])
30571+ # Static-false fold: a predicate whose static type is `nil`
30572+ # (e.g. an attr_reader for an ivar only ever assigned `nil`)
30573+ # collapses to `if (FALSE) { … }`. The body is unreachable, but
30574+ # its statements still pass through the C compiler — and they
30575+ # often type-error against ivars/methods whose shapes only make
30576+ # sense when the predicate is true. Drop the body entirely; emit
30577+ # the else branch (if any) at the surrounding scope.
30578+ if cond == "FALSE"
30579+ sub_sf = @nd_subsequent[nid]
30580+ if sub_sf >= 0
30581+ if @nd_type[sub_sf] == "ElseNode"
30582+ compile_stmts_body(@nd_body[sub_sf])
30583+ else
30584+ compile_if_stmt(sub_sf)
30585+ end
30586+ end
30587+ return
30588+ end
30589+ if cond == "TRUE"
30590+ compile_stmts_body(@nd_body[nid])
30591+ return
30592+ end
3057130593 emit(" if (" + cond + ") {")
3057230594 @indent = @indent + 1
3057330595 compile_stmts_body(@nd_body[nid])
@@ -30602,6 +30624,20 @@
3060230624
3060330625 def compile_unless_stmt(nid)
3060430626 cond = compile_cond_expr(@nd_predicate[nid])
30627+ # Symmetric to compile_if_stmt's static-fold: an `unless` whose
30628+ # predicate is statically TRUE drops its body, FALSE drops the
30629+ # else branch.
30630+ if cond == "TRUE"
30631+ ec_sf = @nd_else_clause[nid]
30632+ if ec_sf >= 0
30633+ compile_stmts_body(@nd_body[ec_sf])
30634+ end
30635+ return
30636+ end
30637+ if cond == "FALSE"
30638+ compile_stmts_body(@nd_body[nid])
30639+ return
30640+ end
3060530641 emit(" if (!(" + cond + ")) {")
3060630642 @indent = @indent + 1
3060730643 compile_stmts_body(@nd_body[nid])