ReefVM/tests/functions.test.ts
2025-10-05 19:56:56 -07:00

61 lines
1.3 KiB
TypeScript

import { test, expect } from "bun:test"
import { toBytecode } from "#bytecode"
import { VM } from "#vm"
test("MAKE_FUNCTION - creates function with captured scope", async () => {
const bytecode = toBytecode(`
MAKE_FUNCTION () #999
`)
const result = await new VM(bytecode).run()
expect(result.type).toBe('function')
if (result.type === 'function') {
expect(result.body).toBe(999)
expect(result.params).toEqual([])
}
})
test("CALL and RETURN - basic function call", async () => {
const bytecode = toBytecode(`
MAKE_FUNCTION () #3
CALL #0
HALT
PUSH 42
RETURN
`)
const result = await new VM(bytecode).run()
expect(result).toEqual({ type: 'number', value: 42 })
})
test("CALL and RETURN - function with one parameter", async () => {
const bytecode = toBytecode(`
MAKE_FUNCTION (x) #4
PUSH 100
CALL #1
HALT
LOAD x
RETURN
`)
const result = await new VM(bytecode).run()
expect(result).toEqual({ type: 'number', value: 100 })
})
test("CALL and RETURN - function with two parameters", async () => {
const bytecode = toBytecode(`
MAKE_FUNCTION (a b) #5
PUSH 10
PUSH 20
CALL #2
HALT
LOAD a
LOAD b
ADD
RETURN
`)
const result = await new VM(bytecode).run()
expect(result).toEqual({ type: 'number', value: 30 })
})