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

@@ -4288,10 +4288,22 @@
42884288 }
42894289
42904290 /* block_given? / self.block_given? -> true inside an inlined yielding
4291- method (we only inline when a block is present) */
4291+ method (we only inline when a block is present). In a lowered yielding
4292+ method the block is the `__yblk__` proc parameter, which is non-NULL
4293+ exactly when the caller passed a block, so test it directly. */
42924294 if (!strcmp(name, "block_given?") &&
42934295 (recv < 0 || (nt_type(nt, recv) && !strcmp(nt_type(nt, recv), "SelfNode")))) {
4294- buf_puts(b, g_block_id >= 0 ? "1" : "0");
4296+ /* block_given? asks about the innermost method. An inlined yielding method
4297+ (g_block_id >= 0) statically has a block, so fold to 1 even when the
4298+ enclosing method is lowered; only a genuinely lowered scope inspects its
4299+ runtime __yblk__ parameter. */
4300+ if (g_block_id >= 0) {
4301+ buf_puts(b, "1");
4302+ } else if (g_current_scope_is_lowered) {
4303+ buf_puts(b, "("); emit_yblk_ref(b); buf_puts(b, " != NULL)");
4304+ } else {
4305+ buf_puts(b, "0");
4306+ }
42954307 return;
42964308 }
42974309