Shrimp accepts custom globals

This commit is contained in:
Chris Wanstrath 2025-11-05 13:41:08 -08:00
parent 0e96911879
commit a535dc9605
2 changed files with 19 additions and 4 deletions

View File

@ -9,16 +9,19 @@ export { globals } from '#prelude'
export class Shrimp { export class Shrimp {
vm: VM vm: VM
private globals?: Record<string, any>
constructor() { constructor(globals?: Record<string, any>) {
this.vm = new VM({ instructions: [], constants: [], labels: new Map() }, shrimpGlobals) const emptyBytecode = { instructions: [], constants: [], labels: new Map() }
this.vm = new VM(emptyBytecode, Object.assign({}, shrimpGlobals, globals ?? {}))
this.globals = globals
} }
async run(code: string | Bytecode): Promise<any> { async run(code: string | Bytecode): Promise<any> {
let bytecode let bytecode
if (typeof code === 'string') { if (typeof code === 'string') {
const compiler = new Compiler(code, Object.keys(shrimpGlobals)) const compiler = new Compiler(code, Object.keys(Object.assign({}, shrimpGlobals, this.globals ?? {})))
bytecode = compiler.bytecode bytecode = compiler.bytecode
} else { } else {
bytecode = code bytecode = code

View File

@ -5,8 +5,12 @@ import { Shrimp } from '..'
describe('Shrimp', () => { describe('Shrimp', () => {
test('allows running Shrimp code', async () => { test('allows running Shrimp code', async () => {
const shrimp = new Shrimp() const shrimp = new Shrimp()
expect(await shrimp.run(`1 + 5`)).toEqual(6) expect(await shrimp.run(`1 + 5`)).toEqual(6)
expect(await shrimp.run(`type 5`)).toEqual('number')
})
test('maintains state across runs', async () => {
const shrimp = new Shrimp()
await shrimp.run(`abc = true`) await shrimp.run(`abc = true`)
expect(shrimp.get('abc')).toEqual(true) expect(shrimp.get('abc')).toEqual(true)
@ -18,4 +22,12 @@ describe('Shrimp', () => {
await shrimp.run(`abc = false`) await shrimp.run(`abc = false`)
expect(shrimp.get('abc')).toEqual(false) expect(shrimp.get('abc')).toEqual(false)
}) })
test('allows setting your own globals', async () => {
const shrimp = new Shrimp({ hiya: () => 'hey there' })
await shrimp.run('abc = hiya')
expect(shrimp.get('abc')).toEqual('hey there')
expect(await shrimp.run('type abc')).toEqual('string')
})
}) })