Commit 9aa3594a

9aa3594a0b6cMerged

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

Description

fix(codegen): exception object methods, bare-raise re-raise, propagate-on-no-match

This patch makes spinel's rescue semantics line up with CRuby on three correctness gaps that share the same machinery — a snapshot of the in-flight exception's class+message taken at rescue body entry.

  1. .message / .class / .to_s / .inspect / .full_message / .backtrace on a rescue => e variable. Spinel binds e to the message string for backward compatibility with existing puts e tests, but now also tracks e as an exception in parallel @exc_var_names / @exc_var_cls_vars stacks. The top of compile_call_expr and infer_call_type short-circuit method calls on these variables to read the snapshot. puts e still works (drops to string dispatch). e.message returns lv_e. e.class returns the snapshotted class string. e.inspect returns "#<ClassName: msg>". .full_message returns "ClassName: msg". .backtrace returns nil (spinel doesn't track backtraces).

  2. Bare raise inside a rescue body re-raises the original exception with its class+message intact. Previously every bare raise emitted sp_raise("RuntimeError"), losing the original class. Now it emits sp_raise_cls(saved_cls, saved_msg) reading from the snapshot stack pushed by compile_rescue_chain. Outside a rescue body, bare raise still defaults to RuntimeError (CRuby's behavior). The three emit sites (compile_no_recv_call_expr's raise arm and the two arms of compile_control_call_stmt) share one emit_bare_raise helper to stay in lockstep.

  3. Propagation when no rescue type matches. Previously a typed-rescue clause whose sp_exc_is_a check returned false silently dropped the exception (the surrounding setjmp had already decremented sp_exc_top). Now the else-branch of the type check re-raises via sp_raise_cls(saved_cls, saved_msg) so the enclosing handler — or unhandled-exception path — sees it.

The snapshot lives in C locals declared BEFORE the type-check if so both branches can reference it, fixing a scope bug discovered during implementation.

New test: test/exception_object_methods.rb covers:

  • Object methods on default-raise, ArgumentError, TypeError
  • Bare-raise re-raise preserving class+msg
  • Backward-compatible puts e shape
  • Propagation through a non-matching typed rescue (fix #3)
  • .backtrace returns nil
  • .full_message returns "ClassName: message"
  • Multi-clause rescue chain (recursive sub-chain in compile_rescue_chain)

Existing test/rescue.rb (which uses puts e to print the message) continues to pass without modification.

Tests: 381 pass, 0 fail, 0 error. Bootstrap: gen2.c == gen3.c.

Co-Authored-By: Claude Opus 4.7 (1M context) [email protected]

Details

Commit
9aa3594a0b6c
Parent
2e1c2c409741

spinel_codegen.rbmodifiedView file

@@ -302,6 +302,19 @@
302302 @needs_sym_str_hash = 0
303303 @needs_sym_intern = 0
304304 @needs_setjmp = 0
305+ # Stack of (class_var, msg_var) pairs naming the snapshot locals
306+ # emitted at the top of each rescue body. A bare `raise` inside a
307+ # rescue body re-raises with the snapshotted class+message rather
308+ # than fabricating a fresh RuntimeError. Empty outside any rescue.
309+ @rescue_cls_stack = "".split(",")
310+ @rescue_msg_stack = "".split(",")
311+ @rescue_depth = 0
312+ # Exception variable bindings: parallel stacks of (var_name, cls_var).
313+ # A `rescue => e` binds `e` to the message string and registers it
314+ # here so that `e.message`, `e.class`, `e.to_s`, and `e.inspect`
315+ # dispatch correctly. Pushed at rescue body entry, popped at exit.
316+ @exc_var_names = "".split(",")
317+ @exc_var_cls_vars = "".split(",")
305318 @needs_mutable_str = 0
306319 @needs_rb_value = 0
307320 @needs_regexp = 0
@@ -1270,6 +1283,33 @@
12701283 0
12711284 end
12721285
1286+ # Returns the snapshot class-name C variable for an exception
1287+ # variable currently bound by an enclosing `rescue => name`, or
1288+ # empty string if `name` is not an active exception binding.
1289+ def find_exc_var_cls(name)
1290+ i = @exc_var_names.length - 1
1291+ while i >= 0
1292+ if @exc_var_names[i] == name
1293+ return @exc_var_cls_vars[i]
1294+ end
1295+ i = i - 1
1296+ end
1297+ ""
1298+ end
1299+
1300+ # Emit a bare `raise` (no message arg). Inside a rescue body the
1301+ # snapshotted class+message is re-raised; outside any rescue it
1302+ # falls back to a fresh RuntimeError, matching CRuby.
1303+ def emit_bare_raise
1304+ if @rescue_cls_stack.length > 0
1305+ rcls = @rescue_cls_stack.last
1306+ rmsg = @rescue_msg_stack.last
1307+ emit(" sp_raise_cls(" + rcls + ", " + rmsg + ");")
1308+ else
1309+ emit(" sp_raise(\"RuntimeError\");")
1310+ end
1311+ end
1312+
12731313 def find_var_type(name)
12741314 # Type-narrow override (issue #207): walk top-down so the
12751315 # innermost is_a? guard wins. Skipped for the unscoped global
@@ -2706,6 +2746,20 @@
27062746 mname = @nd_name[nid]
27072747 recv = @nd_receiver[nid]
27082748
2749+ # Methods on a `rescue => e` bound exception variable. The variable
2750+ # itself is string-typed but .class / .message / .to_s / .inspect /
2751+ # .full_message return strings; .backtrace returns nil for now.
2752+ if recv >= 0 && @nd_type[recv] == "LocalVariableReadNode"
2753+ if find_exc_var_cls(@nd_name[recv]) != ""
2754+ if mname == "message" || mname == "to_s" || mname == "class" || mname == "inspect" || mname == "full_message"
2755+ return "string"
2756+ end
2757+ if mname == "backtrace"
2758+ return "nil"
2759+ end
2760+ end
2761+ end
2762+
27092763 # `recv.__sp_ieval_<N>(...)`: the rewritten form of an
27102764 # `recv.instance_eval { ... }` call. v1 only fired on top-level call
27112765 # sites, where the call's value was always discarded — so its return
@@ -21278,6 +21332,35 @@
2127821332 mname = @nd_name[nid]
2127921333 recv = @nd_receiver[nid]
2128021334
21335+ # Exception variable bound by `rescue => e`: spinel binds `e` to
21336+ # the message string but tracks it as an exception in
21337+ # @exc_var_names so .class / .message / .to_s / .inspect dispatch
21338+ # correctly. The variable's static type is still "string", so any
21339+ # other method call falls through to string method dispatch — this
21340+ # preserves backward compatibility for the common `puts e` shape.
21341+ if recv >= 0 && @nd_type[recv] == "LocalVariableReadNode"
21342+ exc_cls = find_exc_var_cls(@nd_name[recv])
21343+ if exc_cls != ""
21344+ recv_name = @nd_name[recv]
21345+ if mname == "message" || mname == "to_s"
21346+ return "lv_" + recv_name
21347+ end
21348+ if mname == "class"
21349+ return exc_cls
21350+ end
21351+ if mname == "inspect"
21352+ return "sp_sprintf(\"#<%s: %s>\", " + exc_cls + ", lv_" + recv_name + ")"
21353+ end
21354+ if mname == "backtrace"
21355+ # Spinel doesn't track per-exception backtraces; return nil.
21356+ return "0"
21357+ end
21358+ if mname == "full_message"
21359+ return "sp_sprintf(\"%s: %s\", " + exc_cls + ", lv_" + recv_name + ")"
21360+ end
21361+ end
21362+ end
21363+
2128121364 # Issue #126: `Module.accessor.<method>` where the slot was
2128221365 # resolved by `resolve_module_singleton_accessors`. With a single
2128321366 # constant in the resolved set, inline the call directly. With
@@ -22121,7 +22204,7 @@
2212122204 emit(" sp_raise(" + compile_expr(arg_ids[0]) + ");")
2212222205 end
2212322206 else
22124- emit(" sp_raise(\"RuntimeError\");")
22207+ emit_bare_raise
2212522208 end
2212622209 return "0"
2212722210 end
@@ -31397,11 +31480,11 @@
3139731480 emit(" sp_raise(" + compile_expr(arg_ids[0]) + ");")
3139831481 end
3139931482 else
31400- emit(" sp_raise(\"RuntimeError\");")
31483+ emit_bare_raise
3140131484 end
3140231485 end
3140331486 else
31404- emit(" sp_raise(\"RuntimeError\");")
31487+ emit_bare_raise
3140531488 end
3140631489 return 1
3140731490 end
@@ -35867,6 +35950,19 @@
3586735950 # Check for exception type matching
3586835951 exc_types = parse_id_list(@nd_exceptions[rc])
3586935952 ref = @nd_reference[rc]
35953+ # Snapshot the in-flight exception BEFORE the type-check `if` so
35954+ # that the else-branch (re-raise / propagation) can also reference
35955+ # the snapshot. Bare `raise` inside this body re-raises with the
35956+ # original class+message even if the body itself triggers (and
35957+ # catches) a nested raise that would otherwise clobber
35958+ # sp_last_exc_cls / sp_exc_msg[sp_exc_top].
35959+ @rescue_depth = @rescue_depth + 1
35960+ saved_cls = "_rescue_cls_" + @rescue_depth.to_s
35961+ saved_msg = "_rescue_msg_" + @rescue_depth.to_s
35962+ emit(" const char *" + saved_cls + " = (const char *)sp_last_exc_cls;")
35963+ emit(" const char *" + saved_msg + " = sp_exc_msg[sp_exc_top];")
35964+ @rescue_cls_stack.push(saved_cls)
35965+ @rescue_msg_stack.push(saved_msg)
3587035966 has_type_check = 0
3587135967 if exc_types.length > 0
3587235968 has_type_check = 1
@@ -35883,11 +35979,21 @@
3588335979 emit(" if (" + cond + ") {")
3588435980 @indent = @indent + 1
3588535981 end
35982+ bound_rname = ""
3588635983 if ref >= 0
35887- rname = @nd_name[ref]
35888- emit(" lv_" + rname + " = sp_exc_msg[sp_exc_top];")
35984+ bound_rname = @nd_name[ref]
35985+ emit(" lv_" + bound_rname + " = " + saved_msg + ";")
35986+ @exc_var_names.push(bound_rname)
35987+ @exc_var_cls_vars.push(saved_cls)
3588935988 end
3589035989 compile_rescue_body(@nd_body[rc], has_retry)
35990+ if bound_rname != ""
35991+ @exc_var_names.pop
35992+ @exc_var_cls_vars.pop
35993+ end
35994+ @rescue_cls_stack.pop
35995+ @rescue_msg_stack.pop
35996+ @rescue_depth = @rescue_depth - 1
3589135997 if has_type_check == 1
3589235998 @indent = @indent - 1
3589335999 # Check for subsequent rescue
@@ -35897,6 +36003,13 @@
3589736003 @indent = @indent + 1
3589836004 compile_rescue_chain(sub, has_retry)
3589936005 @indent = @indent - 1
36006+ else
36007+ # No subsequent clause and the type check missed: re-raise
36008+ # using the snapshotted class+message so an enclosing handler
36009+ # can match it (or the program terminates with the original
36010+ # diagnostic). Without this the exception was silently dropped.
36011+ emit(" } else {")
36012+ emit(" sp_raise_cls(" + saved_cls + ", " + saved_msg + ");")
3590036013 end
3590136014 emit(" }")
3590236015 end