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
6 changes: 6 additions & 0 deletions internal/vm/binding.go
Original file line number Diff line number Diff line change
Expand Up @@ -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])
})
Expand Down
31 changes: 31 additions & 0 deletions internal/vm/toplevel_binding_internal_test.go
Original file line number Diff line number Diff line change
@@ -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")
}
}
}