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, but31459+
# its statements still pass through the C compiler — and they31460+
# often type-error against ivars/methods whose shapes only make31461+
# sense when the predicate is true. Drop the body entirely; emit31462+
# the else branch (if any) at the surrounding scope.31463+
if cond == "FALSE"31464+
sub_sf = @nd_subsequent[nid]31465+
if sub_sf >= 031466+
if @nd_type[sub_sf] == "ElseNode"31467+
compile_stmts_body(@nd_body[sub_sf])31468+
else31469+
compile_if_stmt(sub_sf)31470+
end31471+
end31472+
return31473+
end31474+
if cond == "TRUE"31475+
compile_stmts_body(@nd_body[nid])31476+
return31477+
end3145631478
emit(" if (" + cond + ") {")3145731479
@indent = @indent + 13145831480
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` whose31514+
# predicate is statically TRUE drops its body, FALSE drops the31515+
# else branch.31516+
if cond == "TRUE"31517+
ec_sf = @nd_else_clause[nid]31518+
if ec_sf >= 031519+
compile_stmts_body(@nd_body[ec_sf])31520+
end31521+
return31522+
end31523+
if cond == "FALSE"31524+
compile_stmts_body(@nd_body[nid])31525+
return31526+
end3149131527
emit(" if (!(" + cond + ")) {")3149231528
@indent = @indent + 13149331529
compile_stmts_body(@nd_body[nid])test/if_static_false_skips_dead_branch_compile.rbaddedView file
Loading diff…
test/if_static_false_skips_dead_branch_compile.rb.expectedaddedView file
Loading diff…