Commit 88277dcb

88277dcb77d9Merged

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

Description

Carry yield's value (and type) out of inlined yield-using methods

A yield-using method called with a literal block dropped or mistyped the yielded value (#1362): an instance method in expression position emitted sp_C_m(recv, NULL, NULL) (block discarded, returns 0), and the inlined result was typed by the method's declared return type (int default), so a string body truncated to a %lld pointer.

  • Add compile_yield_method_call_expr: the expression-position counterpart of compile_yield_method_call_stmt, inlining the body and capturing its value into a typed temp; wire it into the obj-method call path.
  • Type yield (in the inline window) and the captured result by the block's actual return type, computed before honoring analyze's int cache. infer_type gains a yield-call arm so callers (puts, =, concat) see the real type; the refinement only fires when the declared return type is the int default, leaving concrete analyze types authoritative.
  • compile_expr_remap lowers string s + x to sp_str_concat instead of raw pointer + so "[" + yield + "]" bodies compile.
  • Refuse to inline self-recursive yield methods (receiver-aware check, so a method delegating to a same-named method on another receiver -- e.g. def each; @data.each { yield } end -- is still inlined); they fall back to the non-inline path instead of expanding forever.

Known limitations (tracked under #1362): &block.call with a non-int return is still mistyped (polymorphic return in a non-inlined method); recursive-yield-value methods drop the value via the non-inline fallback; param-using blocks fall back to the declared return type; and local = m { "string" } works at runtime but emits a -Wint-conversion warning (the analyze-side typing that removes it is future work).

Refs #1362

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

Details

Commit
88277dcb77d9
Parent
f01243db55b3

spinel_codegen.rbmodifiedView file

@@ -3533,6 +3533,38 @@
35333533 return "curried"
35343534 end
35353535 end
3536+ # Inside the inline window of a yield-using method, `yield` evaluates to
3537+ # the (statically known) literal block's body value. Type it as the
3538+ # block's return type — BEFORE honoring the cache, which analyze filled
3539+ # with the int default — so `"[" + yield + "]"` and the captured result
3540+ # temp use the real type. Bounded by @inline_yield_blk: no effect
3541+ # outside an inline window.
3542+ if @nd_type[nid] == "YieldNode" && @inline_yield_blk >= 0
3543+ yb_blk = @nd_body[@inline_yield_blk]
3544+ if yb_blk >= 0
3545+ yb_stmts = get_stmts(yb_blk)
3546+ if yb_stmts.length > 0
3547+ yb_t = infer_type(yb_stmts.last)
3548+ if yb_t != "" && yb_t != "void"
3549+ return yb_t
3550+ end
3551+ end
3552+ end
3553+ return "int"
3554+ end
3555+ # A yield-using method called with a literal block returns the inlined
3556+ # body's value (with `yield` resolving to the block's return type), not
3557+ # the method's declared return type. analyze caches the call as the int
3558+ # default, so compute and return the inline type BEFORE honoring that
3559+ # cache — otherwise `puts m { "x" }` / `x = m { "x" }` mistype the
3560+ # result. Gated on a literal block, so the hot no-block path is
3561+ # untouched.
3562+ if @nd_type[nid] == "CallNode" && @nd_block[nid] >= 0 && has_literal_block(nid) == 1
3563+ yci_t = yield_call_inline_type(nid)
3564+ if yci_t != ""
3565+ return yci_t
3566+ end
3567+ end
35363568 # Cache lookup. analyze.rb's annotate_all_node_types fills
35373569 # @nd_inferred_type for every reachable node OUTSIDE block bodies
35383570 # (block-iteration scope is iterator-specific and dispatched at
@@ -10752,6 +10784,77 @@
1075210784 0
1075310785 end
1075410786
10787+ # 1 if `nid`'s subtree contains a *self*-call to `mname` -- a
10788+ # receiverless or `self.`-receiver call. Unlike node_calls_name? (which
10789+ # matches any CallNode by name, e.g. `@data.each` while inside `each`),
10790+ # this only flags genuine self-recursion, so the yield-inline guard
10791+ # doesn't wrongly refuse a method that delegates to a same-named method
10792+ # on another receiver (the T_enumerable#each -> @data.each shape).
10793+ def yield_body_self_recurses?(nid, mname)
10794+ if nid < 0
10795+ return 0
10796+ end
10797+ if @nd_type[nid] == "CallNode" && @nd_name[nid] == mname
10798+ rcv = @nd_receiver[nid]
10799+ if rcv < 0 || @nd_type[rcv] == "SelfNode"
10800+ return 1
10801+ end
10802+ end
10803+ if @nd_receiver[nid] >= 0 && yield_body_self_recurses?(@nd_receiver[nid], mname) == 1
10804+ return 1
10805+ end
10806+ args_id = @nd_arguments[nid]
10807+ if args_id >= 0
10808+ arr = get_args(args_id)
10809+ k = 0
10810+ while k < arr.length
10811+ if yield_body_self_recurses?(arr[k], mname) == 1
10812+ return 1
10813+ end
10814+ k = k + 1
10815+ end
10816+ end
10817+ if @nd_body[nid] >= 0 && yield_body_self_recurses?(@nd_body[nid], mname) == 1
10818+ return 1
10819+ end
10820+ if @nd_block[nid] >= 0 && yield_body_self_recurses?(@nd_block[nid], mname) == 1
10821+ return 1
10822+ end
10823+ if @nd_else_clause[nid] >= 0 && yield_body_self_recurses?(@nd_else_clause[nid], mname) == 1
10824+ return 1
10825+ end
10826+ stmts = parse_id_list(@nd_stmts[nid])
10827+ k = 0
10828+ while k < stmts.length
10829+ if yield_body_self_recurses?(stmts[k], mname) == 1
10830+ return 1
10831+ end
10832+ k = k + 1
10833+ end
10834+ if @nd_subsequent[nid] >= 0 && yield_body_self_recurses?(@nd_subsequent[nid], mname) == 1
10835+ return 1
10836+ end
10837+ 0
10838+ end
10839+
10840+ # 1 if class ci's method midx body self-recurses on `mname`. Used to
10841+ # refuse inlining a self-recursive yield method, which would otherwise
10842+ # expand forever (the call count isn't const-folded).
10843+ def cls_meth_body_calls_self?(ci, midx, mname)
10844+ if ci < 0 || midx < 0
10845+ return 0
10846+ end
10847+ bodies = @cls_meth_bodies[ci].split(";", -1)
10848+ if midx >= bodies.length
10849+ return 0
10850+ end
10851+ bid = bodies[midx].to_i
10852+ if bid < 0
10853+ return 0
10854+ end
10855+ yield_body_self_recurses?(bid, mname)
10856+ end
10857+
1075510858 # Should the emit pipeline skip class ci's struct + constructor +
1075610859 # gc_scan + initialize? Currently only Method (the built-in
1075710860 # registered by spinel_analyze) qualifies, and only when no usage
@@ -20389,7 +20492,7 @@
2038920492 # `, NULL, NULL` yargs path below produces `sp_measure(, NULL, NULL)`
2039020493 # which doesn't compile. Mirror compile_yield_call_stmt's inline
2039120494 # path but capture the body's last expression into a result temp.
20392- if @meth_has_yield[mi] == 1 && has_literal_block(nid) == 1 && meth_has_block_param(mi) == 0
20495+ if @meth_has_yield[mi] == 1 && has_literal_block(nid) == 1 && meth_has_block_param(mi) == 0 && yield_body_self_recurses?(@meth_body_ids[mi], mname) == 0
2039320496 return compile_yield_call_expr(nid, mi)
2039420497 end
2039520498 yargs = ""
@@ -31322,6 +31425,16 @@
3132231425 if oci2 >= 0
3132331426 midx2 = cls_find_method_direct(oci2, mname)
3132431427 end
31428+ # yield-using instance method called with a literal block in
31429+ # expression position: inline the body and capture the yielded
31430+ # value, mirroring the top-level compile_yield_call_expr path.
31431+ # Without this the call emits sp_<C>_<m>(recv, NULL, NULL) — the
31432+ # literal block is dropped and yield returns 0.
31433+ if oci2 >= 0 && midx2 >= 0 && has_literal_block(nid) == 1 &&
31434+ cls_method_has_yield(oci2, midx2) == 1 && cls_method_has_block_param(oci2, midx2) == 0 &&
31435+ cls_meth_body_calls_self?(oci2, midx2, mname) == 0
31436+ return compile_yield_method_call_expr(nid, oci2, midx2, mname)
31437+ end
3132531438 # Omit the trailing &block slot from default-padding when the
3132631439 # callee declares one — we'll fill it explicitly from the
3132731440 # call site's literal block below.
@@ -42001,7 +42114,7 @@
4200142114 # block local to `blk_y<N>` but leaves the body's `blk.call`
4200242115 # referencing the original `lv_blk`. Fall through to the regular
4200342116 # call path, which forwards the literal block into the &blk slot.
42004- if @meth_has_yield[mi] == 1 && meth_has_block_param(mi) == 0
42117+ if @meth_has_yield[mi] == 1 && meth_has_block_param(mi) == 0 && yield_body_self_recurses?(@meth_body_ids[mi], mname) == 0
4200542118 compile_yield_call_stmt(nid, mi)
4200642119 return 1
4200742120 end
@@ -50174,7 +50287,27 @@
5017450287 kf = kf + 1
5017550288 end
5017650289 end
50290+ # Type the captured result by the inlined body's actual value type
50291+ # (yield window open so `yield` resolves to the block's return type)
50292+ # rather than the declared return type, which defaults to int and
50293+ # truncates a string/pointer body. Fall back to the declared type.
5017750294 rt_yc = @meth_return_types[mi]
50295+ # Only refine the int default (see compile_yield_method_call_expr).
50296+ if base_type(rt_yc) == "int" && bid >= 0
50297+ st_chk_yc = get_stmts(bid)
50298+ if st_chk_yc.length > 0
50299+ sv_iyb_yc = @inline_yield_blk
50300+ sv_iybp_yc = @inline_yield_bp_names
50301+ @inline_yield_blk = blk
50302+ @inline_yield_bp_names = bp_names
50303+ inf_rt_yc = infer_type(st_chk_yc.last)
50304+ @inline_yield_blk = sv_iyb_yc
50305+ @inline_yield_bp_names = sv_iybp_yc
50306+ if inf_rt_yc != "" && inf_rt_yc != "void"
50307+ rt_yc = inf_rt_yc
50308+ end
50309+ end
50310+ end
5017850311 result_tmp = new_temp
5017950312 emit(" " + c_type(rt_yc) + " " + result_tmp + " = " + c_return_default(rt_yc) + ";")
5018050313 saved_in_rmf = @inline_rename_map_from
@@ -50833,6 +50966,31 @@
5083350966 end
5083450967 end
5083550968 if mname == "+"
50969+ # String receiver: lower `s + x` to sp_str_concat (coercing an int
50970+ # rhs via sp_int_to_s) instead of raw C pointer `+`, which is a hard
50971+ # type error. Mirrors compile_call's string-`+` path for the inlined
50972+ # yield-body remap (e.g. `"[" + yield + "]"`).
50973+ recv_t_plus = base_type(infer_type(recv))
50974+ if recv_t_plus == "string" || recv_t_plus == "mutable_str"
50975+ lhs_plus = compile_expr_remap(recv, map_from, map_to)
50976+ arg0_plus = compile_expr_remap_arg0(nid, map_from, map_to)
50977+ arg_t_plus = "int"
50978+ args_id_plus = @nd_arguments[nid]
50979+ if args_id_plus >= 0
50980+ ap_plus = get_args(args_id_plus)
50981+ if ap_plus.length > 0
50982+ arg_t_plus = base_type(infer_type(ap_plus[0]))
50983+ end
50984+ end
50985+ if arg_t_plus == "string" || arg_t_plus == "mutable_str"
50986+ return "sp_str_concat(" + lhs_plus + ", " + arg0_plus + ")"
50987+ end
50988+ if arg_t_plus == "int"
50989+ return "sp_str_concat(" + lhs_plus + ", sp_int_to_s(" + arg0_plus + "))"
50990+ end
50991+ @needs_rb_value = 1
50992+ return "sp_str_concat(" + lhs_plus + ", sp_poly_to_s(" + arg0_plus + "))"
50993+ end
5083650994 return "(" + compile_expr_remap(recv, map_from, map_to) + " + " + compile_expr_remap_arg0(nid, map_from, map_to) + ")"
5083750995 end
5083850996 if mname == "-"
@@ -50954,7 +51112,7 @@
5095451112 if midx < 0
5095551113 return 0
5095651114 end
50957- if cls_method_has_yield(cls_idx, midx) == 1 && cls_method_has_block_param(cls_idx, midx) == 0
51115+ if cls_method_has_yield(cls_idx, midx) == 1 && cls_method_has_block_param(cls_idx, midx) == 0 && cls_meth_body_calls_self?(cls_idx, midx, mname) == 0
5095851116 compile_yield_method_call_stmt(nid, cls_idx, midx, mname)
5095951117 return 1
5096051118 end
@@ -51328,6 +51486,267 @@
5132851486 @current_class_idx = saved_ci
5132951487 end
5133051488
51489+ # Expression-position variant of compile_yield_method_call_stmt: inline
51490+ # a yield-using instance method called with a literal block and capture
51491+ # the method body's value into a temp, so `x = recv.m { ... }` /
51492+ # `puts recv.m { ... }` see the yielded value instead of a dropped
51493+ # `, NULL, NULL` block (returns 0). Mirrors compile_yield_call_expr's
51494+ # last-statement capture.
51495+ def compile_yield_method_call_expr(nid, cci, midx, mname)
51496+ blk = @nd_block[nid]
51497+ if blk < 0
51498+ return "0"
51499+ end
51500+ bp_names = "".split(",", -1)
51501+ bp = @nd_parameters[blk]
51502+ if bp >= 0
51503+ inner = @nd_parameters[bp]
51504+ if inner >= 0
51505+ reqs = parse_id_list(@nd_requireds[inner])
51506+ k = 0
51507+ while k < reqs.length
51508+ bp_names.push(@nd_name[reqs[k]])
51509+ k = k + 1
51510+ end
51511+ end
51512+ end
51513+
51514+ recv = @nd_receiver[nid]
51515+ if recv < 0
51516+ rc = "self"
51517+ else
51518+ rc = compile_expr_gc_rooted(recv)
51519+ end
51520+
51521+ bodies = @cls_meth_bodies[cci].split(";", -1)
51522+ bid = -1
51523+ if midx < bodies.length
51524+ bid = bodies[midx].to_i
51525+ end
51526+
51527+ saved_ci = @current_class_idx
51528+ @current_class_idx = cci
51529+ saved_self_override = @self_override
51530+ if cci >= 0 && cci < @cls_is_value_type.length && @cls_is_value_type[cci] != 1
51531+ @self_override = "((sp_" + @cls_names[cci] + " *)" + rc + ")"
51532+ else
51533+ @self_override = rc
51534+ end
51535+
51536+ @block_counter = @block_counter + 1
51537+ suffix = "_y" + @block_counter.to_s
51538+
51539+ pnames = cls_meth_pnames_get(cci, midx)
51540+ ptypes = cls_meth_ptypes_get(cci, midx)
51541+
51542+ map_from = "".split(",", -1)
51543+ map_to = "".split(",", -1)
51544+ map_from.push("_self_")
51545+ map_to.push(rc)
51546+
51547+ args_id = @nd_arguments[nid]
51548+ arg_ids = []
51549+ if args_id >= 0
51550+ arg_ids = get_args(args_id)
51551+ end
51552+
51553+ k = 0
51554+ while k < pnames.length
51555+ pt = "int"
51556+ if k < ptypes.length
51557+ pt = ptypes[k]
51558+ end
51559+ tname = pnames[k] + suffix
51560+ val = c_default_val(pt)
51561+ if k < arg_ids.length
51562+ val = compile_expr(arg_ids[k])
51563+ arg_t_ym = infer_type(arg_ids[k])
51564+ if base_type(pt) == "bigint" && arg_t_ym == "int"
51565+ @needs_bigint = 1
51566+ val = "sp_bigint_new_int(" + val + ")"
51567+ elsif base_type(pt) == "int" && arg_t_ym == "bigint"
51568+ @needs_bigint = 1
51569+ val = "sp_bigint_to_int((sp_Bigint *)" + val + ")"
51570+ end
51571+ end
51572+ emit(" " + c_type(pt) + " lv_" + tname + " = " + val + ";")
51573+ map_from.push(pnames[k])
51574+ map_to.push(tname)
51575+ declare_var(tname, pt)
51576+ declare_var(pnames[k], pt)
51577+ k = k + 1
51578+ end
51579+
51580+ if bid >= 0
51581+ flocals_n = "".split(",", -1)
51582+ flocals_t = "".split(",", -1)
51583+ sn_f = @nd_scope_names[bid]
51584+ if sn_f != ""
51585+ flocals_n = sn_f.split("|", -1)
51586+ flocals_t = @nd_scope_types[bid].split("|", -1)
51587+ end
51588+ k = 0
51589+ while k < flocals_n.length
51590+ tname = flocals_n[k] + suffix
51591+ emit(" " + c_type(flocals_t[k]) + " lv_" + tname + " = " + c_default_val(flocals_t[k]) + ";")
51592+ map_from.push(flocals_n[k])
51593+ map_to.push(tname)
51594+ declare_var(tname, flocals_t[k])
51595+ declare_var(flocals_n[k], flocals_t[k])
51596+ k = k + 1
51597+ end
51598+ end
51599+
51600+ # Type the captured result by the inlined body's actual value type
51601+ # (with the yield window open so `yield` resolves to the block's
51602+ # return type) rather than the method's declared return type, which
51603+ # defaults to int and would truncate a string/pointer body. Fall back
51604+ # to the declared return type when the body type can't be resolved.
51605+ rt_ym = cls_method_return(cci, mname)
51606+ # Only refine the int default from the inlined body type; a concrete
51607+ # analyze return type is authoritative (recompute here lacks the
51608+ # method's local scope and could mis-resolve body locals).
51609+ if base_type(rt_ym) == "int" && bid >= 0
51610+ st_chk = get_stmts(bid)
51611+ if st_chk.length > 0
51612+ sv_iyb_t = @inline_yield_blk
51613+ sv_iybp_t = @inline_yield_bp_names
51614+ @inline_yield_blk = blk
51615+ @inline_yield_bp_names = bp_names
51616+ inf_rt = infer_type(st_chk.last)
51617+ @inline_yield_blk = sv_iyb_t
51618+ @inline_yield_bp_names = sv_iybp_t
51619+ if inf_rt != "" && inf_rt != "void"
51620+ rt_ym = inf_rt
51621+ end
51622+ end
51623+ end
51624+ result_tmp = new_temp
51625+ emit(" " + c_type(rt_ym) + " " + result_tmp + " = " + c_return_default(rt_ym) + ";")
51626+
51627+ saved_in_rmf = @inline_rename_map_from
51628+ saved_in_rmt = @inline_rename_map_to
51629+ @inline_rename_map_from = map_from
51630+ @inline_rename_map_to = map_to
51631+ saved_iyb = @inline_yield_blk
51632+ saved_iybp = @inline_yield_bp_names
51633+ @inline_yield_blk = blk
51634+ @inline_yield_bp_names = bp_names
51635+ if bid >= 0
51636+ stmts = get_stmts(bid)
51637+ n = stmts.length
51638+ ks = 0
51639+ while ks < n - 1
51640+ compile_stmt_with_block(stmts[ks], blk, bp_names, map_from, map_to)
51641+ ks = ks + 1
51642+ end
51643+ if n > 0
51644+ last_y = stmts.last
51645+ last_t = @nd_type[last_y]
51646+ if last_t == "YieldNode"
51647+ compile_yield_inline_capture(last_y, blk, bp_names, map_from, map_to, result_tmp, rt_ym)
51648+ elsif last_t == "IfNode" || last_t == "CaseNode" ||
51649+ last_t == "WhileNode" || last_t == "BeginNode" || last_t == "ReturnNode" ||
51650+ last_t == "LocalVariableWriteNode" || last_t == "InstanceVariableWriteNode" ||
51651+ last_t == "ClassVariableWriteNode" || last_t == "GlobalVariableWriteNode"
51652+ compile_stmt_with_block(last_y, blk, bp_names, map_from, map_to)
51653+ else
51654+ last_val = compile_expr_remap(last_y, map_from, map_to)
51655+ emit(" " + result_tmp + " = " + last_val + ";")
51656+ end
51657+ end
51658+ end
51659+ @inline_rename_map_from = saved_in_rmf
51660+ @inline_rename_map_to = saved_in_rmt
51661+ @inline_yield_blk = saved_iyb
51662+ @inline_yield_bp_names = saved_iybp
51663+ @self_override = saved_self_override
51664+ @current_class_idx = saved_ci
51665+ result_tmp
51666+ end
51667+
51668+ # Return type of a `m { ... }` call where `m` is a yield-using method
51669+ # (top-level or instance) with no &block param, called with a literal
51670+ # block: the inlined body's value type with `yield` resolving to the
51671+ # block's return type. Returns "" when the call isn't this shape (so
51672+ # infer_type falls through to the cache / declared return type). Used
51673+ # by infer_type so callers (`puts`, assignment) see the real type.
51674+ def yield_call_inline_type(nid)
51675+ blk = @nd_block[nid]
51676+ if blk < 0
51677+ return ""
51678+ end
51679+ mname = @nd_name[nid]
51680+ recv = @nd_receiver[nid]
51681+ bid = -1
51682+ decl_rt = "int"
51683+ if recv < 0
51684+ mi = find_method_idx(mname)
51685+ if mi >= 0 && @meth_has_yield[mi] == 1 && meth_has_block_param(mi) == 0 && yield_body_self_recurses?(@meth_body_ids[mi], mname) == 0
51686+ bid = @meth_body_ids[mi]
51687+ decl_rt = @meth_return_types[mi]
51688+ end
51689+ else
51690+ rt = base_type(infer_type(recv))
51691+ if is_obj_type(rt) == 1
51692+ cn = rt[4, rt.length - 4]
51693+ cci = find_class_idx(cn)
51694+ if cci >= 0
51695+ owner = find_method_owner(cci, mname)
51696+ if owner != ""
51697+ oci = find_class_idx(owner)
51698+ midx = -1
51699+ if oci >= 0
51700+ midx = cls_find_method_direct(oci, mname)
51701+ end
51702+ if oci >= 0 && midx >= 0 && cls_method_has_yield(oci, midx) == 1 && cls_method_has_block_param(oci, midx) == 0 && cls_meth_body_calls_self?(oci, midx, mname) == 0
51703+ bodies = @cls_meth_bodies[oci].split(";", -1)
51704+ if midx < bodies.length
51705+ bid = bodies[midx].to_i
51706+ end
51707+ decl_rt = cls_method_return(oci, mname)
51708+ end
51709+ end
51710+ end
51711+ end
51712+ end
51713+ if bid < 0
51714+ return ""
51715+ end
51716+ # Only refine the unhelpful int default. When analyze already inferred
51717+ # a concrete return type (str_array from `free.push(yield); free`,
51718+ # string from a concat body, etc.) it is authoritative — recomputing
51719+ # here without the method's local scope would mis-resolve body locals.
51720+ if base_type(decl_rt) != "int"
51721+ return ""
51722+ end
51723+ st = get_stmts(bid)
51724+ if st.length == 0
51725+ return ""
51726+ end
51727+ bp_names = "".split(",", -1)
51728+ bp = @nd_parameters[blk]
51729+ if bp >= 0
51730+ inner = @nd_parameters[bp]
51731+ if inner >= 0
51732+ reqs = parse_id_list(@nd_requireds[inner])
51733+ kbp = 0
51734+ while kbp < reqs.length
51735+ bp_names.push(@nd_name[reqs[kbp]])
51736+ kbp = kbp + 1
51737+ end
51738+ end
51739+ end
51740+ sv_iyb = @inline_yield_blk
51741+ sv_iybp = @inline_yield_bp_names
51742+ @inline_yield_blk = blk
51743+ @inline_yield_bp_names = bp_names
51744+ rt_inf = infer_type(st.last)
51745+ @inline_yield_blk = sv_iyb
51746+ @inline_yield_bp_names = sv_iybp
51747+ rt_inf
51748+ end
51749+
5133151750 # Two-level yield inline: `outer do |x| yield x*2 end` appearing
5133251751 # inside an already-inlined caller (`inner`) where `outer` is itself a
5133351752 # yield-using top-level method. The callee body's yield gets replaced