diff --git a/internal/vm/method.go b/internal/vm/method.go index d762b059..189c0a3c 100644 --- a/internal/vm/method.go +++ b/internal/vm/method.go @@ -21,6 +21,22 @@ func (vm *VM) newBoundMethod(recv object.Value, name string, m *Method) *BoundMe return &BoundMethod{recv: recv, name: name, m: m, vm: vm} } +// methodMissingMethod builds the synthetic Method returned by Object#method for +// a name the receiver only answers via respond_to_missing?. Its owner is the +// receiver's class (so Method#owner reports it) and its body forwards to +// method_missing(name, *args, &blk), resolved dynamically at call time. +func (vm *VM) methodMissingMethod(recv object.Value, name string) *Method { + return &Method{ + name: name, + owner: vm.classOf(recv), + viaMissing: true, + native: func(vm *VM, self object.Value, args []object.Value, blk *Proc) object.Value { + fwd := append([]object.Value{object.Symbol(name)}, args...) + return vm.send(self, "method_missing", fwd, blk) + }, + } +} + // every Method created by define / OpDefineMethod / define_(singleton_)method // carries a non-nil owner, so b.m.owner is always set. func (b *BoundMethod) ToS() string { @@ -38,6 +54,14 @@ func (vm *VM) registerMethod() { name := args[0].ToS() m := vm.resolveMethod(self, name) if m == nil { + // A name the receiver answers only through respond_to_missing? (with + // include_private true) still yields a callable Method whose body routes + // to method_missing dynamically — MRI resolves method_missing at call + // time, so redefining it after the fact changes the result and the + // original name is never invoked even if it later comes to exist. + if vm.send(self, "respond_to_missing?", []object.Value{object.Symbol(name), object.True}, nil).Truthy() { + return vm.newBoundMethod(self, name, vm.methodMissingMethod(self, name)) + } return raise("NameError", "undefined method '%s' for %s", name, vm.classOf(self).name) } return vm.newBoundMethod(self, name, m) diff --git a/internal/vm/method_reflect.go b/internal/vm/method_reflect.go index 51fd291a..a8351b1d 100644 --- a/internal/vm/method_reflect.go +++ b/internal/vm/method_reflect.go @@ -31,6 +31,28 @@ func methodDefKey(m *Method) uintptr { } } +// methodSameDef reports whether two Method records share an underlying +// definition. A method_missing-backed Method (Object#method for a name answered +// only via respond_to_missing?) has no shared record, so two of them are equal +// exactly when they carry the same name; otherwise the definition-key rule +// applies. +func methodSameDef(a, b *Method) bool { + if a.viaMissing || b.viaMissing { + return a.viaMissing && b.viaMissing && a.name == b.name + } + return methodDefKey(a) == methodDefKey(b) +} + +// methodDefHash gives a Method a hash that agrees with methodSameDef: a +// method_missing-backed Method hashes on its name (so two equal ones agree), +// every other on its definition-key pointer. +func methodDefHash(m *Method) int64 { + if m.viaMissing { + return fnvHash("mm:" + m.name) + } + return int64(methodDefKey(m)) +} + // registerMethodReflect adds the reflection operators that compare, hash, // compose and curry Method objects (and the composition operators on Proc, // which share the same semantics). Behaviour matches MRI 3.4. @@ -42,7 +64,7 @@ func (vm *VM) registerMethodReflect() { if !ok { return object.False } - return object.Bool(a.recv == b.recv && methodDefKey(a.m) == methodDefKey(b.m)) + return object.Bool(a.recv == b.recv && methodSameDef(a.m, b.m)) } vm.cMethod.define("==", methodEq) // Method#eql? is an alias of Method#== (they share one record, so @@ -50,7 +72,7 @@ func (vm *VM) registerMethodReflect() { aliasBuiltin(vm.cMethod, "eql?", "==") vm.cMethod.define("hash", func(vm *VM, self object.Value, _ []object.Value, _ *Proc) object.Value { b := self.(*BoundMethod) - return object.IntValue(vm.hashValue(b.recv) ^ int64(methodDefKey(b.m))) + return object.IntValue(vm.hashValue(b.recv) ^ methodDefHash(b.m)) }) // Method#>> and Method#<< compose the method with another callable. diff --git a/internal/vm/object_model.go b/internal/vm/object_model.go index ee7afa98..1b956ca5 100644 --- a/internal/vm/object_model.go +++ b/internal/vm/object_model.go @@ -187,6 +187,12 @@ type Method struct { // iseq.Name when present, else fall back to name" (see methodOriginalName), so // a plain def and an `alias` (which shares the iseq) need not set it. origName string + // viaMissing marks the synthetic Method that Object#method returns for a name + // answered only through respond_to_missing? (its body forwards to + // method_missing). Two such Methods on the same receiver with the same name + // are one and the same method to MRI even though each is a distinct record, so + // equality keys on the name rather than the record pointer. + viaMissing bool } // RClass is a class (the live, mutable method table that makes monkey-patching, @@ -2059,9 +2065,14 @@ func (vm *VM) bindBlockPositionals(p *Proc, args []object.Value) []object.Value if p.iseq.SplatIndex >= 0 { // A *rest block param has variable arity: pad up to the required // positionals, then pass every argument through so exec's splat binding - // collects the rest (instead of the fixed-arity truncation below). - if len(args) < p.iseq.NumRequired { - padded := make([]object.Value, p.iseq.NumRequired) + // collects the rest (instead of the fixed-arity truncation below). The + // required count includes the post-splat parameters (`|*a, b|`, `|a, *b, c|`) + // — a lenient proc fills those with nil (and leaves the splat empty) rather + // than raising, so the pad target is the leading required plus the post + // count, and the padding nils land at the tail where the post params bind. + required := p.iseq.NumRequired + (np - p.iseq.SplatIndex - 1) + if len(args) < required { + padded := make([]object.Value, required) copy(padded, args) for i := len(args); i < len(padded); i++ { padded[i] = object.NilV diff --git a/internal/vm/proc.go b/internal/vm/proc.go index c9407e15..53529fc8 100644 --- a/internal/vm/proc.go +++ b/internal/vm/proc.go @@ -77,9 +77,9 @@ func (vm *VM) registerProcMethods() { // since the VM tracks no per-instruction line), but carries the meaningful, // deterministic tags: " (lambda)" for a lambda and " (&:name)" for a // Symbol#to_proc proc. #inspect is the same method record as #to_s (MRI - // aliases them). + // aliases them). MRI tags the result ASCII-8BIT (BINARY), so match that. vm.cProc.define("to_s", func(_ *VM, self object.Value, _ []object.Value, _ *Proc) object.Value { - return object.NewString(procToS(self.(*Proc))) + return object.NewStringViewEnc(procToS(self.(*Proc)), "ASCII-8BIT") }) aliasBuiltin(vm.cProc, "inspect", "to_s") } diff --git a/internal/vm/proc_method_wave10_test.go b/internal/vm/proc_method_wave10_test.go new file mode 100644 index 00000000..e5ea47ae --- /dev/null +++ b/internal/vm/proc_method_wave10_test.go @@ -0,0 +1,152 @@ +package vm_test + +import "testing" + +// TestUnboundBindModuleOwner covers that an UnboundMethod whose owner is a +// Module (not a Class) may be bound to any object — MRI only enforces the +// kind_of? rule for methods owned by a Class. Exercises the isModule short +// circuit in checkBindable. +func TestUnboundBindModuleOwner(t *testing.T) { + src := ` +module M + def greeting; "hi"; end +end +um = M.instance_method(:greeting) +p um.bind(Object.new).call +` + if got := eval(t, src); got != "\"hi\"\n" { + t.Errorf("module-owned bind = %q, want %q", got, "\"hi\"\n") + } +} + +// TestUnboundBindModuleOwnerBindCall covers the same relaxation on bind_call. +func TestUnboundBindModuleOwnerBindCall(t *testing.T) { + src := ` +module M + def echo(x); x; end +end +p M.instance_method(:echo).bind_call(Object.new, 42) +` + if got := eval(t, src); got != "42\n" { + t.Errorf("module-owned bind_call = %q, want %q", got, "42\n") + } +} + +// TestProcToSBinaryEncoding covers that Proc#to_s (and its #inspect alias) is +// tagged ASCII-8BIT (BINARY), as MRI reports. +func TestProcToSBinaryEncoding(t *testing.T) { + for _, tc := range []struct{ name, src string }{ + {"proc", `p proc { }.to_s.encoding`}, + {"lambda", `p ->() { }.to_s.encoding`}, + {"inspect", `p proc { }.inspect.encoding`}, + } { + t.Run(tc.name, func(t *testing.T) { + if got := eval(t, tc.src); got != "#\n" { + t.Errorf("%s => %q, want BINARY encoding", tc.src, got) + } + }) + } +} + +// TestProcPostSplatBindingLenient covers that a non-lambda proc with post-splat +// required parameters (|*a, b|, |a, *b, c|) is lenient: too few arguments fill +// the post parameters with nil and leave the splat empty rather than raising. +func TestProcPostSplatBindingLenient(t *testing.T) { + for _, tc := range []struct{ name, src, want string }{ + {"star_a_b_none", `p (proc { |*a, b| [a, b] }).call`, "[[], nil]\n"}, + {"a_star_b_c_one", `p (proc { |a, *b, c| [a, b, c] }).call(1)`, "[1, [], nil]\n"}, + {"a_star_b_c_none", `p (proc { |a, *b, c| [a, b, c] }).call`, "[nil, [], nil]\n"}, + {"a_star_b_c_many", `p (proc { |a, *b, c| [a, b, c] }).call(1, 2, 3, 4)`, "[1, [2, 3], 4]\n"}, + } { + t.Run(tc.name, func(t *testing.T) { + if got := eval(t, tc.src); got != tc.want { + t.Errorf("%s => %q, want %q", tc.src, got, tc.want) + } + }) + } +} + +// missingSrc is a class that answers :ghost only through respond_to_missing? + +// method_missing, used by the Method-via-missing tests. +const missingSrc = ` +class Ghosted + def respond_to_missing?(name, priv) = name == :ghost + def method_missing(name, *args) + name == :ghost ? [:ghost, *args] : super + end +end +` + +// TestMethodViaRespondToMissing covers Object#method returning a callable Method +// for a name answered only via respond_to_missing?, whose body forwards to +// method_missing, plus that Method's name/owner/receiver reflection. +func TestMethodViaRespondToMissing(t *testing.T) { + cases := []struct{ name, expr, want string }{ + {"call", `g.method(:ghost).call(1, 2)`, "[:ghost, 1, 2]\n"}, + {"name", `g.method(:ghost).name`, ":ghost\n"}, + {"owner", `g.method(:ghost).owner`, "Ghosted\n"}, + {"receiver", `g.method(:ghost).receiver.equal?(g)`, "true\n"}, + {"eq", `g.method(:ghost) == g.method(:ghost)`, "true\n"}, + {"eq_other_recv", `g.method(:ghost) == Ghosted.new.method(:ghost)`, "false\n"}, + {"hash_eq", `g.method(:ghost).hash == g.method(:ghost).hash`, "true\n"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + src := missingSrc + "g = Ghosted.new\np(" + tc.expr + ")\n" + if got := eval(t, src); got != tc.want { + t.Errorf("%s => %q, want %q", tc.expr, got, tc.want) + } + }) + } +} + +// TestMethodViaRespondToMissingDynamic confirms the Method forwards to +// method_missing resolved at call time: redefining method_missing after the +// Method is built changes the result. +func TestMethodViaRespondToMissingDynamic(t *testing.T) { + src := missingSrc + ` +g = Ghosted.new +m = g.method(:ghost) +def g.method_missing(*) + :changed +end +p m.call +` + if got := eval(t, src); got != ":changed\n" { + t.Errorf("dynamic method_missing => %q, want %q", got, ":changed\n") + } +} + +// TestMethodMissingUnknownStillRaises confirms a name that respond_to_missing? +// rejects still raises NameError from Object#method. +func TestMethodMissingUnknownStillRaises(t *testing.T) { + src := missingSrc + ` +g = Ghosted.new +begin + g.method(:nope) + puts "no-raise" +rescue NameError + puts "raised" +end +` + if got := eval(t, src); got != "raised\n" { + t.Errorf("unknown method => %q, want %q", got, "raised\n") + } +} + +// TestUnboundBindClassOwnerStillChecked confirms a Class-owned UnboundMethod +// still rejects an incompatible receiver (the raise path is preserved). +func TestUnboundBindClassOwnerStillChecked(t *testing.T) { + src := ` +class A; def foo; end; end +begin + A.instance_method(:foo).bind(Object.new) + puts "no-raise" +rescue TypeError + puts "raised" +end +` + if got := eval(t, src); got != "raised\n" { + t.Errorf("class-owned bind of wrong receiver = %q, want %q", got, "raised\n") + } +} diff --git a/internal/vm/reflection.go b/internal/vm/reflection.go index 6a8001f5..cb8e996c 100644 --- a/internal/vm/reflection.go +++ b/internal/vm/reflection.go @@ -183,6 +183,14 @@ func (vm *VM) checkBindable(u *UnboundMethod, recv object.Value) { // singleton class. classOf(recv) returns the regular class and never reaches // the singleton in its super chain, so also walk from recv's own singleton // class — recv is trivially an instance of it — before rejecting the bind. + // A method whose owner is a Module (not a Class) may be bound to ANY + // object — MRI only enforces the kind_of? rule for methods owned by a + // Class. This covers `Mod.instance_method(:foo).bind(anything)` and Kernel + // methods (`Object.instance_method(:instance_of?)`) bound onto unrelated + // receivers such as a BasicObject. + if u.owner != nil && u.owner.isModule { + return + } if classIsA(vm.classOf(recv), u.owner) { return }