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
37 changes: 31 additions & 6 deletions internal/vm/builtins.go
Original file line number Diff line number Diff line change
Expand Up @@ -139,11 +139,23 @@ func (vm *VM) bootstrap() {
// copies for the rarer native-block target, so the OpSend fast path may hand
// them the live operand-stack region without a defensive copy (defineNR).
vm.cProc.defineNR("call", procCall)
vm.cProc.defineNR("[]", procCall)
vm.cProc.defineNR("yield", procCall)
// Proc#=== is an alias of #call, so a proc/lambda can be used as a case /
// grep pattern (pattern === element).
vm.cProc.define("===", procCall)
// Proc#[], #yield and #=== are genuine built-in aliases of Proc#call: MRI
// exposes them as the same method definition, so #instance_method(:[]) equals
// #instance_method(:call) (and #=== lets a proc/lambda act as a case / grep
// pattern). aliasBuiltin shares the one non-retaining *Method record; a fresh
// define would compare unequal even with an identical body.
aliasBuiltin(vm.cProc, "[]", "call")
aliasBuiltin(vm.cProc, "yield", "call")
aliasBuiltin(vm.cProc, "===", "call")
// Proc#== is identity equality (a Proc never equals a distinct Proc, even one
// with the same body and environment; a #dup returns the same object, so it
// equals its original). Proc#eql? is the same definition. Defining it on Proc
// — rather than inheriting BasicObject#== — is what MRI does, so #== shows up
// in Proc.public_instance_methods(false) and pairs with #eql?.
vm.cProc.define("==", func(_ *VM, self object.Value, args []object.Value, _ *Proc) object.Value {
return object.Bool(self == args[0])
})
aliasBuiltin(vm.cProc, "eql?", "==")
vm.cProc.define("arity", func(_ *VM, self object.Value, _ []object.Value, _ *Proc) object.Value {
return object.IntValue(int64(self.(*Proc).arityVal()))
})
Expand Down Expand Up @@ -171,8 +183,21 @@ func (vm *VM) bootstrap() {
}
if len(args) > 0 {
need = int(intArg(args[0]))
// A lambda enforces its arity, so currying it to an arity it cannot
// satisfy — fewer than its required positionals, or more than it will
// accept when it has no splat — raises, exactly as calling it would. A
// non-lambda proc never enforces arity, so it curries to any width.
if p.isLambda {
required, total, hasSplat := procPositionalInfo(p.iseq)
if need < required || (!hasSplat && need > total) {
raise("ArgumentError", "wrong number of arguments (given %d, expected %d)", need, required)
}
}
}
return vm.curried(p, need, nil)
// The curried Proc keeps the receiver's lambda-ness (and propagates it to
// every partial application), so ->{}.curry.lambda? is true while
// proc{}.curry.lambda? is false.
return vm.curriedProc(p, need, p.isLambda, nil)
})
dupFn := func(_ *VM, self object.Value, _ []object.Value, _ *Proc) object.Value {
return dupValue(self)
Expand Down
8 changes: 6 additions & 2 deletions internal/vm/method.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,12 @@ func (vm *VM) registerMethod() {
return vm.invoke(b.m, b.recv, args, blk)
}
vm.cMethod.define("call", call)
vm.cMethod.define("[]", call)
vm.cMethod.define("===", call)
// Method#[] and Method#=== are genuine built-in aliases of Method#call: MRI
// exposes them as the same method definition, so #instance_method(:[]) equals
// #instance_method(:call). aliasBuiltin shares the one *Method record (a fresh
// define would compare unequal even with an identical body).
aliasBuiltin(vm.cMethod, "[]", "call")
aliasBuiltin(vm.cMethod, "===", "call")
vm.cMethod.define("name", func(_ *VM, self object.Value, _ []object.Value, _ *Proc) object.Value {
return object.Symbol(self.(*BoundMethod).name)
})
Expand Down
26 changes: 26 additions & 0 deletions internal/vm/proc.go
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,32 @@ func procToS(p *Proc) string {
return s + ">"
}

// curriedProc builds a curried Proc that gathers arguments across successive
// calls until it has at least need of them, then invokes p with the lot. Each
// intermediate proc it returns carries the same lam (lambda-ness) as the
// original, so #lambda? is preserved through every partial application. It is the
// lambda-aware sibling of curried (which is fixed to a lambda result).
func (vm *VM) curriedProc(p *Proc, need int, lam bool, got []object.Value) *Proc {
return &Proc{isLambda: lam, nativeArity: -1, native: func(vm *VM, args []object.Value) object.Value {
all := append(append([]object.Value{}, got...), args...)
if len(all) >= need {
return vm.callBlock(p, all)
}
return vm.curriedProc(p, need, lam, all)
}}
}

// procPositionalInfo reports a proc's positional-parameter shape for lambda curry
// validation: the count of required positionals (leading plus any after a splat),
// the total number of positional slots, and whether it has a *splat. A native or
// sourceless proc has no fixed shape, so it accepts any arity (hasSplat true).
func procPositionalInfo(is *bytecode.ISeq) (required, total int, hasSplat bool) {
if is == nil {
return 0, 0, true
}
return iseqRequiredPositional(is), len(is.Params), is.SplatIndex >= 0
}

// trailingKwHash returns the trailing keyword Hash of a native call's argument
// list, or nil when the last argument is not a Hash.
func trailingKwHash(args []object.Value) *object.Hash {
Expand Down
137 changes: 137 additions & 0 deletions internal/vm/proc_method_residuals_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
package vm_test

import (
"strings"
"testing"
)

// TestProcCallAliasIdentity covers that Proc#[], #yield and #=== are the same
// built-in definition as Proc#call, and Method#[] / #=== the same as Method#call
// — so #instance_method compares them equal (MRI 4.0.6 genuine aliases).
func TestProcCallAliasIdentity(t *testing.T) {
cases := []struct{ name, src string }{
{"proc_index", `p Proc.instance_method(:[]) == Proc.instance_method(:call)`},
{"proc_yield", `p Proc.instance_method(:yield) == Proc.instance_method(:call)`},
{"proc_case", `p Proc.instance_method(:===) == Proc.instance_method(:call)`},
{"proc_eql", `p Proc.instance_method(:eql?) == Proc.instance_method(:==)`},
{"method_index", `p Method.instance_method(:[]) == Method.instance_method(:call)`},
{"method_case", `p Method.instance_method(:===) == Method.instance_method(:call)`},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
if got := eval(t, tc.src); got != "true\n" {
t.Errorf("%s = %q, want \"true\\n\"", tc.src, got)
}
})
}
}

