Commit e6bdc7d8

e6bdc7d8f6ddMerged

Yukihiro "Matz" Matsumoto <[email protected]> · 5 months ago · 1 file · ~1 modified

Description

Merge pull request #1278 from rubys/fix-covariant-return-dispatch

Dispatch implicit-self calls with covariant object return types (fixes #1277)

Details

Commit
e6bdc7d8f6dd
Parent
bf0d02eb0409
Merge parent
97459e90443a

spinel_codegen.rbmodifiedView file

@@ -19131,8 +19131,30 @@
1913119131 cand_owner = p[1].to_i
1913219132 cand_rt = cls_method_return(cand_owner, mname)
1913319133 if c_type(cand_rt) != base_rt_c
19134- rt_ok = 0
19135- ol = ovr_list.length
19134+ # Covariant object return: the override returns a proper
19135+ # subtype of the base's declared return (e.g. an RBS base
19136+ # `() -> Base` with a subclass `() -> Sub`, or `self`-
19137+ # returning per-model primitives). The C types differ
19138+ # (sp_Sub* vs sp_Base*) but the dispatch is still valid —
19139+ # the switch arm upcasts the result to the base C type.
19140+ # Without this, an RBS signature on the base method
19141+ # suppresses dispatch entirely (matz/spinel#1277).
19142+ base_bt = base_type(base_rt)
19143+ cand_bt = base_type(cand_rt)
19144+ covariant = 0
19145+ if is_obj_type(base_bt) == 1 && is_obj_type(cand_bt) == 1
19146+ # Strip the "obj_" prefix (codebase idiom) to name the
19147+ # classes, then test the subtype relationship.
19148+ base_cls = find_class_idx(base_bt[4, base_bt.length - 4])
19149+ cand_cls = find_class_idx(cand_bt[4, cand_bt.length - 4])
19150+ covariant = cls_is_descendant(cand_cls, base_cls)
19151+ end
19152+ if covariant == 1
19153+ ol = ol + 1
19154+ else
19155+ rt_ok = 0
19156+ ol = ovr_list.length
19157+ end
1913619158 else
1913719159 ol = ol + 1
1913819160 end
@@ -19158,7 +19180,17 @@
1915819180 cand_name = @cls_names[cand_owner2]
1915919181 cand_recv = "(sp_" + cand_name + " *)" + self_expr
1916019182 cand_call = "sp_" + cand_name + "_" + sanitize_name(mname) + "(" + cand_recv + build_call_tail(ca, bp, yargs) + ")"
19161- emit(" case " + cand_cid.to_s + "LL: " + tmp + " = " + cand_call + "; break;")
19183+ # Upcast covariant object returns to the base C type: the
19184+ # arm's call yields a subtype pointer (sp_Sub *) while tmp is
19185+ # the base type (sp_Base *). Only emit the cast when the C
19186+ # types actually differ, so an exact-match arm keeps full
19187+ # compiler diagnostics (matz/spinel#1277).
19188+ cand_arm_rt = cls_method_return(cand_owner2, mname)
19189+ arm_val = cand_call
19190+ if c_type(cand_arm_rt) != rt_c
19191+ arm_val = "(" + rt_c + ")" + cand_call
19192+ end
19193+ emit(" case " + cand_cid.to_s + "LL: " + tmp + " = " + arm_val + "; break;")
1916219194 ol2 = ol2 + 1
1916319195 end
1916419196 emit(" default: " + tmp + " = " + default_call + "; break;")