From 6c2e89f2840771437be4736c6515491b708ddaa7 Mon Sep 17 00:00:00 2001 From: tannevaled Date: Tue, 8 Sep 2026 20:22:32 +0200 Subject: [PATCH 1/2] kernel: Kernel#loop rescues StopIteration + blockless Enumerator; add Kernel#fail MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Kernel#loop (internal/vm/builtins.go): - With no block, return an infinite Enumerator over Kernel#loop whose #size is Float::INFINITY (was: raise LocalJumpError). loop.each re-drives loop with the given block. Ref: ruby/ruby v3_4_0 eval.c rb_f_loop / loop_size. - A StopIteration (or subclass) raised in the block now ends the loop cleanly and loop returns that exception's #result; every other exception (and break) still propagates. Ref: eval.c rb_f_loop (rb_rescue2 over StopIteration). Verified byte-for-byte vs MRI 4.0.5 for: rescue StopIteration, rescue a StopIteration subclass, StopIteration#result, does-not-rescue-StandardError, break value, blockless enumerator, loop.size == Float::INFINITY. Kernel#fail: a genuine alias of Kernel#raise (shared method record via aliasBuiltin), mirrored onto the Kernel module beside "raise" so Kernel.instance_method(:fail) == …(:raise) and Kernel.method(:fail) == …(:raise), with fail private on instances and Kernel.fail public. Ref: eval.c rb_f_raise registered under both names. Verified vs MRI 4.0.5. core/kernel: pass 1822 -> 1829, error 135 -> 128 (loop x5, fail x2); fail count unchanged. ruby/spec corpus @ 87b1631992. Co-Authored-By: Claude Opus 4.8 --- internal/vm/builtins.go | 36 ++++++++++++++++++++++++++++++------ 1 file changed, 30 insertions(+), 6 deletions(-) diff --git a/internal/vm/builtins.go b/internal/vm/builtins.go index d0387f41..dd67c53e 100644 --- a/internal/vm/builtins.go +++ b/internal/vm/builtins.go @@ -309,12 +309,30 @@ func (vm *VM) bootstrap() { } return self }) - vm.cObject.define("loop", func(vm *VM, _ object.Value, _ []object.Value, blk *Proc) object.Value { + vm.cObject.define("loop", func(vm *VM, self object.Value, _ []object.Value, blk *Proc) (result object.Value) { if blk == nil { - raise("LocalJumpError", "no block given (loop)") - } - // Runs forever; a `break` in the block unwinds to the call site (its - // value becomes loop's result) via the enclosing sendCatchBreak. + // With no block, Kernel#loop returns an infinite Enumerator over itself: + // `loop.each { … }` re-drives loop with that block, and its #size is + // Float::INFINITY. Reference: ruby/ruby v3_4_0 eval.c rb_f_loop / loop_size. + return &Enumerator{recv: self, meth: "loop", sizeSpec: object.Float(math.Inf(1)), sizeSpecSet: true} + } + // A StopIteration (or subclass) raised in the block ends the loop cleanly and + // Kernel#loop returns that exception's #result (a finished iterator's value); + // every other exception propagates. A `break` still unwinds to the call site + // (its value becomes loop's result) via the enclosing sendCatchBreak — the + // recover here re-raises anything that is not a StopIteration, so the break + // signal reaches it untouched. Reference: ruby/ruby v3_4_0 eval.c rb_f_loop + // (rb_rescue2 over StopIteration, returning the exception's result). + result = object.NilV + defer func() { + if r := recover(); r != nil { + if re, ok := r.(RubyError); ok && vm.errIsStopIteration(re) { + result = vm.send(vm.exceptionObject(re), "result", nil, nil) + return + } + panic(r) + } + }() for { vm.callBlock(blk, nil) } @@ -1020,6 +1038,12 @@ func (vm *VM) bootstrap() { return object.Bool(vm.classOf(self) == classArg(args[0])) }) vm.cObject.define("raise", nativeRaise) + // Kernel#fail is a genuine alias of Kernel#raise in MRI: the two names share one + // method record, so Kernel.instance_method(:fail) == …(:raise) and + // Kernel.method(:fail) == …(:raise). The shared record is mirrored onto the + // Kernel module by registerKernelModuleFunctions ("fail" listed beside "raise"). + // Reference: ruby/ruby v3_4_0 eval.c (rb_f_raise registered under both names). + aliasBuiltin(vm.cObject, "fail", "raise") vm.cObject.define("Integer", func(vm *VM, _ object.Value, args []object.Value, _ *Proc) object.Value { args, doRaise := popExceptionKwarg(args) // fail either raises (the default) or, under `exception: false`, yields nil. @@ -6223,7 +6247,7 @@ func (vm *VM) registerKernelModuleFunctions() { "Array", "Complex", "Float", "Hash", "Integer", "Rational", "String", "__dir__", "abort", "at_exit", "autoload", "autoload?", "caller", "caller_locations", - "catch", "eval", "exec", "exit", "exit!", "fork", "format", "lambda", + "catch", "eval", "exec", "exit", "exit!", "fail", "fork", "format", "lambda", "load", "loop", "open", "p", "print", "printf", "proc", "puts", "raise", "rand", "require", "require_relative", "sleep", "sprintf", "srand", "system", "throw", "trap", "warn", From 4611df8825709fbb35746b467ace5ce4afe8fbd4 Mon Sep 17 00:00:00 2001 From: tannevaled Date: Tue, 8 Sep 2026 20:30:34 +0200 Subject: [PATCH 2/2] kernel: tests for Kernel#loop StopIteration/blockless-Enumerator and Kernel#fail New whitebox suite (internal/vm/kernel_loop_fail_wave21_internal_test.go, package vm) covers every new branch: loop rescuing StopIteration and a subclass, the StopIteration#result return, a break unwinding through the recover, propagation of a non-StopIteration error (the panic re-raise), the blockless Enumerator + Float::INFINITY size, and Kernel#fail sharing raise's instance/singleton records. Updated TestLoopNoBlock (phase5w_test.go): blockless Kernel#loop now returns an infinite Enumerator (MRI eval.c rb_f_loop), not a LocalJumpError; the assertion is pinned to the MRI 4.0.5 behaviour and the now-unused strings import dropped. vm package: all tests pass, 99.9% coverage; the new branches are covered and bootstrap holds at its pre-existing 99.7%. Co-Authored-By: Claude Opus 4.8 --- .../kernel_loop_fail_wave21_internal_test.go | 84 +++++++++++++++++++ internal/vm/phase5w_test.go | 10 ++- 2 files changed, 91 insertions(+), 3 deletions(-) create mode 100644 internal/vm/kernel_loop_fail_wave21_internal_test.go diff --git a/internal/vm/kernel_loop_fail_wave21_internal_test.go b/internal/vm/kernel_loop_fail_wave21_internal_test.go new file mode 100644 index 00000000..e46f2665 --- /dev/null +++ b/internal/vm/kernel_loop_fail_wave21_internal_test.go @@ -0,0 +1,84 @@ +// Copyright (c) the go-embedded-ruby/ruby authors +// +// SPDX-License-Identifier: BSD-3-Clause + +package vm + +import ( + "strings" + "testing" +) + +// TestKernelLoopStopIteration covers Kernel#loop's StopIteration handling: a +// StopIteration (or subclass) raised in the block ends the loop cleanly, and the +// loop's value is that exception's #result. Reference: ruby/ruby v3_4_0 eval.c +// rb_f_loop. Verified byte-for-byte against MRI 4.0.5. +func TestKernelLoopStopIteration(t *testing.T) { + cases := []struct{ name, src, want string }{ + // Plain StopIteration: loop returns nil (its #result is unset). + {"bare_stop", `p(loop { raise StopIteration })`, "nil"}, + // A StopIteration subclass is rescued the same way. + {"subclass_stop", `Sub = Class.new(StopIteration); p(loop { raise Sub })`, "nil"}, + // The loop value is the finished iterator's StopIteration#result. + {"result_value", `e = Enumerator.new { |y| y << 1; y << 2; :done }; p(loop { e.next })`, ":done"}, + // A break unwinds to the call site with its value (the recover re-raises the + // break signal untouched). + {"break_value", `p(loop { break 7 })`, "7"}, + {"break_bare", `p(loop { break })`, "nil"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := runSrc(t, tc.src); got != tc.want { + t.Fatalf("src=%q got=%q want=%q", tc.src, got, tc.want) + } + }) + } +} + +// TestKernelLoopPropagatesOtherErrors proves the recover re-raises a non- +// StopIteration Ruby exception rather than swallowing it (the `panic(r)` branch). +func TestKernelLoopPropagatesOtherErrors(t *testing.T) { + err := runStragglerErr(t, `loop { raise "boom" }`) + if err == nil { + t.Fatal("expected loop to propagate a RuntimeError, got nil") + } + if !strings.Contains(err.Error(), "boom") { + t.Fatalf("expected the RuntimeError to propagate, got %v", err) + } +} + +// TestKernelLoopNoBlock covers the blockless branch: Kernel#loop returns an +// infinite Enumerator over itself whose #size is Float::INFINITY, and re-driving +// it with a block runs the loop. +func TestKernelLoopNoBlock(t *testing.T) { + if got := runSrc(t, `p loop.instance_of?(Enumerator)`); got != "true" { + t.Fatalf("loop.instance_of?(Enumerator): got %q want true", got) + } + if got := runSrc(t, `p loop.size`); got != "Infinity" { + t.Fatalf("loop.size: got %q want Infinity", got) + } + // The returned Enumerator re-drives Kernel#loop with the given block. + if got := runSrc(t, `c = 0; p(loop.each { c += 1; break c if c >= 5 })`); got != "5" { + t.Fatalf("loop.each drive: got %q want 5", got) + } +} + +// TestKernelFailAliasOfRaise proves Kernel#fail shares Kernel#raise's method +// record on both the instance and singleton sides, and that it raises. Reference: +// ruby/ruby v3_4_0 eval.c (rb_f_raise registered under raise and fail). +func TestKernelFailAliasOfRaise(t *testing.T) { + cases := []struct{ name, src, want string }{ + {"instance_method_eq", `p(Kernel.instance_method(:fail) == Kernel.instance_method(:raise))`, "true"}, + {"singleton_method_eq", `p(Kernel.method(:fail) == Kernel.method(:raise))`, "true"}, + {"private_on_instances", `p Kernel.private_instance_methods(false).include?(:fail)`, "true"}, + {"public_on_module", `p Kernel.public_methods(false).include?(:fail)`, "true"}, + {"raises_runtimeerror", `begin; fail "x"; rescue => e; p e.class; end`, "RuntimeError"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := runSrc(t, tc.src); got != tc.want { + t.Fatalf("src=%q got=%q want=%q", tc.src, got, tc.want) + } + }) + } +} diff --git a/internal/vm/phase5w_test.go b/internal/vm/phase5w_test.go index 665f465c..fc8e28fb 100644 --- a/internal/vm/phase5w_test.go +++ b/internal/vm/phase5w_test.go @@ -1,7 +1,6 @@ package vm_test import ( - "strings" "testing" ) @@ -23,7 +22,12 @@ func TestKernelLoop(t *testing.T) { } func TestLoopNoBlock(t *testing.T) { - if err := runErr(t, `loop`); err == nil || !strings.Contains(err.Error(), "LocalJumpError") { - t.Fatalf("got %v want LocalJumpError", err) + // Kernel#loop with no block returns an infinite Enumerator over itself (MRI + // eval.c rb_f_loop / loop_size), not a LocalJumpError as it once did. + if got := eval(t, `p loop.instance_of?(Enumerator)`); got != "true\n" { + t.Fatalf("loop.instance_of?(Enumerator): got %q want \"true\\n\"", got) + } + if got := eval(t, `p loop.size`); got != "Infinity\n" { + t.Fatalf("loop.size: got %q want \"Infinity\\n\"", got) } }