Commit 1961599c

1961599cfed8Merged

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

Description

refactor: extract poly-recv dispatch helpers to compiler_helpers.rb

Followup to d9b9b47 (nil-guard extraction). Move the four poly-dispatch helpers (poly_dispatch_return_type / poly_dispatch_narrow_class_set / poly_dispatch_class_in_set / poly_dispatch_arm_param_compat) to the shared file too.

Pre-extraction the analyze and codegen copies had drifted:

  • analyze was missing the fetch and gsub/sub early- return arms that codegen had since #549. Without them analyze could pick a scalar common return type while codegen widened to poly for the same dispatch site, giving the inferred return type and the emitted temp type divergent answers.
  • analyze used cls_find_method_direct while codegen used cls_find_method (inherited-walk variant); for a hash method defined on a base class but called on a subclass recv, analyze missed the inherited definition.

Reconcile to the codegen variant (with parent-walk + fetch/gsub/sub arms), keep the permissive analyze-style signature (mname, nid = -1, arg_types = nil) so the no-context callers still work. Both files now require_relative "compiler_helpers" for the shared implementation; the in-file definitions are replaced by a short pointer comment.

Verified: 527 tests pass, optcarrot checksum 59662 preserved.

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

Details

Commit
1961599cfed8
Parent
0eb0fff518a0

compiler_helpers.rbmodifiedView file

