diff --git a/packages/codemode/src/interpreter/extensions.ts b/packages/codemode/src/interpreter/extensions.ts index 3e65dc5c168..22218606b14 100644 --- a/packages/codemode/src/interpreter/extensions.ts +++ b/packages/codemode/src/interpreter/extensions.ts @@ -181,26 +181,22 @@ export const extensionGlobals = ( if (isAsync(value)) return pending( Effect.andThen(before ?? Effect.void, settle(Effect.suspend(() => callHost(value, args).effect))), + label, site, ) if (before) yield ctx.runner.blocking(before) const host = callHost(value, args) - if (host.async) return pending(settle(host.effect), site) + if (host.async) return pending(settle(host.effect), label, site) return (yield ctx.runner.blocking(settle(host.effect))) as Value }, }) } // An asynchronous host call: the program holds a promise that settles when the host's work does. - const pending = (work: Effect.Effect, site: AstNode | undefined) => { - const promise = ctx.runner.newPromise() - const resolving = ctx.runner.resolving(promise, site) - ctx.runner.host( - work, - (settled) => (settled.ok ? resolving.resolve(settled.value as Value) : resolving.reject(settled.error)), - site, - ) - return promise + const pending = (work: Effect.Effect, label: string, site: AstNode | undefined) => { + const resolving = ctx.runner.resolving(ctx.runner.newPromise(), site) + ctx.runner.host(work, { label, result: "value", resolving, site }) + return resolving.promise } return extensions.flatMap((extension) => diff --git a/packages/codemode/src/interpreter/generators.ts b/packages/codemode/src/interpreter/generators.ts index 27a31acc528..aee63489aa0 100644 --- a/packages/codemode/src/interpreter/generators.ts +++ b/packages/codemode/src/interpreter/generators.ts @@ -139,17 +139,19 @@ const drainQueue = (ctx: Interpreter, generator: GeneratorObj) => { // AsyncGeneratorAwaitReturn: a `return(value)` on an ended or unstarted generator settles once `value` does. const awaitReturn = (ctx: Interpreter, generator: GeneratorObj) => { const runner = ctx.runner - const finish = (completion: Completion) => { - completeStep(ctx, generator, completion, true) - drainQueue(ctx, generator) - } try { - runner.then(runner.promiseResolve(generator.queue[0]!.request.value), finish) + runner.then(runner.promiseResolve(generator.queue[0]!.request.value), { kind: "awaitReturn", generator }) } catch (error) { - finish(abrupt(error)) + finishAwaitReturn(ctx, generator, abrupt(error)) } } +/** The `awaitReturn` reaction: answers the `return` request with how its value settled, then drains the queue. */ +export const finishAwaitReturn = (ctx: Interpreter, generator: GeneratorObj, completion: Completion) => { + completeStep(ctx, generator, completion, true) + drainQueue(ctx, generator) +} + /** Where a generator body splits off the stack when it yields, and how its end answers the request that ran it. */ class GeneratorBoundary implements Boundary { readonly generator = true diff --git a/packages/codemode/src/interpreter/interpreter.ts b/packages/codemode/src/interpreter/interpreter.ts index e6d2a53aefb..4422ffe2b05 100644 --- a/packages/codemode/src/interpreter/interpreter.ts +++ b/packages/codemode/src/interpreter/interpreter.ts @@ -583,14 +583,13 @@ class Frame { const body = function* (): Eval { const json: Array = [] for (const arg of args) json.push(yield* toBoundary(ctx, arg)) - runner.host( - ctx.tools.execute(path, json), - (settled) => - settled.ok - ? resolving.resolve(fromJson(ctx, settled.value as Json | undefined)) - : resolving.reject(settled.error), + runner.host(ctx.tools.execute(path, json), { + label: path.join("."), + args: json, + result: "json", + resolving, site, - ) + }) } return (yield new Call( body(), @@ -1029,12 +1028,14 @@ class Frame { wrapper = runner.promiseResolve(step.value) } catch (error) { const start = rejected(error) - if (start !== undefined) runner.enqueue(() => start) + if (start !== undefined) runner.enqueue({ kind: "resume", task: start.task, input: start.input }) return } - runner.then(wrapper, (settled) => - settled.ok ? made.resolve(result(settled.value as Value, step.done)) : rejected(settled.error), - ) + runner.then(wrapper, { + kind: "callback", + run: (settled) => + settled.ok ? made.resolve(result(settled.value as Value, step.done)) : rejected(settled.error), + }) } const next = asyncFromSyncMethod(builtins, "next", function* (_, args) { const made = capability(ctx, node) diff --git a/packages/codemode/src/interpreter/promises.ts b/packages/codemode/src/interpreter/promises.ts index 91299f48fcc..54804dfed53 100644 --- a/packages/codemode/src/interpreter/promises.ts +++ b/packages/codemode/src/interpreter/promises.ts @@ -5,7 +5,18 @@ import { createAggregateErrorValue, materialize } from "./errors.js" import { describeValue, typeofValue } from "./references.js" import { isSupportedCallback } from "./callback.js" import type { Interpreter } from "./interpreter.js" -import { type Completion, type Eval, Interruption, normal, type Reaction, type Resolving, Task } from "./runner.js" +import { + type Combination, + type Completion, + type Eval, + Interruption, + normal, + type Reaction, + type Resolving, + type Start, + Task, +} from "./runner.js" +import { finishAwaitReturn } from "./generators.js" // A `resolve`/`reject` handed to an executor or thenable: calling it settles the capability. const resolvingFunctions = (ctx: Interpreter, resolving: Resolving) => ({ @@ -24,36 +35,60 @@ export const capability = (ctx: Interpreter, site: AstNode | undefined): R const settleWith = (resolving: Resolving, completion: Completion) => completion.ok ? resolving.resolve(completion.value as Value) : resolving.reject(completion.error) -/** - * A promise reaction that calls program code: the handler runs as a job, and its result or failure settles the - * derived promise. A missing handler passes the outcome through. - */ -const handlerReaction = - ( - ctx: Interpreter, - onFulfilled: Callable | undefined, - onRejected: Callable | undefined, - derived: Resolving | undefined, - ): Reaction => - (settled) => { - const handler = settled.ok ? onFulfilled : onRejected - if (handler === undefined || (!settled.ok && settled.error instanceof Interruption)) { - if (derived !== undefined) settleWith(derived, settled) +/** Runs a settled promise's reaction as a job: it finishes at once, or returns the task that calls program code. */ +export const react = ( + ctx: Interpreter, + reaction: Exclude, + settled: Completion, +): Start | void => { + switch (reaction.kind) { + case "settle": + return settleWith(reaction.target, settled) + case "handler": + return handle(ctx, reaction, settled) + case "combinator": + return combine(ctx, reaction, settled) + case "finally": + return cleanUp(ctx, reaction, settled) + case "finallyCleaned": + return settled.ok ? reaction.target.resolve(undefined) : reaction.target.reject(settled.error) + case "finallyOutcome": + return settleWith(reaction.target, settled.ok ? reaction.outcome : settled) + case "awaitReturn": + return finishAwaitReturn(ctx, reaction.generator, settled) + case "callback": + return reaction.run(settled) + } +} + +/** A task that runs `body` as its own job. */ +const job = (body: Eval): Start => ({ task: new Task([{ body, boundary: undefined }]), input: normal(undefined) }) + +// A `then`/`catch` reaction calls program code: the handler runs as a job, and its result or failure settles the +// derived promise. A missing handler passes the outcome through. +const handle = ( + ctx: Interpreter, + reaction: Extract, + settled: Completion, +): Start | void => { + const handler = settled.ok ? reaction.onFulfilled : reaction.onRejected + const derived = reaction.derived + if (handler === undefined || (!settled.ok && settled.error instanceof Interruption)) { + return settleWith(derived, settled) + } + const argument = settled.ok ? (settled.value as Value) : materialize(ctx, settled.error) + const body = function* (): Eval { + let result: Value + try { + result = yield* ctx.call(handler, undefined, [argument]) + } catch (error) { + derived.reject(error) return } - const argument = settled.ok ? (settled.value as Value) : materialize(ctx, settled.error) - const body = function* (): Eval { - let result: Value - try { - result = yield* ctx.call(handler, undefined, [argument]) - } catch (error) { - derived?.reject(error) - return - } - derived?.resolve(result) - } - return { task: new Task([{ body: body(), boundary: undefined }]), input: normal(undefined) } + derived.resolve(result) } + return job(body()) +} const promiseStatics = ["all", "allSettled", "race", "any", "resolve", "reject", "withResolvers", "try"] as const @@ -106,68 +141,82 @@ function* combinator( if (cursor === undefined) { throw typeError(`Promise.${name} expects a synchronous iterable, received ${describeValue(iterable)}.`) } - const values: Array = [] - const reasons: Array = [] - // Once the result settles early, the remaining members' reactions can do nothing: detach them so a member that - // stays pending for the rest of the program does not keep them. - const attached: Array = [] - const decided = (settle: () => void) => { - settle() - for (const [item, reaction] of attached) runner.detach(item, reaction) - } - let remaining = 1 + const combination: Combination = { name, made, values: [], reasons: [], remaining: 1, attached: [] } let index = 0 - const finish = () => { - if (--remaining > 0) return - if (name === "any") { - made.reject(new Throw(createAggregateErrorValue(ctx, reasons, "All promises were rejected"))) - return - } - made.resolve(new Arr(ctx.builtins.Array, values)) - } while (true) { const step = yield* cursor.next() if (step.done) break const item = runner.promiseResolve(step.value) - const at = index++ - values.push(undefined) - reasons.push(undefined) - remaining++ - let called = false - const reaction: Reaction = (settled) => { - if (called) return - called = true - if (name === "race" || (!settled.ok && settled.error instanceof Interruption)) { - return decided(() => settleWith(made, settled)) - } - if (name === "all") { - if (!settled.ok) return decided(() => made.reject(settled.error)) - values[at] = settled.value as Value - return finish() - } - if (name === "any") { - if (settled.ok) return decided(() => made.resolve(settled.value as Value)) - reasons[at] = materialize(ctx, settled.error) - return finish() - } - values[at] = settled.ok - ? record(ctx.builtins.Object, { status: "fulfilled", value: settled.value as Value }) - : record(ctx.builtins.Object, { status: "rejected", reason: materialize(ctx, settled.error) }) - finish() - } - attached.push([item, reaction]) + const reaction: Reaction = { kind: "combinator", combination, index: index++, called: false } + combination.values.push(undefined) + combination.reasons.push(undefined) + combination.remaining++ + combination.attached.push([item, reaction]) runner.then(item, reaction) } if (name === "race" && index === 0) { throw typeError("Promise.race([]) would never settle; provide at least one promise or value.") } - finish() + finishCombination(ctx, combination) } catch (error) { made.reject(error) } return made.promise } +// One member settled. Once the result settles early, the remaining members' reactions can do nothing: they are +// detached so a member that stays pending for the rest of the program does not keep them. +const combine = ( + ctx: Interpreter, + reaction: Extract, + settled: Completion, +) => { + if (reaction.called) return + reaction.called = true + const combination = reaction.combination + const made = combination.made + const name = combination.name + if (name === "race" || (!settled.ok && settled.error instanceof Interruption)) { + settleWith(made, settled) + return detachAll(ctx, combination) + } + if (name === "all") { + if (!settled.ok) { + made.reject(settled.error) + return detachAll(ctx, combination) + } + combination.values[reaction.index] = settled.value as Value + return finishCombination(ctx, combination) + } + if (name === "any") { + if (settled.ok) { + made.resolve(settled.value as Value) + return detachAll(ctx, combination) + } + combination.reasons[reaction.index] = materialize(ctx, settled.error) + return finishCombination(ctx, combination) + } + combination.values[reaction.index] = settled.ok + ? record(ctx.builtins.Object, { status: "fulfilled", value: settled.value as Value }) + : record(ctx.builtins.Object, { status: "rejected", reason: materialize(ctx, settled.error) }) + finishCombination(ctx, combination) +} + +const detachAll = (ctx: Interpreter, combination: Combination) => { + for (const [item, reaction] of combination.attached) ctx.runner.detach(item, reaction) +} + +const finishCombination = (ctx: Interpreter, combination: Combination) => { + if (--combination.remaining > 0) return + if (combination.name === "any") { + combination.made.reject( + new Throw(createAggregateErrorValue(ctx, combination.reasons, "All promises were rejected")), + ) + return + } + combination.made.resolve(new Arr(ctx.builtins.Array, combination.values)) +} + const instanceMethod = ( ctx: Interpreter, name: "then" | "catch" | "finally", @@ -181,7 +230,7 @@ const instanceMethod = ( const onFulfilled = name === "then" ? reactionHandler(args[0], method) : undefined const onRejected = reactionHandler(name === "then" ? args[1] : args[0], method) const made = capability(ctx, site) - ctx.runner.then(promise, handlerReaction(ctx, onFulfilled, onRejected, made)) + ctx.runner.then(promise, { kind: "handler", onFulfilled, onRejected, derived: made }) return made.promise } @@ -193,39 +242,46 @@ const chainFinally = ( cleanup: Callable | undefined, site: AstNode | undefined, ): PromiseObj => { - const runner = ctx.runner const made = capability(ctx, site) - if (cleanup === undefined) { - runner.then(source, (settled) => settleWith(made, settled)) - return made.promise - } - runner.then(source, (settled) => { - if (!settled.ok && settled.error instanceof Interruption) return made.reject(settled.error) - const body = function* (): Eval { - let result: Value - try { - result = yield* ctx.call(cleanup, undefined, []) - } catch (error) { - made.reject(error) - return - } - let after: PromiseObj - try { - after = runner.promiseResolve(result) - } catch (error) { - made.reject(error) - return - } - // The spec chains `then(valueThunk)` onto the cleanup's promise: one more job before the outcome passes. - const derived = capability(ctx, site) - runner.then(after, (cleaned) => (cleaned.ok ? derived.resolve(undefined) : derived.reject(cleaned.error))) - runner.then(derived.promise, (cleaned) => settleWith(made, cleaned.ok ? settled : cleaned)) - } - return { task: new Task([{ body: body(), boundary: undefined }]), input: normal(undefined) } - }) + ctx.runner.then( + source, + cleanup === undefined ? { kind: "settle", target: made } : { kind: "finally", cleanup, target: made, site }, + ) return made.promise } +const cleanUp = ( + ctx: Interpreter, + reaction: Extract, + settled: Completion, +) => { + const runner = ctx.runner + const made = reaction.target + if (!settled.ok && settled.error instanceof Interruption) return made.reject(settled.error) + const cleanup = reaction.cleanup + const body = function* (): Eval { + let result: Value + try { + result = yield* ctx.call(cleanup, undefined, []) + } catch (error) { + made.reject(error) + return + } + let after: PromiseObj + try { + after = runner.promiseResolve(result) + } catch (error) { + made.reject(error) + return + } + // The spec chains `then(valueThunk)` onto the cleanup's promise: one more job before the outcome passes. + const derived = capability(ctx, reaction.site) + runner.then(after, { kind: "finallyCleaned", target: derived }) + runner.then(derived.promise, { kind: "finallyOutcome", target: made, outcome: settled }) + } + return job(body()) +} + const reactionHandler = (value: Value, method: string): Callable | undefined => { if (isSupportedCallback(value)) return value if (typeofValue(value) === "function") { diff --git a/packages/codemode/src/interpreter/runner.ts b/packages/codemode/src/interpreter/runner.ts index 18732b90f4d..942685d05e7 100644 --- a/packages/codemode/src/interpreter/runner.ts +++ b/packages/codemode/src/interpreter/runner.ts @@ -4,7 +4,9 @@ import { locate, normalizeError } from "./errors.js" import type { Interpreter } from "./interpreter.js" import { MAX_PENDING_PROMISES } from "./limits.js" import { type AstNode, type GeneratorRequestKind, PendingThrow, rangeError, typeError } from "./model.js" -import { type Callable, get, Obj, PromiseObj, Resolver, type Value } from "./objects.js" +import { type Callable, type GeneratorObj, get, Obj, PromiseObj, Resolver, type Value } from "./objects.js" +import { react } from "./promises.js" +import { fromJson, type Json } from "../data.js" import { typeofValue } from "./references.js" /** @@ -113,11 +115,82 @@ export class Task { constructor(readonly stack: Array) {} } -/** A settled promise's reaction, run as a job: it either finishes at once or starts a task. */ -export type Reaction = (settled: Completion) => Start | void - export type Start = { readonly task: Task; readonly input: Completion } +/** What the member reactions of one `Promise.all`/`allSettled`/`race`/`any` share. */ +export type Combination = { + readonly name: "all" | "allSettled" | "race" | "any" + /** Settles the combinator's result. */ + readonly made: Resolving + readonly values: Array + readonly reasons: Array + /** Members still to settle, plus one until iteration ends. */ + remaining: number + /** Every member's reaction, detached once the result is decided. */ + readonly attached: Array +} + +/** + * A settled promise's reaction, as data. It runs as a job (see `react` in promises.ts) and either finishes at once or + * starts a task. The kinds: + * - `await`: resume the async body parked on the promise. + * - `settle`: pass the outcome on to `target`. + * - `handler`: `then`/`catch` handlers; the handler's result settles `derived`. + * - `combinator`: one member of a `Promise` combinator. + * - `finally`, `finallyCleaned`, `finallyOutcome`: the steps of `Promise.prototype.finally` with a cleanup. + * - `awaitReturn`: an async generator's `return(value)` once `value` settles. + * - `callback`: a host closure, still used by the async-from-sync iterator adapter. + */ +export type Reaction = + | { readonly kind: "await"; readonly task: Task } + | { readonly kind: "settle"; readonly target: Resolving } + | { + readonly kind: "handler" + readonly onFulfilled: Callable | undefined + readonly onRejected: Callable | undefined + readonly derived: Resolving + } + | { readonly kind: "combinator"; readonly combination: Combination; readonly index: number; called: boolean } + | { + readonly kind: "finally" + readonly cleanup: Callable + readonly target: Resolving + readonly site: AstNode | undefined + } + | { readonly kind: "finallyCleaned"; readonly target: Resolving } + | { readonly kind: "finallyOutcome"; readonly target: Resolving; readonly outcome: Completion } + | { readonly kind: "awaitReturn"; readonly generator: GeneratorObj } + | { readonly kind: "callback"; readonly run: (settled: Completion) => Start | void } + +/** One queued job, as data: run a settled promise's reaction, resume a task, or adopt a thenable. */ +export type Job = + | { readonly kind: "reaction"; readonly reaction: Reaction; readonly settled: Completion } + | { readonly kind: "resume"; readonly task: Task; readonly input: Completion } + | { readonly kind: "thenable"; readonly promise: PromiseObj; readonly thenable: Obj; readonly then: Value } + +/** + * Host work the program waits on: a tool or extension call, running as a fiber the runner keeps by `id`. Its outcome + * arrives as an inbox record and settles the call's promise in a later job. + */ +export class HostCall { + status: "inFlight" | "completed" = "inFlight" + constructor( + readonly id: number, + /** What runs: a tool path, or an extension function's label. */ + readonly label: string, + /** A tool's arguments, as they crossed. */ + readonly args: ReadonlyArray | undefined, + /** How the result becomes a program value: a tool's crosses as JSON, an extension's is already one. */ + readonly result: "json" | "value", + readonly resolving: Resolving, + /** The call that started the work, where a defect it raises is located. */ + readonly site: AstNode | undefined, + ) {} +} + +/** A host call's outcome, waiting to be delivered. */ +type Delivery = { readonly call: HostCall; readonly completion: Completion } + /** * CreateResolvingFunctions as data: settles one promise at most once, however many `Resolver`s share it. `reject` takes * the failure as thrown; one without a location is located at `site`, the call that created the promise. @@ -143,8 +216,6 @@ export class Resolving { } } -type Job = () => Start | void - type Pause = | { readonly kind: "slice"; readonly input: Completion } | { readonly kind: "host"; readonly effect: Effect.Effect } @@ -174,12 +245,14 @@ export class Runner { private sliceStart = 0 private pending = 0 private nextID = 0 + private nextHostID = 0 /** Rejections nothing handled yet, described when they happened so reporting them at the end is cheap. */ private readonly unhandled = new Map() /** Bodies suspended at an `await` and the promise each waits on, so a stall can point at the one that is stuck. */ private readonly parked = new Map() - private readonly fibers = new Set>() - private readonly inbox: Array<() => void> = [] + /** Running host work by `HostCall` id; fibers stay here and never become part of the program's state. */ + private readonly fibers = new Map>() + private readonly inbox: Array = [] private wake: (() => void) | undefined private stopping = false @@ -218,13 +291,13 @@ export class Runner { if (start === undefined) { const job = self.dequeue() if (job !== undefined) { - start = job() ?? undefined + start = self.runJob(job) ?? undefined if (start === undefined && self.tick()) yield* self.yieldToHost continue } - const settle = self.inbox.shift() - if (settle !== undefined) { - settle() + const delivery = self.inbox.shift() + if (delivery !== undefined) { + self.deliver(delivery) continue } if (self.fibers.size > 0) { @@ -267,7 +340,7 @@ export class Runner { const self = this return Effect.gen(function* () { self.stopping = true - while (self.fibers.size > 0) yield* Fiber.interruptAll([...self.fibers]) + while (self.fibers.size > 0) yield* Fiber.interruptAll([...self.fibers.values()]) }) } @@ -276,7 +349,8 @@ export class Runner { * program did settles first, so its failures count even though no later job ran. */ diagnostics(): Array { - for (let settle = this.inbox.shift(); settle !== undefined; settle = this.inbox.shift()) settle() + for (let delivery = this.inbox.shift(); delivery !== undefined; delivery = this.inbox.shift()) + this.deliver(delivery) return [...this.unhandled].sort(([left], [right]) => left.id - right.id).map(([, diagnostic]) => diagnostic) } @@ -297,32 +371,52 @@ export class Runner { } /** - * Starts host work now; its completion settles through `settle` in a later job, in completion order. A defect is - * located at `site`, the call that started the work. + * Starts host work now, settling `resolving`'s promise in a later job, in completion order. A defect is located at + * `site`, the call that started the work. */ - host(effect: Effect.Effect, settle: (completion: Completion) => void, site?: AstNode): void { + host( + effect: Effect.Effect, + call: { + readonly label: string + readonly args?: ReadonlyArray + readonly result: "json" | "value" + readonly resolving: Resolving + readonly site: AstNode | undefined + }, + ): HostCall { + const record = new HostCall(this.nextHostID++, call.label, call.args, call.result, call.resolving, call.site) // Starts synchronously, so admission and hooks happen at the call site. const fiber = Effect.runForkWith(this.services)(effect) - this.fibers.add(fiber) + this.fibers.set(record.id, fiber) fiber.addObserver((exit) => { - this.fibers.delete(fiber) + this.fibers.delete(record.id) // Interrupted by the program ending: nothing is left to settle. if (this.stopping) return - this.inbox.push(() => - settle( - Exit.isSuccess(exit) - ? normal(exit.value) - : abrupt( - Cause.hasInterruptsOnly(exit.cause) - ? new Interruption(exit.cause) - : Cause.hasDies(exit.cause) - ? locate(Cause.squash(exit.cause), site) - : Cause.squash(exit.cause), - ), - ), - ) + this.inbox.push({ + call: record, + completion: Exit.isSuccess(exit) + ? normal(exit.value) + : abrupt( + Cause.hasInterruptsOnly(exit.cause) + ? new Interruption(exit.cause) + : Cause.hasDies(exit.cause) + ? locate(Cause.squash(exit.cause), record.site) + : Cause.squash(exit.cause), + ), + }) this.wake?.() }) + return record + } + + private deliver(delivery: Delivery): void { + const call = delivery.call + const completion = delivery.completion + call.status = "completed" + if (!completion.ok) return call.resolving.reject(completion.error) + call.resolving.resolve( + call.result === "json" ? fromJson(this.ctx, completion.value as Json | undefined) : (completion.value as Value), + ) } // --- Promise abstract operations --- @@ -348,7 +442,7 @@ export class Runner { else { if (promise.state === "rejected") this.unhandled.delete(promise) const settled = promise.state === "fulfilled" ? normal(promise.result) : abrupt(promise.result) - this.enqueue(() => reaction(settled)) + this.enqueue({ kind: "reaction", reaction, settled }) } promise.handled = true } @@ -386,7 +480,7 @@ export class Runner { message: `Unhandled rejection from an un-awaited promise: ${failure.message}`, }) } - for (const reaction of reactions) this.enqueue(() => reaction(completion)) + for (const reaction of reactions) this.enqueue({ kind: "reaction", reaction, settled: completion }) } /** ResolvePromise: adopts a thenable, otherwise fulfills. */ @@ -398,7 +492,7 @@ export class Runner { if (!(resolution instanceof Obj)) return this.settle(promise, normal(resolution)) const then = get(resolution, "then") if (typeofValue(then) !== "function") return this.settle(promise, normal(resolution)) - this.enqueue(() => this.thenableJob(promise, resolution, then)) + this.enqueue({ kind: "thenable", promise, thenable: resolution, then }) } // NewPromiseResolveThenableJob. Adopting a native promise through the intrinsic `then` takes the same jobs as @@ -406,9 +500,7 @@ export class Runner { private thenableJob(promise: PromiseObj, thenable: Obj, then: Value): Start | void { const resolving = this.resolving(promise) if (then === this.intrinsicThen && thenable instanceof PromiseObj) { - this.then(thenable, (settled) => - settled.ok ? resolving.resolve(settled.value as Value) : resolving.reject(settled.error), - ) + this.then(thenable, { kind: "settle", target: resolving }) return } const proto = this.ctx.builtins.Function @@ -425,6 +517,15 @@ export class Runner { return { task: new Task([{ body: body(), boundary: undefined }]), input: normal(undefined) } } + private runJob(job: Job): Start | void { + if (job.kind === "resume") return { task: job.task, input: job.input } + if (job.kind === "thenable") return this.thenableJob(job.promise, job.thenable, job.then) + const reaction = job.reaction + if (reaction.kind !== "await") return react(this.ctx, reaction, job.settled) + this.parked.delete(reaction.task) + return { task: reaction.task, input: job.settled } + } + // --- Driver --- // Runs a task until its stack empties or it pauses for a slice or host work, which resumes it before any other job. @@ -476,10 +577,7 @@ export class Runner { const boundary = stack[index]!.boundary! const continuation = new Task(stack.splice(index)) this.parked.set(continuation, { promise, node: signal.node }) - this.then(promise, (settled) => { - this.parked.delete(continuation) - return { task: continuation, input: settled } - }) + this.then(promise, { kind: "await", task: continuation }) completion = boundary.suspended() continue }