refactor(codemode): queue jobs, reactions and host calls as data records

This commit is contained in:
James Long
2026-11-04 20:06:38 +00:00
Unverified
parent 90b228dfe8
commit 9c239c1b73
5 changed files with 326 additions and 173 deletions
@@ -181,26 +181,22 @@ export const extensionGlobals = <R>(
if (isAsync(value))
return pending(
Effect.andThen(before ?? Effect.void, settle(Effect.suspend(() => callHost<R>(value, args).effect))),
label,
site,
)
if (before) yield ctx.runner.blocking(before)
const host = callHost<R>(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<Value, Throw, R>, 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<Value, Throw, R>, 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) =>
@@ -139,17 +139,19 @@ const drainQueue = <R>(ctx: Interpreter<R>, generator: GeneratorObj) => {
// AsyncGeneratorAwaitReturn: a `return(value)` on an ended or unstarted generator settles once `value` does.
const awaitReturn = <R>(ctx: Interpreter<R>, 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 = <R>(ctx: Interpreter<R>, 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<R> implements Boundary {
readonly generator = true
@@ -583,14 +583,13 @@ class Frame<R> {
const body = function* (): Eval<void> {
const json: Array<Json | undefined> = []
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<R> {
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)
+160 -104
View File
@@ -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 = <R>(ctx: Interpreter<R>, resolving: Resolving) => ({
@@ -24,36 +35,60 @@ export const capability = <R>(ctx: Interpreter<R>, 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 =
<R>(
ctx: Interpreter<R>,
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 = <R>(
ctx: Interpreter<R>,
reaction: Exclude<Reaction, { readonly kind: "await" }>,
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<void>): 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 = <R>(
ctx: Interpreter<R>,
reaction: Extract<Reaction, { readonly kind: "handler" }>,
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<void> {
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<void> {
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<R>(
if (cursor === undefined) {
throw typeError(`Promise.${name} expects a synchronous iterable, received ${describeValue(iterable)}.`)
}
const values: Array<Value> = []
const reasons: Array<Value> = []
// 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<readonly [PromiseObj, Reaction]> = []
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 = <R>(
ctx: Interpreter<R>,
reaction: Extract<Reaction, { readonly kind: "combinator" }>,
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 = <R>(ctx: Interpreter<R>, combination: Combination) => {
for (const [item, reaction] of combination.attached) ctx.runner.detach(item, reaction)
}
const finishCombination = <R>(ctx: Interpreter<R>, 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 = <R>(
ctx: Interpreter<R>,
name: "then" | "catch" | "finally",
@@ -181,7 +230,7 @@ const instanceMethod = <R>(
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 = <R>(
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<void> {
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 = <R>(
ctx: Interpreter<R>,
reaction: Extract<Reaction, { readonly kind: "finally" }>,
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<void> {
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") {
+140 -42
View File
@@ -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<Entry>) {}
}
/** 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<Value>
readonly reasons: Array<Value>
/** Members still to settle, plus one until iteration ends. */
remaining: number
/** Every member's reaction, detached once the result is decided. */
readonly attached: Array<readonly [PromiseObj, Reaction]>
}
/**
* 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<Json | undefined> | 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<unknown, unknown> }
@@ -174,12 +245,14 @@ export class Runner<R> {
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<PromiseObj, Diagnostic>()
/** 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<Task, { readonly promise: PromiseObj; readonly node: AstNode | undefined }>()
private readonly fibers = new Set<Fiber.Fiber<unknown, unknown>>()
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<number, Fiber.Fiber<unknown, unknown>>()
private readonly inbox: Array<Delivery> = []
private wake: (() => void) | undefined
private stopping = false
@@ -218,13 +291,13 @@ export class Runner<R> {
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<R> {
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<R> {
* program did settles first, so its failures count even though no later job ran.
*/
diagnostics(): Array<Diagnostic> {
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<R> {
}
/**
* 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<unknown, unknown, R>, settle: (completion: Completion) => void, site?: AstNode): void {
host(
effect: Effect.Effect<unknown, unknown, R>,
call: {
readonly label: string
readonly args?: ReadonlyArray<Json | undefined>
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<R> {
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<R> {
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<R> {
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<R> {
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<R> {
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<R> {
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
}