diff --git a/internal/vm/builtins.go b/internal/vm/builtins.go index e76ef14e..5e22ed64 100644 --- a/internal/vm/builtins.go +++ b/internal/vm/builtins.go @@ -366,11 +366,24 @@ func (vm *VM) bootstrap() { vm.cObject.define("instance_variables", func(_ *VM, self object.Value, _ []object.Value, _ *Proc) object.Value { return object.NewArrayFromSlice(ivarNamesInOrder(self)) }) - vm.cBasicObject.define("instance_eval", func(vm *VM, self object.Value, _ []object.Value, blk *Proc) object.Value { - if blk == nil { - raise("LocalJumpError", "no block given (yield)") + vm.cBasicObject.define("instance_eval", func(vm *VM, self object.Value, args []object.Value, blk *Proc) object.Value { + if blk != nil { + if len(args) != 0 { + raise("ArgumentError", "wrong number of arguments (given %d, expected 0)", len(args)) + } + return vm.callBlockSelf(blk, self, nil) + } + // String form: instance_eval("code" [, filename [, lineno]]) evaluates the + // source with self as the receiver and its singleton class as the definee. + if len(args) < 1 || len(args) > 3 { + raise("ArgumentError", "wrong number of arguments (given %d, expected 1..3)", len(args)) + } + src := vm.coerceFormatString(args[0]) + file := vm.currentFile() + if len(args) >= 2 { + file = vm.coerceFormatString(args[1]) // filename, coerced via #to_str } - return vm.callBlockSelf(blk, self, nil) + return vm.instanceEvalString(self, src, file) }) vm.cBasicObject.define("instance_exec", func(vm *VM, self object.Value, args []object.Value, blk *Proc) object.Value { if blk == nil { diff --git a/internal/vm/eval.go b/internal/vm/eval.go index 3f6f04a2..def2e2b7 100644 --- a/internal/vm/eval.go +++ b/internal/vm/eval.go @@ -4,6 +4,27 @@ import ( "github.com/go-embedded-ruby/ruby/internal/object" ) +// instanceEvalString backs the String form of BasicObject#instance_eval: it +// compiles src and runs it with self as the receiver and the receiver's +// singleton class as the definee, so a `def` in the source becomes a singleton +// method and `self`/instance variables resolve to the receiver. An immediate +// receiver has no singleton class, so its own class stands in as the definee +// (source that only reads still works). +func (vm *VM) instanceEvalString(self object.Value, src, file string) object.Value { + iseq, cerr := parseCompileFn(src) + if cerr != nil { + return raise("SyntaxError", "%s", cerr.Error()) + } + iseq.Name = "(eval)" + iseq.File = file // the given filename, or the caller's file by default + definee, ok := vm.ensureSingleton(self) + if !ok { + definee = vm.classOf(self) + } + vm.pendingMethodCtx = vm.currentMethodCtxPtr() + return vm.exec(iseq, self, nil, definee, "", nil, nil, nil, nil) +} + // registerEval installs Kernel#eval — the embedded front-end's reason for being. // Because the lexer/parser/compiler ship inside the binary, a running program // can compile and run new Ruby at runtime. diff --git a/internal/vm/instance_eval_string_internal_test.go b/internal/vm/instance_eval_string_internal_test.go new file mode 100644 index 00000000..bce738cd --- /dev/null +++ b/internal/vm/instance_eval_string_internal_test.go @@ -0,0 +1,40 @@ +// Copyright (c) the go-embedded-ruby/ruby authors +// +// SPDX-License-Identifier: BSD-3-Clause + +package vm + +import "testing" + +// TestInstanceEvalString covers the String form of BasicObject#instance_eval: +// evaluating source with the receiver as self (reading its instance variables, +// defining a singleton method), on an immediate receiver, the optional filename +// argument, the arity errors, a block-plus-arguments error, and a SyntaxError +// for bad source. Verified against ruby 4.0.6. +func TestInstanceEvalString(t *testing.T) { + cases := []struct{ src, want string }{ + // self and instance variables resolve to the receiver. + {`o = Object.new; o.instance_variable_set(:@x, 42); p o.instance_eval("@x")`, `42`}, + {`o = Object.new; p o.instance_eval("self").equal?(o)`, `true`}, + // A def in the source becomes a singleton method of the receiver. + {`o = Object.new; o.instance_eval("def greet; :hi; end"); p o.greet`, `:hi`}, + // An immediate receiver can still be read through. + {`p 5.instance_eval("self + 1")`, `6`}, + // The block form still works, and returns the block's value. + {`o = Object.new; o.instance_variable_set(:@v, 7); p o.instance_eval { @v }`, `7`}, + // Arity: no block and no args, or too many args. + {`begin; Object.new.instance_eval; rescue ArgumentError => e; p e.class; end`, `ArgumentError`}, + {`begin; Object.new.instance_eval("x", "f", 1, 2); rescue ArgumentError => e; p e.class; end`, `ArgumentError`}, + // A block together with arguments is an ArgumentError. + {`begin; Object.new.instance_eval("x") {}; rescue ArgumentError => e; p e.class; end`, `ArgumentError`}, + // The two-argument (source, filename) form is accepted. + {`p Object.new.instance_eval("1 + 1", "myfile.rb")`, `2`}, + // Bad source raises SyntaxError. + {`begin; Object.new.instance_eval("def ("); rescue SyntaxError => e; p e.class; end`, `SyntaxError`}, + } + for _, c := range cases { + if got := eval(t, c.src); got != c.want+"\n" { + t.Errorf("src=%q got=%q want=%q", c.src, got, c.want+"\n") + } + } +} diff --git a/internal/vm/phase5k_test.go b/internal/vm/phase5k_test.go index 1207258c..f139a54c 100644 --- a/internal/vm/phase5k_test.go +++ b/internal/vm/phase5k_test.go @@ -32,9 +32,13 @@ func TestInstanceReflection(t *testing.T) { } func TestInstanceEvalNoBlock(t *testing.T) { - for _, src := range []string{`5.instance_eval`, `5.instance_exec`} { - if err := runErr(t, src); err == nil || !strings.Contains(err.Error(), "LocalJumpError") { - t.Fatalf("src=%q got %v want LocalJumpError", src, err) - } + // instance_exec is block-only, so with no block (and no args) it raises + // LocalJumpError. instance_eval also accepts a String form, so no block and no + // args is instead a wrong-number-of-arguments ArgumentError, as MRI reports. + if err := runErr(t, `5.instance_exec`); err == nil || !strings.Contains(err.Error(), "LocalJumpError") { + t.Fatalf("instance_exec got %v want LocalJumpError", err) + } + if err := runErr(t, `5.instance_eval`); err == nil || !strings.Contains(err.Error(), "ArgumentError") { + t.Fatalf("instance_eval got %v want ArgumentError", err) } }