Commit 0a69b225

0a69b225ac5dMerged

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

Description

Merge pull request #360 from mame/pr/ensure-runs-on-return

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

Details

Commit
0a69b225ac5d
Parent
90214e2fa8d5
Merge parent
fa5a85870694

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`
@@ -8153,6 +8170,12 @@
81538170 scan_ivars(ci, elems[k])
81548171 k = k + 1
81558172 end
8173+ if @nd_rescue_clause[nid] >= 0
8174+ scan_ivars(ci, @nd_rescue_clause[nid])
8175+ end
8176+ if @nd_ensure_clause[nid] >= 0
8177+ scan_ivars(ci, @nd_ensure_clause[nid])
8178+ end
81568179 end
81578180
81588181 def infer_ivar_init_type(nid)
@@ -30804,6 +30827,14 @@
3080430827 emit(" " + arr_tmp + "->_" + k.to_s + " = " + compile_expr(arg_ids[k]) + ";")
3080530828 k = k + 1
3080630829 end
30830+ # Replay any in-scope `ensure` bodies before the return.
30831+ # Ruby semantics: return value is already materialized, ensure
30832+ # may mutate locals/ivars but does not affect the saved value.
30833+ # `sp_exc_top -= N` undoes the setjmps we pushed; emit it once
30834+ # before the replays so a nested `return` inside an ensure
30835+ # body doesn't double-pop.
30836+ emit_setjmp_depth_unwind
30837+ emit_ensure_replays
3080730838 if @in_gc_scope == 1
3080830839 emit(" SP_GC_RESTORE();")
3080930840 end
@@ -30811,21 +30842,43 @@
3081130842 return
3081230843 end
3081330844 if arg_ids.length > 0
30845+ # `pre_return_unwind` = needs `sp_exc_top -= N;` and/or
30846+ # ensure-body replays. When neither, we can leave the
30847+ # original simple `return <expr>;` shape alone.
30848+ pre_return_unwind = 0
30849+ if @ensure_stack.length > 0
30850+ pre_return_unwind = 1
30851+ end
30852+ if @setjmp_depth > 0
30853+ pre_return_unwind = 1
30854+ end
3081430855 if @current_method_return == "poly"
3081530856 ret_expr = box_expr_to_poly(arg_ids[0])
3081630857 if @in_gc_scope == 1
3081730858 tmp = new_temp
3081830859 emit(" sp_RbVal " + tmp + " = " + ret_expr + ";")
30860+ emit_setjmp_depth_unwind
30861+ emit_ensure_replays
3081930862 emit(" SP_GC_RESTORE();")
3082030863 emit(" return " + tmp + ";")
3082130864 else
30822- emit(" return " + ret_expr + ";")
30865+ if pre_return_unwind == 1
30866+ tmp = new_temp
30867+ emit(" sp_RbVal " + tmp + " = " + ret_expr + ";")
30868+ emit_setjmp_depth_unwind
30869+ emit_ensure_replays
30870+ emit(" return " + tmp + ";")
30871+ else
30872+ emit(" return " + ret_expr + ";")
30873+ end
3082330874 end
3082430875 return
3082530876 end
3082630877 rt = infer_type(arg_ids[0])
3082730878 # return nil in a nullable pointer method → return NULL
3082830879 if rt == "nil" && is_nullable_pointer_type(@current_method_return) == 1
30880+ emit_setjmp_depth_unwind
30881+ emit_ensure_replays
3082930882 if @in_gc_scope == 1
3083030883 emit(" SP_GC_RESTORE();")
3083130884 end
@@ -30833,13 +30886,24 @@
3083330886 return
3083430887 end
3083530888 if @in_gc_scope == 1
30836- # Save return value, restore GC, then return
30889+ # Save return value, run ensure replays (which may mutate
30890+ # ivars/locals), restore GC, then return the saved value.
3083730891 tmp = new_temp
3083830892 emit(" " + c_type(rt) + " " + tmp + " = " + compile_expr(arg_ids[0]) + ";")
30893+ emit_setjmp_depth_unwind
30894+ emit_ensure_replays
3083930895 emit(" SP_GC_RESTORE();")
3084030896 emit(" return " + tmp + ";")
3084130897 else
30842- emit(" return " + compile_expr(arg_ids[0]) + ";")
30898+ if pre_return_unwind == 1
30899+ tmp = new_temp
30900+ emit(" " + c_type(rt) + " " + tmp + " = " + compile_expr(arg_ids[0]) + ";")
30901+ emit_setjmp_depth_unwind
30902+ emit_ensure_replays
30903+ emit(" return " + tmp + ";")
30904+ else
30905+ emit(" return " + compile_expr(arg_ids[0]) + ";")
30906+ end
3084330907 end
3084430908 return
3084530909 end
@@ -30858,6 +30922,8 @@
3085830922 # NULLed the instance on the early-return branch; in the void
3085930923 # `sp_<C>_initialize` form it was a `void function should not
3086030924 # return a value` C error.
30925+ emit_setjmp_depth_unwind
30926+ emit_ensure_replays
3086130927 if @in_gc_scope == 1
3086230928 emit(" SP_GC_RESTORE();")
3086330929 end
@@ -36431,6 +36497,24 @@
3643136497 end
3643236498 end
3643336499
36500+ # Outer setjmp wraps the body (and any rescue chain) so the ensure
36501+ # clause runs on the exception path too. Without this, a `raise`
36502+ # from inside the body would unwind past us with `ensure` skipped.
36503+ ensure_cls_var = ""
36504+ ensure_msg_var = ""
36505+ if has_ensure
36506+ @ensure_emit_depth = @ensure_emit_depth + 1
36507+ ensure_cls_var = "_ensure_cls_" + @ensure_emit_depth.to_s
36508+ ensure_msg_var = "_ensure_msg_" + @ensure_emit_depth.to_s
36509+ emit(" const char *" + ensure_cls_var + " = (const char *)0;")
36510+ emit(" const char *" + ensure_msg_var + " = (const char *)0;")
36511+ emit(" sp_exc_top++;")
36512+ emit(" if (setjmp(sp_exc_stack[sp_exc_top-1]) == 0) {")
36513+ @indent = @indent + 1
36514+ @setjmp_depth = @setjmp_depth + 1
36515+ @ensure_stack.push(@nd_ensure_clause[nid].to_s)
36516+ end
36517+
3643436518 if has_retry == 1
3643536519 emit(" for (;;) {")
3643636520 @indent = @indent + 1
@@ -36438,6 +36522,7 @@
3643836522
3643936523 if has_rescue
3644036524 emit(" sp_exc_top++;")
36525+ @setjmp_depth = @setjmp_depth + 1
3644136526 emit(" if (setjmp(sp_exc_stack[sp_exc_top-1]) == 0) {")
3644236527 @indent = @indent + 1
3644336528 compile_stmts_body(@nd_body[nid])
@@ -36457,6 +36542,7 @@
3645736542 @indent = @indent - 1
3645836543 end
3645936544 emit(" }")
36545+ @setjmp_depth = @setjmp_depth - 1
3646036546 else
3646136547 compile_stmts_body(@nd_body[nid])
3646236548 end
@@ -36467,10 +36553,77 @@
3646736553 end
3646836554
3646936555 if has_ensure
36556+ @ensure_stack.pop
36557+ # End of the if-success branch: pop our setjmp and close the
36558+ # brace. After this the codegen is conceptually back at the
36559+ # surrounding scope — drop the depth bump even though more
36560+ # code (the else branch and fall-through ensure) is still
36561+ # being emitted; both run with sp_exc_top already restored.
36562+ emit(" sp_exc_top--;")
36563+ @indent = @indent - 1
36564+ @setjmp_depth = @setjmp_depth - 1
36565+ emit(" } else {")
36566+ @indent = @indent + 1
36567+ # Exception path: pop our setjmp, snapshot the in-flight
36568+ # exception (because nested raises inside the ensure body
36569+ # would clobber sp_last_exc_cls / sp_exc_msg), run the
36570+ # ensure body, then re-raise so the exception keeps
36571+ # propagating. If the ensure body contains its own `return`,
36572+ # the re-raise becomes dead code — that's the explicit
36573+ # "ensure overrides exception with return" semantics.
36574+ emit(" sp_exc_top--;")
36575+ emit(" " + ensure_cls_var + " = (const char *)sp_last_exc_cls;")
36576+ emit(" " + ensure_msg_var + " = sp_exc_msg[sp_exc_top];")
3647036577 ec = @nd_ensure_clause[nid]
3647136578 if ec >= 0
3647236579 compile_stmts_body(@nd_body[ec])
3647336580 end
36581+ emit(" sp_raise_cls(" + ensure_cls_var + ", " + ensure_msg_var + ");")
36582+ @indent = @indent - 1
36583+ emit(" }")
36584+ # Normal-path ensure (fall-through after success branch).
36585+ if ec >= 0
36586+ compile_stmts_body(@nd_body[ec])
36587+ end
36588+ @ensure_emit_depth = @ensure_emit_depth - 1
36589+ end
36590+ end
36591+
36592+ # Replay all in-scope ensure bodies inline (innermost-first) ahead
36593+ # of an early-exit `return`. Each ensure is popped from the stack
36594+ # *before* its body is emitted, so a nested `return` inside the
36595+ # ensure body sees only the *outer* ensures still active and
36596+ # doesn't replay the same ensure recursively. Stack is restored
36597+ # afterwards so the caller continues with the same view.
36598+ #
36599+ # @setjmp_depth is stashed to 0 during the replay because the
36600+ # caller is responsible for emitting `sp_exc_top -= N` *once*
36601+ # before the replays — a nested `return` inside an ensure body
36602+ # would otherwise re-emit that decrement and over-pop the stack.
36603+ def emit_ensure_replays
36604+ if @ensure_stack.length == 0
36605+ return
36606+ end
36607+ saved_setjmp_depth = @setjmp_depth
36608+ @setjmp_depth = 0
36609+ popped = "".split(",")
36610+ while @ensure_stack.length > 0
36611+ ec_str = @ensure_stack.pop
36612+ popped.push(ec_str)
36613+ compile_stmts_body(@nd_body[ec_str.to_i])
36614+ end
36615+ while popped.length > 0
36616+ @ensure_stack.push(popped.pop)
36617+ end
36618+ @setjmp_depth = saved_setjmp_depth
36619+ end
36620+
36621+ # Emit the `sp_exc_top -= N;` that an early `return` needs in
36622+ # order to leave sp_exc_top balanced. Called immediately before
36623+ # `emit_ensure_replays` at every `return` emission site.
36624+ def emit_setjmp_depth_unwind
36625+ if @setjmp_depth > 0
36626+ emit(" sp_exc_top -= " + @setjmp_depth.to_s + ";")
3647436627 end
3647536628 end
3647636629