@@ -132,4 +132,242 @@
132132 ""
133133 end
134134
135+ # ---- Poly-recv dispatch helpers (#549) ----
136+
137+ # For a `<poly>.<mname>(args)` site, return the static C type
138+ # the dispatch result temp should have. Returns "poly" when
139+ # the surviving cls_id arms can't agree on a single scalar.
140+ # nid + arg_types let the helper apply the same arm-suppression
141+ # logic the emit loop uses (param-incompat + observed-class
142+ # narrow), so unreachable arms don't widen the result.
143+ def poly_dispatch_return_type(mname, nid = -1, arg_types = nil)
144+ if arg_types == nil
145+ arg_types = "".split(",")
146+ end
147+ if mname == "[]"
148+ @needs_rb_value = 1
149+ return "poly"
150+ end
151+ # Hash-shape preserving methods on a poly recv carrying hash
152+ # storage. The result temp must be sp_RbVal so the per-cls_id
153+ # arm's `tmp = sp_box_obj(...)` lands. Without this, the temp
154+ # is mrb_int and the assignment silently no-ops, leaving every
155+ # downstream consumer reading the int 0 default.
156+ if mname == "dup" || mname == "each" || mname == "to_h" || mname == "merge"
157+ @needs_rb_value = 1
158+ return "poly"
159+ end
160+ # `fetch` on a poly recv: runtime cls_id picks between user-class
161+ # `fetch` arms and built-in Hash-variant arms (StrIntHash /
162+ # StrStrHash / StrPolyHash). Each arm's value type differs (int /
163+ # string / poly) so the result temp must be sp_RbVal -- without
164+ # widening, the temp's static C type comes from the first user
165+ # class's `fetch` return and other arms' rhs fails to compile
166+ # against it. Sibling to `[]` widening above; same rationale.
167+ if mname == "fetch"
168+ @needs_rb_value = 1
169+ return "poly"
170+ end
171+ # Source-level narrow set from ivar observations: when the
172+ # receiver reads from an ivar whose observed type set is all
173+ # obj_X (no poly / no primitives), the dispatch can only ever
174+ # land on those classes. Combined with the param-incompat
175+ # check below, this prunes arms whose return type would
176+ # otherwise widen the dispatch result to sp_RbVal even though
177+ # they can never fire at runtime. Issues #549, #531.
178+ narrow_set = poly_dispatch_narrow_class_set(nid)
179+ # Built-in string methods that compile_poly_method_call also
180+ # lowers via a SP_TAG_STR arm -- their result temp needs to be
181+ # at least string-typed so the per-tag dispatch assignment
182+ # doesn't try to store const char * into a mrb_int slot. If a
183+ # user class also defines the method with a different return
184+ # type, the per-class loop below escalates to "poly".
185+ if mname == "gsub" || mname == "sub"
186+ ci_s = 0
187+ diverges = 0
188+ while ci_s < @cls_names.length
189+ if narrow_set != "" && poly_dispatch_class_in_set(narrow_set, ci_s) == 0
190+ ci_s = ci_s + 1
191+ else
192+ if cls_find_method(ci_s, mname) >= 0 && poly_dispatch_arm_param_compat(ci_s, mname, arg_types) == 1
193+ urt = cls_method_return(ci_s, mname)
194+ if urt != "" && urt != "string"
195+ diverges = 1
196+ ci_s = @cls_names.length
197+ end
198+ end
199+ ci_s = ci_s + 1
200+ end
201+ end
202+ if diverges == 1
203+ @needs_rb_value = 1
204+ return "poly"
205+ end
206+ return "string"
207+ end
208+ # Setters: mname ends with "=" and at least one class has an
209+ # attr_writer for the bare name. Return type is the ivar type
210+ # (Ruby returns the rhs from `x = v`); without this, the result
211+ # tmp's C type defaults to `mrb_int` and `tmp = rhs` mismatches
212+ # for non-int slots.
213+ setter_bname = ""
214+ if mname.length > 1 && mname[mname.length - 1] == "="
215+ setter_bname = mname[0, mname.length - 1]
216+ end
217+ common = ""
218+ ci = 0
219+ while ci < @cls_names.length
220+ if narrow_set != "" && poly_dispatch_class_in_set(narrow_set, ci) == 0
221+ ci = ci + 1
222+ else
223+ rt = ""
224+ if cls_find_method(ci, mname) >= 0
225+ # Skip arms whose param types can't accept the dispatch
226+ # site's arg types -- mirrors the arm_incompat check in
227+ # the emit loop so the result-type union doesn't see
228+ # return types from arms the runtime can't reach.
229+ if poly_dispatch_arm_param_compat(ci, mname, arg_types) == 0
230+ rt = ""
231+ else
232+ rt = cls_method_return(ci, mname)
233+ end
234+ elsif cls_has_attr_reader(ci, mname) == 1
235+ # An attr_reader returns the ivar type. .
236+ rt = cls_ivar_type(ci, "@" + mname)
237+ elsif setter_bname != "" && cls_has_attr_writer(ci, setter_bname) == 1
238+ # An attr_writer setter returns the ivar's type.
239+ rt = cls_ivar_type(ci, "@" + setter_bname)
240+ end
241+ if rt != ""
242+ if common == ""
243+ common = rt
244+ elsif common != rt
245+ return "poly"
246+ end
247+ end
248+ ci = ci + 1
249+ end
250+ end
251+ common == "" ? "int" : common
252+ end
253+
254+ # Returns a comma-separated list of class indices the dispatch
255+ # site can possibly land on, derived from the receiver ivar's
256+ # observed type set. Returns "" when no narrowing is safe
257+ # (non-ivar receiver, partial observation, or any non-obj
258+ # observation like "poly" / "int" / "string"). Issue #549.
259+ def poly_dispatch_narrow_class_set(nid)
260+ if nid < 0
261+ return ""
262+ end
263+ if @current_class_idx < 0
264+ return ""
265+ end
266+ recv_id = @nd_receiver[nid]
267+ if recv_id < 0
268+ return ""
269+ end
270+ if @nd_type[recv_id] != "InstanceVariableReadNode"
271+ return ""
272+ end
273+ iname = @nd_name[recv_id]
274+ obs = cls_ivar_observed_types_for(@current_class_idx, iname)
275+ if obs == ""
276+ return ""
277+ end
278+ out = ""
279+ parts = obs.split(",")
280+ k = 0
281+ while k < parts.length
282+ t = parts[k]
283+ if t == ""
284+ # blank slot -- uninformative, skip
285+ elsif is_obj_type(t) == 1
286+ cname = t[4, t.length - 4]
287+ cidx = find_class_idx(cname)
288+ if cidx >= 0
289+ s_idx = cidx.to_s
290+ if out == ""
291+ out = s_idx
292+ else
293+ # dedup
294+ already = 0
295+ seen = out.split(",")
296+ sk = 0
297+ while sk < seen.length
298+ if seen[sk] == s_idx
299+ already = 1
300+ end
301+ sk = sk + 1
302+ end
303+ if already == 0
304+ out = out + "," + s_idx
305+ end
306+ end
307+ end
308+ else
309+ # Any non-obj observation ("poly", "int", "string", etc.)
310+ # means the ivar can hold values whose dispatch is broader
311+ # than the obj-class set we can enumerate. Bail out so we
312+ # don't unsoundly prune.
313+ return ""
314+ end
315+ k = k + 1
316+ end
317+ out
318+ end
319+
320+ def poly_dispatch_class_in_set(set, ci)
321+ if set == ""
322+ return 1
323+ end
324+ target = ci.to_s
325+ parts = set.split(",")
326+ k = 0
327+ while k < parts.length
328+ if parts[k] == target
329+ return 1
330+ end
331+ k = k + 1
332+ end
333+ 0
334+ end
335+
336+ # Mirrors the arm_incompat check inside compile_poly_method_call's
337+ # emit loop. Returns 1 when the arm's param types are compatible
338+ # with the dispatch site's arg types, 0 when at least one slot
339+ # has a base-type mismatch outside the int/symbol/bool family.
340+ def poly_dispatch_arm_param_compat(ci, mname, arg_types)
341+ midx = cls_find_method_direct(ci, mname)
342+ owner_idx = ci
343+ if midx < 0
344+ owner_name = find_method_owner(ci, mname)
345+ if owner_name != ""
346+ owner_idx = find_class_idx(owner_name)
347+ if owner_idx >= 0
348+ midx = cls_find_method_direct(owner_idx, mname)
349+ end
350+ end
351+ end
352+ if midx < 0
353+ return 1
354+ end
355+ arm_ptypes = cls_meth_ptypes_get(owner_idx, midx)
356+ pk = 0
357+ while pk < arm_ptypes.length && pk < arg_types.length
358+ at_b = base_type(arg_types[pk])
359+ pt_b = base_type(arm_ptypes[pk])
360+ if at_b != "" && pt_b != "" && at_b != "poly" && pt_b != "poly" && at_b != pt_b
361+ if (at_b == "int" && pt_b == "symbol") || (at_b == "symbol" && pt_b == "int") ||
362+ (at_b == "int" && pt_b == "bool") || (at_b == "bool" && pt_b == "int")
363+ # compatible
364+ else
365+ return 0
366+ end
367+ end
368+ pk = pk + 1
369+ end
370+ 1
371+ end
372+
135373 end