From 0e96911879e21803b11e6d3b6f68301011a06216 Mon Sep 17 00:00:00 2001 From: Chris Wanstrath Date: Wed, 5 Nov 2025 13:33:32 -0800 Subject: [PATCH] add Shrimp class as a nicer way to run code --- src/index.ts | 28 ++++++++++++++++++++++++++++ src/tests/shrimp.test.ts | 21 +++++++++++++++++++++ 2 files changed, 49 insertions(+) create mode 100644 src/tests/shrimp.test.ts diff --git a/src/index.ts b/src/index.ts index 48fa3e7..dad8935 100644 --- a/src/index.ts +++ b/src/index.ts @@ -7,6 +7,34 @@ export { Compiler } from '#compiler/compiler' export { parser } from '#parser/shrimp' export { globals } from '#prelude' +export class Shrimp { + vm: VM + + constructor() { + this.vm = new VM({ instructions: [], constants: [], labels: new Map() }, shrimpGlobals) + } + + async run(code: string | Bytecode): Promise { + let bytecode + + if (typeof code === 'string') { + const compiler = new Compiler(code, Object.keys(shrimpGlobals)) + bytecode = compiler.bytecode + } else { + bytecode = code + } + + this.vm.appendBytecode(bytecode) + await this.vm.continue() + return this.vm.stack.length ? fromValue(this.vm.stack.at(-1)!) : null + } + + get(name: string): any { + const value = this.vm.scope.get(name) + return value ? fromValue(value) : null + } +} + export async function runFile(path: string, globals?: Record): Promise { const code = readFileSync(path, 'utf-8') return await runCode(code, globals) diff --git a/src/tests/shrimp.test.ts b/src/tests/shrimp.test.ts new file mode 100644 index 0000000..b71c458 --- /dev/null +++ b/src/tests/shrimp.test.ts @@ -0,0 +1,21 @@ +import { describe } from 'bun:test' +import { expect, test } from 'bun:test' +import { Shrimp } from '..' + +describe('Shrimp', () => { + test('allows running Shrimp code', async () => { + const shrimp = new Shrimp() + + expect(await shrimp.run(`1 + 5`)).toEqual(6) + + await shrimp.run(`abc = true`) + expect(shrimp.get('abc')).toEqual(true) + + await shrimp.run(`name = Bob`) + expect(shrimp.get('abc')).toEqual(true) + expect(shrimp.get('name')).toEqual('Bob') + + await shrimp.run(`abc = false`) + expect(shrimp.get('abc')).toEqual(false) + }) +}) \ No newline at end of file