// TestProcCallAliasesBehave confirms the aliased names still invoke the proc.
func TestProcCallAliasesBehave(t *testing.T) {
cases := []struct{ name, src, want string }{
{"index", `add = ->(a, b) { a + b }; p add[2, 3]`, "5\n"},
{"yield", `add = ->(a, b) { a + b }; p add.yield(2, 3)`, "5\n"},
{"case", `even = ->(n) { n.even? }; p(even === 4)`, "true\n"},
}
for _, tc := range cases {
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)
}
})
}
}

// TestProcEquality covers Proc#== identity semantics and #eql? as its alias:
// same object (and its #dup) equal; distinct procs, and non-Procs, unequal.
func TestProcEquality(t *testing.T) {
cases := []struct{ name, src, want string }{
{"same", `p = proc { :foo }; p(p == p)`, "true\n"},
{"dup", `p = proc { :foo }; p(p == p.dup)`, "true\n"},
{"eql_same", `p = proc { :foo }; p(p.eql?(p))`, "true\n"},
{"distinct", `p(proc { :foo } == proc { :foo })`, "false\n"},
{"lambda_vs_proc", `p(-> { :foo } == proc { :foo })`, "false\n"},
{"non_proc", `p(proc { :foo } == [])`, "false\n"},
{"is_public", `p Proc.public_instance_methods(false).include?(:==)`, "true\n"},
}
for _, tc := range cases {
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)
}
})
}
}

// TestProcCurryLambdaness covers that Proc#curry keeps the receiver's lambda-ness
// and propagates it through partial application (proc{}.curry.lambda? is false;
// ->{}.curry.lambda? is true, even after a call that is short of the arity).
func TestProcCurryLambdaness(t *testing.T) {
cases := []struct{ name, src, want string }{
{"lambda", `p((->{}).curry.lambda?)`, "true\n"},
{"proc", `p((proc{}).curry.lambda?)`, "false\n"},
{"procnew", `p(Proc.new{}.curry.lambda?)`, "false\n"},
{"lambda_partial", `p((-> x, y {}).curry.call(42).lambda?)`, "true\n"},
{"proc_partial", `p((proc{|x,y|}).curry.call(42).lambda?)`, "false\n"},
}
for _, tc := range cases {
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)
}
})
}
}

// TestProcCurryApplies drives the gather-then-invoke path of a curried proc,
// through both one-at-a-time and grouped argument delivery.
func TestProcCurryApplies(t *testing.T) {
cases := []struct{ name, src, want string }{
{"one_at_a_time", `add = proc { |x, y, z| x + y + z }; p add.curry[1][2][3]`, "6\n"},
{"grouped", `add = proc { |x, y, z| x + y + z }; p add.curry[1, 2][3]`, "6\n"},
{"arity_arg", `add = ->(x, y, z) { x + y + z }; p add.curry(3)[1][2][3]`, "6\n"},
{"native_lambda", `def foo(a, b); a + b; end; p method(:foo).to_proc.curry(2)[4][5]`, "9\n"},
}
for _, tc := range cases {
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)
}
})
}
}

// TestProcCurryArityErrors covers the lambda-only arity validation of
// Proc#curry(n): fewer than the required arity, or more than a splat-less lambda
// accepts, raises ArgumentError; a non-lambda proc never raises.
func TestProcCurryArityErrors(t *testing.T) {
raises := []string{
`(-> x, y, z {}).curry(2)`, // fewer than required
`(-> x, y, z {}).curry(4)`, // more than accepted, no splat
`(-> x, y, z, *more {}).curry(2)`, // fewer than required, with splat
`(-> { true }).curry(1)`, // more than accepted (zero params)
`(-> a, b = nil {}).curry(5)`, // more than optional-max
}
for _, src := range raises {
t.Run("raises_"+src, func(t *testing.T) {
err := runErr(t, src)
if err == nil || !strings.Contains(err.Error(), "ArgumentError") {
t.Errorf("%s: want ArgumentError, got %v", src, err)
}
})
}

ok := []string{
`(-> a, b, c, d = nil, e = nil {}).curry(4)`, // within optional range
`(-> a, b, c, *d {}).curry(4)`, // splat absorbs the excess
`(proc { |x, y, z| }).curry(2)`, // a proc never enforces arity
`(proc { |x, y, z| }).curry(9)`, // even well past its width
}
for _, src := range ok {
t.Run("ok_"+src, func(t *testing.T) {
if err := runErr(t, src); err != nil {
t.Errorf("%s: want no error, got %v", src, err)
}
})
}
}