Commit 9fdf82e3

9fdf82e37fe5Merged

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

Description

fix(codegen): rescue + is_a? walk the class hierarchy

rescue ParentClass => e should catch a raised subclass instance, and e.is_a?(AncestorClass) should walk the class chain. Pre-fix sp_exc_is_a in lib/sp_runtime.h did a plain strcmp on the class name, so raise C where C < B < A < StandardError skipped every intermediate rescue arm and is_a? returned false for every ancestor (including the exact class once dispatched).

The codegen now emits two name-keyed helpers when the program contains any RescueNode:

sp_exc_parent_of(name) -> NULL or parent name sp_exc_class_le(name, target) -> walks the parent chain

The parent table has two parts: a built-in chain that mirrors MRI's Exception hierarchy (StandardError -> Exception, RuntimeError -> StandardError, ArgumentError / TypeError / IndexError / etc. -> StandardError, KeyError -> IndexError, ...) plus the user-defined (cname, parent) pairs from @cls_names / @cls_parents. The walker is name-based (not cls_id-based) because the rescue path tracks sp_last_exc_cls as a string and the raised class might be a CRuby built-in that spinel doesn't carry in sp_class_names[].

compile_rescue_chain (both the dispatch and the chain-into-tmp variant for method-level rescues) now lowers the explicit-class arm to sp_exc_class_le. The exception-variable dispatch in compile_call_expr picks up .is_a? / .kind_of? alongside the existing .class / .message / .to_s / .inspect / .full_message arms.

emit_class_runtime gains an emit_exc_class_hierarchy_helpers sub-call, hoisted out of the @needs_class_table early-return so small programs with rescue but no Class-value usage still pick up the helper. scan_for_class_hierarchy_usage flips @needs_exc_class_hierarchy on RescueNode discovery so the helper exists by emit time.

Fixes #627

Co-Authored-By: Claude Opus 4.7 [email protected]

Details

Commit
9fdf82e37fe5
Parent
89366c49afe9

spinel_codegen.rbmodifiedView file

