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 {
vm: VM
private globals?: Record<string, any>
constructor() {
this.vm = new VM({ instructions: [], constants: [], labels: new Map() }, shrimpGlobals)
constructor(globals?: Record<string, any>) {
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> {
let bytecode
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
} else {
bytecode = code

View File

@ -5,8 +5,12 @@ import { Shrimp } from '..'
describe('Shrimp', () => {
test('allows running Shrimp code', async () => {
const shrimp = new Shrimp()
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`)
expect(shrimp.get('abc')).toEqual(true)
@ -18,4 +22,12 @@ describe('Shrimp', () => {
await shrimp.run(`abc = 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')
})
})