diff --git a/internal/vm/binding.go b/internal/vm/binding.go index 647b63a1..27b515b8 100644 --- a/internal/vm/binding.go +++ b/internal/vm/binding.go @@ -33,6 +33,12 @@ func (vm *VM) registerBinding() { cBinding := newClass("Binding", vm.cObject) vm.consts["Binding"] = cBinding + // TOPLEVEL_BINDING is a Binding for the top level: its self is main and its + // definee is Object, so TOPLEVEL_BINDING.eval("def m; end" / "private :m") + // defines and sets visibility on Object exactly as top-level code does. It + // starts with no locals of its own. + vm.consts["TOPLEVEL_BINDING"] = &Binding{env: &Env{}, self: vm.main, definee: vm.cObject} + cBinding.define("eval", func(vm *VM, self object.Value, args []object.Value, _ *Proc) object.Value { return vm.bindingEval(self.(*Binding), args[0]) }) diff --git a/internal/vm/toplevel_binding_internal_test.go b/internal/vm/toplevel_binding_internal_test.go new file mode 100644 index 00000000..94ae5b79 --- /dev/null +++ b/internal/vm/toplevel_binding_internal_test.go @@ -0,0 +1,31 @@ +// Copyright (c) the go-embedded-ruby/ruby authors +// +// SPDX-License-Identifier: BSD-3-Clause + +package vm + +import "testing" + +// TestTopLevelBinding covers the TOPLEVEL_BINDING constant: it is a Binding +// whose receiver is main and whose definee is Object, so evaluating code through +// it defines methods and constants at the top level and reports main as self. +// Verified against ruby 4.0.6. +func TestTopLevelBinding(t *testing.T) { + cases := []struct{ src, want string }{ + {`p TOPLEVEL_BINDING.class`, `Binding`}, + {`p TOPLEVEL_BINDING.eval("self")`, `main`}, + {`p TOPLEVEL_BINDING.receiver`, `main`}, + {`p TOPLEVEL_BINDING.eval("2 * 21")`, `42`}, + // A def evaluated through it becomes a top-level (Object) method. + {`TOPLEVEL_BINDING.eval("def tlb_defined; 7; end"); p tlb_defined`, `7`}, + // A constant assigned through it is a top-level constant. + {`TOPLEVEL_BINDING.eval("TLB_CONST = 99"); p TLB_CONST`, `99`}, + // It starts with no locals of its own. + {`p TOPLEVEL_BINDING.local_variables`, `[]`}, + } + 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") + } + } +}