Commit fa5a8587

fa5a85870694Merged

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

Description

fix(codegen): run ensure clause on return and raise exits

begin..ensure..end previously skipped its ensure body on every non-fall-through path: a return from inside the body emitted a plain C return (with the ensure body left as dead code after it), and a raise longjmped past the begin entirely (no setjmp was emitted for ensure-only blocks).

Three coordinated changes:

  1. compile_begin_stmt wraps the body (and any rescue chain) in an outer setjmp when the block has ensure. The success branch falls through to the normal-path ensure; the else branch snapshots sp_last_exc_cls / sp_exc_msg, runs the ensure body, and re-raises so propagation continues.

  2. compile_return_stmt replays each in-scope ensure body inline ahead of the C return. Returns are tracked through a new @ensure_stack; each ensure is popped before its body is emitted so a nested return inside the ensure body sees only the outer ensures still active.

  3. @setjmp_depth tracks how many sp_exc_top++s are live at the current emit point. Early returns now emit sp_exc_top -= N; to balance them, fixing a pre-existing leak where return from inside begin..rescue..end left sp_exc_top stuck above the caller's level.

scan_ivars_children also now descends into rescue / ensure clauses so an ivar assigned only in an ensure block gets registered on the class struct (otherwise the writeback emitted self->iv_<X> for a field that didn't exist).

Six new tests cover return paths (bare, value-returning, multi- return-path, nested, return-from-rescue) and raise paths (raise through ensure, nested raise, ensure-side raise overriding the body exception).

Details

Commit
fa5a85870694
Parent
f6b89b028b0c

spinel_codegen.rbmodifiedView file

@@ -309,6 +309,23 @@
309309 @rescue_cls_stack = "".split(",")
310310 @rescue_msg_stack = "".split(",")
311311 @rescue_depth = 0
312+ # Stack of ensure-clause node IDs (encoded as strings) currently in
313+ # scope. Each entry corresponds to an enclosing `begin..ensure..end`
314+ # whose body is being compiled. When `return` is emitted from inside
315+ # the body, each ensure body is replayed (innermost-first) before
316+ # the C `return`, so writebacks in `ensure` execute on early return.
317+ @ensure_stack = "".split(",")
318+ # Number of `sp_exc_top++` pushes emitted along the static
319+ # fall-through path leading to the current emit point but not
320+ # yet matched by an emitted `sp_exc_top--`. An early `return`
321+ # emits `sp_exc_top -= N` to balance them, so the caller doesn't
322+ # longjmp into our stale stack frame after we've returned.
323+ @setjmp_depth = 0
324+ # Counter used to mint unique snapshot variable names
325+ # (`_ensure_cls_<n>`, `_ensure_msg_<n>`) for re-raising the
326+ # in-flight exception after an ensure body runs on the
327+ # exception path of a `begin..ensure..end`.
328+ @ensure_emit_depth = 0
312329 # Exception variable bindings: parallel stacks of (var_name, cls_var).
313330 # A `rescue => e` binds `e` to the message string and registers it
314331 # here so that `e.message`, `e.class`, `e.to_s`, and `e.inspect`
@@ -8063,6 +8080,12 @@
80638080 scan_ivars(ci, elems[k])
80648081 k = k + 1
80658082 end
8083+ if @nd_rescue_clause[nid] >= 0
8084+ scan_ivars(ci, @nd_rescue_clause[nid])
8085+ end
8086+ if @nd_ensure_clause[nid] >= 0
8087+ scan_ivars(ci, @nd_ensure_clause[nid])
8088+ end
80668089 end
80678090
80688091 def infer_ivar_init_type(nid)
@@ -30503,6 +30526,14 @@
3050330526 emit(" " + arr_tmp + "->_" + k.to_s + " = " + compile_expr(arg_ids[k]) + ";")
3050430527 k = k + 1
3050530528 end
30529+ # Replay any in-scope `ensure` bodies before the return.
30530+ # Ruby semantics: return value is already materialized, ensure
30531+ # may mutate locals/ivars but does not affect the saved value.
30532+ # `sp_exc_top -= N` undoes the setjmps we pushed; emit it once
30533+ # before the replays so a nested `return` inside an ensure
30534+ # body doesn't double-pop.
30535+ emit_setjmp_depth_unwind
30536+ emit_ensure_replays
3050630537 if @in_gc_scope == 1
3050730538 emit(" SP_GC_RESTORE();")
3050830539 end
@@ -30510,21 +30541,43 @@
3051030541 return
3051130542 end
3051230543 if arg_ids.length > 0
30544+ # `pre_return_unwind` = needs `sp_exc_top -= N;` and/or
30545+ # ensure-body replays. When neither, we can leave the
30546+ # original simple `return <expr>;` shape alone.
30547+ pre_return_unwind = 0
30548+ if @ensure_stack.length > 0
30549+ pre_return_unwind = 1
30550+ end
30551+ if @setjmp_depth > 0
30552+ pre_return_unwind = 1
30553+ end
3051330554 if @current_method_return == "poly"
3051430555 ret_expr = box_expr_to_poly(arg_ids[0])
3051530556 if @in_gc_scope == 1
3051630557 tmp = new_temp
3051730558 emit(" sp_RbVal " + tmp + " = " + ret_expr + ";")
30559+ emit_setjmp_depth_unwind
30560+ emit_ensure_replays
3051830561 emit(" SP_GC_RESTORE();")
3051930562 emit(" return " + tmp + ";")
3052030563 else
30521- emit(" return " + ret_expr + ";")
30564+ if pre_return_unwind == 1
30565+ tmp = new_temp
30566+ emit(" sp_RbVal " + tmp + " = " + ret_expr + ";")
30567+ emit_setjmp_depth_unwind
30568+ emit_ensure_replays
30569+ emit(" return " + tmp + ";")
30570+ else
30571+ emit(" return " + ret_expr + ";")
30572+ end
3052230573 end
3052330574 return
3052430575 end
3052530576 rt = infer_type(arg_ids[0])
3052630577 # return nil in a nullable pointer method → return NULL
3052730578 if rt == "nil" && is_nullable_pointer_type(@current_method_return) == 1
30579+ emit_setjmp_depth_unwind
30580+ emit_ensure_replays
3052830581 if @in_gc_scope == 1
3052930582 emit(" SP_GC_RESTORE();")
3053030583 end
@@ -30532,13 +30585,24 @@
3053230585 return
3053330586 end
3053430587 if @in_gc_scope == 1
30535- # Save return value, restore GC, then return
30588+ # Save return value, run ensure replays (which may mutate
30589+ # ivars/locals), restore GC, then return the saved value.
3053630590 tmp = new_temp
3053730591 emit(" " + c_type(rt) + " " + tmp + " = " + compile_expr(arg_ids[0]) + ";")
30592+ emit_setjmp_depth_unwind
30593+ emit_ensure_replays
3053830594 emit(" SP_GC_RESTORE();")
3053930595 emit(" return " + tmp + ";")
3054030596 else
30541- emit(" return " + compile_expr(arg_ids[0]) + ";")
30597+ if pre_return_unwind == 1
30598+ tmp = new_temp
30599+ emit(" " + c_type(rt) + " " + tmp + " = " + compile_expr(arg_ids[0]) + ";")
30600+ emit_setjmp_depth_unwind
30601+ emit_ensure_replays
30602+ emit(" return " + tmp + ";")
30603+ else
30604+ emit(" return " + compile_expr(arg_ids[0]) + ";")
30605+ end
3054230606 end
3054330607 return
3054430608 end
@@ -30557,6 +30621,8 @@
3055730621 # NULLed the instance on the early-return branch; in the void
3055830622 # `sp_<C>_initialize` form it was a `void function should not
3055930623 # return a value` C error.
30624+ emit_setjmp_depth_unwind
30625+ emit_ensure_replays
3056030626 if @in_gc_scope == 1
3056130627 emit(" SP_GC_RESTORE();")
3056230628 end
@@ -36093,6 +36159,24 @@
3609336159 end
3609436160 end
3609536161
36162+ # Outer setjmp wraps the body (and any rescue chain) so the ensure
36163+ # clause runs on the exception path too. Without this, a `raise`
36164+ # from inside the body would unwind past us with `ensure` skipped.
36165+ ensure_cls_var = ""
36166+ ensure_msg_var = ""
36167+ if has_ensure
36168+ @ensure_emit_depth = @ensure_emit_depth + 1
36169+ ensure_cls_var = "_ensure_cls_" + @ensure_emit_depth.to_s
36170+ ensure_msg_var = "_ensure_msg_" + @ensure_emit_depth.to_s
36171+ emit(" const char *" + ensure_cls_var + " = (const char *)0;")
36172+ emit(" const char *" + ensure_msg_var + " = (const char *)0;")
36173+ emit(" sp_exc_top++;")
36174+ emit(" if (setjmp(sp_exc_stack[sp_exc_top-1]) == 0) {")
36175+ @indent = @indent + 1
36176+ @setjmp_depth = @setjmp_depth + 1
36177+ @ensure_stack.push(@nd_ensure_clause[nid].to_s)
36178+ end
36179+
3609636180 if has_retry == 1
3609736181 emit(" for (;;) {")
3609836182 @indent = @indent + 1
@@ -36100,6 +36184,7 @@
3610036184
3610136185 if has_rescue
3610236186 emit(" sp_exc_top++;")
36187+ @setjmp_depth = @setjmp_depth + 1
3610336188 emit(" if (setjmp(sp_exc_stack[sp_exc_top-1]) == 0) {")
3610436189 @indent = @indent + 1
3610536190 compile_stmts_body(@nd_body[nid])
@@ -36119,6 +36204,7 @@
3611936204 @indent = @indent - 1
3612036205 end
3612136206 emit(" }")
36207+ @setjmp_depth = @setjmp_depth - 1
3612236208 else
3612336209 compile_stmts_body(@nd_body[nid])
3612436210 end
@@ -36129,10 +36215,77 @@
3612936215 end
3613036216
3613136217 if has_ensure
36218+ @ensure_stack.pop
36219+ # End of the if-success branch: pop our setjmp and close the
36220+ # brace. After this the codegen is conceptually back at the
36221+ # surrounding scope — drop the depth bump even though more
36222+ # code (the else branch and fall-through ensure) is still
36223+ # being emitted; both run with sp_exc_top already restored.
36224+ emit(" sp_exc_top--;")
36225+ @indent = @indent - 1
36226+ @setjmp_depth = @setjmp_depth - 1
36227+ emit(" } else {")
36228+ @indent = @indent + 1
36229+ # Exception path: pop our setjmp, snapshot the in-flight
36230+ # exception (because nested raises inside the ensure body
36231+ # would clobber sp_last_exc_cls / sp_exc_msg), run the
36232+ # ensure body, then re-raise so the exception keeps
36233+ # propagating. If the ensure body contains its own `return`,
36234+ # the re-raise becomes dead code — that's the explicit
36235+ # "ensure overrides exception with return" semantics.
36236+ emit(" sp_exc_top--;")
36237+ emit(" " + ensure_cls_var + " = (const char *)sp_last_exc_cls;")
36238+ emit(" " + ensure_msg_var + " = sp_exc_msg[sp_exc_top];")
3613236239 ec = @nd_ensure_clause[nid]
3613336240 if ec >= 0
3613436241 compile_stmts_body(@nd_body[ec])
3613536242 end
36243+ emit(" sp_raise_cls(" + ensure_cls_var + ", " + ensure_msg_var + ");")
36244+ @indent = @indent - 1
36245+ emit(" }")
36246+ # Normal-path ensure (fall-through after success branch).
36247+ if ec >= 0
36248+ compile_stmts_body(@nd_body[ec])
36249+ end
36250+ @ensure_emit_depth = @ensure_emit_depth - 1
36251+ end
36252+ end
36253+
36254+ # Replay all in-scope ensure bodies inline (innermost-first) ahead
36255+ # of an early-exit `return`. Each ensure is popped from the stack
36256+ # *before* its body is emitted, so a nested `return` inside the
36257+ # ensure body sees only the *outer* ensures still active and
36258+ # doesn't replay the same ensure recursively. Stack is restored
36259+ # afterwards so the caller continues with the same view.
36260+ #
36261+ # @setjmp_depth is stashed to 0 during the replay because the
36262+ # caller is responsible for emitting `sp_exc_top -= N` *once*
36263+ # before the replays — a nested `return` inside an ensure body
36264+ # would otherwise re-emit that decrement and over-pop the stack.
36265+ def emit_ensure_replays
36266+ if @ensure_stack.length == 0
36267+ return
36268+ end
36269+ saved_setjmp_depth = @setjmp_depth
36270+ @setjmp_depth = 0
36271+ popped = "".split(",")
36272+ while @ensure_stack.length > 0
36273+ ec_str = @ensure_stack.pop
36274+ popped.push(ec_str)
36275+ compile_stmts_body(@nd_body[ec_str.to_i])
36276+ end
36277+ while popped.length > 0
36278+ @ensure_stack.push(popped.pop)
36279+ end
36280+ @setjmp_depth = saved_setjmp_depth
36281+ end
36282+
36283+ # Emit the `sp_exc_top -= N;` that an early `return` needs in
36284+ # order to leave sp_exc_top balanced. Called immediately before
36285+ # `emit_ensure_replays` at every `return` emission site.
36286+ def emit_setjmp_depth_unwind
36287+ if @setjmp_depth > 0
36288+ emit(" sp_exc_top -= " + @setjmp_depth.to_s + ";")
3613636289 end
3613736290 end
3613836291