Repository navigation
Expand file tree
/
Copy pathiterator.ts
More file actions
348 lines (339 loc) · 10.7 KB
/
Copy pathiterator.ts
File metadata and controls
348 lines (339 loc) · 10.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
import { Cause, Effect, Exit } from "effect"
import { applyCollectionCallback } from "../interpreter/callback.js"
import type { Interpreter } from "../interpreter/interpreter.js"
import { rangeError, typeError } from "../interpreter/model.js"
import { constructor, fn, methods, receiver, requiresNew } from "../interpreter/native.js"
import {
Arr,
coerceToNumber,
type Cursor,
define,
hasPrototype,
hidden,
IteratorObj,
Obj,
record,
type Step,
type Value,
} from "../interpreter/objects.js"
import { describeValue } from "../interpreter/references.js"
const finished: Step = { done: true, value: undefined }
// Every built-in iterator and helper shares the Iterator prototype; JS gives each collection its own, which is only
// observable through getPrototypeOf.
export const iteratorGlobals = <R>(ctx: Interpreter<R>) => {
const builtins = ctx.builtins
const proto = builtins.Iterator
const method = (name: string) => `Iterator.prototype.${name}`
// A step that runs program code: when it throws, close the source first, as IteratorClose does.
const guarded = <A>(source: Cursor<R>, body: Effect.Effect<A, unknown, R>) =>
Effect.flatMap(Effect.exit(body), (exit) => {
if (Exit.isSuccess(exit)) return Effect.succeed(exit.value)
if (Cause.hasInterruptsOnly(exit.cause)) return Effect.failCause(exit.cause)
return Effect.andThen(Effect.exit(source.close), Effect.failCause(exit.cause))
})
// A lazy helper: `pull` advances it once. 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.
const helper = (source: Cursor<R>, pull: Effect.Effect<Step, unknown, R>, close = source.close) => {
let done = false
let running = false
const enter = () => {
if (running) throw typeError("Iterator helper is already running.")
running = true
}
return new IteratorObj(builtins.IteratorHelper, {
next: Effect.suspend(() => {
if (done) return Effect.succeed(finished)
enter()
return Effect.flatMap(Effect.exit(pull), (exit) => {
running = false
done = Exit.isSuccess(exit) ? exit.value.done : true
return exit
})
}),
close: Effect.suspend(() => {
if (done) return Effect.void
enter()
done = true
return Effect.ensuring(
close,
Effect.sync(() => {
running = false
}),
)
}),
})
}
// GetIteratorFlattenable: an iterable by `[Symbol.iterator]`, otherwise the object itself as an iterator.
const flattenable = (value: Value, name: string, strings: boolean) =>
Effect.gen(function* () {
if (typeof value === "string" ? !strings : !(value instanceof Obj)) {
throw typeError(`${name} expects an iterable or iterator, received ${describeValue(value)}.`)
}
return (yield* ctx.iterate(value)) ?? ctx.iterateDirect(value)
})
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
}
methods(builtins, proto, [
[
"next",
0,
(thisValue) =>
Effect.map(receiver(IteratorObj, thisValue, method("next")).cursor.next, (step) =>
record(builtins.Object, { value: step.value, done: step.done }),
),
],
[
"map",
1,
(thisValue, args) => {
const source = ctx.iterateDirect(thisValue)
const apply = applyCollectionCallback(ctx, args[0], method("map"))
let counter = 0
return helper(
source,
Effect.gen(function* () {
const step = yield* source.next
if (step.done) return finished
return { done: false, value: yield* guarded(source, apply([step.value, counter++])) }
}),
)
},
],
[
"filter",
1,
(thisValue, args) => {
const source = ctx.iterateDirect(thisValue)
const apply = applyCollectionCallback(ctx, args[0], method("filter"))
let counter = 0
return helper(
source,
Effect.gen(function* () {
while (true) {
const step = yield* source.next
if (step.done) return finished
if (yield* guarded(source, apply([step.value, counter++]))) return step
}
}),
)
},
],
[
"take",
1,
(thisValue, args) => {
const source = ctx.iterateDirect(thisValue)
let remaining = limit(args[0], "take")
return helper(
source,
Effect.gen(function* () {
if (remaining === 0) {
yield* source.close
return finished
}
remaining -= 1
return yield* source.next
}),
)
},
],
[
"drop",
1,
(thisValue, args) => {
const source = ctx.iterateDirect(thisValue)
let remaining = limit(args[0], "drop")
return helper(
source,
Effect.gen(function* () {
while (remaining > 0) {
remaining -= 1
const step = yield* source.next
if (step.done) return finished
}
return yield* source.next
}),
)
},
],
[
"flatMap",
1,
(thisValue, args) => {
const source = ctx.iterateDirect(thisValue)
const apply = applyCollectionCallback(ctx, args[0], method("flatMap"))
let counter = 0
let inner: Cursor<R> | undefined
return helper(
source,
Effect.gen(function* () {
while (true) {
if (inner !== undefined) {
const step = yield* guarded(source, inner.next)
if (!step.done) return step
inner = undefined
}
const step = yield* source.next
if (step.done) return finished
inner = yield* guarded(
source,
Effect.flatMap(apply([step.value, counter++]), (mapped) =>
flattenable(mapped, method("flatMap"), false),
),
)
}
}),
Effect.suspend(() => (inner === undefined ? source.close : Effect.andThen(inner.close, source.close))),
)
},
],
[
"reduce",
1,
(thisValue, args) => {
const source = ctx.iterateDirect(thisValue)
const apply = applyCollectionCallback(ctx, args[0], method("reduce"))
return Effect.gen(function* () {
let counter = 0
let accumulator = args[1]
if (args.length < 2) {
const first = yield* source.next
if (first.done) throw typeError("Iterator.prototype.reduce of an empty iterator with no initial value.")
accumulator = first.value
counter = 1
}
while (true) {
const step = yield* source.next
if (step.done) return accumulator
accumulator = yield* guarded(source, apply([accumulator, step.value, counter++]))
}
})
},
],
[
"toArray",
0,
(thisValue) => {
const source = ctx.iterateDirect(thisValue)
return Effect.gen(function* () {
const items: Array<Value> = []
while (true) {
const step = yield* source.next
if (step.done) return new Arr(builtins.Array, items)
items.push(step.value)
}
})
},
],
[
"forEach",
1,
(thisValue, args) => {
const source = ctx.iterateDirect(thisValue)
const apply = applyCollectionCallback(ctx, args[0], method("forEach"))
return Effect.gen(function* () {
let counter = 0
while (true) {
const step = yield* source.next
if (step.done) return undefined
yield* guarded(source, apply([step.value, counter++]))
}
})
},
],
[
"some",
1,
(thisValue, args) => {
const source = ctx.iterateDirect(thisValue)
const apply = applyCollectionCallback(ctx, args[0], method("some"))
return Effect.gen(function* () {
let counter = 0
while (true) {
const step = yield* source.next
if (step.done) return false
if (yield* guarded(source, apply([step.value, counter++]))) {
yield* source.close
return true
}
}
})
},
],
[
"every",
1,
(thisValue, args) => {
const source = ctx.iterateDirect(thisValue)
const apply = applyCollectionCallback(ctx, args[0], method("every"))
return Effect.gen(function* () {
let counter = 0
while (true) {
const step = yield* source.next
if (step.done) return true
if (!(yield* guarded(source, apply([step.value, counter++])))) {
yield* source.close
return false
}
}
})
},
],
[
"find",
1,
(thisValue, args) => {
const source = ctx.iterateDirect(thisValue)
const apply = applyCollectionCallback(ctx, args[0], method("find"))
return Effect.gen(function* () {
let counter = 0
while (true) {
const step = yield* source.next
if (step.done) return undefined
if (yield* guarded(source, apply([step.value, counter++]))) {
yield* source.close
return step.value
}
}
})
},
],
])
// Helpers and `Iterator.from` wrappers can be closed; collection iterators, as in JS, cannot.
methods(builtins, builtins.IteratorHelper, [
[
"return",
0,
(thisValue) =>
Effect.map(receiver(IteratorObj, thisValue, "Iterator.prototype.return").cursor.close, () =>
record(builtins.Object, { value: undefined, done: true }),
),
],
])
const iterator = constructor<R>(builtins, proto, {
name: "Iterator",
length: 0,
call: requiresNew("Iterator"),
construct: () =>
Effect.sync(() => {
throw typeError("Iterator is abstract; use Iterator.from(...) or a built-in iterator.")
}),
})
define(
iterator,
"from",
fn(builtins, "from", 1, (_, args) =>
Effect.gen(function* () {
if (args[0] instanceof Obj && hasPrototype(args[0], proto)) return args[0]
return new IteratorObj(builtins.IteratorHelper, yield* flattenable(args[0], "Iterator.from", true))
}),
),
hidden,
)
return iterator
}