pushScope accepts locals

This commit is contained in:
Chris Wanstrath 2025-11-05 13:55:59 -08:00
parent 54cd9ce8e8
commit f1cc717711
2 changed files with 22 additions and 6 deletions

View File

@ -60,8 +60,12 @@ export class VM {
this.scope.set(name, { type: 'native', fn, value: '<function>' }) this.scope.set(name, { type: 'native', fn, value: '<function>' })
} }
pushScope() { pushScope(locals?: Record<string, any>) {
this.scope = new Scope(this.scope) this.scope = new Scope(this.scope)
if (locals)
for (const [name, value] of Object.entries(locals))
this.set(name, value)
} }
popScope() { popScope() {

View File

@ -9,14 +9,12 @@ describe("VM scope methods", () => {
const vm = new VM(bytecode) const vm = new VM(bytecode)
vm.set("x", 42) vm.set("x", 42)
vm.pushScope() vm.pushScope()
const xValue = vm.scope.get("x") const xValue = vm.scope.get("x")
expect(xValue).toEqual({ type: "number", value: 42 }) expect(xValue).toEqual({ type: "number", value: 42 })
vm.set("y", 100) vm.set("y", 100)
expect(vm.scope.get("x")).toEqual({ type: "number", value: 42 }) expect(vm.scope.get("x")).toEqual({ type: "number", value: 42 })
expect(vm.scope.get("y")).toEqual({ type: "number", value: 100 }) expect(vm.scope.get("y")).toEqual({ type: "number", value: 100 })
}) })
@ -26,7 +24,6 @@ describe("VM scope methods", () => {
const vm = new VM(bytecode) const vm = new VM(bytecode)
vm.set("x", 42) vm.set("x", 42)
vm.pushScope() vm.pushScope()
vm.set("y", 100) vm.set("y", 100)
@ -34,9 +31,24 @@ describe("VM scope methods", () => {
expect(vm.scope.get("y")).toEqual({ type: "number", value: 100 }) expect(vm.scope.get("y")).toEqual({ type: "number", value: 100 })
vm.popScope() vm.popScope()
expect(vm.scope.get("x")).toEqual({ type: "number", value: 42 }) expect(vm.scope.get("x")).toEqual({ type: "number", value: 42 })
expect(vm.scope.get("y")).toBeUndefined() expect(vm.scope.get("y")).toBeUndefined()
}) })
test("pushScope with locals initializes child scope with variables", async () => {
const bytecode = toBytecode([["HALT"]])
const vm = new VM(bytecode)
vm.set("x", 42)
vm.pushScope({ y: 100, z: "hello" })
expect(vm.scope.get("x")).toEqual({ type: "number", value: 42 })
expect(vm.scope.get("y")).toEqual({ type: "number", value: 100 })
expect(vm.scope.get("z")).toEqual({ type: "string", value: "hello" })
vm.popScope()
expect(vm.scope.get("x")).toEqual({ type: "number", value: 42 })
expect(vm.scope.get("y")).toBeUndefined()
expect(vm.scope.get("z")).toBeUndefined()
})
}) })