diff --git a/internal/vm/builtins.go b/internal/vm/builtins.go index 1149011e..a3d937b6 100644 --- a/internal/vm/builtins.go +++ b/internal/vm/builtins.go @@ -5848,6 +5848,7 @@ func (vm *VM) registerKernelModuleFunctions() { names := []string{ "Array", "Complex", "Float", "Hash", "Integer", "Rational", "String", "__dir__", "abort", "at_exit", "autoload", "autoload?", "caller", + "caller_locations", "catch", "eval", "exec", "exit", "exit!", "fork", "format", "lambda", "load", "loop", "open", "p", "print", "printf", "proc", "puts", "raise", "rand", "require", "require_relative", "sleep", "sprintf", @@ -8963,20 +8964,37 @@ func nativeRaise(vm *VM, _ object.Value, args []object.Value, _ *Proc) object.Va if !object.IsNil(vm.curExc) { panic(vm.excError(vm.captureBacktrace(vm.curExc))) } + // A bare `raise` with nothing being handled raises RuntimeError with an + // empty message, as MRI does (its #message then reports the class name). panic(vm.excError(vm.captureBacktrace(vm.send(vm.consts["RuntimeError"].(*RClass), "new", - []object.Value{object.NewString("unhandled exception")}, nil)))) + []object.Value{object.NewString("")}, nil)))) default: exc := vm.raiseExceptionObject(args) + // A cause: that reaches the exception being raised through its own cause + // chain is a circular reference — MRI rejects it before linking. cause == exc + // itself is not circular (it is simply not set); the walk starts one link in. + if causeGiven && !object.IsNil(causeVal) && causeVal != exc { + for c := getIvar(causeVal, causeIvar); !object.IsNil(c); c = getIvar(c, causeIvar) { + if c == exc { + raise("ArgumentError", "circular causes") + } + } + } vm.applyRaiseCause(exc, causeGiven, causeVal) panic(vm.excError(vm.captureBacktrace(exc))) } } // raiseExceptionObject builds the exception object for a raise from a non-empty -// argument list, matching MRI's Kernel#raise coercion: a String becomes a -// RuntimeError with that message; an exception Class is instantiated (with the -// message when a class+message pair is given); an exception instance is used -// as-is. Anything else is a TypeError. It does NOT capture a backtrace or +// argument list, matching MRI's make_exception (eval.c). A lone String is +// shorthand for a RuntimeError with that message. Otherwise the first argument's +// #exception method is invoked — with the second argument as its message when a +// message is present (a class+message pair, then, instantiates via +// Exception.exception == .new; a bare exception instance returns itself, or a +// re-messaged copy). An object that does not respond to #exception (a plain +// object, true/false/nil, a String with extra positional args) is a TypeError +// "exception class/object expected"; one whose #exception returns a non-Exception +// is a TypeError "exception object expected". It does NOT capture a backtrace or // panic — callers do that (Kernel#raise raises here and now; Thread#raise queues // the object for the target thread, where the backtrace is captured). Shared so // Thread#raise coerces its arguments exactly like Kernel#raise. @@ -8987,26 +9005,23 @@ func (vm *VM) raiseExceptionObject(args []object.Value) object.Value { return vm.send(vm.consts["RuntimeError"].(*RClass), "new", []object.Value{s}, nil) } } - // Otherwise the first argument must be an exception class (instantiated, with - // the message when a second argument is present) or an exception instance - // (used as-is). Anything else — a String with extra arguments, a non-exception - // class or object, true/false/nil — is a TypeError, matching MRI. - switch a := args[0].(type) { - case *RClass: - if classIsA(a, vm.consts["Exception"].(*RClass)) { - var ctorArgs []object.Value - if len(args) >= 2 { - ctorArgs = []object.Value{args[1]} - } - return vm.send(a, "new", ctorArgs, nil) - } - case *RObject: - if classIsA(vm.classOf(a), vm.consts["Exception"].(*RClass)) { - return a - } + first := args[0] + // MRI calls first.exception(msg?) — the message is the SECOND positional + // argument only (a third argument, the backtrace, is applied separately by the + // caller). An object with no #exception (which includes true/false/nil and a + // String carrying extra positional args) cannot be an exception. + if !vm.respondsTo(first, "exception") { + raise("TypeError", "exception class/object expected") } - raise("TypeError", "exception class/object expected") - return object.NilV + var excArgs []object.Value + if len(args) >= 2 { + excArgs = []object.Value{args[1]} + } + exc := vm.send(first, "exception", excArgs, nil) + if !classIsA(vm.classOf(exc), vm.consts["Exception"].(*RClass)) { + raise("TypeError", "exception object expected") + } + return exc } // captureBacktrace stamps the current frame stack onto exc as its backtrace, the diff --git a/internal/vm/kernel_caller_raise_internal_test.go b/internal/vm/kernel_caller_raise_internal_test.go new file mode 100644 index 00000000..d160acd4 --- /dev/null +++ b/internal/vm/kernel_caller_raise_internal_test.go @@ -0,0 +1,190 @@ +// Copyright (c) the go-embedded-ruby/ruby authors +// +// SPDX-License-Identifier: BSD-3-Clause + +package vm + +import "testing" + +// TestKernelCallerArguments covers Kernel#caller's argument handling — the shared +// callerSlice over caller(0): the default start, an explicit Integer start, a +// length cap (including a nil length), a Range, Float coercion, and the nil result +// when the start overshoots the stack (distinct from an empty array at the exact +// end). The Range/(start,length) results are checked for internal consistency +// against Array#[] on caller(0), which holds regardless of the frame count. +func TestKernelCallerArguments(t *testing.T) { + tests := []struct{ name, src, want string }{ + // caller(0) keeps the current frame; the default (== caller(1)) drops it. + {"start_zero_has_frame", `p caller(0).length >= 1`, "true\n"}, + {"default_drops_one", `p caller == caller(1)`, "true\n"}, + {"start_one_equals_slice", `p caller(1) == caller(0)[1..]`, "true\n"}, + // Length cap: caller(0, 1) is one frame; caller(0, 0) is empty. + {"length_cap_one", `p caller(0, 1).length`, "1\n"}, + {"length_cap_zero", `p caller(0, 0).length`, "0\n"}, + // A nil length behaves like no length at all. + {"nil_length", `p caller(0, nil) == caller(0)`, "true\n"}, + // A Range slices caller(0) exactly like Array#[], nested so the stack is deep. + {"range_matches_slice", `def a; [caller(0), caller(1..2)]; end +def b; a; end +f, r = b +p f[1..2] == r`, "true\n"}, + {"start_length_matches_slice", `def a; [caller(0), caller(1, 1)]; end +def b; a; end +f, l = b +p f[1, 1] == l`, "true\n"}, + // Float start/length truncate toward zero via #to_int. + {"float_coercion", `p caller(0.9, 1.9) == caller(0, 1)`, "true\n"}, + // Overshooting the stack returns nil (not []); the exact end returns []. + {"overshoot_nil", `p caller(1000)`, "nil\n"}, + {"overshoot_range_nil", `p caller(1000..-1)`, "nil\n"}, + // The frames are Strings. + {"frames_are_strings", `p caller(0)[0].class`, "String\n"}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + if got := eval(t, tc.src); got != tc.want { + t.Fatalf("src=%q: got %q, want %q", tc.src, got, tc.want) + } + }) + } +} + +// TestKernelCallerErrors covers the negative-argument guards in callerSlice, which +// raise ArgumentError with MRI's exact messages (a Range is exempt — its negative +// bounds are legal). +func TestKernelCallerErrors(t *testing.T) { + tests := []struct{ name, src, class, msg string }{ + {"negative_start", `caller(-1)`, "ArgumentError", "negative level (-1)"}, + {"negative_length", `caller(0, -1)`, "ArgumentError", "negative size (-1)"}, + {"negative_start_loc", `caller_locations(-1)`, "ArgumentError", "negative level (-1)"}, + {"negative_length_loc", `caller_locations(0, -1)`, "ArgumentError", "negative size (-1)"}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + class, msg := evalErr(t, tc.src) + if class != tc.class || msg != tc.msg { + t.Fatalf("src=%q: got %s/%q, want %s/%q", tc.src, class, msg, tc.class, tc.msg) + } + }) + } +} + +// TestKernelCallerLocations covers Kernel#caller_locations: each level is a +// Thread::Backtrace::Location answering #to_s / #path / #lineno, it shares +// #caller's argument handling (a Range and the nil-overshoot result), and it is a +// Kernel module function (private instance + public module method). +func TestKernelCallerLocations(t *testing.T) { + tests := []struct{ name, src, want string }{ + {"is_location", `p caller_locations(0, 1)[0].kind_of?(Thread::Backtrace::Location)`, "true\n"}, + {"location_to_s", `p caller_locations(0, 1)[0].to_s.class`, "String\n"}, + {"location_path", `p caller_locations(0, 1)[0].path.class`, "String\n"}, + {"location_lineno", `p caller_locations(0, 1)[0].lineno.class`, "Integer\n"}, + {"range_form", `p caller_locations(0..0).length`, "1\n"}, + {"overshoot_nil", `p caller_locations(1000)`, "nil\n"}, + {"empty_at_end", `p caller_locations(caller_locations(0).length).length`, "0\n"}, + {"private_on_kernel", `p Kernel.private_instance_methods(false).include?(:caller_locations)`, "true\n"}, + {"public_on_kernel", `p Kernel.public_methods(false).include?(:caller_locations)`, "true\n"}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + if got := eval(t, tc.src); got != tc.want { + t.Fatalf("src=%q: got %q, want %q", tc.src, got, tc.want) + } + }) + } +} + +// TestKernelRaiseExceptionProtocol covers raiseExceptionObject's MRI make_exception +// path: a lone String becomes a RuntimeError; an exception instance is returned by +// its own #exception (identity); an exception class is instantiated; a non-Exception +// object's #exception(msg) is honoured; a bare object is a TypeError; and an +// #exception that returns a non-Exception is the "exception object expected" TypeError. +func TestKernelRaiseExceptionProtocol(t *testing.T) { + valueTests := []struct{ name, src, want string }{ + {"string_shorthand", `begin; raise "boom"; rescue => e; p [e.class, e.message]; end`, "[RuntimeError, \"boom\"]\n"}, + {"instance_identity", `x = RuntimeError.new("z") +begin; raise(x); rescue => e; p e.equal?(x); end`, "true\n"}, + {"class_instantiated", `begin; raise(ArgumentError, "m"); rescue => e; p [e.class, e.message]; end`, "[ArgumentError, \"m\"]\n"}, + {"exception_protocol_with_msg", `e = Object.new +def e.exception(m); StandardError.new(m); end +begin; raise e, "foo"; rescue => x; p [x.class, x.message]; end`, "[StandardError, \"foo\"]\n"}, + {"exception_protocol_no_msg", `e = Object.new +def e.exception; StandardError.new("z"); end +begin; raise e; rescue => x; p x.class; end`, "StandardError\n"}, + } + for _, tc := range valueTests { + t.Run(tc.name, func(t *testing.T) { + if got := eval(t, tc.src); got != tc.want { + t.Fatalf("src=%q: got %q, want %q", tc.src, got, tc.want) + } + }) + } + + errTests := []struct{ name, src, class, msg string }{ + {"bare_object", `raise Object.new`, "TypeError", "exception class/object expected"}, + {"true_value", `raise true`, "TypeError", "exception class/object expected"}, + {"exception_returns_nonexception", `e = Object.new +def e.exception; Array; end +raise e`, "TypeError", "exception object expected"}, + } + for _, tc := range errTests { + t.Run(tc.name, func(t *testing.T) { + class, msg := evalErr(t, tc.src) + if class != tc.class || msg != tc.msg { + t.Fatalf("src=%q: got %s/%q, want %s/%q", tc.src, class, msg, tc.class, tc.msg) + } + }) + } +} + +// TestKernelRaiseBareAndCause covers nativeRaise's edges: a bare raise with nothing +// being handled yields RuntimeError with an empty message; a cause: that loops back +// to the raised exception is rejected with "circular causes"; a cause: equal to the +// raised exception itself is NOT circular; and a non-Exception cause: is a TypeError. +func TestKernelRaiseBareAndCause(t *testing.T) { + t.Run("bare_empty_message", func(t *testing.T) { + class, msg := evalErr(t, `raise`) + if class != "RuntimeError" || msg != "" { + t.Fatalf("got %s/%q, want RuntimeError/\"\"", class, msg) + } + }) + t.Run("circular_cause", func(t *testing.T) { + src := `begin + raise "1" +rescue => e1 + begin + raise "2" + rescue => e2 + begin + raise "3" + rescue => e3 + raise(e1, cause: e3) + end + end +end` + class, msg := evalErr(t, src) + if class != "ArgumentError" || msg != "circular causes" { + t.Fatalf("got %s/%q, want ArgumentError/\"circular causes\"", class, msg) + } + }) + t.Run("cause_equal_self_not_circular", func(t *testing.T) { + src := `c = StandardError.new("c") +begin; raise(c, cause: c); rescue => e; p e.class; end` + if got := eval(t, src); got != "StandardError\n" { + t.Fatalf("got %q, want StandardError\\n", got) + } + }) + t.Run("bad_cause_type", func(t *testing.T) { + class, msg := evalErr(t, `raise("m", cause: Object.new)`) + if class != "TypeError" || msg != "exception object expected" { + t.Fatalf("got %s/%q, want TypeError/\"exception object expected\"", class, msg) + } + }) + t.Run("explicit_cause_chained", func(t *testing.T) { + src := `c = StandardError.new("x") +begin; raise("y", cause: c); rescue => e; p e.cause.message; end` + if got := eval(t, src); got != "\"x\"\n" { + t.Fatalf("got %q, want \"x\"\\n", got) + } + }) +} diff --git a/internal/vm/kernel_introspect.go b/internal/vm/kernel_introspect.go index 4a62660e..bf24d550 100644 --- a/internal/vm/kernel_introspect.go +++ b/internal/vm/kernel_introspect.go @@ -120,11 +120,34 @@ func (vm *VM) registerKernelIntrospection() { vm.cKernel.smethods[name] = &Method{name: name, owner: vm.cKernel, native: fn} } - // caller: a best-effort backtrace as a String array, outermost-first omitted - // like MRI — it excludes the frame that called caller and lists the rest from - // nearest to the top level. Without source line tracking the line is 0. - vm.cObject.define("caller", func(vm *VM, _ object.Value, _ []object.Value, _ *Proc) object.Value { - return object.NewArrayFromSlice(vm.callerFrames()) + // caller(start=1, length=nil) / caller(range): a best-effort backtrace as a + // String array, listed nearest-first. Like MRI, `start` omits that many + // innermost levels (caller == caller(1) drops the frame that called caller; + // caller(0) keeps it), `length` caps the count, and a Range selects levels the + // way Array#[] slices caller(0). A start past the top returns nil (distinct from + // []). Without source line tracking the line is 0. + vm.cObject.define("caller", func(vm *VM, _ object.Value, args []object.Value, _ *Proc) object.Value { + frames, present := vm.callerSlice(args) + if !present { + return object.NilV + } + return object.NewArrayFromSlice(frames) + }) + + // caller_locations(start=1, length=nil) / caller_locations(range): like #caller + // but each level is a Thread::Backtrace::Location value object (answering #path, + // #lineno, #label, #absolute_path, #to_s) instead of a plain String. It shares + // #caller's argument handling exactly, including the nil-for-overshoot result. + vm.cObject.define("caller_locations", func(vm *VM, _ object.Value, args []object.Value, _ *Proc) object.Value { + frames, present := vm.callerSlice(args) + if !present { + return object.NilV + } + locs := make([]object.Value, len(frames)) + for i, f := range frames { + locs[i] = vm.backtraceLocation(f.ToS()) + } + return object.NewArrayFromSlice(locs) }) // __FILE__: the path of the file currently executing. During a require it is @@ -219,11 +242,49 @@ func (vm *VM) currentMethodCtxPtr() *frameMethod { return &ctx } -// callerFrames builds caller's String array. It drops the topmost frame (the one -// that invoked caller) and walks outward, formatting each as MRI does, with a -// placeholder line number since this VM does not yet track source positions. -func (vm *VM) callerFrames() []object.Value { - return vm.backtraceFrames(1) +// callerSlice selects the levels Kernel#caller / #caller_locations return from the +// argument list, applying MRI's semantics over caller(0) — backtraceFrames(0), +// the current frame stack nearest-first. A Range slices that list exactly like +// Array#[] (endless, beginless and negative bounds included); an Integer start +// (default 1) omits that many innermost levels, with an optional non-negative +// length cap. A negative start/length is an ArgumentError, as MRI; a start past +// the top of the stack yields (nil, false) so the caller returns Ruby nil, +// distinct from an empty array (an exactly-past-the-end start yields []). The +// start/length are coerced through #to_int, so a Float level truncates. +func (vm *VM) callerSlice(args []object.Value) ([]object.Value, bool) { + full := vm.backtraceFrames(0) + fullArr := object.NewArrayFromSlice(full) + // Range form: forward to Array#[], which already handles every bound shape. + if len(args) >= 1 { + if _, isRange := args[0].(*object.Range); isRange { + res := vm.send(fullArr, "[]", []object.Value{args[0]}, nil) + if object.IsNil(res) { + return nil, false + } + return res.(*object.Array).Elems, true + } + } + start := int64(1) + if len(args) >= 1 { + start = vm.toIntCoerce(args[0]) + } + if start < 0 { + raise("ArgumentError", "negative level (%d)", start) + } + // A start-only call is caller(0)[start..]: at most len(full) elements from + // start, which Array#[](start, len(full)+1) yields with the right nil/[] edges. + length := int64(len(full)) + 1 + if len(args) >= 2 && !object.IsNil(args[1]) { + length = vm.toIntCoerce(args[1]) + if length < 0 { + raise("ArgumentError", "negative size (%d)", length) + } + } + res := vm.send(fullArr, "[]", []object.Value{object.IntValue(start), object.IntValue(length)}, nil) + if object.IsNil(res) { + return nil, false + } + return res.(*object.Array).Elems, true } // backtraceFrames renders the current frame stack as an MRI-shaped backtrace diff --git a/internal/vm/phase3a_test.go b/internal/vm/phase3a_test.go index aca1ed55..47fefb4b 100644 --- a/internal/vm/phase3a_test.go +++ b/internal/vm/phase3a_test.go @@ -52,7 +52,11 @@ func TestRaise(t *testing.T) { {"class", `raise TypeError`, "TypeError: TypeError"}, {"class_message", `raise ArgumentError, "bad arg"`, "ArgumentError: bad arg"}, {"instance", "e = RuntimeError.new(\"oops\")\nraise e", "RuntimeError: oops"}, - {"bare", `raise`, "RuntimeError: unhandled exception"}, + // MRI 4.0: a bare `raise` with no current exception raises RuntimeError with + // an EMPTY message (`raise; rescue=>e; e.message` => ""). "unhandled exception" + // is only the display default of RuntimeError#detailed_message, not the message + // itself — see exception_residuals_test.go. err.Error() is "RuntimeError: ". + {"bare", `raise`, "RuntimeError: "}, {"non_exception", `raise 5`, "TypeError"}, {"is_a_bad_arg", `5.is_a?(3)`, "TypeError"}, {"instance_of_bad_arg", `5.instance_of?("x")`, "TypeError"},