Commit 9319c969
9319c96911dfMerged
Ryan Seys <[email protected]> · 5 months ago · 3 files · +2 added · ~1 modified
Description
codegen: fix block_given? in lowered yielding methods
A self-recursive yielding method is not inlined; it is emitted as a real C
function whose block becomes an sp_Proc *__yblk__ parameter ("lowered"
form), with yield lowering to sp_proc_call(__yblk__, ...). In that form
block_given? was still emitted from the inline-path rule -- g_block_id >= 0 ? "1" : "0" -- and g_block_id is always -1 in a lowered body, so it folded
to a constant 0. A method like
def gen(n)
return -1 unless block_given?
yield n
gen(n - 1) { |x| yield x } if n > 1
n
end
then took the no-block branch even when called with a block, yielding nothing.
block_given? asks about the innermost method, so resolve it in precedence
order: an inlined yielding method (g_block_id >= 0) statically has its block
and folds to 1 even when the enclosing method is lowered; otherwise a lowered
scope inspects its runtime block via (__yblk__ != NULL) (through
emit_yblk_ref, so the captured-in-proc case reads the cell correctly); else 0.
The proc parameter is non-NULL exactly when the caller passed a block -- the
call site already passes NULL for a blockless call -- so this matches Ruby
semantics. The plain inline and non-lowered paths are unchanged.
Gates: tests pass; bootstrap IR+C fixpoint byte-identical for analyze and codegen (no self-host method depended on the prior behavior).
Co-Authored-By: Claude Opus 4.8 (1M context) [email protected]
Details
- Commit
- 9319c96911df
- Parent
- b1e4d47607fd
src/codegen_call.cmodifiedView file
} /* block_given? / self.block_given? -> true inside an inlined yielding method (we only inline when a block is present) */ method (we only inline when a block is present). In a lowered yielding method the block is the `__yblk__` proc parameter, which is non-NULL exactly when the caller passed a block, so test it directly. */ if (!strcmp(name, "block_given?") && (recv < 0 || (nt_type(nt, recv) && !strcmp(nt_type(nt, recv), "SelfNode")))) { buf_puts(b, g_block_id >= 0 ? "1" : "0"); /* block_given? asks about the innermost method. An inlined yielding method (g_block_id >= 0) statically has a block, so fold to 1 even when the enclosing method is lowered; only a genuinely lowered scope inspects its runtime __yblk__ parameter. */ if (g_block_id >= 0) { buf_puts(b, "1"); } else if (g_current_scope_is_lowered) { buf_puts(b, "("); emit_yblk_ref(b); buf_puts(b, " != NULL)"); } else { buf_puts(b, "0"); } return; }test/lowered_block_given.rbaddedView file
Loading diff…
test/lowered_block_given.rb.expectedaddedView file
Loading diff…