Commit b8372148

b837214871fbMerged

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

Description

Merge pull request #375 from mame/pr/static-false-if-fold

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

Details

Commit
b837214871fb
Parent
23955d9bbcc4
Merge parent
d20b4715d1e6

spinel_codegen.rbmodifiedView file

@@ -31453,6 +31453,28 @@
3145331453
3145431454 def compile_if_stmt(nid)
3145531455 cond = compile_cond_expr(@nd_predicate[nid])
31456+ # Static-false fold: a predicate whose static type is `nil`
31457+ # (e.g. an attr_reader for an ivar only ever assigned `nil`)
31458+ # collapses to `if (FALSE) { … }`. The body is unreachable, but
31459+ # its statements still pass through the C compiler — and they
31460+ # often type-error against ivars/methods whose shapes only make
31461+ # sense when the predicate is true. Drop the body entirely; emit
31462+ # the else branch (if any) at the surrounding scope.
31463+ if cond == "FALSE"
31464+ sub_sf = @nd_subsequent[nid]
31465+ if sub_sf >= 0
31466+ if @nd_type[sub_sf] == "ElseNode"
31467+ compile_stmts_body(@nd_body[sub_sf])
31468+ else
31469+ compile_if_stmt(sub_sf)
31470+ end
31471+ end
31472+ return
31473+ end
31474+ if cond == "TRUE"
31475+ compile_stmts_body(@nd_body[nid])
31476+ return
31477+ end
3145631478 emit(" if (" + cond + ") {")
3145731479 @indent = @indent + 1
3145831480 compile_stmts_body(@nd_body[nid])
@@ -31488,6 +31510,20 @@
3148831510
3148931511 def compile_unless_stmt(nid)
3149031512 cond = compile_cond_expr(@nd_predicate[nid])
31513+ # Symmetric to compile_if_stmt's static-fold: an `unless` whose
31514+ # predicate is statically TRUE drops its body, FALSE drops the
31515+ # else branch.
31516+ if cond == "TRUE"
31517+ ec_sf = @nd_else_clause[nid]
31518+ if ec_sf >= 0
31519+ compile_stmts_body(@nd_body[ec_sf])
31520+ end
31521+ return
31522+ end
31523+ if cond == "FALSE"
31524+ compile_stmts_body(@nd_body[nid])
31525+ return
31526+ end
3149131527 emit(" if (!(" + cond + ")) {")
3149231528 @indent = @indent + 1
3149331529 compile_stmts_body(@nd_body[nid])