mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-29 11:42:17 +00:00
refactor(codemode): write iterator helpers and Iterator.from as prelude generators; drop the Helper cursor and its kinds
This commit is contained in:
parent
6759bff034
commit
2cdf6a67e8
12 changed files with 161 additions and 378 deletions
|
|
@ -6,16 +6,16 @@ import { Push } from "./signals.js"
|
|||
import { Adapter, AsyncFromSyncIterator, generatorRequest, generatorStep } from "../machine/generators.js"
|
||||
|
||||
/**
|
||||
* `next`/`return`/`throw` on the generator prototypes (async generators answer with promises) and on the
|
||||
* async-from-sync iterator. Each runs as frames on the caller's stack: a generator's suspended body, or the adapter's.
|
||||
* `next`/`return`/`throw` on the generator prototypes (async generators answer with promises), on iterator helpers,
|
||||
* and on the async-from-sync iterator. Each runs as frames on the caller's stack: a generator's suspended body, or the adapter's.
|
||||
*/
|
||||
export const generatorGlobals = <R>(ctx: Interpreter<R>): void => {
|
||||
const builtins = ctx.builtins
|
||||
const sync = (kind: GeneratorRequestKind): Method => [
|
||||
const sync = (kind: GeneratorRequestKind, owner = "Generator.prototype"): Method => [
|
||||
kind,
|
||||
1,
|
||||
(thisValue, args) => {
|
||||
const method = `Generator.prototype.${kind}`
|
||||
const method = `${owner}.${kind}`
|
||||
const generator = receiver(GeneratorObj, thisValue, method)
|
||||
if (generator.asynchronous) throw typeError(`${method} called on incompatible receiver an async generator.`)
|
||||
return generatorStep(ctx, generator, kind, args[0])
|
||||
|
|
@ -33,6 +33,8 @@ export const generatorGlobals = <R>(ctx: Interpreter<R>): void => {
|
|||
new Push(Adapter, [receiver(AsyncFromSyncIterator, thisValue, `AsyncFromSyncIterator.${kind}`), kind, args]),
|
||||
]
|
||||
methods(builtins, builtins.Generator, [sync("next"), sync("return"), sync("throw")])
|
||||
// Iterator helpers are the prelude's generators (see prelude.ts).
|
||||
methods(builtins, builtins.IteratorHelper, [sync("next", "%IteratorHelper%"), sync("return", "%IteratorHelper%")])
|
||||
methods(builtins, builtins.AsyncGenerator, [async("next"), async("return"), async("throw")])
|
||||
methods(builtins, builtins.AsyncFromSyncIterator, [adapter("next"), adapter("return"), adapter("throw")])
|
||||
define(
|
||||
|
|
|
|||
|
|
@ -371,11 +371,11 @@ export class GeneratorObj extends Opaque {
|
|||
export type Step = { readonly done: boolean; readonly value: Value }
|
||||
|
||||
/**
|
||||
* An iterator the interpreter drives, as data: a built-in cursor over a collection (`Position`), an iterator helper
|
||||
* (`Helper`), or a program iterator driven by its own `next` method (`CustomIterator`). The machine steps and closes
|
||||
* An iterator the interpreter drives, as data: a built-in cursor over a collection (`Position`), or a program
|
||||
* iterator driven by its own `next` method (`CustomIterator`). The machine steps and closes
|
||||
* each kind (see `iteratorStep` in machine/iteration.ts).
|
||||
*/
|
||||
export type Cursor = Position | Helper | CustomIterator
|
||||
export type Cursor = Position | CustomIterator
|
||||
|
||||
/** A program iterator record: the iterator, its `next` method, and whether its results are awaited. */
|
||||
export type CustomIterator = {
|
||||
|
|
@ -384,27 +384,6 @@ export type CustomIterator = {
|
|||
readonly asynchronous: boolean
|
||||
}
|
||||
|
||||
/** What an iterator helper does with its source's values. */
|
||||
export type HelperOp = "map" | "filter" | "take" | "drop" | "flatMap"
|
||||
|
||||
/**
|
||||
* An iterator helper's state, as data: what it does, its source, its callback, and its counter (the next index it
|
||||
* passes the callback, or how many values `take` and `drop` have left). Once it reports done, throws, or is closed, it
|
||||
* stays done; a callback that re-enters its own helper is a TypeError, as for a running generator.
|
||||
*/
|
||||
export class Helper {
|
||||
done = false
|
||||
running = false
|
||||
/** `flatMap`'s inner iterator, while it has one. */
|
||||
inner: Cursor | undefined = undefined
|
||||
constructor(
|
||||
readonly op: HelperOp,
|
||||
readonly source: Cursor,
|
||||
readonly callback: Value,
|
||||
public count: number,
|
||||
) {}
|
||||
}
|
||||
|
||||
const finished: Step = { done: true, value: undefined }
|
||||
|
||||
/** What a built-in iterator yields for each entry: `keys()`, `values()`, or `entries()`. */
|
||||
|
|
|
|||
|
|
@ -1,246 +0,0 @@
|
|||
import { type AstNode, typeError } from "../interpreter/model.js"
|
||||
import { type Cursor, Helper, Obj, type Step, type Value } from "../interpreter/objects.js"
|
||||
import { describeValue } from "../interpreter/references.js"
|
||||
import { Interruption } from "../interpreter/signals.js"
|
||||
import { type Frame, kind, type Out, PENDING } from "./frame.js"
|
||||
import { iterate, iterateDirect, iteratorClose, iteratorStep } from "./iteration.js"
|
||||
import type { MachineTask } from "./task.js"
|
||||
|
||||
// Iterator helpers (`map`, `filter`, `take`, `drop`, `flatMap`) as frames over a `Helper` record. A helper's own
|
||||
// failures are not located here: a built-in that drives it (`Iterator.prototype.next`) locates them at its call, as
|
||||
// a statement that drives it leaves them.
|
||||
|
||||
const finished: Step = { done: true, value: undefined }
|
||||
const site = undefined as unknown as AstNode
|
||||
|
||||
// The phases of `next`: start, have the source's step, have the callback's result (map, filter, flatMap), have the
|
||||
// inner iterator, have the inner step, have the source closed (take), and closing the source after a callback failed.
|
||||
const START = 0
|
||||
const STEPPED = 1
|
||||
const CALLED = 2
|
||||
const FLATTENED = 3
|
||||
const INNER = 4
|
||||
const TAKEN = 5
|
||||
const GUARD_CLOSING = 6
|
||||
const GUARD_CLOSED = 7
|
||||
const DROPPED = 8
|
||||
const REENTERED = 9
|
||||
|
||||
// The phases whose failure closes the source first: the callback, and (flatMap) flattening and the inner iterator.
|
||||
const guarded = (phase: number) => phase === CALLED || phase === FLATTENED || phase === INNER
|
||||
|
||||
/** GetIteratorFlattenable: an iterable by `[Symbol.iterator]`, otherwise the object itself as an iterator. */
|
||||
export const flattenable = (
|
||||
task: MachineTask,
|
||||
value: Value,
|
||||
name: string,
|
||||
strings: boolean,
|
||||
node: AstNode,
|
||||
): Out<Cursor> => {
|
||||
if (typeof value === "string" ? !strings : !(value instanceof Obj)) {
|
||||
throw typeError(`${name} expects an iterable or iterator, received ${describeValue(value)}.`)
|
||||
}
|
||||
const mark = task.stack.length
|
||||
const opened = iterate(task, value, node)
|
||||
if (opened === PENDING) return task.park(undefined, mark, Flatten, node, 1, [value])
|
||||
return opened ?? iterateDirect(value, undefined)
|
||||
}
|
||||
|
||||
const Flatten = kind(
|
||||
"IteratorFlattenable",
|
||||
(_task, frame: Frame, _node, input) =>
|
||||
(input as Cursor | undefined) ?? iterateDirect(frame.slots[0] as Value, undefined),
|
||||
)
|
||||
|
||||
// Slots: the helper, and the callback failure the source is closed for.
|
||||
function nextStep(task: MachineTask, frame: Frame, input: unknown): Out<Step> {
|
||||
const helper = frame.slots[0] as Helper
|
||||
let phase = frame.phase
|
||||
if (phase === GUARD_CLOSING) {
|
||||
frame.phase = GUARD_CLOSED
|
||||
if (iteratorClose(task, helper.source, site) === PENDING) return PENDING
|
||||
phase = GUARD_CLOSED
|
||||
}
|
||||
if (phase === GUARD_CLOSED) throw frame.slots[1]
|
||||
if (phase === START) {
|
||||
if (helper.done) return finished
|
||||
if (helper.running) {
|
||||
frame.phase = REENTERED
|
||||
throw typeError("Iterator helper is already running.")
|
||||
}
|
||||
helper.running = true
|
||||
}
|
||||
const step = pull(task, frame, helper, phase, input)
|
||||
if (step === PENDING) return PENDING
|
||||
helper.done = step.done
|
||||
helper.running = false
|
||||
return step
|
||||
}
|
||||
|
||||
// Advances the helper from `phase`; parks the frame at the next phase whenever the work it started is pending.
|
||||
function pull(task: MachineTask, frame: Frame, helper: Helper, phase: number, input: unknown): Out<Step> {
|
||||
const wait = (next: number): typeof PENDING => {
|
||||
frame.phase = next
|
||||
return PENDING
|
||||
}
|
||||
const source = helper.source
|
||||
switch (helper.op) {
|
||||
case "map": {
|
||||
if (phase === START) {
|
||||
const step = iteratorStep(task, source, site)
|
||||
if (step === PENDING) return wait(STEPPED)
|
||||
input = step
|
||||
phase = STEPPED
|
||||
}
|
||||
if (phase === STEPPED) {
|
||||
const step = input as Step
|
||||
if (step.done) return finished
|
||||
frame.phase = CALLED
|
||||
const mapped = task.call(helper.callback, undefined, [step.value, helper.count++], site)
|
||||
if (mapped === PENDING) return PENDING
|
||||
input = mapped
|
||||
}
|
||||
return { done: false, value: input as Value }
|
||||
}
|
||||
case "filter": {
|
||||
while (true) {
|
||||
if (phase === START) {
|
||||
frame.phase = START
|
||||
const step = iteratorStep(task, source, site)
|
||||
if (step === PENDING) return wait(STEPPED)
|
||||
input = step
|
||||
phase = STEPPED
|
||||
}
|
||||
if (phase === STEPPED) {
|
||||
const step = input as Step
|
||||
if (step.done) return finished
|
||||
frame.slots[1] = step
|
||||
frame.phase = CALLED
|
||||
const kept = task.call(helper.callback, undefined, [step.value, helper.count++], site)
|
||||
if (kept === PENDING) return PENDING
|
||||
input = kept
|
||||
}
|
||||
if (input) return frame.slots[1] as Step
|
||||
phase = START
|
||||
}
|
||||
}
|
||||
case "take": {
|
||||
if (phase === TAKEN) return finished
|
||||
if (phase === STEPPED) return input as Step
|
||||
if (helper.count === 0) {
|
||||
if (iteratorClose(task, source, site) === PENDING) return wait(TAKEN)
|
||||
return finished
|
||||
}
|
||||
helper.count -= 1
|
||||
const step = iteratorStep(task, source, site)
|
||||
if (step === PENDING) return wait(STEPPED)
|
||||
return step
|
||||
}
|
||||
case "drop": {
|
||||
if (phase === STEPPED) {
|
||||
if ((input as Step).done) return finished
|
||||
}
|
||||
if (phase === DROPPED) return input as Step
|
||||
while (helper.count > 0) {
|
||||
helper.count -= 1
|
||||
const step = iteratorStep(task, source, site)
|
||||
if (step === PENDING) return wait(STEPPED)
|
||||
if (step.done) return finished
|
||||
}
|
||||
const step = iteratorStep(task, source, site)
|
||||
if (step === PENDING) return wait(DROPPED)
|
||||
return step
|
||||
}
|
||||
case "flatMap": {
|
||||
while (true) {
|
||||
if (phase === START && helper.inner !== undefined) {
|
||||
frame.phase = INNER
|
||||
const step = iteratorStep(task, helper.inner, site)
|
||||
if (step === PENDING) return PENDING
|
||||
input = step
|
||||
phase = INNER
|
||||
}
|
||||
if (phase === INNER) {
|
||||
const step = input as Step
|
||||
if (!step.done) return step
|
||||
helper.inner = undefined
|
||||
phase = START
|
||||
}
|
||||
if (phase === START) {
|
||||
frame.phase = START
|
||||
const step = iteratorStep(task, source, site)
|
||||
if (step === PENDING) return wait(STEPPED)
|
||||
input = step
|
||||
phase = STEPPED
|
||||
}
|
||||
if (phase === STEPPED) {
|
||||
const step = input as Step
|
||||
if (step.done) return finished
|
||||
frame.phase = CALLED
|
||||
const mapped = task.call(helper.callback, undefined, [step.value, helper.count++], site)
|
||||
if (mapped === PENDING) return PENDING
|
||||
input = mapped
|
||||
phase = CALLED
|
||||
}
|
||||
if (phase === CALLED) {
|
||||
frame.phase = FLATTENED
|
||||
const inner = flattenable(task, input as Value, "Iterator.prototype.flatMap", false, site)
|
||||
if (inner === PENDING) return PENDING
|
||||
input = inner
|
||||
}
|
||||
helper.inner = input as Cursor
|
||||
phase = START
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A helper's `next`: the step it produces. */
|
||||
export const HelperNext = kind(
|
||||
"IteratorHelper.next",
|
||||
(task, frame: Frame, _node, input) => nextStep(task, frame, input),
|
||||
{
|
||||
unwind: (_task, frame, error) => {
|
||||
const helper = frame.slots[0] as Helper
|
||||
if (frame.phase === REENTERED) return false
|
||||
if (guarded(frame.phase) && !(error instanceof Interruption)) {
|
||||
frame.phase = GUARD_CLOSING
|
||||
frame.slots[1] = error
|
||||
return true
|
||||
}
|
||||
helper.done = true
|
||||
helper.running = false
|
||||
// The callback's failure wins over a failing close.
|
||||
if (frame.phase === GUARD_CLOSING || frame.phase === GUARD_CLOSED) throw frame.slots[1]
|
||||
return false
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
/** A helper's `return`: closes its inner iterator (flatMap) and its source, once. */
|
||||
export const HelperClose = kind(
|
||||
"IteratorHelper.return",
|
||||
(task, frame: Frame, _node, _input) => {
|
||||
const helper = frame.slots[0] as Helper
|
||||
if (frame.phase === 0) {
|
||||
if (helper.done) return undefined
|
||||
if (helper.running) throw typeError("Iterator helper is already running.")
|
||||
helper.running = true
|
||||
helper.done = true
|
||||
frame.phase = 1
|
||||
if (helper.inner !== undefined && iteratorClose(task, helper.inner, site) === PENDING) return PENDING
|
||||
}
|
||||
if (frame.phase === 1) {
|
||||
frame.phase = 2
|
||||
if (iteratorClose(task, helper.source, site) === PENDING) return PENDING
|
||||
}
|
||||
helper.running = false
|
||||
return undefined
|
||||
},
|
||||
{
|
||||
unwind: (_task, frame) => {
|
||||
if (frame.phase !== 0) (frame.slots[0] as Helper).running = false
|
||||
return false
|
||||
},
|
||||
},
|
||||
)
|
||||
|
|
@ -4,7 +4,6 @@ import {
|
|||
type Cursor,
|
||||
type CustomIterator,
|
||||
get,
|
||||
Helper,
|
||||
IteratorObj,
|
||||
Obj,
|
||||
Position,
|
||||
|
|
@ -16,7 +15,6 @@ import { describeValue } from "../interpreter/references.js"
|
|||
import { Await } from "../interpreter/signals.js"
|
||||
import { type Frame, kind, type Out, PENDING, type Pending } from "./frame.js"
|
||||
import { ev } from "./expressions.js"
|
||||
import { HelperClose, HelperNext } from "./helpers.js"
|
||||
import type { MachineTask } from "./task.js"
|
||||
|
||||
/** An iterator the machine drives: a built-in cursor, a helper, or a program object with its own `next`. */
|
||||
|
|
@ -75,7 +73,6 @@ export const iterateDirect = (value: Value, node: AstNode | undefined): Iter =>
|
|||
/** IteratorStep: the next result, as `for...of` sees it. An async iterator's result is awaited first. */
|
||||
export function iteratorStep(task: MachineTask, iterator: Iter, node: AstNode): Out<Step> {
|
||||
if (iterator instanceof Position) return iterator.step()
|
||||
if (iterator instanceof Helper) return task.push(HelperNext, undefined, [iterator])
|
||||
return stepStep(task, undefined, node, undefined, iterator)
|
||||
}
|
||||
|
||||
|
|
@ -108,7 +105,6 @@ const IteratorStep = kind("IteratorStep", stepStep)
|
|||
/** IteratorClose: calls the iterator's `return`, when it has one, and checks what it returned. */
|
||||
export function iteratorClose(task: MachineTask, iterator: Iter, node: AstNode): Out<undefined> {
|
||||
if (iterator instanceof Position) return undefined
|
||||
if (iterator instanceof Helper) return task.push(HelperClose, undefined, [iterator]) as Pending
|
||||
return closeStep(task, undefined, node, undefined, iterator)
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -8,11 +8,9 @@ import "../interpreter/extensions.js"
|
|||
import "../interpreter/interpreter.js"
|
||||
import "../interpreter/promises.js"
|
||||
import "../stdlib/array.js"
|
||||
import "../stdlib/iterator.js"
|
||||
import "./calls.js"
|
||||
import "./expressions.js"
|
||||
import "./generators.js"
|
||||
import "./helpers.js"
|
||||
import "./iteration.js"
|
||||
import "./patterns.js"
|
||||
import "./statements.js"
|
||||
|
|
|
|||
|
|
@ -1,6 +1,5 @@
|
|||
import { isSupportedCallback, requireCallback } from "../interpreter/callback.js"
|
||||
import type { Builtins } from "../interpreter/intrinsics.js"
|
||||
import { iterateDirect } from "../machine/iteration.js"
|
||||
import { finishBytes } from "../stdlib/bytes.js"
|
||||
import { weakKey } from "../stdlib/collections.js"
|
||||
import { buildPairs } from "../stdlib/url.js"
|
||||
|
|
@ -33,7 +32,7 @@ import {
|
|||
WeakMapObj,
|
||||
WeakSetObj,
|
||||
} from "../interpreter/objects.js"
|
||||
import { builtinCursor } from "../interpreter/operations.js"
|
||||
import { builtinCursor, requireIteratorObject } from "../interpreter/operations.js"
|
||||
import { containsOpaqueReference, describeValue, isOpaque } from "../interpreter/references.js"
|
||||
import { Invoke } from "../interpreter/signals.js"
|
||||
|
||||
|
|
@ -86,8 +85,6 @@ export const helpers = (ctx: Interpreter<unknown>): Array<readonly [string, Valu
|
|||
],
|
||||
$Describe: [1, ([value]) => describeValue(value)],
|
||||
$Inherits: [2, ([value, proto]) => hasPrototype(value, proto as Obj)],
|
||||
/** An iterator wrapped as `Iterator.from` returns it. */
|
||||
$Wrap: [1, ([value]) => new IteratorObj(builtins.IteratorHelper, iterateDirect(value, undefined))],
|
||||
/** An object's own enumerable string keys. */
|
||||
$Keys: [1, ([value]) => new Arr(builtins.Array, keys(value as Obj))],
|
||||
/** Defines an own data property, enumerable or hidden, and returns the object. */
|
||||
|
|
@ -115,13 +112,22 @@ export const helpers = (ctx: Interpreter<unknown>): Array<readonly [string, Valu
|
|||
buildPairs({ kind: kind as "Headers", proto: proto as Obj }, value, String(label)),
|
||||
],
|
||||
$IsCallable: [1, ([value]) => isSupportedCallback(value)],
|
||||
/** An iterator object as `for...of` steps it, reading `next` once (GetIteratorDirect); with `arrays`, an array's values. */
|
||||
/**
|
||||
* An iterator object as `for...of` steps it, reading `next` once and calling it only then (GetIteratorDirect);
|
||||
* with `arrays`, an array's values.
|
||||
*/
|
||||
$Direct: [
|
||||
2,
|
||||
([value, arrays]) =>
|
||||
arrays === true && value instanceof Arr
|
||||
? positionIterator(builtins, value, "values")
|
||||
: new IteratorObj(builtins.Iterator, iterateDirect(value, undefined)),
|
||||
: value instanceof IteratorObj
|
||||
? value
|
||||
: new IteratorObj(builtins.Iterator, {
|
||||
iterator: requireIteratorObject(value, "An iterator"),
|
||||
next: get(value as Obj, "next"),
|
||||
asynchronous: false,
|
||||
}),
|
||||
],
|
||||
/** What the collection built-ins need from a Map, Set, WeakMap, or WeakSet's table; see `table`. */
|
||||
$Table: [4, ([op, target, key, value]) => table(builtins, String(op), target, key, value)],
|
||||
|
|
|
|||
|
|
@ -12,7 +12,7 @@ import { code } from "./source.js"
|
|||
// source is parsed once per process. Each runtime makes its top-level functions as `Fn`s over a private scope (the
|
||||
// intrinsic globals, the `$` helpers, and the prelude's own functions), so programs can't reach the helpers, and
|
||||
// replacing a global can't change what a built-in does. A function named `Array$prototype$map` is installed as
|
||||
// `Array.prototype.map`; one without a `$` is internal. Snapshots name prelude nodes by id in the "prelude" source and
|
||||
// `Array.prototype.map`; one without a `$` is internal. Its generators make iterator helpers. Snapshots name prelude nodes by id in the "prelude" source and
|
||||
// never copy it; its hash is part of the build id.
|
||||
|
||||
let parsed: Source | undefined
|
||||
|
|
@ -47,6 +47,8 @@ export class Prelude {
|
|||
for (const node of program.body as Array<FunctionDeclaration>) {
|
||||
const path = node.id.name.split("$")
|
||||
const made = createFunction(builtins, scopes, node, path.at(-1))
|
||||
// The prelude's generators are iterator helpers.
|
||||
if (node.generator) define(made, "prototype", builtins.IteratorHelper, hidden)
|
||||
bind(node.id.name, made)
|
||||
define(this.functions, node.id.name, made, hidden)
|
||||
if (path.length === 1) continue
|
||||
|
|
|
|||
|
|
@ -200,11 +200,137 @@ function pairsForEach(target, pairs, callback, thisArg) {
|
|||
index++
|
||||
}
|
||||
}
|
||||
// Iterator helpers are prelude generators, made with %IteratorHelper% as their prototype. Each is primed to its first
|
||||
// yield, so a return() before the first next() still closes the source, from its finally.
|
||||
function Iterator$from(value) {
|
||||
if ($IsObject(value) && $Inherits(value, Iterator.prototype)) return value
|
||||
if (typeof value !== "string" && !$IsObject(value)) $Throw("TypeError", "Iterator.from expects an iterable or iterator, received " + $Describe(value) + ".")
|
||||
return prime(wrapHelper(value, flattenable(value, true, "Iterator.from")))
|
||||
}
|
||||
function* wrapHelper(source, iterator) {
|
||||
let started = false
|
||||
try {
|
||||
yield
|
||||
started = true
|
||||
for (const item of iterator) yield item
|
||||
} finally {
|
||||
if (!started) closeIterator(source)
|
||||
}
|
||||
}
|
||||
|
||||
function Iterator$prototype$map(mapper) {
|
||||
const iterator = $Direct(this, false)
|
||||
$Callback(mapper, "Iterator.prototype.map")
|
||||
return prime(mapHelper(this, iterator, mapper))
|
||||
}
|
||||
function* mapHelper(source, iterator, mapper) {
|
||||
let started = false
|
||||
try {
|
||||
yield
|
||||
started = true
|
||||
let counter = 0
|
||||
for (const item of iterator) yield mapper(item, counter++)
|
||||
} finally {
|
||||
if (!started) closeIterator(source)
|
||||
}
|
||||
}
|
||||
|
||||
function Iterator$prototype$filter(predicate) {
|
||||
const iterator = $Direct(this, false)
|
||||
$Callback(predicate, "Iterator.prototype.filter")
|
||||
return prime(filterHelper(this, iterator, predicate))
|
||||
}
|
||||
function* filterHelper(source, iterator, predicate) {
|
||||
let started = false
|
||||
try {
|
||||
yield
|
||||
started = true
|
||||
let counter = 0
|
||||
for (const item of iterator) if (predicate(item, counter++)) yield item
|
||||
} finally {
|
||||
if (!started) closeIterator(source)
|
||||
}
|
||||
}
|
||||
|
||||
function Iterator$prototype$take(limit) {
|
||||
const iterator = $Direct(this, false)
|
||||
return prime(takeHelper(this, iterator, count(limit, "take")))
|
||||
}
|
||||
function* takeHelper(source, iterator, remaining) {
|
||||
let started = false
|
||||
try {
|
||||
yield
|
||||
started = true
|
||||
if (remaining === 0) return closeIterator(source)
|
||||
for (const item of iterator) {
|
||||
remaining--
|
||||
yield item
|
||||
if (remaining === 0) break
|
||||
}
|
||||
} finally {
|
||||
if (!started) closeIterator(source)
|
||||
}
|
||||
}
|
||||
|
||||
function Iterator$prototype$drop(limit) {
|
||||
const iterator = $Direct(this, false)
|
||||
return prime(dropHelper(this, iterator, count(limit, "drop")))
|
||||
}
|
||||
function* dropHelper(source, iterator, remaining) {
|
||||
let started = false
|
||||
try {
|
||||
yield
|
||||
started = true
|
||||
for (const item of iterator) {
|
||||
if (remaining > 0) remaining--
|
||||
else yield item
|
||||
}
|
||||
} finally {
|
||||
if (!started) closeIterator(source)
|
||||
}
|
||||
}
|
||||
|
||||
function Iterator$prototype$flatMap(mapper) {
|
||||
const iterator = $Direct(this, false)
|
||||
$Callback(mapper, "Iterator.prototype.flatMap")
|
||||
return prime(flatMapHelper(this, iterator, mapper))
|
||||
}
|
||||
function* flatMapHelper(source, iterator, mapper) {
|
||||
let started = false
|
||||
try {
|
||||
yield
|
||||
started = true
|
||||
let counter = 0
|
||||
for (const item of iterator) {
|
||||
for (const inner of flattenable(mapper(item, counter++), false, "Iterator.prototype.flatMap")) yield inner
|
||||
}
|
||||
} finally {
|
||||
if (!started) closeIterator(source)
|
||||
}
|
||||
}
|
||||
|
||||
function prime(helper) {
|
||||
helper.next()
|
||||
return helper
|
||||
}
|
||||
|
||||
// A take or drop count: a number that is not NaN or negative.
|
||||
function count(limit, name) {
|
||||
const number = +limit
|
||||
const integer = number === Infinity || number === -Infinity ? number : number - (number % 1)
|
||||
if (number !== number || integer < 0) $Throw("RangeError", "Iterator.prototype." + name + " expects a non-negative count, received " + number + ".")
|
||||
return integer
|
||||
}
|
||||
|
||||
// GetIteratorFlattenable: an iterable by its [Symbol.iterator], otherwise the object itself as an iterator.
|
||||
function flattenable(value, strings, name) {
|
||||
if (typeof value === "string" ? !strings : !$IsObject(value)) $Throw("TypeError", name + " expects an iterable or iterator, received " + $Describe(value) + ".")
|
||||
const method = value[Symbol.iterator]
|
||||
return $Wrap(method === undefined || method === null ? value : $Call(method, value))
|
||||
return $Direct(method === undefined || method === null ? value : $Call(method, value), false)
|
||||
}
|
||||
|
||||
function closeIterator(iterator) {
|
||||
const method = iterator.return
|
||||
if (method !== undefined && method !== null && !$IsObject($Call(method, iterator))) $Throw("TypeError", "Iterator return() must return an object.")
|
||||
}
|
||||
|
||||
function Iterator$prototype$toArray() {
|
||||
|
|
|
|||
|
|
@ -21,7 +21,6 @@ import {
|
|||
Fn,
|
||||
GeneratorObj,
|
||||
HeadersObj,
|
||||
Helper,
|
||||
IteratorObj,
|
||||
MapObj,
|
||||
Native,
|
||||
|
|
@ -213,7 +212,6 @@ const specs: ReadonlyArray<ClassSpec> = [
|
|||
obj: true,
|
||||
constants: { tag: "AsyncFromSyncIterator" },
|
||||
},
|
||||
{ name: "Helper", ctor: Helper, fields: ["done", "running", "inner", "op", "source", "callback", "count"] },
|
||||
{ name: "Position", ctor: Position, fields: ["index", "done", "source", "kind", "arrays"] },
|
||||
{
|
||||
name: "OrderedTable",
|
||||
|
|
|
|||
|
|
@ -1,80 +1,26 @@
|
|||
import { nativeKind, site } from "../machine/native-kind.js"
|
||||
import { requireCallback } from "../interpreter/callback.js"
|
||||
import type { Interpreter } from "../interpreter/interpreter.js"
|
||||
import { rangeError, typeError } from "../interpreter/model.js"
|
||||
import { typeError } from "../interpreter/model.js"
|
||||
import { constructor, methods, receiver, requiresNew } from "../interpreter/native.js"
|
||||
import {
|
||||
coerceToNumber,
|
||||
type Cursor,
|
||||
Helper,
|
||||
type HelperOp,
|
||||
iteratorResult,
|
||||
IteratorObj,
|
||||
Position,
|
||||
type Step,
|
||||
type Value,
|
||||
} from "../interpreter/objects.js"
|
||||
import { Push } from "../interpreter/signals.js"
|
||||
import { PENDING } from "../machine/frame.js"
|
||||
import { iterateDirect, iteratorClose, iteratorStep } from "../machine/iteration.js"
|
||||
|
||||
const method = (name: string) => `Iterator.prototype.${name}`
|
||||
import { iteratorResult, IteratorObj, Position } from "../interpreter/objects.js"
|
||||
|
||||
// Every built-in iterator and helper shares the Iterator prototype; JS gives each collection its own, which is only
|
||||
// observable through getPrototypeOf.
|
||||
// observable through getPrototypeOf. The helpers (`map`, `take`, `Iterator.from`, ...) are the prelude's.
|
||||
export const iteratorGlobals = <R>(ctx: Interpreter<R>) => {
|
||||
const builtins = ctx.builtins
|
||||
const proto = builtins.Iterator
|
||||
|
||||
const limit = (value: Value, name: string) => {
|
||||
const count = Math.trunc(coerceToNumber(value))
|
||||
if (Number.isNaN(count) || count < 0) {
|
||||
throw rangeError(`${method(name)} expects a non-negative count, received ${count}.`)
|
||||
}
|
||||
return count
|
||||
}
|
||||
const helper = (op: HelperOp, thisValue: Value, callback: Value, count: number) =>
|
||||
new IteratorObj(builtins.IteratorHelper, new Helper(op, iterateDirect(thisValue, undefined), callback, count))
|
||||
const lazy = (op: "map" | "filter" | "flatMap") =>
|
||||
[
|
||||
op,
|
||||
1,
|
||||
(thisValue: Value, args: Array<Value>) => {
|
||||
const source = iterateDirect(thisValue, undefined)
|
||||
const callback = requireCallback(args[0], method(op))
|
||||
return new IteratorObj(builtins.IteratorHelper, new Helper(op, source, callback, 0))
|
||||
},
|
||||
] as const
|
||||
methods(builtins, proto, [
|
||||
[
|
||||
"next",
|
||||
0,
|
||||
(thisValue) => {
|
||||
const cursor = receiver(IteratorObj, thisValue, method("next")).cursor
|
||||
if (cursor instanceof Position) {
|
||||
const step = cursor.step()
|
||||
return iteratorResult(builtins.Object, step.value, step.done)
|
||||
}
|
||||
return new Push(IteratorNext, [cursor])
|
||||
const cursor = receiver(IteratorObj, thisValue, "Iterator.prototype.next").cursor
|
||||
if (!(cursor instanceof Position)) throw typeError("Iterator.prototype.next called on an internal iterator.")
|
||||
const step = cursor.step()
|
||||
return iteratorResult(builtins.Object, step.value, step.done)
|
||||
},
|
||||
],
|
||||
lazy("map"),
|
||||
lazy("filter"),
|
||||
["take", 1, (thisValue, args) => helper("take", thisValue, undefined, limit(args[0], "take"))],
|
||||
["drop", 1, (thisValue, args) => helper("drop", thisValue, undefined, limit(args[0], "drop"))],
|
||||
lazy("flatMap"),
|
||||
])
|
||||
|
||||
// Helpers and `Iterator.from` wrappers can be closed; collection iterators, as in JS, cannot.
|
||||
methods(builtins, builtins.IteratorHelper, [
|
||||
[
|
||||
"return",
|
||||
0,
|
||||
(thisValue) => new Push(IteratorReturn, [receiver(IteratorObj, thisValue, "Iterator.prototype.return").cursor]),
|
||||
],
|
||||
])
|
||||
|
||||
const iterator = constructor(builtins, proto, {
|
||||
return constructor(builtins, proto, {
|
||||
name: "Iterator",
|
||||
length: 0,
|
||||
call: requiresNew("Iterator"),
|
||||
|
|
@ -82,27 +28,4 @@ export const iteratorGlobals = <R>(ctx: Interpreter<R>) => {
|
|||
throw typeError("Iterator is abstract; use Iterator.from(...) or a built-in iterator.")
|
||||
},
|
||||
})
|
||||
return iterator
|
||||
}
|
||||
|
||||
// Slots: the cursor.
|
||||
const IteratorNext = nativeKind("Iterator.prototype.next", (task, frame, input) => {
|
||||
let step = input as Step
|
||||
if (frame.phase === 0) {
|
||||
const stepped = iteratorStep(task, frame.slots[0] as Cursor, site(frame))
|
||||
if (stepped === PENDING) {
|
||||
frame.phase = 1
|
||||
return PENDING
|
||||
}
|
||||
step = stepped
|
||||
}
|
||||
return iteratorResult(task.ctx.builtins.Object, step.value, step.done)
|
||||
})
|
||||
|
||||
const IteratorReturn = nativeKind("%IteratorHelper%.return", (task, frame) => {
|
||||
if (frame.phase === 0) {
|
||||
frame.phase = 1
|
||||
if (iteratorClose(task, frame.slots[0] as Cursor, site(frame)) === PENDING) return PENDING
|
||||
}
|
||||
return iteratorResult(task.ctx.builtins.Object, undefined, true)
|
||||
})
|
||||
|
|
|
|||
|
|
@ -408,7 +408,6 @@ describe("built-ins as data", () => {
|
|||
"Array callback",
|
||||
"Call",
|
||||
"Convert",
|
||||
"IteratorHelper.next",
|
||||
"JSON.stringify walk",
|
||||
"Tool call",
|
||||
"Promise combinator",
|
||||
|
|
|
|||
|
|
@ -1376,7 +1376,7 @@ describe("Iterator helpers", () => {
|
|||
const it = g().map(() => it.next())
|
||||
return it.next()
|
||||
`),
|
||||
).toMatchObject({ message: expect.stringContaining("Iterator helper is already running.") })
|
||||
).toMatchObject({ message: expect.stringContaining("is already running.") })
|
||||
})
|
||||
})
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue