Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 30 additions & 6 deletions internal/vm/builtins.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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",
Expand Down
84 changes: 84 additions & 0 deletions internal/vm/kernel_loop_fail_wave21_internal_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
})
}
}
10 changes: 7 additions & 3 deletions internal/vm/phase5w_test.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package vm_test

import (
"strings"
"testing"
)

Expand All @@ -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)
}
}