Skip to content

Commit e66e0cd

Browse files
tannevaledclaude
andauthored
kernel: Kernel#loop rescues StopIteration + blockless Enumerator; add Kernel#fail (#599)
* kernel: Kernel#loop rescues StopIteration + blockless Enumerator; add Kernel#fail 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 <noreply@anthropic.com> * 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 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
1 parent 415efad commit e66e0cd

3 files changed

Lines changed: 121 additions & 9 deletions

File tree

‎internal/vm/builtins.go‎

Lines changed: 30 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -309,12 +309,30 @@ func (vm *VM) bootstrap() {
309309
}
310310
return self
311311
})
312-
vm.cObject.define("loop", func(vm *VM, _ object.Value, _ []object.Value, blk *Proc) object.Value {
312+
vm.cObject.define("loop", func(vm *VM, self object.Value, _ []object.Value, blk *Proc) (result object.Value) {
313313
if blk == nil {
314-
raise("LocalJumpError", "no block given (loop)")
315-
}
316-
// Runs forever; a `break` in the block unwinds to the call site (its
317-
// value becomes loop's result) via the enclosing sendCatchBreak.
314+
// With no block, Kernel#loop returns an infinite Enumerator over itself:
315+
// `loop.each { … }` re-drives loop with that block, and its #size is
316+
// Float::INFINITY. Reference: ruby/ruby v3_4_0 eval.c rb_f_loop / loop_size.
317+
return &Enumerator{recv: self, meth: "loop", sizeSpec: object.Float(math.Inf(1)), sizeSpecSet: true}
318+
}
319+
// A StopIteration (or subclass) raised in the block ends the loop cleanly and
320+
// Kernel#loop returns that exception's #result (a finished iterator's value);
321+
// every other exception propagates. A `break` still unwinds to the call site
322+
// (its value becomes loop's result) via the enclosing sendCatchBreak — the
323+
// recover here re-raises anything that is not a StopIteration, so the break
324+
// signal reaches it untouched. Reference: ruby/ruby v3_4_0 eval.c rb_f_loop
325+
// (rb_rescue2 over StopIteration, returning the exception's result).
326+
result = object.NilV
327+
defer func() {
328+
if r := recover(); r != nil {
329+
if re, ok := r.(RubyError); ok && vm.errIsStopIteration(re) {
330+
result = vm.send(vm.exceptionObject(re), "result", nil, nil)
331+
return
332+
}
333+
panic(r)
334+
}
335+
}()
318336
for {
319337
vm.callBlock(blk, nil)
320338
}
@@ -1020,6 +1038,12 @@ func (vm *VM) bootstrap() {
10201038
return object.Bool(vm.classOf(self) == classArg(args[0]))
10211039
})
10221040
vm.cObject.define("raise", nativeRaise)
1041+
// Kernel#fail is a genuine alias of Kernel#raise in MRI: the two names share one
1042+
// method record, so Kernel.instance_method(:fail) == …(:raise) and
1043+
// Kernel.method(:fail) == …(:raise). The shared record is mirrored onto the
1044+
// Kernel module by registerKernelModuleFunctions ("fail" listed beside "raise").
1045+
// Reference: ruby/ruby v3_4_0 eval.c (rb_f_raise registered under both names).
1046+
aliasBuiltin(vm.cObject, "fail", "raise")
10231047
vm.cObject.define("Integer", func(vm *VM, _ object.Value, args []object.Value, _ *Proc) object.Value {
10241048
args, doRaise := popExceptionKwarg(args)
10251049
// fail either raises (the default) or, under `exception: false`, yields nil.
@@ -6223,7 +6247,7 @@ func (vm *VM) registerKernelModuleFunctions() {
62236247
"Array", "Complex", "Float", "Hash", "Integer", "Rational", "String",
62246248
"__dir__", "abort", "at_exit", "autoload", "autoload?", "caller",
62256249
"caller_locations",
6226-
"catch", "eval", "exec", "exit", "exit!", "fork", "format", "lambda",
6250+
"catch", "eval", "exec", "exit", "exit!", "fail", "fork", "format", "lambda",
62276251
"load", "loop", "open", "p", "print", "printf", "proc", "puts",
62286252
"raise", "rand", "require", "require_relative", "sleep", "sprintf",
62296253
"srand", "system", "throw", "trap", "warn",
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
// Copyright (c) the go-embedded-ruby/ruby authors
2+
//
3+
// SPDX-License-Identifier: BSD-3-Clause
4+
5+
package vm
6+
7+
import (
8+
"strings"
9+
"testing"
10+
)
11+
12+
// TestKernelLoopStopIteration covers Kernel#loop's StopIteration handling: a
13+
// StopIteration (or subclass) raised in the block ends the loop cleanly, and the
14+
// loop's value is that exception's #result. Reference: ruby/ruby v3_4_0 eval.c
15+
// rb_f_loop. Verified byte-for-byte against MRI 4.0.5.
16+
func TestKernelLoopStopIteration(t *testing.T) {
17+
cases := []struct{ name, src, want string }{
18+
// Plain StopIteration: loop returns nil (its #result is unset).
19+
{"bare_stop", `p(loop { raise StopIteration })`, "nil"},
20+
// A StopIteration subclass is rescued the same way.
21+
{"subclass_stop", `Sub = Class.new(StopIteration); p(loop { raise Sub })`, "nil"},
22+
// The loop value is the finished iterator's StopIteration#result.
23+
{"result_value", `e = Enumerator.new { |y| y << 1; y << 2; :done }; p(loop { e.next })`, ":done"},
24+
// A break unwinds to the call site with its value (the recover re-raises the
25+
// break signal untouched).
26+
{"break_value", `p(loop { break 7 })`, "7"},
27+
{"break_bare", `p(loop { break })`, "nil"},
28+
}
29+
for _, tc := range cases {
30+
t.Run(tc.name, func(t *testing.T) {
31+
if got := runSrc(t, tc.src); got != tc.want {
32+
t.Fatalf("src=%q got=%q want=%q", tc.src, got, tc.want)
33+
}
34+
})
35+
}
36+
}
37+
38+
// TestKernelLoopPropagatesOtherErrors proves the recover re-raises a non-
39+
// StopIteration Ruby exception rather than swallowing it (the `panic(r)` branch).
40+
func TestKernelLoopPropagatesOtherErrors(t *testing.T) {
41+
err := runStragglerErr(t, `loop { raise "boom" }`)
42+
if err == nil {
43+
t.Fatal("expected loop to propagate a RuntimeError, got nil")
44+
}
45+
if !strings.Contains(err.Error(), "boom") {
46+
t.Fatalf("expected the RuntimeError to propagate, got %v", err)
47+
}
48+
}
49+
50+
// TestKernelLoopNoBlock covers the blockless branch: Kernel#loop returns an
51+
// infinite Enumerator over itself whose #size is Float::INFINITY, and re-driving
52+
// it with a block runs the loop.
53+
func TestKernelLoopNoBlock(t *testing.T) {
54+
if got := runSrc(t, `p loop.instance_of?(Enumerator)`); got != "true" {
55+
t.Fatalf("loop.instance_of?(Enumerator): got %q want true", got)
56+
}
57+
if got := runSrc(t, `p loop.size`); got != "Infinity" {
58+
t.Fatalf("loop.size: got %q want Infinity", got)
59+
}
60+
// The returned Enumerator re-drives Kernel#loop with the given block.
61+
if got := runSrc(t, `c = 0; p(loop.each { c += 1; break c if c >= 5 })`); got != "5" {
62+
t.Fatalf("loop.each drive: got %q want 5", got)
63+
}
64+
}
65+
66+
// TestKernelFailAliasOfRaise proves Kernel#fail shares Kernel#raise's method
67+
// record on both the instance and singleton sides, and that it raises. Reference:
68+
// ruby/ruby v3_4_0 eval.c (rb_f_raise registered under raise and fail).
69+
func TestKernelFailAliasOfRaise(t *testing.T) {
70+
cases := []struct{ name, src, want string }{
71+
{"instance_method_eq", `p(Kernel.instance_method(:fail) == Kernel.instance_method(:raise))`, "true"},
72+
{"singleton_method_eq", `p(Kernel.method(:fail) == Kernel.method(:raise))`, "true"},
73+
{"private_on_instances", `p Kernel.private_instance_methods(false).include?(:fail)`, "true"},
74+
{"public_on_module", `p Kernel.public_methods(false).include?(:fail)`, "true"},
75+
{"raises_runtimeerror", `begin; fail "x"; rescue => e; p e.class; end`, "RuntimeError"},
76+
}
77+
for _, tc := range cases {
78+
t.Run(tc.name, func(t *testing.T) {
79+
if got := runSrc(t, tc.src); got != tc.want {
80+
t.Fatalf("src=%q got=%q want=%q", tc.src, got, tc.want)
81+
}
82+
})
83+
}
84+
}

‎internal/vm/phase5w_test.go‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
package vm_test
22

33
import (
4-
"strings"
54
"testing"
65
)
76

@@ -23,7 +22,12 @@ func TestKernelLoop(t *testing.T) {
2322
}
2423

2524
func TestLoopNoBlock(t *testing.T) {
26-
if err := runErr(t, `loop`); err == nil || !strings.Contains(err.Error(), "LocalJumpError") {
27-
t.Fatalf("got %v want LocalJumpError", err)
25+
// Kernel#loop with no block returns an infinite Enumerator over itself (MRI
26+
// eval.c rb_f_loop / loop_size), not a LocalJumpError as it once did.
27+
if got := eval(t, `p loop.instance_of?(Enumerator)`); got != "true\n" {
28+
t.Fatalf("loop.instance_of?(Enumerator): got %q want \"true\\n\"", got)
29+
}
30+
if got := eval(t, `p loop.size`); got != "Infinity\n" {
31+
t.Fatalf("loop.size: got %q want \"Infinity\\n\"", got)
2832
}
2933
}

0 commit comments

Comments
 (0)