Skip to content

Commit 9622aeb

Browse files
committed
feat: Runtime.compile runs a program compiled once many times
runtime.compile(code) parses and compiles a program once, or gives the diagnostic its run would fail with first; program() and execute() take the Compiled as they take source, on the Promise and Effect APIs. A run of it, and a state saved from one, are the same as from its source.
1 parent d4aa191 commit 9622aeb

5 files changed

Lines changed: 147 additions & 29 deletions

File tree

‎src/effect/runtime.ts‎

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,11 @@ export * as Runtime from "./runtime.js"
33
import { type Context, Effect } from "effect"
44
import { adapt } from "./work.js"
55
import { type DurableFn, type Fn, Interrupted, type Namespace } from "../runtime/contract.js"
6+
import type { Diagnostic } from "../runtime/model.js"
67
import {
78
checkMaxBytes,
9+
Compiled,
10+
compileProgram,
811
finishExecution,
912
makeProgram,
1013
type Outcome,
@@ -18,16 +21,23 @@ import {
1821
import { type Globals, makeSetup, type Options, type ProgramOptions, type SuspendOptions } from "../runtime/options.js"
1922
import { SnapshotError } from "../snapshot/snapshot.js"
2023

21-
export { SuspendError }
24+
export { Compiled, SuspendError }
2225
export type { Outcome, Result, Run, Suspended }
2326
export type { Globals, Limits, Options, ProgramOptions, SuspendOptions, Translate } from "../runtime/options.js"
2427

2528
/** A reusable confined runtime over host globals. */
2629
export type Runtime<R = never> = {
27-
/** Runs a program to its end. */
28-
readonly execute: (code: string, options?: ProgramOptions) => Effect.Effect<Result, never, R>
29-
/** A program ready to run once; nothing runs until `program.run()`. */
30-
readonly program: (code: string, options?: ProgramOptions) => Program<R>
30+
/** Runs a program, from its source or compiled, to its end. */
31+
readonly execute: (code: string | Compiled, options?: ProgramOptions) => Effect.Effect<Result, never, R>
32+
/** A program, from its source or compiled, ready to run once; nothing runs until `program.run()`. */
33+
readonly program: (code: string | Compiled, options?: ProgramOptions) => Program<R>
34+
/**
35+
* Parses and compiles a program once, for `program` and `execute` to run many times without doing it again; or the
36+
* diagnostic a run of it would fail with first (an empty program, a syntax error).
37+
*/
38+
readonly compile: (
39+
code: string,
40+
) => { readonly ok: true; readonly compiled: Compiled } | { readonly ok: false; readonly error: Diagnostic }
3141
/**
3242
* A suspended run (its `state`, or that state as bytes) as a program to continue in this runtime, which must be the
3343
* same build with the same host globals. The state is checked when it runs: `run()` fails with a `SnapshotError`
@@ -70,7 +80,7 @@ type ServicesOf<T, Depth extends ReadonlyArray<unknown>> = Depth["length"] exten
7080
export const make = <const G extends Globals = {}>(options: Options<G> = {}): Runtime<Services<G>> => {
7181
type R = Services<G>
7282
const setup = { ...makeSetup<R>(options), adapt }
73-
const program = (code: string, programOptions?: ProgramOptions): Program<R> =>
83+
const program = (code: string | Compiled, programOptions?: ProgramOptions): Program<R> =>
7484
wrap(makeProgram(() => startProgram(setup, code, programOptions?.bindings, programOptions?.runId)))
7585
return {
7686
execute: (code, programOptions) =>
@@ -85,6 +95,7 @@ export const make = <const G extends Globals = {}>(options: Options<G> = {}): Ru
8595
),
8696
) as Effect.Effect<Result, never, R>,
8797
program,
98+
compile: compileProgram,
8899
resume: (state) => wrap(makeProgram(() => resumeProgram(setup, state))) as Program<R, SnapshotError>,
89100
}
90101
}

‎src/runtime.ts‎

Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,11 @@
11
export * as Runtime from "./runtime.js"
22

33
import { Interrupted } from "./runtime/contract.js"
4+
import type { Diagnostic } from "./runtime/model.js"
45
import {
56
checkMaxBytes,
7+
Compiled,
8+
compileProgram,
69
finishExecution,
710
makeProgram,
811
type Outcome,
@@ -15,7 +18,7 @@ import {
1518
} from "./runtime/execute.js"
1619
import { type Globals, makeSetup, type Options, type ProgramOptions, type SuspendOptions } from "./runtime/options.js"
1720

18-
export { SuspendError }
21+
export { Compiled, SuspendError }
1922
export type { Outcome, Result, Run, Suspended }
2023
export type { Globals, Limits, Options, ProgramOptions, SuspendOptions, Translate } from "./runtime/options.js"
2124

@@ -29,10 +32,20 @@ export type ExecuteOptions = ProgramOptions & RunOptions
2932

3033
/** A reusable confined runtime over host globals. */
3134
export type Runtime = {
32-
/** Runs a program to its end. Rejects with an `AbortError` when `options.signal` aborts. */
33-
readonly execute: (code: string, options?: ExecuteOptions) => Promise<Result>
34-
/** A program ready to run once; nothing runs until `program.run()`. */
35-
readonly program: (code: string, options?: ProgramOptions) => Program
35+
/**
36+
* Runs a program, from its source or compiled, to its end. Rejects with an `AbortError` when `options.signal`
37+
* aborts.
38+
*/
39+
readonly execute: (code: string | Compiled, options?: ExecuteOptions) => Promise<Result>
40+
/** A program, from its source or compiled, ready to run once; nothing runs until `program.run()`. */
41+
readonly program: (code: string | Compiled, options?: ProgramOptions) => Program
42+
/**
43+
* Parses and compiles a program once, for `program` and `execute` to run many times without doing it again; or the
44+
* diagnostic a run of it would fail with first (an empty program, a syntax error).
45+
*/
46+
readonly compile: (
47+
code: string,
48+
) => { readonly ok: true; readonly compiled: Compiled } | { readonly ok: false; readonly error: Diagnostic }
3649
/**
3750
* A suspended run (its `state`, or that state as bytes) as a program to continue in this runtime, which must be the
3851
* same build with the same host globals. The state is checked when it runs: `run()` rejects with a `SnapshotError`
@@ -63,12 +76,13 @@ export type Program = {
6376
*/
6477
export const make = <const G extends Globals = {}>(options: Options<G> = {}): Runtime => {
6578
const setup = makeSetup<never>(options)
66-
const start = (code: string, programOptions?: ProgramOptions) =>
79+
const start = (code: string | Compiled, programOptions?: ProgramOptions) =>
6780
makeProgram(() => startProgram(setup, code, programOptions?.bindings, programOptions?.runId))
6881
return {
6982
execute: (code, executeOptions) =>
7083
aborting(finishExecution(start(code, executeOptions).run({ signal: executeOptions?.signal })), executeOptions?.signal),
7184
program: (code, programOptions) => wrap(start(code, programOptions)),
85+
compile: compileProgram,
7286
resume: (state) => wrap(makeProgram(() => resumeProgram(setup, state))),
7387
}
7488
}

‎src/runtime/execute.ts‎

Lines changed: 35 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,8 @@ import { type Diagnostic, formatLocation, sourceLocation } from "./model.js"
1111
import { CANCELLED, Driver, SUSPENDED } from "./driver.js"
1212
import { Interruption } from "./signals.js"
1313
import { Source } from "./source.js"
14-
import type { Vm } from "../vm.js"
14+
import { compileCodes, type Vm } from "../vm.js"
15+
import type { Code } from "../code.js"
1516
import type { Translate } from "../runtime.js"
1617

1718
/**
@@ -136,23 +137,49 @@ export const finishExecution = async (outcome: Promise<Outcome>): Promise<Result
136137
}
137138
}
138139

140+
/**
141+
* A program compiled once to run many times, in any runtime: its parse and its bytecode, which no run changes. A run
142+
* of it is the same as a run of its source, and so is a state saved from one.
143+
*/
144+
export class Compiled {
145+
/** @internal */
146+
constructor(
147+
/** The program's source. */
148+
readonly code: string,
149+
/** @internal */
150+
readonly source: Source,
151+
/** @internal */
152+
readonly codes: ReadonlyArray<Code> | RangeError,
153+
) {}
154+
}
155+
156+
/**
157+
* Parses and compiles a program, or gives the diagnostic its run would fail with before running anything: an empty
158+
* program or a syntax error. Unsupported syntax still fails where it runs, as from source.
159+
*/
160+
export const compileProgram = (
161+
code: string,
162+
): { readonly ok: true; readonly compiled: Compiled } | { readonly ok: false; readonly error: Diagnostic } => {
163+
if (code.trim().length === 0) return { ok: false, error: { kind: "ParseError", message: "Code cannot be empty." } }
164+
const parsed = parseProgram(code)
165+
if (!parsed.ok) return parsed
166+
return { ok: true, compiled: new Compiled(code, parsed.source, compileCodes(parsed.source)) }
167+
}
168+
139169
/** A program ready to run on the VM: nothing runs until `run`. */
140170
export const startProgram = <R>(
141171
setup: Setup<R>,
142-
code: string,
172+
code: string | Compiled,
143173
bindings?: Readonly<Record<string, Json>>,
144174
runId: string = crypto.randomUUID(),
145175
): Running<R> =>
146176
new Running(setup, 0, () => {
147-
if (code.trim().length === 0) {
148-
return { ok: false, error: { kind: "ParseError", message: "Code cannot be empty." }, metadata: null }
149-
}
150-
const parsed = parseProgram(code)
151-
if (!parsed.ok) return { ok: false, error: parsed.error, metadata: null }
177+
const compiled = typeof code === "string" ? compileProgram(code) : { ok: true as const, compiled: code }
178+
if (!compiled.ok) return { ok: false, error: compiled.error, metadata: null }
152179
const run: Run = { id: runId, metadata: null }
153180
const runtime = instantiate(setup, run, bindings)
154181
runtime.vm.hosts.runId = runId
155-
runtime.vm.start(parsed.source)
182+
runtime.vm.start(compiled.compiled.source, compiled.compiled.codes)
156183
return [runtime, run] as const
157184
})
158185

‎src/vm.ts‎

Lines changed: 16 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -213,6 +213,16 @@ const allocRegs = (size: number): Array<unknown> => {
213213
return regs
214214
}
215215

216+
/** A program's bytecode, or the RangeError of one nested deeper than the compiler's host stack. */
217+
export const compileCodes = (source: Source): ReadonlyArray<Code> | RangeError => {
218+
try {
219+
return compileSource(source)
220+
} catch (error) {
221+
if (!(error instanceof RangeError)) throw error
222+
return error
223+
}
224+
}
225+
216226
/** Internal closure wrapper that does not touch `builtins.Function` or `nativeRule.sealed`. */
217227
export class VmInternalFn {
218228
constructor(
@@ -297,17 +307,14 @@ export class Vm {
297307
return this.intrinsics.get(name)
298308
}
299309

300-
/** Queues the program's body as the root frame. */
301-
start(source: Source): void {
310+
/** Queues the program's body as the root frame, from its bytecode (`compileCodes`) when it is compiled already. */
311+
start(source: Source, compiled?: ReadonlyArray<Code> | RangeError): void {
302312
if (!warmed) warmupVm(this)
303313
this.ctx.sources.set(source.id, source)
304-
let codes: ReadonlyArray<Code>
305-
try {
306-
codes = compileSource(source)
307-
} catch (error) {
308-
// A program nested deeper than the compiler's host stack fails the run, as running it would.
309-
if (!(error instanceof RangeError)) throw error
310-
this.outcome = abrupt(error)
314+
const codes = compiled ?? compileCodes(source)
315+
// A program nested deeper than the compiler's host stack fails the run, as running it would.
316+
if (codes instanceof RangeError) {
317+
this.outcome = abrupt(codes)
311318
return
312319
}
313320
this.sourceCodes.set(source.id, codes)

‎test/language.test.ts‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -363,3 +363,62 @@ describe("translate", () => {
363363
expect(calls).toEqual([[{ n: 7 }]])
364364
})
365365
})
366+
367+
describe("runtime.compile", () => {
368+
const runtime = Runtime.make({ globals: () => ({ twice: Host.fn((args) => Number(args[0]) * 2) }) })
369+
const compiled = (code: string) => {
370+
const result = runtime.compile(code)
371+
if (!result.ok) throw new Error(`expected a compiled program, got ${result.error.message}`)
372+
return result.compiled
373+
}
374+
375+
test("a compiled program runs as its source does, again and at once, with each run's bindings", async () => {
376+
const code = `let n = 0; for (const x of xs) n += twice(x); return [n, typeof seen]`
377+
const program = compiled(code)
378+
const runs = [[1], [2, 3], [4, 5, 6]].map((xs) => runtime.execute(program, { bindings: { xs } }))
379+
const results = await Promise.all(runs.map((run) => Effect.runPromise(run)))
380+
expect(results.map((result) => (result.ok ? result.value : result.error))).toEqual([
381+
[2, "undefined"],
382+
[10, "undefined"],
383+
[30, "undefined"],
384+
])
385+
expect(await Effect.runPromise(runtime.execute(program, { bindings: { xs: [7] } }))).toEqual(
386+
await Effect.runPromise(runtime.execute(code, { bindings: { xs: [7] } })),
387+
)
388+
})
389+
390+
test("compiling gives the diagnostic a run would fail with first; unsupported syntax still fails where it runs", async () => {
391+
for (const code of [" ", "return (", "export const x = 1"]) {
392+
const result = runtime.compile(code)
393+
if (result.ok) throw new Error(`expected ${JSON.stringify(code)} not to compile`)
394+
expect(await run(runtime, code)).toEqual({ ok: false, error: result.error, metadata: null })
395+
}
396+
const unsupported = `const a = 1; class A {}`
397+
expect(await Effect.runPromise(runtime.execute(compiled(unsupported)))).toEqual(await run(runtime, unsupported))
398+
})
399+
400+
test("a state saved from a compiled program is its source's, and resumes like it", async () => {
401+
const gate = latch()
402+
const waiting = latch()
403+
const durable = Runtime.make({
404+
globals: () => ({
405+
wait: Host.fn(
406+
() => Effect.andThen(Effect.sync(waiting.resolve), Effect.promise(() => gate.promise)),
407+
{ type: "async", idempotent: true },
408+
),
409+
}),
410+
})
411+
const code = `const a = 20; await wait(); return a + 22`
412+
const result = durable.compile(code)
413+
if (!result.ok) throw new Error(result.error.message)
414+
const program = durable.program(result.compiled, { runId: "c" })
415+
const fiber = Effect.runFork(program.run())
416+
await waiting.promise
417+
const suspended = await Effect.runPromise(program.suspend())
418+
if (suspended.ok !== "suspended") throw new Error("expected a suspended run")
419+
await Effect.runPromise(Fiber.join(fiber))
420+
expect(suspended.state.header.sources.map((source) => source.code)).toEqual([code])
421+
gate.resolve()
422+
expect(await Effect.runPromise(durable.resume(toBytes(suspended.state)).run())).toMatchObject({ ok: true, value: 42 })
423+
})
424+
})

0 commit comments

Comments
 (0)