@@ -204,6 +204,11 @@
204204 # @needs_class_table covers the names table; these extend it.
205205 @needs_class_parents = 0
206206 @needs_class_ancestors = 0
207+ # Set when `rescue ExplicitClass` or `e.is_a?(C)` (where e was
208+ # bound by a rescue) needs to walk a class-name parent chain at
209+ # runtime. Gates sp_exc_parent_of + sp_exc_class_le emission.
210+ # Issue #627.
211+ @needs_exc_class_hierarchy = 0
207212 @cls_ivar_names = "".split(",")
208213 @cls_ivar_types = "".split(",")
209214 # Per-ivar flag: was the ivar's first scanned write a definite
@@ -7300,6 +7305,10 @@
73007305 # a definition.
73017306 if @needs_class_table == 0
73027307 emit_raw("static const char *sp_class_to_s(sp_Class c){(void)c;return \"\";}")
7308+ # Exception-class hierarchy helpers stand alone (don't need
7309+ # sp_class_names[]), so emit them even when the rest of the
7310+ # class-runtime cluster is skipped. Issue #627.
7311+ emit_exc_class_hierarchy_helpers
73037312 return
73047313 end
73057314 emit_raw("/* sp_Class names table */")
@@ -7468,6 +7477,7 @@
74687477 emit_raw("static sp_PolyArray *sp_class_ancestors_arr(sp_Class c) __attribute__((unused));")
74697478 emit_raw("static sp_PolyArray *sp_class_ancestors_arr(sp_Class c){sp_PolyArray*r=sp_PolyArray_new();if(c.cls_id<0||c.cls_id>=SP_CLASS_COUNT)return r;mrb_int s=sp_class_ancestors_off[c.cls_id];mrb_int e=sp_class_ancestors_off[c.cls_id+1];for(mrb_int k=s;k<e;k++){sp_Class el={sp_class_ancestors_flat[k]};sp_PolyArray_push(r,sp_box_class(el));}return r;}")
74707479 end
7480+ emit_exc_class_hierarchy_helpers
74717481 if @needs_class_for_poly == 1
74727482 # Tier 4: recover the cls_id of a poly value. Each primitive
74737483 # tag maps to the corresponding built-in cls_id (Integer=9,
@@ -7482,6 +7492,83 @@
74827492 emit_raw("")
74837493 end
74847494
7495+ # Exception class-name parent walker. `rescue ParentClass` and
7496+ # `e.is_a?(ParentClass)` need to know that `class B < A` makes
7497+ # any `raise B` instance match a `rescue A`. The walker takes
7498+ # class names (not cls_ids) because the rescue path tracks
7499+ # sp_last_exc_cls as a string -- the raised class might not be
7500+ # in the codegen-emitted sp_class_names[] table (e.g. when the
7501+ # raised class is one of the built-in CRuby exception classes
7502+ # like StandardError that spinel doesn't track as a user class).
7503+ # Issue #627. Independent of @needs_class_table since the walker
7504+ # uses inline strcmp / no sp_class_names lookup.
7505+ def emit_exc_class_hierarchy_helpers
7506+ if @needs_exc_class_hierarchy == 0
7507+ return
7508+ end
7509+ emit_raw("static const char *sp_exc_parent_of(const char *cls) __attribute__((unused));")
7510+ ep_body = "static const char *sp_exc_parent_of(const char *cls){"
7511+ # Built-in exception class hierarchy. Matches MRI's
7512+ # Exception class chain that user code routinely names in
7513+ # `rescue` / `raise` clauses without ever defining them.
7514+ builtin_parents = [
7515+ ["StandardError", "Exception"],
7516+ ["RuntimeError", "StandardError"],
7517+ ["ArgumentError", "StandardError"],
7518+ ["TypeError", "StandardError"],
7519+ ["IndexError", "StandardError"],
7520+ ["KeyError", "IndexError"],
7521+ ["RangeError", "StandardError"],
7522+ ["FloatDomainError", "RangeError"],
7523+ ["NameError", "StandardError"],
7524+ ["NoMethodError", "NameError"],
7525+ ["ZeroDivisionError", "StandardError"],
7526+ ["IOError", "StandardError"],
7527+ ["EOFError", "IOError"],
7528+ ["FrozenError", "RuntimeError"],
7529+ ["NotImplementedError", "ScriptError"],
7530+ ["ScriptError", "Exception"],
7531+ ["LoadError", "ScriptError"],
7532+ ["SyntaxError", "ScriptError"],
7533+ ["StopIteration", "IndexError"],
7534+ ["RegexpError", "StandardError"],
7535+ ["EncodingError", "StandardError"],
7536+ ["SystemCallError", "StandardError"],
7537+ ["LocalJumpError", "StandardError"],
7538+ ["FiberError", "StandardError"],
7539+ ["Exception", ""],
7540+ ]
7541+ bp = 0
7542+ while bp < builtin_parents.length
7543+ cname_bp = builtin_parents[bp][0]
7544+ pname_bp = builtin_parents[bp][1]
7545+ if pname_bp == ""
7546+ ep_body = ep_body + "if(strcmp(cls,\"" + cname_bp + "\")==0)return NULL;"
7547+ else
7548+ ep_body = ep_body + "if(strcmp(cls,\"" + cname_bp + "\")==0)return \"" + pname_bp + "\";"
7549+ end
7550+ bp = bp + 1
7551+ end
7552+ # User exception classes (and any user class -- the walker is
7553+ # name-based so it works uniformly). Emit each (cname, parent)
7554+ # pair from @cls_names + @cls_parents.
7555+ uc = 0
7556+ while uc < @cls_names.length
7557+ pname_uc = ""
7558+ if uc < @cls_parents.length
7559+ pname_uc = @cls_parents[uc]
7560+ end
7561+ if pname_uc != ""
7562+ ep_body = ep_body + "if(strcmp(cls,\"" + @cls_names[uc] + "\")==0)return \"" + pname_uc + "\";"
7563+ end
7564+ uc = uc + 1
7565+ end
7566+ ep_body = ep_body + "return NULL;}"
7567+ emit_raw(ep_body)
7568+ emit_raw("static mrb_bool sp_exc_class_le(const char *cls, const char *target) __attribute__((unused));")
7569+ emit_raw("static mrb_bool sp_exc_class_le(const char *cls, const char *target){if(!cls||!target)return FALSE;if(strcmp(cls,target)==0)return TRUE;const char *cur=cls;int depth=0;while(cur&&depth<32){cur=sp_exc_parent_of(cur);if(!cur)return FALSE;if(strcmp(cur,target)==0)return TRUE;depth++;}return FALSE;}")
7570+ end
7571+
74857572 # unified cls_id space layout.
74867573 # The emit-side cls_id is global: built-ins occupy
74877574 # [0 .. builtin_class_count - 1], user classes
@@ -10454,10 +10541,19 @@
1045410541 if nid < 0
1045510542 return
1045610543 end
10457- if @needs_class_parents == 1 && @needs_class_ancestors == 1 && @needs_class_for_poly == 1
10544+ t_ch = @nd_type[nid]
10545+ # Any RescueNode means we'll need the exception-class hierarchy
10546+ # walker -- the rescue dispatch uses it for `rescue ParentClass`,
10547+ # and any `e.is_a?(X)` inside the body also needs it. Conservative
10548+ # (bare `rescue` doesn't strictly need the helper, but the cost
10549+ # is a couple-hundred bytes of dead code on programs without
10550+ # is_a? on the bound var). Issue #627.
10551+ if t_ch == "RescueNode"
10552+ @needs_exc_class_hierarchy = 1
10553+ end
10554+ if @needs_class_parents == 1 && @needs_class_ancestors == 1 && @needs_class_for_poly == 1 && @needs_exc_class_hierarchy == 1
1045810555 return
1045910556 end
10460- t_ch = @nd_type[nid]
1046110557 if t_ch == "ConstantReadNode"
1046210558 cname_ch = @nd_name[nid]
1046310559 # ConstantReadNode resolving to a class / module / built-in
@@ -13122,6 +13218,25 @@
1312213218 if mname == "full_message"
1312313219 return "sp_sprintf(\"%s: %s\", " + exc_cls + ", lv_" + recv_name + ")"
1312413220 end
13221+ # `e.is_a?(X)` / `.kind_of?(X)` on an exception binding walks
13222+ # the class-name parent chain so a `rescue => e` catching a
13223+ # subclass instance still answers true for the parent class.
13224+ # Issue #627. The class-snapshot string `exc_cls` carries the
13225+ # raised class name (set by sp_raise_cls); sp_exc_class_le
13226+ # walks the parent table emitted from emit_class_runtime.
13227+ if mname == "is_a?" || mname == "kind_of?"
13228+ args_id_is = @nd_arguments[nid]
13229+ if args_id_is >= 0
13230+ ais = get_args(args_id_is)
13231+ if ais.length > 0
13232+ arg_name_is = resolve_introspection_arg_name(ais[0])
13233+ if arg_name_is != ""
13234+ @needs_exc_class_hierarchy = 1
13235+ return "sp_exc_class_le(" + exc_cls + ", \"" + arg_name_is + "\")"
13236+ end
13237+ end
13238+ end
13239+ end
1312513240 end
1312613241 end
1312713242
@@ -33643,14 +33758,17 @@
3364333758 has_type_check = 0
3364433759 if exc_types.length > 0
3364533760 has_type_check = 1
33646- # Build condition: sp_exc_is_a(sp_last_exc_cls, "ClassName")
33761+ # Build condition: sp_exc_class_le(sp_last_exc_cls, "ClassName")
33762+ # walks the class-name parent chain so `rescue ParentClass`
33763+ # catches a raised subclass. Issue #627.
33764+ @needs_exc_class_hierarchy = 1
3364733765 cond = ""
3364833766 k = 0
3364933767 while k < exc_types.length
3365033768 if k > 0
3365133769 cond = cond + " || "
3365233770 end
33653- cond = cond + "sp_exc_is_a((const char*)sp_last_exc_cls, \"" + @nd_name[exc_types[k]] + "\")"
33771+ cond = cond + "sp_exc_class_le((const char*)sp_last_exc_cls, \"" + @nd_name[exc_types[k]] + "\")"
3365433772 k = k + 1
3365533773 end
3365633774 emit(" if (" + cond + ") {")
@@ -34899,13 +35017,15 @@
3489935017 has_type_check = 0
3490035018 if exc_types.length > 0
3490135019 has_type_check = 1
35020+ # See compile_rescue_chain for sp_exc_class_le rationale (#627).
35021+ @needs_exc_class_hierarchy = 1
3490235022 cond = ""
3490335023 k = 0
3490435024 while k < exc_types.length
3490535025 if k > 0
3490635026 cond = cond + " || "
3490735027 end
34908- cond = cond + "sp_exc_is_a((const char*)sp_last_exc_cls, \"" + @nd_name[exc_types[k]] + "\")"
35028+ cond = cond + "sp_exc_class_le((const char*)sp_last_exc_cls, \"" + @nd_name[exc_types[k]] + "\")"
3490935029 k = k + 1
3491035030 end
3491135031 emit(" if (" + cond + ") {")