@opencode/codemode 2.2.0 → 2.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/README.md +33 -4
  2. package/dist/codemode.d.ts +9 -7
  3. package/dist/codemode.js +1 -1
  4. package/dist/data.d.ts +5 -4
  5. package/dist/data.js +7 -4
  6. package/dist/extension.d.ts +17 -4
  7. package/dist/extension.js +8 -0
  8. package/dist/interpreter/callback.d.ts +10 -10
  9. package/dist/interpreter/callback.js +43 -31
  10. package/dist/interpreter/errors.d.ts +1 -1
  11. package/dist/interpreter/errors.js +12 -15
  12. package/dist/interpreter/execute.js +59 -29
  13. package/dist/interpreter/extensions.d.ts +2 -2
  14. package/dist/interpreter/extensions.js +46 -18
  15. package/dist/interpreter/generators.js +162 -19
  16. package/dist/interpreter/globals.js +12 -9
  17. package/dist/interpreter/interpreter.d.ts +20 -13
  18. package/dist/interpreter/interpreter.js +1343 -1149
  19. package/dist/interpreter/intrinsics.js +1 -2
  20. package/dist/interpreter/model.d.ts +4 -7
  21. package/dist/interpreter/model.js +1 -11
  22. package/dist/interpreter/native.d.ts +7 -8
  23. package/dist/interpreter/native.js +4 -10
  24. package/dist/interpreter/objects.d.ts +47 -21
  25. package/dist/interpreter/objects.js +33 -12
  26. package/dist/interpreter/promises.d.ts +15 -53
  27. package/dist/interpreter/promises.js +226 -401
  28. package/dist/interpreter/runner.d.ts +188 -0
  29. package/dist/interpreter/runner.js +492 -0
  30. package/dist/stdlib/array.d.ts +3 -3
  31. package/dist/stdlib/array.js +106 -102
  32. package/dist/stdlib/bytes.d.ts +3 -3
  33. package/dist/stdlib/bytes.js +46 -41
  34. package/dist/stdlib/collections.d.ts +5 -5
  35. package/dist/stdlib/collections.js +160 -165
  36. package/dist/stdlib/date.d.ts +1 -1
  37. package/dist/stdlib/date.js +28 -20
  38. package/dist/stdlib/headers.d.ts +1 -1
  39. package/dist/stdlib/headers.js +14 -19
  40. package/dist/stdlib/iterator.d.ts +1 -1
  41. package/dist/stdlib/iterator.js +140 -122
  42. package/dist/stdlib/json.js +9 -12
  43. package/dist/stdlib/math.js +10 -10
  44. package/dist/stdlib/number.d.ts +2 -2
  45. package/dist/stdlib/object.d.ts +1 -1
  46. package/dist/stdlib/object.js +21 -22
  47. package/dist/stdlib/regexp.d.ts +1 -1
  48. package/dist/stdlib/regexp.js +2 -3
  49. package/dist/stdlib/string.d.ts +1 -1
  50. package/dist/stdlib/string.js +18 -20
  51. package/dist/stdlib/url.d.ts +5 -5
  52. package/dist/stdlib/url.js +32 -33
  53. package/dist/stdlib/value.d.ts +2 -2
  54. package/dist/stdlib/web.d.ts +2 -2
  55. package/dist/tool-schema.js +7 -3
  56. package/package.json +2 -2
@@ -1,15 +1,16 @@
1
- import { Cause, Deferred, Effect, Exit } from "effect";
2
1
  import { fromJson, toBoundary } from "../data.js";
3
2
  import { ToolReference } from "../tool-runtime.js";
4
- import { AsyncIteratorSymbol, CallSite, GeneratorReturn, IteratorSymbol, OptionalShortCircuit, invalidData, Throw, rangeError, typeError, unsupportedSyntax, } from "./model.js";
3
+ import { AsyncIteratorSymbol, GeneratorReturn, IteratorSymbol, OptionalShortCircuit, invalidData, Throw, rangeError, typeError, unsupportedSyntax, } from "./model.js";
5
4
  import { checkStringLength } from "./limits.js";
6
5
  import { locate, materialize } from "./errors.js";
7
6
  import { primitivePrototype } from "./intrinsics.js";
8
7
  import { globals } from "./globals.js";
9
- import { assign, Callable, define, frozen, get, hostCursor, IteratorObj, has, hidden, hasPrototype, keys, Native, parseArrayIndex, Arguments, Arr, Fn, GeneratorObj, Obj, PromiseObj, record, remove, set, coerceToNumber, coerceToString, } from "./objects.js";
8
+ import { assign, Callable, define, frozen, get, hostCursor, IteratorObj, has, hasOwn, hidden, hasPrototype, keys, Native, parseArrayIndex, Arguments, Arr, Fn, GeneratorObj, Obj, PromiseObj, iteratorResult, remove, set, coerceToNumber, coerceToString, } from "./objects.js";
10
9
  import { preserveConsumerError, toPrimitive } from "./callback.js";
11
- import { Pending, resolvePromise, resolvePromiseValue } from "./promises.js";
10
+ import { AsyncBoundary, Await, Call, Interruption, isEval, MAX_CALL_DEPTH, Runner, Slice, Task, Yield, normal, } from "./runner.js";
12
11
  import { describeValue, isOpaque, rejectCircularInsertion, typeofValue } from "./references.js";
12
+ import { fn } from "./native.js";
13
+ import { capability, promiseLike } from "./promises.js";
13
14
  import { ScopeStack } from "./scope.js";
14
15
  import { constructRegExp } from "../stdlib/regexp.js";
15
16
  import { enumerableSource } from "../stdlib/object.js";
@@ -134,6 +135,24 @@ const usesArguments = (fn) => {
134
135
  argumentsUse.set(fn.body, found);
135
136
  return found;
136
137
  };
138
+ // Whether evaluating a node can create a function, which could capture a loop's per-iteration bindings.
139
+ const closures = new WeakMap();
140
+ const createsClosure = (node) => {
141
+ const cached = closures.get(node);
142
+ if (cached !== undefined)
143
+ return cached;
144
+ const found = (function visit(item) {
145
+ if (item === null || typeof item !== "object")
146
+ return false;
147
+ if (item.type === "FunctionExpression" ||
148
+ item.type === "ArrowFunctionExpression" ||
149
+ item.type === "FunctionDeclaration")
150
+ return true;
151
+ return Object.values(item).some((child) => Array.isArray(child) ? child.some((entry) => visit(entry)) : visit(child));
152
+ })(node);
153
+ closures.set(node, found);
154
+ return found;
155
+ };
137
156
  // `var` names declared anywhere in a function body except inside nested functions, which own theirs.
138
157
  // Memoized per body: a function's var names never change, and hoisting runs on every call.
139
158
  const varNames = new WeakMap();
@@ -197,10 +216,37 @@ const loopDeclaration = (left, statement) => {
197
216
  lexical: kind !== "var",
198
217
  };
199
218
  };
200
- /** One program execution: the tool bridge, promise scheduler, captured logs, and the global scope built once. */
219
+ const none = { kind: "none" };
220
+ /** Marks an operand a fast path has not evaluated yet, since `undefined` is a value. */
221
+ const unevaluated = Symbol("codemode.unevaluated");
222
+ // Parameter lists of plain names bind without evaluating anything, so a call needs no binding work.
223
+ const simpleParameters = new WeakMap();
224
+ const isSimple = (parameters) => {
225
+ const cached = simpleParameters.get(parameters);
226
+ if (cached !== undefined)
227
+ return cached;
228
+ const simple = parameters.every((parameter) => parameter.type === "Identifier");
229
+ simpleParameters.set(parameters, simple);
230
+ return simple;
231
+ };
232
+ // A block that declares nothing lexically needs no scope of its own.
233
+ const blockScopes = new WeakMap();
234
+ const declaresLexically = (statements) => {
235
+ const cached = blockScopes.get(statements);
236
+ if (cached !== undefined)
237
+ return cached;
238
+ const declares = statements.some((statement) => statement.type === "FunctionDeclaration" ||
239
+ (statement.type === "VariableDeclaration" && statement.kind !== "var"));
240
+ blockScopes.set(statements, declares);
241
+ return declares;
242
+ };
243
+ const isAbrupt = (result) => result.kind === "return" || result.kind === "break" || result.kind === "continue";
244
+ // A thenable the program's implicit async body adopts before copy-out.
245
+ const isThenable = (value) => value instanceof PromiseObj || (value instanceof Obj && typeofValue(get(value, "then")) === "function");
246
+ /** One program execution: the tool bridge, job queue, captured logs, and the global scope built once. */
201
247
  export class Interpreter {
202
248
  tools;
203
- pending;
249
+ runner;
204
250
  builtins;
205
251
  logs;
206
252
  /** Template objects by site: a tag sees the same `strings` array every time its literal is evaluated, as in JS. */
@@ -208,9 +254,9 @@ export class Interpreter {
208
254
  root;
209
255
  constructor(options) {
210
256
  this.tools = options.tools;
211
- this.pending = options.pending;
212
257
  this.builtins = options.builtins;
213
258
  this.logs = options.logs ?? [];
259
+ this.runner = new Runner(this, options.services);
214
260
  // Program code has no receiver: top-level `this` is undefined, as in a module.
215
261
  const globalScope = new Map([["this", { mutable: false, value: undefined }]]);
216
262
  // Calling back into the program never reads frame state, so any frame serves; the root is always alive.
@@ -219,14 +265,17 @@ export class Interpreter {
219
265
  globalScope.set(name, { mutable: false, value });
220
266
  }
221
267
  }
222
- run(program) {
223
- return this.root.run(program);
268
+ /** The program's body, as the first job: its completion value, copied out for the host. */
269
+ *main(program) {
270
+ return yield* toBoundary(this, yield* this.root.run(program));
224
271
  }
225
- call(callable, thisValue, args) {
226
- return this.root.call(callable, thisValue, args);
272
+ /** Calls into the program; a built-in passes its own call site so failures inside are located there. */
273
+ call(callable, thisValue, args, site) {
274
+ return this.root.call(callable, thisValue, args, site);
227
275
  }
228
- await(promise) {
229
- return this.root.await(promise);
276
+ /** Await: suspends the innermost async body until `value` settles. */
277
+ *awaitValue(value, node) {
278
+ return (yield new Await(value, node));
230
279
  }
231
280
  iterate(value) {
232
281
  return this.root.iterate(value);
@@ -234,45 +283,43 @@ export class Interpreter {
234
283
  iterateDirect(value) {
235
284
  return this.root.iterateDirect(value);
236
285
  }
237
- /** Runs one host tool: arguments cross as JSON and the result comes back as program values. */
238
- tool(run, args) {
239
- const ctx = this;
240
- return Effect.gen(function* () {
241
- const json = yield* Effect.forEach(args, (arg) => toBoundary(ctx, arg));
242
- return fromJson(ctx, yield* run(json));
243
- });
286
+ /** Runs one host call to completion before any other job: arguments cross as JSON, the result comes back as values. */
287
+ *tool(run, args) {
288
+ const json = [];
289
+ for (const arg of args)
290
+ json.push(yield* toBoundary(this, arg));
291
+ return fromJson(this, (yield this.runner.blocking(run(json))));
292
+ }
293
+ /** The built-in search: its result is usable directly, and can also be awaited or chained like a Promise. */
294
+ *search(args) {
295
+ return promiseLike(this, yield* this.tool(this.tools.search, args));
244
296
  }
245
297
  }
246
- const MAX_CALL_DEPTH = 10_000;
247
298
  /** One activation: the top-level program or a single function call, evaluating against its own scope chain. */
248
299
  class Frame {
249
300
  ctx;
250
301
  scopes;
251
- depth;
252
- generatorState;
302
+ /** The body of a generator function, where `yield` suspends. */
303
+ generator = false;
253
304
  generatorAsync = false;
254
- constructor(ctx, scopes,
255
- /** Nested call depth; resets when an await resumes, since the continuation runs from the job queue. */
256
- depth = 0) {
305
+ constructor(ctx, scopes) {
257
306
  this.ctx = ctx;
258
307
  this.scopes = scopes;
259
- this.depth = depth;
260
308
  }
261
- run(program) {
262
- const self = this;
309
+ *run(program) {
263
310
  // Keep top-level declarations separate so they can shadow builtins.
264
311
  this.scopes.push();
265
- return Effect.gen(function* () {
266
- self.predeclareLexical(program.body);
267
- self.hoistFunctions(program.body);
268
- self.hoistVars(program.body);
312
+ try {
313
+ this.predeclareLexical(program.body);
314
+ this.hoistFunctions(program.body);
315
+ this.hoistVars(program.body);
269
316
  let value = undefined;
270
317
  for (const [index, statement] of program.body.entries()) {
271
318
  if (index === program.body.length - 1 && statement.type === "ExpressionStatement") {
272
- value = yield* self.evaluateExpression(statement.expression);
319
+ value = yield* this.evaluateExpression(statement.expression);
273
320
  break;
274
321
  }
275
- const result = yield* self.evaluateStatement(statement);
322
+ const result = yield* this.evaluateStatement(statement);
276
323
  if (result.kind === "return") {
277
324
  value = result.value;
278
325
  break;
@@ -282,40 +329,51 @@ class Frame {
282
329
  }
283
330
  }
284
331
  // The implicit async body adopts returned promises before copy-out.
285
- value = yield* resolvePromiseValue(self.ctx, value);
286
- return value;
287
- }).pipe(Effect.ensuring(Effect.sync(() => self.scopes.pop())));
288
- }
289
- // Fork at the call site so admission and hooks occur when the call is made. Arguments cross on the caller's turn,
290
- // since `toJSON` is program code; the host call runs without it, so tool calls stay concurrent.
291
- createToolCallPromise(path, args) {
292
- const pending = this.ctx.pending;
293
- return pending.create(this.ctx.tool((json) => pending.turn.leave(this.ctx.tools.execute(path, json)), args));
294
- }
295
- // Fiber exits make settlement idempotent; yielding prevents inline continuation.
296
- await(promise) {
297
- const pending = this.ctx.pending;
298
- return Effect.suspend(() => {
299
- pending.markObserved(promise);
300
- return Effect.flatten(pending.turn.suspend(Effect.flatMap(pending.await(promise), (exit) => Effect.as(Effect.yieldNow, exit))));
301
- });
332
+ return isThenable(value) ? yield* this.awaitValue(value) : value;
333
+ }
334
+ finally {
335
+ this.scopes.pop();
336
+ }
337
+ }
338
+ // The call returns its promise at once. Arguments cross on the caller's stack, since `toJSON` is program code, and a
339
+ // promise argument is awaited first; the host call starts once they have crossed, so admission and hooks happen at
340
+ // the call site, and runs concurrently with the program.
341
+ *createToolCallPromise(path, args, site) {
342
+ const ctx = this.ctx;
343
+ const runner = ctx.runner;
344
+ const promise = runner.newPromise();
345
+ const resolving = runner.resolving(promise);
346
+ const body = function* () {
347
+ const json = [];
348
+ for (const arg of args)
349
+ json.push(yield* toBoundary(ctx, arg));
350
+ runner.host(ctx.tools.execute(path, json), (settled) => settled.ok
351
+ ? resolving.resolve(fromJson(ctx, settled.value))
352
+ : resolving.reject(settled.error), site);
353
+ };
354
+ return (yield new Call(body(), new AsyncBoundary((completion) => {
355
+ if (!completion.ok)
356
+ resolving.reject(completion.error);
357
+ }, promise)));
302
358
  }
303
- // End this job; the program continues in a later one, after the jobs already waiting.
304
- nextJob() {
305
- return this.ctx.pending.turn.suspend(Effect.yieldNow);
359
+ awaitValue(value, node) {
360
+ return this.ctx.awaitValue(value, node);
306
361
  }
307
- evaluateStatement(node) {
362
+ *evaluateStatement(node) {
363
+ const result = this.execute(node);
364
+ return isEval(result) ? yield* result : result;
365
+ }
366
+ // Like `evaluate`: statements that cannot run program code complete without a generator.
367
+ execute(node) {
308
368
  switch (node.type) {
309
- case "ExpressionStatement":
310
- return Effect.as(this.evaluateExpression(node.expression), { kind: "none" });
311
- case "VariableDeclaration":
312
- return Effect.map(this.evaluateVariableDeclaration(node), () => ({ kind: "none" }));
313
- case "ReturnStatement": {
314
- const argumentNode = node.argument;
315
- return argumentNode
316
- ? Effect.map(this.evaluateExpression(argumentNode), (value) => ({ kind: "return", value }))
317
- : Effect.succeed({ kind: "return", value: undefined });
369
+ case "ExpressionStatement": {
370
+ const result = this.evaluate(node.expression);
371
+ return isEval(result) ? this.finishExpressionStatement(result) : none;
318
372
  }
373
+ case "VariableDeclaration":
374
+ return this.evaluateVariableStatement(node);
375
+ case "ReturnStatement":
376
+ return this.evaluateReturnStatement(node);
319
377
  case "BlockStatement":
320
378
  return this.evaluateBlock(node);
321
379
  case "IfStatement":
@@ -335,36 +393,59 @@ class Frame {
335
393
  case "ForInStatement":
336
394
  return this.evaluateForInStatement(node);
337
395
  case "BreakStatement":
338
- return Effect.succeed(this.evaluateBreakStatement(node));
396
+ return this.evaluateBreakStatement(node);
339
397
  case "ContinueStatement":
340
- return Effect.succeed(this.evaluateContinueStatement(node));
398
+ return this.evaluateContinueStatement(node);
341
399
  case "ThrowStatement":
342
400
  return this.evaluateThrowStatement(node);
343
401
  case "TryStatement":
344
402
  return this.evaluateTryStatement(node);
345
403
  case "EmptyStatement":
346
- return Effect.succeed({ kind: "none" });
404
+ return none;
347
405
  case "FunctionDeclaration":
348
- return Effect.succeed({ kind: "none" });
406
+ return none;
349
407
  default:
350
408
  throw unsupportedSyntax(node.type, node);
351
409
  }
352
410
  }
353
- evaluateBlock(node) {
354
- this.scopes.push();
355
- const self = this;
356
- return Effect.gen(function* () {
357
- const body = node.body;
358
- self.predeclareLexical(body);
359
- self.hoistFunctions(body);
411
+ *finishExpressionStatement(work) {
412
+ yield* work;
413
+ return none;
414
+ }
415
+ *evaluateVariableStatement(node) {
416
+ yield* this.evaluateVariableDeclaration(node);
417
+ return none;
418
+ }
419
+ *evaluateReturnStatement(node) {
420
+ const argumentNode = node.argument;
421
+ if (!argumentNode)
422
+ return { kind: "return", value: undefined };
423
+ const evaluated = this.evaluate(argumentNode);
424
+ const value = isEval(evaluated) ? yield* evaluated : evaluated;
425
+ // An async generator awaits what it returns, as it awaits what it yields.
426
+ return { kind: "return", value: this.generatorAsync ? yield* this.awaitValue(value, node) : value };
427
+ }
428
+ *evaluateBlock(node) {
429
+ const body = node.body;
430
+ const scoped = declaresLexically(body);
431
+ if (scoped) {
432
+ this.scopes.push();
433
+ this.predeclareLexical(body);
434
+ this.hoistFunctions(body);
435
+ }
436
+ try {
360
437
  for (const statement of body) {
361
- const result = yield* self.evaluateStatement(statement);
362
- if (result.kind !== "none") {
438
+ const executed = this.execute(statement);
439
+ const result = isEval(executed) ? yield* executed : executed;
440
+ if (result.kind !== "none")
363
441
  return result;
364
- }
365
442
  }
366
- return { kind: "none" };
367
- }).pipe(Effect.ensuring(Effect.sync(() => self.scopes.pop())));
443
+ return none;
444
+ }
445
+ finally {
446
+ if (scoped)
447
+ this.scopes.pop();
448
+ }
368
449
  }
369
450
  createFunction(node, name = node.type === "ArrowFunctionExpression" ? "" : (node.id?.name ?? "")) {
370
451
  const builtins = this.ctx.builtins;
@@ -379,11 +460,11 @@ class Frame {
379
460
  return fn;
380
461
  }
381
462
  // NamedEvaluation: an anonymous function definition takes the name of what it is assigned to.
382
- evaluateNamed(node, name) {
463
+ *evaluateNamed(node, name) {
383
464
  if (node.type === "ArrowFunctionExpression" || (node.type === "FunctionExpression" && !node.id)) {
384
- return Effect.sync(() => this.createFunction(node, name));
465
+ return this.createFunction(node, name);
385
466
  }
386
- return this.evaluateExpression(node);
467
+ return yield* this.evaluateExpression(node);
387
468
  }
388
469
  // Repeated `function` declarations and `var` clashes are legal: the last declaration wins.
389
470
  hoistFunctions(statements) {
@@ -424,205 +505,337 @@ class Frame {
424
505
  for (const name of collectPatternNames(pattern))
425
506
  this.scopes.reserve(name, mutable, node);
426
507
  }
427
- evaluateIfStatement(node) {
428
- return Effect.flatMap(this.evaluateExpression(node.test), (test) => test
429
- ? this.evaluateStatement(node.consequent)
430
- : node.alternate
431
- ? this.evaluateStatement(node.alternate)
432
- : Effect.succeed({ kind: "none" }));
508
+ *evaluateIfStatement(node) {
509
+ const test = this.evaluate(node.test);
510
+ const branch = (isEval(test) ? yield* test : test) ? node.consequent : node.alternate;
511
+ if (!branch)
512
+ return none;
513
+ const result = this.execute(branch);
514
+ return isEval(result) ? yield* result : result;
433
515
  }
434
- evaluateSwitchStatement(node) {
435
- const self = this;
436
- return Effect.gen(function* () {
437
- const discriminant = yield* self.evaluateExpression(node.discriminant);
438
- self.scopes.push();
439
- return yield* Effect.gen(function* () {
440
- const cases = node.cases;
441
- const statements = cases.flatMap((branch) => branch.consequent);
442
- self.predeclareLexical(statements);
443
- self.hoistFunctions(statements);
444
- let defaultIndex;
445
- let selected;
446
- for (const [index, branch] of cases.entries()) {
447
- const test = branch.test;
448
- if (!test) {
449
- defaultIndex = index;
450
- continue;
451
- }
452
- if ((yield* self.evaluateExpression(test)) === discriminant) {
453
- selected = index;
454
- break;
455
- }
516
+ *evaluateSwitchStatement(node) {
517
+ const discriminant = yield* this.evaluateExpression(node.discriminant);
518
+ this.scopes.push();
519
+ try {
520
+ const cases = node.cases;
521
+ const statements = cases.flatMap((branch) => branch.consequent);
522
+ this.predeclareLexical(statements);
523
+ this.hoistFunctions(statements);
524
+ let defaultIndex;
525
+ let selected;
526
+ for (const [index, branch] of cases.entries()) {
527
+ const test = branch.test;
528
+ if (!test) {
529
+ defaultIndex = index;
530
+ continue;
456
531
  }
457
- const start = selected ?? defaultIndex;
458
- if (start === undefined)
459
- return { kind: "none" };
460
- for (let index = start; index < cases.length; index += 1) {
461
- for (const statement of cases[index].consequent) {
462
- const result = yield* self.evaluateStatement(statement);
463
- if (result.kind === "break") {
464
- if (result.label === undefined)
465
- return { kind: "none" };
466
- return result;
467
- }
468
- if (result.kind === "return" || result.kind === "continue")
469
- return result;
532
+ if ((yield* this.evaluateExpression(test)) === discriminant) {
533
+ selected = index;
534
+ break;
535
+ }
536
+ }
537
+ const start = selected ?? defaultIndex;
538
+ if (start === undefined)
539
+ return none;
540
+ for (let index = start; index < cases.length; index += 1) {
541
+ for (const statement of cases[index].consequent) {
542
+ const result = yield* this.evaluateStatement(statement);
543
+ if (result.kind === "break") {
544
+ if (result.label === undefined)
545
+ return none;
546
+ return result;
470
547
  }
548
+ if (result.kind === "return" || result.kind === "continue")
549
+ return result;
471
550
  }
472
- return { kind: "none" };
473
- }).pipe(Effect.ensuring(Effect.sync(() => self.scopes.pop())));
474
- });
475
- }
476
- evaluateWhileStatement(node, labels) {
477
- const self = this;
478
- return Effect.gen(function* () {
479
- while (yield* self.evaluateExpression(node.test)) {
480
- const exit = loopExit(yield* self.evaluateStatement(node.body), labels);
481
- if (exit !== undefined)
482
- return exit;
483
551
  }
484
- return { kind: "none" };
485
- });
486
- }
487
- evaluateDoWhileStatement(node, labels) {
488
- const self = this;
489
- return Effect.gen(function* () {
490
- do {
491
- const exit = loopExit(yield* self.evaluateStatement(node.body), labels);
492
- if (exit !== undefined)
493
- return exit;
494
- } while (yield* self.evaluateExpression(node.test));
495
- return { kind: "none" };
496
- });
552
+ return none;
553
+ }
554
+ finally {
555
+ this.scopes.pop();
556
+ }
497
557
  }
498
- evaluateForStatement(node, labels) {
558
+ *evaluateWhileStatement(node, labels) {
559
+ const runner = this.ctx.runner;
560
+ while (true) {
561
+ const test = this.evaluate(node.test);
562
+ if (!(isEval(test) ? yield* test : test))
563
+ break;
564
+ const executed = this.execute(node.body);
565
+ const exit = loopExit(isEval(executed) ? yield* executed : executed, labels);
566
+ if (exit !== undefined)
567
+ return exit;
568
+ if (runner.tick())
569
+ yield Slice;
570
+ }
571
+ return none;
572
+ }
573
+ *evaluateDoWhileStatement(node, labels) {
574
+ const runner = this.ctx.runner;
575
+ do {
576
+ const exit = loopExit(yield* this.evaluateStatement(node.body), labels);
577
+ if (exit !== undefined)
578
+ return exit;
579
+ if (runner.tick())
580
+ yield Slice;
581
+ } while (yield* this.evaluateExpression(node.test));
582
+ return none;
583
+ }
584
+ *evaluateForStatement(node, labels) {
585
+ const runner = this.ctx.runner;
499
586
  this.scopes.push();
500
- const self = this;
501
- return Effect.gen(function* () {
587
+ try {
502
588
  const initNode = node.init;
503
589
  const testNode = node.test;
504
590
  const updateNode = node.update;
505
591
  if (initNode?.type === "VariableDeclaration" && initNode.kind !== "var") {
506
- self.predeclareLexical([initNode]);
592
+ this.predeclareLexical([initNode]);
507
593
  }
508
594
  if (initNode) {
509
595
  if (initNode.type === "VariableDeclaration") {
510
- yield* self.evaluateVariableDeclaration(initNode);
596
+ yield* this.evaluateVariableDeclaration(initNode);
511
597
  }
512
598
  else {
513
- yield* self.evaluateExpression(initNode);
599
+ yield* this.evaluateExpression(initNode);
514
600
  }
515
601
  }
516
- const perIterationBindings = initNode?.type === "VariableDeclaration" && initNode.kind !== "var"
517
- ? Array.from(self.scopes.current().keys())
602
+ // Each iteration gets fresh copies of the loop's `let` bindings, but only closures can tell them apart.
603
+ const perIterationBindings = initNode?.type === "VariableDeclaration" &&
604
+ initNode.kind !== "var" &&
605
+ [node.init, node.test, node.update, node.body].some((part) => part && createsClosure(part))
606
+ ? Array.from(this.scopes.current().keys())
518
607
  : [];
519
608
  const nextIteration = () => {
520
609
  if (perIterationBindings.length === 0)
521
610
  return;
522
- const current = self.scopes.current();
523
- self.scopes.pop();
524
- self.scopes.push(new Map(perIterationBindings.map((name) => [name, { ...current.get(name) }])));
611
+ const current = this.scopes.current();
612
+ this.scopes.pop();
613
+ this.scopes.push(new Map(perIterationBindings.map((name) => [name, { ...current.get(name) }])));
525
614
  };
526
615
  nextIteration();
527
- while (testNode ? yield* self.evaluateExpression(testNode) : true) {
528
- const exit = loopExit(yield* self.evaluateStatement(node.body), labels);
616
+ while (true) {
617
+ if (testNode) {
618
+ const test = this.evaluate(testNode);
619
+ if (!(isEval(test) ? yield* test : test))
620
+ break;
621
+ }
622
+ const executed = this.execute(node.body);
623
+ const exit = loopExit(isEval(executed) ? yield* executed : executed, labels);
529
624
  if (exit !== undefined)
530
625
  return exit;
531
626
  nextIteration();
532
627
  if (updateNode) {
533
- yield* self.evaluateExpression(updateNode);
628
+ const update = this.evaluate(updateNode);
629
+ if (isEval(update))
630
+ yield* update;
534
631
  }
632
+ if (runner.tick())
633
+ yield Slice;
535
634
  }
536
- return { kind: "none" };
537
- }).pipe(Effect.ensuring(Effect.sync(() => self.scopes.pop())));
635
+ return none;
636
+ }
637
+ finally {
638
+ this.scopes.pop();
639
+ }
538
640
  }
539
- evaluateForOfStatement(node, labels) {
641
+ *evaluateForOfStatement(node, labels) {
642
+ const runner = this.ctx.runner;
540
643
  const awaiting = node.await;
541
644
  const left = node.left;
542
645
  const declared = loopDeclaration(left, "for...of");
543
646
  if (declared?.lexical)
544
647
  this.scopes.push();
545
- const self = this;
546
- return Effect.gen(function* () {
648
+ try {
547
649
  if (declared?.lexical)
548
- self.predeclarePattern(declared.pattern, declared.mutable, left);
549
- const right = yield* self.evaluateExpression(node.right);
550
- const cursor = self.builtinCursor(right);
551
- const iterator = cursor === undefined ? yield* self.customIterator(right, node, awaiting) : undefined;
552
- if (iterator === undefined && cursor === undefined) {
650
+ this.predeclarePattern(declared.pattern, declared.mutable, left);
651
+ const right = yield* this.evaluateExpression(node.right);
652
+ const builtin = this.builtinCursor(right);
653
+ const custom = builtin === undefined ? yield* this.customIterator(right, node, awaiting) : undefined;
654
+ if (custom === undefined && builtin === undefined) {
553
655
  throw invalidData(`${awaiting ? "for await...of" : "for...of"} requires an iterable value, received ${describeValue(right)}.`, node);
554
656
  }
555
- const close = () => iterator
556
- ? self.closeIterator(iterator, node, awaiting)
557
- : awaiting
558
- ? Effect.andThen(cursor?.close ?? Effect.void, self.nextJob())
559
- : (cursor?.close ?? Effect.void);
657
+ // `for await` over a synchronous iterator drives it through CreateAsyncFromSyncIterator, as JS does.
658
+ const iterator = awaiting && !custom?.asynchronous ? this.asyncFromSync(builtin, custom, node) : custom;
659
+ const cursor = iterator === undefined ? builtin : undefined;
660
+ const self = this;
661
+ const close = function* () {
662
+ if (iterator)
663
+ return yield* self.closeIterator(iterator, node);
664
+ yield* cursor.close();
665
+ };
560
666
  if (left.type === "RestElement" || left.type === "AssignmentPattern") {
561
667
  throw typeError("Unsupported for...of binding.", left);
562
668
  }
563
669
  const assignment = left.type === "VariableDeclaration" ? undefined : left;
564
- const evaluateBody = (value) => Effect.gen(function* () {
565
- if (declared?.lexical) {
566
- self.scopes.push();
567
- self.predeclarePattern(declared.pattern, declared.mutable, left);
568
- yield* self.declarePattern(declared.pattern, value, declared.mutable, left, true);
569
- }
570
- else if (declared) {
571
- yield* self.assignPattern(declared.pattern, value, left);
572
- }
573
- else if (assignment) {
574
- yield* self.assignPattern(assignment, value, left);
575
- }
576
- return yield* self.evaluateStatement(node.body);
577
- }).pipe(Effect.ensuring(Effect.sync(() => {
578
- if (declared?.lexical)
579
- self.scopes.pop();
580
- })));
581
- while (true) {
582
- const current = iterator
583
- ? yield* self.nextIteratorResult(iterator, node, awaiting)
584
- : yield* cursor?.next ?? Effect.die(typeError("Iterator is unavailable.", node));
585
- const step = cursor && awaiting ? { done: current.done, value: yield* self.awaitValue(current.value) } : current;
586
- if (step.done)
587
- return { kind: "none" };
588
- const bodyExit = yield* Effect.exit(evaluateBody(step.value));
589
- if (!Exit.isSuccess(bodyExit)) {
590
- // Process interruption must remain prompt; user cleanup cannot extend a timeout.
591
- if (Cause.hasInterruptsOnly(bodyExit.cause))
592
- return yield* Effect.failCause(bodyExit.cause);
593
- return yield* preserveConsumerError(close(), Effect.failCause(bodyExit.cause));
594
- }
595
- const exit = loopExit(bodyExit.value, labels);
596
- if (exit !== undefined) {
597
- yield* close();
598
- return exit;
670
+ // Each iteration gets a fresh binding, but only a closure in the body can tell; without one, a single
671
+ // `for (const x of ...)` binding is reused.
672
+ const reused = declared?.lexical && declared.pattern.type === "Identifier" && !createsClosure(node.body)
673
+ ? { mutable: declared.mutable, value: undefined, initialized: false }
674
+ : undefined;
675
+ if (reused !== undefined)
676
+ this.scopes.push(new Map([[declared.pattern.name, reused]]));
677
+ try {
678
+ while (true) {
679
+ const step = iterator ? yield* this.nextIteratorResult(iterator, node) : yield* cursor.next();
680
+ if (step.done)
681
+ return none;
682
+ let result;
683
+ try {
684
+ if (reused !== undefined) {
685
+ reused.value = step.value;
686
+ reused.initialized = true;
687
+ const executed = this.execute(node.body);
688
+ result = isEval(executed) ? yield* executed : executed;
689
+ }
690
+ else if (declared?.lexical) {
691
+ this.scopes.push();
692
+ try {
693
+ this.predeclarePattern(declared.pattern, declared.mutable, left);
694
+ yield* this.declarePattern(declared.pattern, step.value, declared.mutable, left, true);
695
+ result = yield* this.evaluateStatement(node.body);
696
+ }
697
+ finally {
698
+ this.scopes.pop();
699
+ }
700
+ }
701
+ else {
702
+ if (declared)
703
+ yield* this.assignPattern(declared.pattern, step.value, left);
704
+ else if (assignment)
705
+ yield* this.assignPattern(assignment, step.value, left);
706
+ result = yield* this.evaluateStatement(node.body);
707
+ }
708
+ }
709
+ catch (error) {
710
+ return yield* preserveConsumerError(close, thrower(error));
711
+ }
712
+ const exit = loopExit(result, labels);
713
+ if (exit !== undefined) {
714
+ yield* close();
715
+ return exit;
716
+ }
717
+ if (runner.tick())
718
+ yield Slice;
599
719
  }
600
720
  }
601
- }).pipe(Effect.ensuring(Effect.sync(() => {
721
+ finally {
722
+ if (reused !== undefined)
723
+ this.scopes.pop();
724
+ }
725
+ }
726
+ finally {
602
727
  if (declared?.lexical)
603
- self.scopes.pop();
604
- })));
605
- }
606
- awaitValue(value) {
607
- return Effect.flatMap(resolvePromise(this.ctx, value), (promise) => Effect.ensuring(this.await(promise), Effect.sync(() => (this.depth = 0))));
728
+ this.scopes.pop();
729
+ }
608
730
  }
609
- awaitAsyncFromSyncValue(iterator, value, node, closeOnRejection) {
731
+ // CreateAsyncFromSyncIterator: an async iterator over a synchronous one. Each `next()` promise settles a job after
732
+ // the value does, and a rejected value closes the synchronous iterator first; `return()` calls the synchronous
733
+ // iterator's own `return`, or settles at once when it has none.
734
+ asyncFromSync(builtin, custom, node) {
735
+ const ctx = this.ctx;
736
+ const runner = ctx.runner;
737
+ const builtins = ctx.builtins;
738
+ const result = (value, done) => iteratorResult(builtins.Object, value, done);
610
739
  const self = this;
611
- return Effect.gen(function* () {
612
- const settled = yield* Effect.exit(self.awaitValue(value));
613
- if (Exit.isSuccess(settled))
614
- return settled.value;
615
- if (closeOnRejection && !Cause.hasInterruptsOnly(settled.cause)) {
616
- yield* Effect.exit(self.closeIterator(iterator, node, false));
617
- }
618
- return yield* Effect.failCause(settled.cause);
740
+ // IteratorNext passes the value `next` received, when it received one.
741
+ const syncNext = function* (args) {
742
+ if (!custom)
743
+ return yield* builtin.next();
744
+ const object = self.requireIteratorObject(yield* self.call(custom.next, custom.iterator, args, node), "Iterator next() result", node);
745
+ return { done: Boolean(get(object, "done")), value: get(object, "value") };
746
+ };
747
+ // The synchronous iterator's `return`, looked up when it is needed; built-in collection iterators have none.
748
+ const syncReturn = () => (custom ? get(custom.iterator, "return") : undefined);
749
+ const settle = (step, closeOnRejection, made) => {
750
+ const rejected = (reason) => {
751
+ if (step.done || !closeOnRejection || reason instanceof Interruption)
752
+ return made.reject(reason);
753
+ const body = function* () {
754
+ try {
755
+ if (custom)
756
+ yield* self.closeIterator(custom, node);
757
+ else
758
+ yield* builtin.close();
759
+ }
760
+ catch {
761
+ // The rejection wins over a failing close.
762
+ }
763
+ made.reject(reason);
764
+ };
765
+ return { task: new Task([{ body: body(), boundary: undefined }]), input: normal(undefined) };
766
+ };
767
+ let wrapper;
768
+ try {
769
+ wrapper = runner.promiseResolve(step.value);
770
+ }
771
+ catch (error) {
772
+ const start = rejected(error);
773
+ if (start !== undefined)
774
+ runner.enqueue(() => start);
775
+ return;
776
+ }
777
+ runner.then(wrapper, (settled) => settled.ok ? made.resolve(result(settled.value, step.done)) : rejected(settled.error));
778
+ };
779
+ const next = fn(builtins, "next", 1, function* (_, args) {
780
+ const made = capability(ctx, node);
781
+ try {
782
+ settle(yield* syncNext(args), true, made);
783
+ }
784
+ catch (error) {
785
+ made.reject(error);
786
+ }
787
+ return made.promise;
788
+ });
789
+ const close = fn(builtins, "return", 1, function* (_, args) {
790
+ const made = capability(ctx, node);
791
+ try {
792
+ const method = syncReturn();
793
+ if (method === undefined || method === null) {
794
+ if (builtin !== undefined)
795
+ yield* builtin.close();
796
+ made.resolve(result(args[0], true));
797
+ return made.promise;
798
+ }
799
+ const returned = self.requireIteratorObject(yield* self.call(self.requireIteratorMethod(method, "Iterator return", node), custom.iterator, args, node), "Iterator return() result", node);
800
+ settle({ done: Boolean(get(returned, "done")), value: get(returned, "value") }, false, made);
801
+ }
802
+ catch (error) {
803
+ made.reject(error);
804
+ }
805
+ return made.promise;
806
+ });
807
+ const raise = fn(builtins, "throw", 1, function* (_, args) {
808
+ const made = capability(ctx, node);
809
+ try {
810
+ const method = custom ? get(custom.iterator, "throw") : undefined;
811
+ if (method === undefined || method === null) {
812
+ if (custom)
813
+ yield* self.closeIterator(custom, node);
814
+ else
815
+ yield* builtin.close();
816
+ made.reject(typeError("The delegated iterator does not provide a throw() method.", node));
817
+ return made.promise;
818
+ }
819
+ const thrown = self.requireIteratorObject(yield* self.call(self.requireIteratorMethod(method, "Iterator throw", node), custom.iterator, args, node), "Iterator throw() result", node);
820
+ settle({ done: Boolean(get(thrown, "done")), value: get(thrown, "value") }, true, made);
821
+ }
822
+ catch (error) {
823
+ made.reject(error);
824
+ }
825
+ return made.promise;
619
826
  });
827
+ const adapter = new Obj(builtins.Object);
828
+ define(adapter, "next", next, hidden);
829
+ define(adapter, "return", close, hidden);
830
+ define(adapter, "throw", raise, hidden);
831
+ return { iterator: adapter, next, asynchronous: true };
620
832
  }
621
- iterate(value, node) {
833
+ *iterate(value, node) {
622
834
  const cursor = this.builtinCursor(value);
623
835
  if (cursor !== undefined)
624
- return Effect.succeed(cursor);
625
- return Effect.map(this.customIterator(value, node, false), (iterator) => iterator === undefined ? undefined : this.customCursor(iterator, node));
836
+ return cursor;
837
+ const iterator = yield* this.customIterator(value, node, false);
838
+ return iterator === undefined ? undefined : this.customCursor(iterator, node);
626
839
  }
627
840
  /** GetIteratorDirect: drive an iterator by its own `next`, without asking for `[Symbol.iterator]`. */
628
841
  iterateDirect(value, node) {
@@ -639,12 +852,11 @@ class Frame {
639
852
  }
640
853
  customCursor(iterator, node) {
641
854
  return {
642
- next: this.nextIteratorResult(iterator, node, false),
643
- close: Effect.suspend(() => this.closeIterator(iterator, node, false)),
855
+ next: () => this.nextIteratorResult(iterator, node),
856
+ close: () => this.closeIterator(iterator, node),
644
857
  };
645
858
  }
646
859
  builtinCursor(value) {
647
- // Natives build their cursors without knowing R, like `lift` in native.ts.
648
860
  if (value instanceof IteratorObj)
649
861
  return value.cursor;
650
862
  const iterator = typeof value === "string"
@@ -654,80 +866,33 @@ class Frame {
654
866
  : undefined;
655
867
  return iterator === undefined ? undefined : hostCursor(iterator);
656
868
  }
657
- customIterator(value, node, allowAsync = true) {
869
+ *customIterator(value, node, allowAsync = true) {
658
870
  if (!(value instanceof Obj))
659
- return Effect.undefined;
871
+ return undefined;
660
872
  const asyncMethod = allowAsync ? get(value, AsyncIteratorSymbol) : undefined;
661
873
  const method = asyncMethod ?? get(value, IteratorSymbol);
662
874
  if (method === undefined || method === null)
663
- return Effect.undefined;
664
- const self = this;
665
- return Effect.map(this.call(this.requireIteratorMethod(method, "Iterator method", node), value, [], node), (iterator) => {
666
- const object = self.requireIteratorObject(iterator, "Iterator method result", node);
667
- return {
668
- iterator: object,
669
- next: self.requireIteratorMethod(get(object, "next"), "Iterator next", node),
670
- asynchronous: asyncMethod !== undefined && asyncMethod !== null,
671
- };
672
- });
875
+ return undefined;
876
+ const iterator = yield* this.call(this.requireIteratorMethod(method, "Iterator method", node), value, [], node);
877
+ const object = this.requireIteratorObject(iterator, "Iterator method result", node);
878
+ return {
879
+ iterator: object,
880
+ next: this.requireIteratorMethod(get(object, "next"), "Iterator next", node),
881
+ asynchronous: asyncMethod !== undefined && asyncMethod !== null,
882
+ };
673
883
  }
674
- nextIteratorResult(iterator, node, awaiting) {
675
- const self = this;
676
- return Effect.gen(function* () {
677
- if (iterator.asynchronous) {
678
- const object = self.requireIteratorObject(yield* self.awaitValue(yield* self.call(iterator.next, iterator.iterator, [], node)), "Iterator next() result", node);
679
- return { done: Boolean(get(object, "done")), value: get(object, "value") };
680
- }
681
- const called = yield* Effect.exit(self.call(iterator.next, iterator.iterator, [], node));
682
- if (!Exit.isSuccess(called)) {
683
- if (awaiting)
684
- yield* self.nextJob();
685
- return yield* Effect.failCause(called.cause);
686
- }
687
- const captured = yield* Effect.exit(Effect.sync(() => {
688
- const object = self.requireIteratorObject(called.value, "Iterator next() result", node);
689
- return { done: Boolean(get(object, "done")), value: get(object, "value") };
690
- }));
691
- if (!Exit.isSuccess(captured)) {
692
- if (awaiting)
693
- yield* self.nextJob();
694
- return yield* Effect.failCause(captured.cause);
695
- }
696
- return {
697
- done: captured.value.done,
698
- value: awaiting
699
- ? yield* self.awaitAsyncFromSyncValue(iterator, captured.value.value, node, !captured.value.done)
700
- : captured.value.value,
701
- };
702
- });
884
+ *nextIteratorResult(iterator, node) {
885
+ const called = yield* this.call(iterator.next, iterator.iterator, [], node);
886
+ const object = this.requireIteratorObject(iterator.asynchronous ? yield* this.awaitValue(called, node) : called, "Iterator next() result", node);
887
+ return { done: Boolean(get(object, "done")), value: get(object, "value") };
703
888
  }
704
- closeIterator(iterator, node, awaiting = true) {
889
+ *closeIterator(iterator, node) {
705
890
  const close = get(iterator.iterator, "return");
706
- if (close === undefined || close === null) {
707
- return iterator.asynchronous || !awaiting ? Effect.void : this.nextJob();
708
- }
709
- const self = this;
710
- return Effect.gen(function* () {
711
- const method = self.requireIteratorMethod(close, "Iterator return", node);
712
- if (iterator.asynchronous) {
713
- self.requireIteratorObject(yield* self.awaitValue(yield* self.call(method, iterator.iterator, [], node)), "Iterator return() result", node);
714
- return;
715
- }
716
- const called = yield* Effect.exit(self.call(method, iterator.iterator, [], node));
717
- if (!Exit.isSuccess(called)) {
718
- if (awaiting)
719
- yield* self.nextJob();
720
- return yield* Effect.failCause(called.cause);
721
- }
722
- const captured = yield* Effect.exit(Effect.sync(() => get(self.requireIteratorObject(called.value, "Iterator return() result", node), "value")));
723
- if (!Exit.isSuccess(captured)) {
724
- if (awaiting)
725
- yield* self.nextJob();
726
- return yield* Effect.failCause(captured.cause);
727
- }
728
- if (awaiting)
729
- yield* self.awaitValue(captured.value);
730
- });
891
+ if (close === undefined || close === null)
892
+ return;
893
+ const method = this.requireIteratorMethod(close, "Iterator return", node);
894
+ const called = yield* this.call(method, iterator.iterator, [], node);
895
+ this.requireIteratorObject(iterator.asynchronous ? yield* this.awaitValue(called, node) : called, "Iterator return() result", node);
731
896
  }
732
897
  requireIteratorObject(value, context, node) {
733
898
  if (value instanceof Obj)
@@ -739,56 +904,73 @@ class Frame {
739
904
  return value;
740
905
  throw typeError(`${context} must be a function.`, node);
741
906
  }
742
- // for...in over null/undefined iterates nothing, like JS.
907
+ // for...in over null/undefined iterates nothing, like JS. After the own keys come each prototype's enumerable
908
+ // string keys, skipping any key a nearer level has, even as a non-enumerable property.
743
909
  enumerableKeys(value, node) {
744
910
  if (value instanceof ToolReference)
745
911
  return [...this.ctx.tools.keys(value.path)];
746
912
  if (value === null || value === undefined)
747
913
  return [];
748
- return keys(enumerableSource(this.ctx, "for...in", value, node));
914
+ const source = enumerableSource(this.ctx, "for...in", value, node);
915
+ const chain = [source];
916
+ // A string's characters stand in an array, but its prototype is String.prototype.
917
+ let proto = primitivePrototype(this.ctx.builtins, value) ?? source.proto;
918
+ while (proto !== null) {
919
+ chain.push(proto);
920
+ proto = proto.proto;
921
+ }
922
+ return chain.flatMap((target, depth) => {
923
+ const nearer = chain.slice(0, depth);
924
+ return keys(target).filter((key) => !nearer.some((level) => hasOwn(level, key)));
925
+ });
749
926
  }
750
- evaluateForInStatement(node, labels) {
927
+ *evaluateForInStatement(node, labels) {
928
+ const runner = this.ctx.runner;
751
929
  const left = node.left;
752
930
  const declared = loopDeclaration(left, "for...in");
753
931
  if (declared?.lexical)
754
932
  this.scopes.push();
755
- const self = this;
756
- return Effect.gen(function* () {
933
+ try {
757
934
  if (declared?.lexical)
758
- self.predeclarePattern(declared.pattern, declared.mutable, left);
759
- const right = yield* self.evaluateExpression(node.right);
760
- const keys = self.enumerableKeys(right, node.right);
935
+ this.predeclarePattern(declared.pattern, declared.mutable, left);
936
+ const right = yield* this.evaluateExpression(node.right);
937
+ const keys = this.enumerableKeys(right, node.right);
761
938
  if (left.type === "RestElement" || left.type === "AssignmentPattern") {
762
939
  throw typeError("Unsupported for...in binding.", left);
763
940
  }
764
941
  const assignment = left.type === "VariableDeclaration" ? undefined : left;
765
942
  for (const key of keys) {
766
- const result = yield* Effect.gen(function* () {
767
- if (declared?.lexical) {
768
- self.scopes.push();
769
- self.predeclarePattern(declared.pattern, declared.mutable, left);
770
- yield* self.declarePattern(declared.pattern, key, declared.mutable, left, true);
771
- }
772
- else if (declared) {
773
- yield* self.assignPattern(declared.pattern, key, left);
943
+ let result;
944
+ if (declared?.lexical) {
945
+ this.scopes.push();
946
+ try {
947
+ this.predeclarePattern(declared.pattern, declared.mutable, left);
948
+ yield* this.declarePattern(declared.pattern, key, declared.mutable, left, true);
949
+ result = yield* this.evaluateStatement(node.body);
774
950
  }
775
- else if (assignment) {
776
- yield* self.assignPattern(assignment, key, left);
951
+ finally {
952
+ this.scopes.pop();
777
953
  }
778
- return yield* self.evaluateStatement(node.body);
779
- }).pipe(Effect.ensuring(Effect.sync(() => {
780
- if (declared?.lexical)
781
- self.scopes.pop();
782
- })));
954
+ }
955
+ else {
956
+ if (declared)
957
+ yield* this.assignPattern(declared.pattern, key, left);
958
+ else if (assignment)
959
+ yield* this.assignPattern(assignment, key, left);
960
+ result = yield* this.evaluateStatement(node.body);
961
+ }
783
962
  const exit = loopExit(result, labels);
784
963
  if (exit !== undefined)
785
964
  return exit;
965
+ if (runner.tick())
966
+ yield Slice;
786
967
  }
787
- return { kind: "none" };
788
- }).pipe(Effect.ensuring(Effect.sync(() => {
968
+ return none;
969
+ }
970
+ finally {
789
971
  if (declared?.lexical)
790
- self.scopes.pop();
791
- })));
972
+ this.scopes.pop();
973
+ }
792
974
  }
793
975
  evaluateBreakStatement(node) {
794
976
  return node.label ? { kind: "break", label: node.label.name } : { kind: "break" };
@@ -796,265 +978,314 @@ class Frame {
796
978
  evaluateContinueStatement(node) {
797
979
  return node.label ? { kind: "continue", label: node.label.name } : { kind: "continue" };
798
980
  }
799
- evaluateLabeledStatement(node) {
981
+ *evaluateLabeledStatement(node) {
800
982
  const labels = new Set();
801
983
  let body = node;
802
984
  while (body.type === "LabeledStatement") {
803
985
  labels.add(body.label.name);
804
986
  body = body.body;
805
987
  }
806
- const evaluated = (() => {
807
- if (body.type === "WhileStatement")
808
- return this.evaluateWhileStatement(body, labels);
809
- if (body.type === "DoWhileStatement")
810
- return this.evaluateDoWhileStatement(body, labels);
811
- if (body.type === "ForStatement")
812
- return this.evaluateForStatement(body, labels);
813
- if (body.type === "ForOfStatement")
814
- return this.evaluateForOfStatement(body, labels);
815
- if (body.type === "ForInStatement")
816
- return this.evaluateForInStatement(body, labels);
817
- return this.evaluateStatement(body);
818
- })();
819
- return Effect.map(evaluated, (result) => result.kind === "break" && result.label !== undefined && labels.has(result.label)
820
- ? { kind: "none" }
821
- : result);
822
- }
823
- evaluateThrowStatement(node) {
824
- return Effect.flatMap(this.evaluateExpression(node.argument), (value) => Effect.fail(new Throw(value)));
825
- }
826
- evaluateTryStatement(node) {
827
- const body = node.block;
988
+ const result = body.type === "WhileStatement"
989
+ ? yield* this.evaluateWhileStatement(body, labels)
990
+ : body.type === "DoWhileStatement"
991
+ ? yield* this.evaluateDoWhileStatement(body, labels)
992
+ : body.type === "ForStatement"
993
+ ? yield* this.evaluateForStatement(body, labels)
994
+ : body.type === "ForOfStatement"
995
+ ? yield* this.evaluateForOfStatement(body, labels)
996
+ : body.type === "ForInStatement"
997
+ ? yield* this.evaluateForInStatement(body, labels)
998
+ : yield* this.evaluateStatement(body);
999
+ return result.kind === "break" && result.label !== undefined && labels.has(result.label) ? none : result;
1000
+ }
1001
+ *evaluateThrowStatement(node) {
1002
+ throw new Throw(yield* this.evaluateExpression(node.argument));
1003
+ }
1004
+ *evaluateTryStatement(node) {
828
1005
  const handler = node.handler;
829
1006
  const finalizer = node.finalizer;
830
- const self = this;
831
- const attempted = Effect.matchCauseEffect(this.evaluateStatement(body), {
832
- onFailure: (cause) => {
833
- if (cause.reasons.some(Cause.isInterruptReason) || Cause.squash(cause) instanceof GeneratorReturn || !handler) {
834
- return Effect.failCause(cause);
835
- }
836
- const caught = materialize(self.ctx, Cause.squash(cause));
1007
+ let result = none;
1008
+ let failure;
1009
+ try {
1010
+ result = yield* this.evaluateStatement(node.block);
1011
+ }
1012
+ catch (error) {
1013
+ if (error instanceof Interruption)
1014
+ throw error;
1015
+ // A generator's return() unwinds through `finally` but is not an exception `catch` sees.
1016
+ if (error instanceof GeneratorReturn || !handler) {
1017
+ if (!finalizer)
1018
+ throw error;
1019
+ failure = { error };
1020
+ }
1021
+ else {
1022
+ const caught = materialize(this.ctx, error);
837
1023
  const parameter = handler.param;
838
- self.scopes.push();
839
- return Effect.gen(function* () {
1024
+ this.scopes.push();
1025
+ try {
840
1026
  if (parameter)
841
- yield* self.declarePattern(parameter, caught, true, handler);
842
- return yield* self.evaluateStatement(handler.body);
843
- }).pipe(Effect.ensuring(Effect.sync(() => self.scopes.pop())));
844
- },
845
- onSuccess: Effect.succeed,
846
- });
1027
+ yield* this.declarePattern(parameter, caught, true, handler);
1028
+ result = yield* this.evaluateStatement(handler.body);
1029
+ }
1030
+ catch (error) {
1031
+ if (!finalizer || error instanceof Interruption)
1032
+ throw error;
1033
+ failure = { error };
1034
+ }
1035
+ finally {
1036
+ this.scopes.pop();
1037
+ }
1038
+ }
1039
+ }
847
1040
  if (!finalizer)
848
- return attempted;
849
- const isAbrupt = (result) => result.kind === "return" || result.kind === "break" || result.kind === "continue";
850
- return Effect.matchCauseEffect(attempted, {
851
- onFailure: (cause) => cause.reasons.some(Cause.isInterruptReason)
852
- ? Effect.failCause(cause)
853
- : Effect.flatMap(this.evaluateStatement(finalizer), (final) => isAbrupt(final) ? Effect.succeed(final) : Effect.failCause(cause)),
854
- onSuccess: (result) => Effect.flatMap(this.evaluateStatement(finalizer), (final) => isAbrupt(final) ? Effect.succeed(final) : Effect.succeed(result)),
855
- });
1041
+ return result;
1042
+ const final = yield* this.evaluateStatement(finalizer);
1043
+ if (isAbrupt(final))
1044
+ return final;
1045
+ if (failure)
1046
+ throw failure.error;
1047
+ return result;
856
1048
  }
857
- evaluateVariableDeclaration(node) {
1049
+ *evaluateVariableDeclaration(node) {
858
1050
  const kind = node.kind;
859
- const self = this;
860
- return Effect.gen(function* () {
861
- for (const declaration of node.declarations) {
862
- if (declaration.type !== "VariableDeclarator") {
863
- throw typeError("Unsupported variable declaration shape.", declaration);
1051
+ for (const declaration of node.declarations) {
1052
+ if (declaration.type !== "VariableDeclarator") {
1053
+ throw typeError("Unsupported variable declaration shape.", declaration);
1054
+ }
1055
+ const init = declaration.init;
1056
+ // `var x` alone is a no-op: the binding was hoisted on function entry.
1057
+ const id = declaration.id;
1058
+ if (kind === "var") {
1059
+ if (init) {
1060
+ const value = id.type === "Identifier" ? yield* this.evaluateNamed(init, id.name) : yield* this.evaluateExpression(init);
1061
+ yield* this.assignPattern(id, value, declaration);
864
1062
  }
865
- const init = declaration.init;
866
- // `var x` alone is a no-op: the binding was hoisted on function entry.
867
- const id = declaration.id;
868
- const evaluate = (init) => id.type === "Identifier" ? self.evaluateNamed(init, id.name) : self.evaluateExpression(init);
869
- if (kind === "var") {
870
- if (init)
871
- yield* self.assignPattern(id, yield* evaluate(init), declaration);
872
- continue;
873
- }
874
- const value = init ? yield* evaluate(init) : undefined;
875
- yield* self.declarePattern(declaration.id, value, kind !== "const", declaration, true);
1063
+ continue;
876
1064
  }
877
- });
1065
+ const value = !init
1066
+ ? undefined
1067
+ : id.type === "Identifier"
1068
+ ? yield* this.evaluateNamed(init, id.name)
1069
+ : yield* this.evaluateExpression(init);
1070
+ yield* this.declarePattern(declaration.id, value, kind !== "const", declaration, true);
1071
+ }
878
1072
  }
879
- declarePattern(pattern, value, mutable, node, initialize = false) {
880
- const self = this;
881
- return Effect.gen(function* () {
882
- if (pattern.type === "Identifier") {
883
- const name = pattern.name;
884
- if (initialize)
885
- self.scopes.initialize(name, value, node);
886
- else
887
- self.scopes.declare(name, value, mutable, node);
888
- return;
889
- }
890
- if (pattern.type === "AssignmentPattern") {
891
- const resolved = value === undefined ? yield* self.evaluateDefault(pattern) : value;
892
- yield* self.declarePattern(pattern.left, resolved, mutable, node, initialize);
893
- return;
894
- }
895
- if (pattern.type === "ObjectPattern") {
896
- if (value === null || value === undefined) {
897
- throw typeError(`Cannot destructure ${describeValue(value)} as it is ${value}.`, pattern);
898
- }
899
- const consumed = new Set();
900
- for (const property of pattern.properties) {
901
- if (property.type === "RestElement") {
902
- const rest = new Obj(self.ctx.builtins.Object);
903
- assign(rest, enumerableSource(self.ctx, "Object destructuring", value, pattern), consumed);
904
- yield* self.declarePattern(property.argument, rest, mutable, property, initialize);
905
- continue;
906
- }
907
- const key = yield* self.destructuringPropertyKey(property);
908
- consumed.add(typeof key === "symbol" ? key : String(key));
909
- yield* self.declarePattern(property.value, self.destructuredProperty(value, key, property), mutable, property, initialize);
1073
+ *declarePattern(pattern, value, mutable, node, initialize = false) {
1074
+ if (pattern.type === "Identifier") {
1075
+ const name = pattern.name;
1076
+ if (initialize)
1077
+ this.scopes.initialize(name, value, node);
1078
+ else
1079
+ this.scopes.declare(name, value, mutable, node);
1080
+ return;
1081
+ }
1082
+ if (pattern.type === "AssignmentPattern") {
1083
+ const resolved = value === undefined ? yield* this.evaluateDefault(pattern) : value;
1084
+ yield* this.declarePattern(pattern.left, resolved, mutable, node, initialize);
1085
+ return;
1086
+ }
1087
+ if (pattern.type === "ObjectPattern") {
1088
+ if (value === null || value === undefined) {
1089
+ throw typeError(`Cannot destructure ${describeValue(value)} as it is ${value}.`, pattern);
1090
+ }
1091
+ const consumed = new Set();
1092
+ for (const property of pattern.properties) {
1093
+ if (property.type === "RestElement") {
1094
+ const rest = new Obj(this.ctx.builtins.Object);
1095
+ assign(rest, enumerableSource(this.ctx, "Object destructuring", value, pattern), consumed);
1096
+ yield* this.declarePattern(property.argument, rest, mutable, property, initialize);
1097
+ continue;
910
1098
  }
911
- return;
1099
+ const key = yield* this.destructuringPropertyKey(property);
1100
+ consumed.add(typeof key === "symbol" ? key : String(key));
1101
+ yield* this.declarePattern(property.value, this.destructuredProperty(value, key, property), mutable, property, initialize);
912
1102
  }
913
- if (pattern.type === "ArrayPattern") {
914
- return yield* self.destructureArrayPattern(pattern, value, (target, item, context) => self.declarePattern(target, item, mutable, context, initialize));
915
- }
916
- throw typeError(`Unsupported binding pattern '${pattern.type}'.`, pattern);
917
- });
1103
+ return;
1104
+ }
1105
+ if (pattern.type === "ArrayPattern") {
1106
+ return yield* this.destructureArrayPattern(pattern, value, (target, item, context) => this.declarePattern(target, item, mutable, context, initialize));
1107
+ }
1108
+ throw typeError(`Unsupported binding pattern '${pattern.type}'.`, pattern);
918
1109
  }
919
- assignPattern(pattern, value, node) {
920
- const self = this;
921
- return Effect.gen(function* () {
922
- if (pattern.type === "Identifier") {
923
- self.scopes.set(pattern.name, value, pattern);
924
- return;
925
- }
926
- if (pattern.type === "MemberExpression") {
927
- yield* self.writeMember(pattern, value);
928
- return;
929
- }
930
- if (pattern.type === "AssignmentPattern") {
931
- const resolved = value === undefined ? yield* self.evaluateDefault(pattern) : value;
932
- yield* self.assignPattern(pattern.left, resolved, node);
933
- return;
934
- }
935
- if (pattern.type === "ObjectPattern") {
936
- if (value === null || value === undefined) {
937
- throw typeError(`Cannot destructure ${describeValue(value)} as it is ${value}.`, pattern);
938
- }
939
- const consumed = new Set();
940
- for (const property of pattern.properties) {
941
- if (property.type === "RestElement") {
942
- const rest = new Obj(self.ctx.builtins.Object);
943
- assign(rest, enumerableSource(self.ctx, "Object destructuring", value, pattern), consumed);
944
- yield* self.assignPattern(property.argument, rest, property);
945
- continue;
946
- }
947
- const key = yield* self.destructuringPropertyKey(property);
948
- consumed.add(typeof key === "symbol" ? key : String(key));
949
- yield* self.assignPattern(property.value, self.destructuredProperty(value, key, property), property);
1110
+ *assignPattern(pattern, value, node) {
1111
+ if (pattern.type === "Identifier") {
1112
+ this.scopes.set(pattern.name, value, pattern);
1113
+ return;
1114
+ }
1115
+ if (pattern.type === "MemberExpression") {
1116
+ yield* this.writeMember(pattern, value);
1117
+ return;
1118
+ }
1119
+ if (pattern.type === "AssignmentPattern") {
1120
+ const resolved = value === undefined ? yield* this.evaluateDefault(pattern) : value;
1121
+ yield* this.assignPattern(pattern.left, resolved, node);
1122
+ return;
1123
+ }
1124
+ if (pattern.type === "ObjectPattern") {
1125
+ if (value === null || value === undefined) {
1126
+ throw typeError(`Cannot destructure ${describeValue(value)} as it is ${value}.`, pattern);
1127
+ }
1128
+ const consumed = new Set();
1129
+ for (const property of pattern.properties) {
1130
+ if (property.type === "RestElement") {
1131
+ const rest = new Obj(this.ctx.builtins.Object);
1132
+ assign(rest, enumerableSource(this.ctx, "Object destructuring", value, pattern), consumed);
1133
+ yield* this.assignPattern(property.argument, rest, property);
1134
+ continue;
950
1135
  }
951
- return;
952
- }
953
- if (pattern.type === "ArrayPattern") {
954
- return yield* self.destructureArrayPattern(pattern, value, (target, item, context) => self.assignPattern(target, item, context));
1136
+ const key = yield* this.destructuringPropertyKey(property);
1137
+ consumed.add(typeof key === "symbol" ? key : String(key));
1138
+ yield* this.assignPattern(property.value, this.destructuredProperty(value, key, property), property);
955
1139
  }
956
- throw typeError(`Unsupported assignment pattern '${pattern.type}'.`, node);
957
- });
1140
+ return;
1141
+ }
1142
+ if (pattern.type === "ArrayPattern") {
1143
+ return yield* this.destructureArrayPattern(pattern, value, (target, item, context) => this.assignPattern(target, item, context));
1144
+ }
1145
+ throw typeError(`Unsupported assignment pattern '${pattern.type}'.`, node);
958
1146
  }
959
1147
  evaluateDefault(pattern) {
960
1148
  return pattern.left.type === "Identifier"
961
1149
  ? this.evaluateNamed(pattern.right, pattern.left.name)
962
1150
  : this.evaluateExpression(pattern.right);
963
1151
  }
964
- destructureArrayPattern(pattern, value, consume) {
965
- const self = this;
966
- return Effect.gen(function* () {
967
- const cursor = yield* self.iterate(value, pattern);
968
- if (cursor === undefined) {
969
- throw typeError("Array destructuring requires a supported iterable value.", pattern);
970
- }
971
- let done = false;
972
- for (const element of pattern.elements) {
973
- if (done) {
974
- if (element === null)
975
- continue;
976
- yield* consume(element.type === "RestElement" ? element.argument : element, element.type === "RestElement" ? new Arr(self.ctx.builtins.Array) : undefined, element);
977
- if (element.type === "RestElement")
978
- return;
979
- continue;
980
- }
981
- const step = yield* cursor.next;
982
- done = step.done;
1152
+ *destructureArrayPattern(pattern, value, consume) {
1153
+ const cursor = yield* this.iterate(value, pattern);
1154
+ if (cursor === undefined) {
1155
+ throw typeError("Array destructuring requires a supported iterable value.", pattern);
1156
+ }
1157
+ let done = false;
1158
+ for (const element of pattern.elements) {
1159
+ if (done) {
983
1160
  if (element === null)
984
1161
  continue;
985
- if (element.type === "RestElement") {
986
- const rest = [];
987
- if (!step.done)
988
- rest.push(step.value);
989
- while (!done) {
990
- const next = yield* cursor.next;
991
- done = next.done;
992
- if (!done)
993
- rest.push(next.value);
994
- }
995
- yield* consume(element.argument, new Arr(self.ctx.builtins.Array, rest), element);
1162
+ yield* consume(element.type === "RestElement" ? element.argument : element, element.type === "RestElement" ? new Arr(this.ctx.builtins.Array) : undefined, element);
1163
+ if (element.type === "RestElement")
996
1164
  return;
1165
+ continue;
1166
+ }
1167
+ const step = yield* cursor.next();
1168
+ done = step.done;
1169
+ if (element === null)
1170
+ continue;
1171
+ if (element.type === "RestElement") {
1172
+ const rest = [];
1173
+ if (!step.done)
1174
+ rest.push(step.value);
1175
+ while (!done) {
1176
+ const next = yield* cursor.next();
1177
+ done = next.done;
1178
+ if (!done)
1179
+ rest.push(next.value);
997
1180
  }
998
- const consumed = consume(element, step.done ? undefined : step.value, pattern);
999
- yield* step.done ? consumed : preserveConsumerError(cursor.close, consumed);
1181
+ yield* consume(element.argument, new Arr(this.ctx.builtins.Array, rest), element);
1182
+ return;
1000
1183
  }
1001
- if (!done)
1002
- yield* cursor.close;
1003
- });
1184
+ const consumed = consume(element, step.done ? undefined : step.value, pattern);
1185
+ yield* step.done ? consumed : preserveConsumerError(cursor.close, consumed);
1186
+ }
1187
+ if (!done)
1188
+ yield* cursor.close();
1004
1189
  }
1005
- destructuringPropertyKey(property) {
1190
+ *destructuringPropertyKey(property) {
1006
1191
  if (property.type !== "Property" || property.kind !== "init") {
1007
1192
  throw typeError("Unsupported object destructuring property.", property);
1008
1193
  }
1009
1194
  const keyNode = property.key;
1010
- if (property.computed) {
1011
- return Effect.flatMap(this.evaluateExpression(keyNode), (value) => this.toPropertyKey(value, keyNode));
1012
- }
1195
+ if (property.computed)
1196
+ return yield* this.toPropertyKey(yield* this.evaluateExpression(keyNode), keyNode);
1013
1197
  if (keyNode.type === "Identifier")
1014
- return Effect.succeed(keyNode.name);
1198
+ return keyNode.name;
1015
1199
  if (keyNode.type === "Literal")
1016
- return Effect.succeed(String(keyNode.value));
1200
+ return String(keyNode.value);
1017
1201
  throw unsupportedSyntax(keyNode.type, keyNode);
1018
1202
  }
1019
- evaluateExpression(node) {
1203
+ *evaluateExpression(node) {
1204
+ const result = this.evaluate(node);
1205
+ return isEval(result) ? yield* result : result;
1206
+ }
1207
+ // Evaluates leaves directly and returns the work for anything that may run program code, so the common cases cost
1208
+ // no generator; callers finish the work with `yield*`.
1209
+ evaluate(node) {
1020
1210
  switch (node.type) {
1021
1211
  case "Literal": {
1022
1212
  const regex = node.regex;
1023
1213
  if (regex)
1024
- return Effect.sync(() => constructRegExp(this.ctx.builtins, [regex.pattern, regex.flags]));
1025
- return Effect.succeed(literal(node));
1214
+ return constructRegExp(this.ctx.builtins, [regex.pattern, regex.flags]);
1215
+ return literal(node);
1026
1216
  }
1027
1217
  case "Identifier":
1028
- return Effect.sync(() => this.scopes.get(node.name, node));
1218
+ return this.scopes.get(node.name, node);
1029
1219
  case "ThisExpression":
1030
- return Effect.sync(() => this.scopes.get("this", node));
1031
- case "BinaryExpression":
1032
- return this.evaluateBinaryExpression(node);
1220
+ return this.scopes.get("this", node);
1221
+ case "BinaryExpression": {
1222
+ const operator = node.operator;
1223
+ if (node.left.type === "PrivateIdentifier")
1224
+ throw unsupportedSyntax(node.left.type, node.left);
1225
+ const left = this.evaluate(node.left);
1226
+ if (isEval(left))
1227
+ return this.evaluateBinaryExpression(node, left);
1228
+ const right = this.evaluate(node.right);
1229
+ if (isEval(right))
1230
+ return this.evaluateBinaryExpression(node, left, right);
1231
+ if (operator === "instanceof")
1232
+ return instanceofValue(left, right, node);
1233
+ if (left instanceof Obj || right instanceof Obj)
1234
+ return this.applyOperator(operator, left, right, node);
1235
+ return this.applyBinaryOperator(operator, left, right, node);
1236
+ }
1033
1237
  case "LogicalExpression":
1034
1238
  return this.evaluateLogicalExpression(node);
1035
1239
  case "UnaryExpression":
1036
1240
  return this.evaluateUnaryExpression(node);
1037
- case "AssignmentExpression":
1038
- return this.evaluateAssignmentExpression(node);
1039
- case "SequenceExpression": {
1040
- const self = this;
1041
- return Effect.gen(function* () {
1042
- let result;
1043
- for (const expression of node.expressions) {
1044
- result = yield* self.evaluateExpression(expression);
1045
- }
1046
- return result;
1047
- });
1048
- }
1241
+ case "AssignmentExpression": {
1242
+ const left = node.left;
1243
+ if (left.type !== "Identifier")
1244
+ return this.evaluateAssignmentExpression(node);
1245
+ if (node.operator === "=") {
1246
+ const right = node.right.type === "ArrowFunctionExpression" ||
1247
+ (node.right.type === "FunctionExpression" && !node.right.id)
1248
+ ? this.createFunction(node.right, left.name)
1249
+ : this.evaluate(node.right);
1250
+ return isEval(right) ? this.assignAfter(left, right) : this.scopes.set(left.name, right, left);
1251
+ }
1252
+ if (!compoundOperators.has(node.operator))
1253
+ return this.evaluateAssignmentExpression(node);
1254
+ const current = this.scopes.get(left.name, left);
1255
+ const right = this.evaluate(node.right);
1256
+ if (isEval(right) || current instanceof Obj || right instanceof Obj)
1257
+ return this.compoundAfter(node, current, right);
1258
+ return this.scopes.set(left.name, this.applyBinaryOperator(node.operator.slice(0, -1), current, right, node), left);
1259
+ }
1260
+ case "SequenceExpression":
1261
+ return this.evaluateSequenceExpression(node);
1049
1262
  case "CallExpression":
1050
1263
  return this.evaluateCallExpression(node);
1051
1264
  case "ArrowFunctionExpression":
1052
1265
  case "FunctionExpression":
1053
- return Effect.sync(() => this.createFunction(node));
1054
- case "MemberExpression":
1055
- return this.readMember(node);
1266
+ return this.createFunction(node);
1267
+ case "MemberExpression": {
1268
+ const objectNode = node.object;
1269
+ const propertyNode = node.property;
1270
+ if (objectNode.type === "Super")
1271
+ throw unsupportedSyntax(objectNode.type, objectNode);
1272
+ if (propertyNode.type === "PrivateIdentifier")
1273
+ throw unsupportedSyntax(propertyNode.type, propertyNode);
1274
+ const object = this.evaluate(objectNode);
1275
+ if (isEval(object))
1276
+ return this.readMember(node, object);
1277
+ if (object === OptionalShortCircuit)
1278
+ return OptionalShortCircuit;
1279
+ if ((object === null || object === undefined) && node.optional)
1280
+ return OptionalShortCircuit;
1281
+ const key = !node.computed && propertyNode.type === "Identifier" ? propertyNode.name : this.evaluate(propertyNode);
1282
+ if (isEval(key))
1283
+ return this.readMember(node, object, key);
1284
+ const reference = this.memberReference(node, object, key);
1285
+ return isEval(reference) ? this.readMember(node, object, key) : this.readResolved(node, reference);
1286
+ }
1056
1287
  case "ChainExpression":
1057
- return Effect.map(this.evaluateExpression(node.expression), (value) => value === OptionalShortCircuit ? undefined : value);
1288
+ return this.evaluateChainExpression(node);
1058
1289
  case "ObjectExpression":
1059
1290
  return this.evaluateObjectExpression(node);
1060
1291
  case "ArrayExpression":
@@ -1065,12 +1296,17 @@ class Frame {
1065
1296
  return this.evaluateTaggedTemplate(node);
1066
1297
  case "ConditionalExpression":
1067
1298
  return this.evaluateConditionalExpression(node);
1068
- case "UpdateExpression":
1069
- return this.evaluateUpdateExpression(node);
1070
- case "AwaitExpression": {
1071
- // Await always suspends, including for plain values.
1072
- return Effect.flatMap(this.evaluateExpression(node.argument), (value) => this.awaitValue(value));
1073
- }
1299
+ case "UpdateExpression": {
1300
+ const argument = node.argument;
1301
+ if (argument.type !== "Identifier")
1302
+ return this.evaluateUpdateExpression(node);
1303
+ const current = this.scopes.get(argument.name, argument);
1304
+ if (current instanceof Obj)
1305
+ return this.evaluateUpdateExpression(node);
1306
+ return this.update(node, argument, current);
1307
+ }
1308
+ case "AwaitExpression":
1309
+ return this.evaluateAwaitExpression(node);
1074
1310
  case "YieldExpression":
1075
1311
  return this.evaluateYieldExpression(node);
1076
1312
  case "NewExpression":
@@ -1079,72 +1315,84 @@ class Frame {
1079
1315
  throw unsupportedSyntax(node.type, node);
1080
1316
  }
1081
1317
  }
1082
- evaluateNewExpression(node) {
1083
- const self = this;
1084
- return Effect.gen(function* () {
1085
- const callee = yield* self.evaluateExpression(node.callee);
1086
- // Globals are built with this interpreter's R; `instanceof` cannot recover the type argument.
1087
- const construct = callee instanceof Native ? callee.construct : undefined;
1088
- if (construct === undefined) {
1089
- // `new` itself is supported, so a non-constructible callee is a TypeError like JS rather than
1090
- // unsupported syntax. Built-ins like Number are real constructors in JS, so do not claim
1091
- // otherwise; say `new` is unsupported for them and point at the plain call.
1092
- const name = calleeDescription(node.callee) ?? "The called value";
1093
- const message = callee instanceof Fn
1094
- ? `${name} cannot be constructed: user-defined constructors and classes are not supported. Call it as a function that returns a plain object instead.`
1095
- : callee instanceof Native
1096
- ? `new ${name}(...) is not supported; call ${name}(...) without new instead.`
1097
- : `${name} is not a constructor.`;
1098
- throw typeError(message, node);
1099
- }
1100
- const args = yield* self.evaluateCallArguments(node.arguments);
1101
- return yield* self.native(() => construct(args, callee), node);
1102
- });
1318
+ *evaluateSequenceExpression(node) {
1319
+ let result;
1320
+ for (const expression of node.expressions) {
1321
+ const value = this.evaluate(expression);
1322
+ result = isEval(value) ? yield* value : value;
1323
+ }
1324
+ return result;
1103
1325
  }
1104
- evaluateBinaryExpression(node) {
1326
+ *evaluateChainExpression(node) {
1327
+ const value = yield* this.evaluateExpression(node.expression);
1328
+ return value === OptionalShortCircuit ? undefined : value;
1329
+ }
1330
+ *evaluateConditionalExpression(node) {
1331
+ const test = this.evaluate(node.test);
1332
+ const branch = this.evaluate((isEval(test) ? yield* test : test) ? node.consequent : node.alternate);
1333
+ return isEval(branch) ? yield* branch : branch;
1334
+ }
1335
+ *evaluateAwaitExpression(node) {
1336
+ // Await always suspends, including for plain values.
1337
+ return yield* this.awaitValue(yield* this.evaluateExpression(node.argument), node);
1338
+ }
1339
+ *evaluateNewExpression(node) {
1340
+ const callee = yield* this.evaluateExpression(node.callee);
1341
+ const construct = callee instanceof Native ? callee.construct : undefined;
1342
+ if (construct === undefined) {
1343
+ // `new` itself is supported, so a non-constructible callee is a TypeError like JS rather than
1344
+ // unsupported syntax. Built-ins like Number are real constructors in JS, so do not claim
1345
+ // otherwise; say `new` is unsupported for them and point at the plain call.
1346
+ const name = calleeDescription(node.callee) ?? "The called value";
1347
+ const message = callee instanceof Fn
1348
+ ? `${name} cannot be constructed: user-defined constructors and classes are not supported. Call it as a function that returns a plain object instead.`
1349
+ : callee instanceof Native
1350
+ ? `new ${name}(...) is not supported; call ${name}(...) without new instead.`
1351
+ : `${name} is not a constructor.`;
1352
+ throw typeError(message, node);
1353
+ }
1354
+ const args = yield* this.evaluateCallArguments(node.arguments);
1355
+ const result = this.native(() => construct(args, callee, node), node);
1356
+ return isEval(result) ? yield* result : result;
1357
+ }
1358
+ // Finishes a binary expression whose left operand (and maybe right) `evaluate` already started.
1359
+ *evaluateBinaryExpression(node, leftValue, started = unevaluated) {
1105
1360
  const operator = node.operator;
1106
- const left = node.left;
1107
- if (left.type === "PrivateIdentifier")
1108
- throw unsupportedSyntax(left.type, left);
1109
- const self = this;
1110
- return Effect.gen(function* () {
1111
- const lhs = yield* self.evaluateExpression(left);
1112
- const rhs = yield* self.evaluateExpression(node.right);
1113
- if (operator === "instanceof")
1114
- return instanceofValue(lhs, rhs, node);
1115
- if (lhs instanceof Obj || rhs instanceof Obj)
1116
- return yield* self.applyOperator(operator, lhs, rhs, node);
1117
- return self.applyBinaryOperator(operator, lhs, rhs, node);
1118
- });
1361
+ const lhs = isEval(leftValue) ? yield* leftValue : leftValue;
1362
+ const rightValue = started === unevaluated ? this.evaluate(node.right) : started;
1363
+ const rhs = isEval(rightValue) ? yield* rightValue : rightValue;
1364
+ if (operator === "instanceof")
1365
+ return instanceofValue(lhs, rhs, node);
1366
+ if (lhs instanceof Obj || rhs instanceof Obj)
1367
+ return yield* this.applyOperator(operator, lhs, rhs, node);
1368
+ return this.applyBinaryOperator(operator, lhs, rhs, node);
1119
1369
  }
1120
1370
  /** ToPrimitive for an operand: data objects run their own methods; opaque values stay for the data gates below. */
1121
- toPrimitive(value, hint, node) {
1122
- return this.native(() => toPrimitive(this.ctx, value, hint), node);
1371
+ *toPrimitive(value, hint, node) {
1372
+ const result = this.native(() => toPrimitive(this.ctx, value, hint), node);
1373
+ return isEval(result) ? yield* result : result;
1123
1374
  }
1124
1375
  // Arithmetic, relational, and bitwise operators convert both operands first, left then right, so a `valueOf`
1125
1376
  // runs (and throws) in spec order; `+` asks for the default hint and the rest for a number.
1126
- applyOperator(operator, lhs, rhs, node) {
1377
+ *applyOperator(operator, lhs, rhs, node) {
1127
1378
  if (!(lhs instanceof Obj || rhs instanceof Obj))
1128
- return Effect.succeed(this.applyBinaryOperator(operator, lhs, rhs, node));
1379
+ return this.applyBinaryOperator(operator, lhs, rhs, node);
1129
1380
  // IsLooselyEqual converts only an object facing a non-nullish primitive; two objects (including tool
1130
1381
  // references, which are not Obj) compare by identity.
1131
1382
  const equality = operator === "==" || operator === "!=";
1132
1383
  // `in` checks the right operand before ToPropertyKey on the left, so a bad right side wins over a bad key.
1133
1384
  if (operator === "in" && lhs instanceof Obj && !isOpaque(lhs) && rhs instanceof Obj) {
1134
- return Effect.map(this.toPropertyKey(lhs, node), (key) => has(rhs, key));
1385
+ return has(rhs, yield* this.toPropertyKey(lhs, node));
1135
1386
  }
1136
1387
  const other = lhs instanceof Obj ? rhs : lhs;
1137
1388
  const converts = primitiveOperators.has(operator) ||
1138
1389
  (equality && other !== null && other !== undefined && typeof other !== "object");
1139
1390
  if (!converts)
1140
- return Effect.succeed(this.applyBinaryOperator(operator, lhs, rhs, node));
1391
+ return this.applyBinaryOperator(operator, lhs, rhs, node);
1141
1392
  const hint = operator === "+" || equality ? "default" : "number";
1142
- const self = this;
1143
- return Effect.gen(function* () {
1144
- const l = yield* self.toPrimitive(lhs, hint, node);
1145
- const r = yield* self.toPrimitive(rhs, hint, node);
1146
- return self.applyBinaryOperator(operator, l, r, node);
1147
- });
1393
+ const l = yield* this.toPrimitive(lhs, hint, node);
1394
+ const r = yield* this.toPrimitive(rhs, hint, node);
1395
+ return this.applyBinaryOperator(operator, l, r, node);
1148
1396
  }
1149
1397
  applyBinaryOperator(operator, lhs, rhs, node) {
1150
1398
  if (operator === "===")
@@ -1217,127 +1465,134 @@ class Frame {
1217
1465
  // Data objects were converted by applyOperator, so only an opaque reference facing a primitive gets here.
1218
1466
  throw invalidData("Binary operators require data values.", node);
1219
1467
  }
1220
- evaluateLogicalExpression(node) {
1468
+ *evaluateLogicalExpression(node) {
1221
1469
  const operator = node.operator;
1222
- return Effect.flatMap(this.evaluateExpression(node.left), (left) => {
1223
- if (operator === "&&")
1224
- return left ? this.evaluateExpression(node.right) : Effect.succeed(left);
1225
- if (operator === "||")
1226
- return left ? Effect.succeed(left) : this.evaluateExpression(node.right);
1227
- if (operator === "??")
1228
- return left !== null && left !== undefined ? Effect.succeed(left) : this.evaluateExpression(node.right);
1229
- throw typeError(`Unsupported logical operator '${operator}'.`, node);
1230
- });
1231
- }
1232
- evaluateUnaryExpression(node) {
1470
+ const leftValue = this.evaluate(node.left);
1471
+ const left = isEval(leftValue) ? yield* leftValue : leftValue;
1472
+ if (operator === "&&")
1473
+ return left ? yield* this.evaluateExpression(node.right) : left;
1474
+ if (operator === "||")
1475
+ return left ? left : yield* this.evaluateExpression(node.right);
1476
+ if (operator === "??")
1477
+ return left !== null && left !== undefined ? left : yield* this.evaluateExpression(node.right);
1478
+ throw typeError(`Unsupported logical operator '${operator}'.`, node);
1479
+ }
1480
+ *evaluateUnaryExpression(node) {
1233
1481
  const operator = node.operator;
1234
1482
  const argument = node.argument;
1235
1483
  if (operator === "delete")
1236
- return this.evaluateDeleteExpression(argument);
1484
+ return yield* this.evaluateDeleteExpression(argument);
1237
1485
  // Undeclared names short-circuit, but declared TDZ bindings must still throw.
1238
1486
  if (operator === "typeof" && argument.type === "Identifier" && !this.scopes.resolve(argument.name)) {
1239
- return Effect.succeed("undefined");
1487
+ return "undefined";
1488
+ }
1489
+ const value = yield* this.evaluateExpression(argument);
1490
+ if (operator === "typeof")
1491
+ return typeofValue(value);
1492
+ if (operator === "!")
1493
+ return !value;
1494
+ if (operator === "void")
1495
+ return undefined;
1496
+ const operand = yield* this.toPrimitive(value, "number", node);
1497
+ if (isOpaque(operand)) {
1498
+ throw invalidData("Unary operators require data values.", node);
1499
+ }
1500
+ switch (operator) {
1501
+ case "+":
1502
+ return +operand;
1503
+ case "-":
1504
+ return -operand;
1505
+ case "~":
1506
+ return ~operand;
1507
+ default:
1508
+ throw typeError(`Unsupported unary operator '${operator}'.`, node);
1240
1509
  }
1241
- const self = this;
1242
- return Effect.gen(function* () {
1243
- const value = yield* self.evaluateExpression(argument);
1244
- if (operator === "typeof")
1245
- return typeofValue(value);
1246
- if (operator === "!")
1247
- return !value;
1248
- if (operator === "void")
1249
- return undefined;
1250
- const operand = yield* self.toPrimitive(value, "number", node);
1251
- if (isOpaque(operand)) {
1252
- throw invalidData("Unary operators require data values.", node);
1253
- }
1254
- let result;
1255
- switch (operator) {
1256
- case "+":
1257
- result = +operand;
1258
- break;
1259
- case "-":
1260
- result = -operand;
1261
- break;
1262
- case "~":
1263
- result = ~operand;
1264
- break;
1265
- default:
1266
- throw typeError(`Unsupported unary operator '${operator}'.`, node);
1267
- }
1268
- return result;
1269
- });
1270
1510
  }
1271
- evaluateAssignmentExpression(node) {
1511
+ *evaluateAssignmentExpression(node) {
1272
1512
  const left = node.left;
1273
1513
  const operator = node.operator;
1274
1514
  // The binary operator a compound assignment applies: `+=` is `+`.
1275
1515
  const binary = operator.slice(0, -1);
1276
- const self = this;
1277
- return Effect.gen(function* () {
1278
- if (operator === "??=" || operator === "||=" || operator === "&&=") {
1279
- return yield* self.evaluateLogicalAssignment(node, left, operator);
1280
- }
1281
- if (operator !== "=" && !compoundOperators.has(operator)) {
1282
- throw typeError(`Unsupported assignment operator '${operator}'.`, node);
1283
- }
1284
- if (operator === "=" && (left.type === "ObjectPattern" || left.type === "ArrayPattern")) {
1516
+ if (operator === "??=" || operator === "||=" || operator === "&&=") {
1517
+ return yield* this.evaluateLogicalAssignment(node, left, operator);
1518
+ }
1519
+ if (operator !== "=" && !compoundOperators.has(operator)) {
1520
+ throw typeError(`Unsupported assignment operator '${operator}'.`, node);
1521
+ }
1522
+ if (operator === "=" && (left.type === "ObjectPattern" || left.type === "ArrayPattern")) {
1523
+ const rightValue = yield* this.evaluateExpression(node.right);
1524
+ yield* this.assignPattern(left, rightValue, node);
1525
+ return rightValue;
1526
+ }
1527
+ if (left.type === "Identifier") {
1528
+ const name = left.name;
1529
+ if (operator !== "=") {
1530
+ const current = this.scopes.get(name, left);
1531
+ const evaluated = this.evaluate(node.right);
1532
+ const rightValue = isEval(evaluated) ? yield* evaluated : evaluated;
1533
+ const next = current instanceof Obj || rightValue instanceof Obj
1534
+ ? yield* this.applyOperator(binary, current, rightValue, node)
1535
+ : this.applyBinaryOperator(binary, current, rightValue, node);
1536
+ return this.scopes.set(name, next, left);
1537
+ }
1538
+ const rightValue = yield* this.evaluateNamed(node.right, name);
1539
+ return this.scopes.set(name, rightValue, left);
1540
+ }
1541
+ if (left.type === "MemberExpression") {
1542
+ const self = this;
1543
+ return yield* this.modifyMember(left, function* (current) {
1285
1544
  const rightValue = yield* self.evaluateExpression(node.right);
1286
- yield* self.assignPattern(left, rightValue, node);
1287
- return rightValue;
1288
- }
1289
- if (left.type === "Identifier") {
1290
- const name = left.name;
1291
- if (operator !== "=") {
1292
- const current = self.scopes.get(name, left);
1293
- const rightValue = yield* self.evaluateExpression(node.right);
1294
- const next = current instanceof Obj || rightValue instanceof Obj
1295
- ? yield* self.applyOperator(binary, current, rightValue, node)
1296
- : self.applyBinaryOperator(binary, current, rightValue, node);
1297
- return self.scopes.set(name, next, left);
1298
- }
1299
- const rightValue = yield* self.evaluateNamed(node.right, name);
1300
- return self.scopes.set(name, rightValue, left);
1301
- }
1302
- if (left.type === "MemberExpression") {
1303
- return yield* self.modifyMember(left, (current) => Effect.flatMap(self.evaluateExpression(node.right), (rightValue) => {
1304
- if (operator === "=")
1305
- return Effect.succeed({ write: true, next: rightValue, result: rightValue });
1306
- return Effect.map(self.applyOperator(binary, current, rightValue, node), (next) => ({
1307
- write: true,
1308
- next,
1309
- result: next,
1310
- }));
1311
- }));
1312
- }
1313
- throw typeError("Assignment target must be an Identifier or MemberExpression.", left);
1314
- });
1545
+ if (operator === "=")
1546
+ return { write: true, next: rightValue, result: rightValue };
1547
+ const next = yield* self.applyOperator(binary, current, rightValue, node);
1548
+ return { write: true, next, result: next };
1549
+ });
1550
+ }
1551
+ throw typeError("Assignment target must be an Identifier or MemberExpression.", left);
1315
1552
  }
1316
- evaluateLogicalAssignment(node, left, operator) {
1317
- const self = this;
1553
+ *assignAfter(left, right) {
1554
+ return this.scopes.set(left.name, yield* right, left);
1555
+ }
1556
+ *compoundAfter(node, current, started) {
1557
+ const left = node.left;
1558
+ const binary = node.operator.slice(0, -1);
1559
+ const right = isEval(started) ? yield* started : started;
1560
+ const next = current instanceof Obj || right instanceof Obj
1561
+ ? yield* this.applyOperator(binary, current, right, node)
1562
+ : this.applyBinaryOperator(binary, current, right, node);
1563
+ return this.scopes.set(left.name, next, left);
1564
+ }
1565
+ // `++`/`--` on a name whose value is already primitive.
1566
+ update(node, argument, current) {
1567
+ if (isOpaque(current))
1568
+ throw invalidData(`'${node.operator}' requires a data value.`, argument);
1569
+ const before = coerceToNumber(current);
1570
+ const next = node.operator === "++" ? before + 1 : before - 1;
1571
+ this.scopes.set(argument.name, next, argument);
1572
+ return node.prefix ? next : before;
1573
+ }
1574
+ *evaluateLogicalAssignment(node, left, operator) {
1318
1575
  const shouldAssign = (current) => operator === "??=" ? current === null || current === undefined : operator === "||=" ? !current : Boolean(current);
1319
1576
  if (left.type === "Identifier") {
1320
1577
  const name = left.name;
1321
- return Effect.gen(function* () {
1322
- const current = self.scopes.get(name, left);
1323
- if (!shouldAssign(current))
1324
- return current;
1325
- const rightValue = yield* self.evaluateNamed(node.right, name);
1326
- return self.scopes.set(name, rightValue, left);
1327
- });
1578
+ const current = this.scopes.get(name, left);
1579
+ if (!shouldAssign(current))
1580
+ return current;
1581
+ const rightValue = yield* this.evaluateNamed(node.right, name);
1582
+ return this.scopes.set(name, rightValue, left);
1328
1583
  }
1329
1584
  if (left.type === "MemberExpression") {
1330
- return self.modifyMember(left, (current) => shouldAssign(current)
1331
- ? Effect.map(self.evaluateExpression(node.right), (rightValue) => ({
1332
- write: true,
1333
- next: rightValue,
1334
- result: rightValue,
1335
- }))
1336
- : Effect.succeed({ write: false, next: current, result: current }));
1585
+ const self = this;
1586
+ return yield* this.modifyMember(left, function* (current) {
1587
+ if (!shouldAssign(current))
1588
+ return { write: false, next: current, result: current };
1589
+ const rightValue = yield* self.evaluateExpression(node.right);
1590
+ return { write: true, next: rightValue, result: rightValue };
1591
+ });
1337
1592
  }
1338
1593
  throw typeError("Assignment target must be an Identifier or MemberExpression.", left);
1339
1594
  }
1340
- evaluateUpdateExpression(node) {
1595
+ *evaluateUpdateExpression(node) {
1341
1596
  const operator = node.operator;
1342
1597
  const argument = node.argument;
1343
1598
  const prefix = node.prefix;
@@ -1355,464 +1610,364 @@ class Frame {
1355
1610
  if (argument.type === "Identifier") {
1356
1611
  const name = argument.name;
1357
1612
  const current = this.scopes.get(name, argument);
1358
- const update = (value) => {
1359
- const before = operand(value);
1360
- const next = before + increment;
1361
- this.scopes.set(name, next, argument);
1362
- return prefix ? next : before;
1363
- };
1364
- if (!(current instanceof Obj))
1365
- return Effect.sync(() => update(current));
1366
- return Effect.map(this.toPrimitive(current, "number", argument), update);
1613
+ const before = operand(current instanceof Obj ? yield* this.toPrimitive(current, "number", argument) : current);
1614
+ const next = before + increment;
1615
+ this.scopes.set(name, next, argument);
1616
+ return prefix ? next : before;
1367
1617
  }
1368
1618
  if (argument.type === "MemberExpression") {
1369
- return this.modifyMember(argument, (current) => Effect.map(this.toPrimitive(current, "number", argument), (primitive) => {
1370
- const value = operand(primitive);
1619
+ const self = this;
1620
+ return yield* this.modifyMember(argument, function* (current) {
1621
+ const value = operand(yield* self.toPrimitive(current, "number", argument));
1371
1622
  const next = value + increment;
1372
1623
  return { write: true, next, result: prefix ? next : value };
1373
- }));
1624
+ });
1374
1625
  }
1375
1626
  throw typeError("Update target must be an Identifier or MemberExpression.", argument);
1376
1627
  }
1377
1628
  // EvaluateCall: a member callee supplies its base object as `this`; anything else calls with undefined.
1378
- evaluateCallExpression(node) {
1629
+ *evaluateCallExpression(node) {
1379
1630
  const callee = node.callee;
1380
- const self = this;
1381
- return Effect.gen(function* () {
1382
- if (callee.type === "Super")
1383
- throw unsupportedSyntax(callee.type, callee);
1384
- const { callable, thisValue } = callee.type === "MemberExpression"
1385
- ? yield* self.readMethod(callee)
1386
- : { callable: yield* self.evaluateExpression(callee), thisValue: undefined };
1387
- if (callable === OptionalShortCircuit)
1388
- return OptionalShortCircuit;
1389
- if ((callable === null || callable === undefined) && node.optional)
1390
- return OptionalShortCircuit;
1391
- const args = yield* self.evaluateCallArguments(node.arguments);
1392
- return yield* self.call(callable, thisValue, args, node, callee);
1393
- });
1394
- }
1395
- readMethod(node) {
1396
- return Effect.map(this.getMemberReference(node), (reference) => {
1397
- if (reference === OptionalShortCircuit)
1398
- return { callable: OptionalShortCircuit, thisValue: undefined };
1399
- if (reference instanceof ToolReference)
1400
- return { callable: reference, thisValue: undefined };
1401
- if ("value" in reference)
1402
- return { callable: reference.value, thisValue: undefined };
1403
- return { callable: this.readReference(reference, node), thisValue: reference.receiver };
1404
- });
1405
- }
1406
- // The single dispatch for every invocation: call expressions and callbacks share it.
1407
- call(callable, thisValue, args, node, callee) {
1408
- const self = this;
1409
- return Effect.gen(function* () {
1410
- if (callable instanceof ToolReference) {
1411
- if (callable.path.length === 0) {
1412
- throw typeError("The tools root is not callable.", callee ?? node);
1413
- }
1414
- return yield* self.createToolCallPromise(callable.path, args);
1415
- }
1416
- if (callable instanceof Fn)
1417
- return yield* self.invokeFunction(callable, thisValue, args, node);
1418
- if (callable instanceof Native) {
1419
- return yield* self.native(() => callable.call(thisValue, args), node);
1631
+ if (callee.type === "Super")
1632
+ throw unsupportedSyntax(callee.type, callee);
1633
+ const { callable, thisValue } = callee.type === "MemberExpression"
1634
+ ? yield* this.readMethod(callee)
1635
+ : { callable: yield* this.evaluateExpression(callee), thisValue: undefined };
1636
+ if (callable === OptionalShortCircuit)
1637
+ return OptionalShortCircuit;
1638
+ if ((callable === null || callable === undefined) && node.optional)
1639
+ return OptionalShortCircuit;
1640
+ const args = yield* this.evaluateCallArguments(node.arguments);
1641
+ const result = this.dispatch(callable, thisValue, args, node, callee);
1642
+ return isEval(result) ? yield* result : result instanceof Call ? (yield result) : result;
1643
+ }
1644
+ *readMethod(node) {
1645
+ const reference = yield* this.getMemberReference(node);
1646
+ if (reference === OptionalShortCircuit)
1647
+ return { callable: OptionalShortCircuit, thisValue: undefined };
1648
+ if (reference instanceof ToolReference)
1649
+ return { callable: reference, thisValue: undefined };
1650
+ if ("value" in reference)
1651
+ return { callable: reference.value, thisValue: undefined };
1652
+ return { callable: this.readReference(reference, node), thisValue: reference.receiver };
1653
+ }
1654
+ *call(callable, thisValue, args, node, callee) {
1655
+ const result = this.dispatch(callable, thisValue, args, node, callee);
1656
+ return isEval(result) ? yield* result : result instanceof Call ? (yield result) : result;
1657
+ }
1658
+ // The single dispatch for every invocation: call expressions and callbacks share it. A program function is a `Call`
1659
+ // for the caller to yield; a built-in that returns a value needs no generator.
1660
+ dispatch(callable, thisValue, args, node, callee) {
1661
+ if (callable instanceof Fn)
1662
+ return this.invokeFunction(callable, thisValue, args, node);
1663
+ if (callable instanceof Native) {
1664
+ // A loop made only of built-in calls has no program call or loop back-edge to count, so count the call.
1665
+ if (this.ctx.runner.tick())
1666
+ return afterSlice(() => this.native(() => callable.call(thisValue, args, node), node));
1667
+ return this.native(() => callable.call(thisValue, args, node), node);
1668
+ }
1669
+ if (callable instanceof ToolReference) {
1670
+ if (callable.path.length === 0) {
1671
+ throw typeError("The tools root is not callable.", callee ?? node);
1420
1672
  }
1421
- throw typeError(`${calleeDescription(callee) ?? "The called value"} is not a function.`, callee ?? node);
1422
- });
1673
+ return this.createToolCallPromise(callable.path, args, node);
1674
+ }
1675
+ throw typeError(`${calleeDescription(callee) ?? "The called value"} is not a function.`, callee ?? node);
1423
1676
  }
1424
- // Built-ins throw without a location, synchronously or inside their Effect; the call site supplies it.
1677
+ // Built-ins throw without a location, synchronously or inside their work; the call site supplies it.
1425
1678
  native(body, node) {
1426
- return Effect.provideService(Effect.catchDefect(Effect.suspend(body), (defect) => Effect.die(locate(defect, node))), CallSite, { node, depth: this.depth });
1427
- }
1428
- evaluateCallArguments(argNodes) {
1429
- const self = this;
1430
- return Effect.gen(function* () {
1431
- const args = [];
1432
- for (const argNode of argNodes) {
1433
- if (argNode.type === "SpreadElement") {
1434
- const spread = yield* self.evaluateExpression(argNode.argument);
1435
- const cursor = yield* self.iterate(spread, argNode);
1436
- if (cursor === undefined)
1437
- throw typeError("Spread arguments require a synchronous iterable.", argNode);
1438
- while (true) {
1439
- const step = yield* cursor.next;
1440
- if (step.done)
1441
- break;
1442
- args.push(step.value);
1443
- }
1444
- }
1445
- else {
1446
- args.push(yield* self.evaluateExpression(argNode));
1679
+ let result;
1680
+ try {
1681
+ result = body();
1682
+ }
1683
+ catch (error) {
1684
+ throw locate(error, node);
1685
+ }
1686
+ return isEval(result) ? located(result, node) : result;
1687
+ }
1688
+ *evaluateCallArguments(argNodes) {
1689
+ const args = [];
1690
+ for (const argNode of argNodes) {
1691
+ if (argNode.type === "SpreadElement") {
1692
+ const spread = yield* this.evaluateExpression(argNode.argument);
1693
+ const cursor = yield* this.iterate(spread, argNode);
1694
+ if (cursor === undefined)
1695
+ throw typeError("Spread arguments require a synchronous iterable.", argNode);
1696
+ while (true) {
1697
+ const step = yield* cursor.next();
1698
+ if (step.done)
1699
+ break;
1700
+ args.push(step.value);
1447
1701
  }
1448
1702
  }
1449
- return args;
1450
- });
1703
+ else {
1704
+ const value = this.evaluate(argNode);
1705
+ args.push(isEval(value) ? yield* value : value);
1706
+ }
1707
+ }
1708
+ return args;
1451
1709
  }
1452
- // A callback invoked by a built-in runs below the call that invoked the built-in, so the deeper of the two counts.
1710
+ // A program call runs as its own activation on the explicit stack, so it is a `Call` for the caller to yield. An
1711
+ // async call returns its promise when the body first suspends or ends; a generator call binds its parameters and
1712
+ // returns the generator without running the body.
1453
1713
  invokeFunction(fn, thisValue, args, node) {
1454
- const self = this;
1455
- return Effect.flatMap(CallSite, (site) => {
1456
- const depth = Math.max(self.depth, site.depth) + 1;
1457
- if (depth > MAX_CALL_DEPTH)
1458
- throw rangeError("Maximum call stack size exceeded", node);
1459
- const invocation = new Frame(this.ctx, new ScopeStack([...fn.capturedScopes, new Map()]), depth);
1460
- const paramScope = invocation.scopes.current();
1461
- // `this` and `arguments` are scope bindings so arrows resolve them lexically; a parameter named
1462
- // `arguments` shadows the object, as in JS.
1463
- if (!fn.arrow)
1464
- paramScope.set("this", { mutable: false, value: thisValue, initialized: true });
1465
- if (!fn.arrow && usesArguments(fn)) {
1466
- paramScope.set("arguments", {
1467
- mutable: true,
1468
- value: new Arguments(self.ctx.builtins.Object, args),
1469
- initialized: true,
1470
- });
1714
+ const runner = this.ctx.runner;
1715
+ // The program's own activation is at the bottom of the stack.
1716
+ if (runner.depth > MAX_CALL_DEPTH)
1717
+ throw rangeError("Maximum call stack size exceeded", node);
1718
+ const invocation = new Frame(this.ctx, new ScopeStack([...fn.capturedScopes, new Map()]));
1719
+ const paramScope = invocation.scopes.current();
1720
+ // `this` and `arguments` are scope bindings so arrows resolve them lexically; a parameter named
1721
+ // `arguments` shadows the object, as in JS.
1722
+ if (!fn.arrow)
1723
+ paramScope.set("this", { mutable: false, value: thisValue, initialized: true });
1724
+ if (!fn.arrow && usesArguments(fn)) {
1725
+ paramScope.set("arguments", {
1726
+ mutable: true,
1727
+ value: new Arguments(this.ctx.builtins.Object, args),
1728
+ initialized: true,
1729
+ });
1730
+ }
1731
+ const simple = isSimple(fn.parameters);
1732
+ if (simple) {
1733
+ // A repeated name takes the last argument for it, as in JS.
1734
+ for (const [index, parameter] of fn.parameters.entries()) {
1735
+ paramScope.set(parameter.name, { mutable: true, value: args[index], initialized: true });
1471
1736
  }
1737
+ }
1738
+ else {
1472
1739
  // Seed all parameters first so defaults cannot fall through to same-named outer bindings.
1473
1740
  for (const parameter of fn.parameters) {
1474
1741
  for (const name of collectPatternNames(parameter)) {
1475
1742
  paramScope.set(name, { mutable: true, value: undefined, initialized: false });
1476
1743
  }
1477
1744
  }
1478
- const parameters = fn.parameters.map((parameter) => parameter.type === "Identifier" ? parameter.name : undefined);
1479
- const bind = Effect.gen(function* () {
1480
- for (const [index, parameter] of fn.parameters.entries()) {
1481
- if (parameter.type === "RestElement") {
1482
- yield* invocation.declarePattern(parameter.argument, new Arr(self.ctx.builtins.Array, args.slice(index)), true, parameter, true);
1483
- break;
1484
- }
1485
- // A sloppy simple parameter list may repeat a name; the last occurrence wins, as in JS.
1486
- if (parameter.type === "Identifier" && parameters.lastIndexOf(parameter.name) !== index)
1487
- continue;
1488
- yield* invocation.declarePattern(parameter, args[index], true, parameter, true);
1489
- }
1490
- });
1491
- const body = Effect.gen(function* () {
1492
- if (fn.body.type === "BlockStatement") {
1493
- invocation.scopes.push();
1494
- invocation.hoistVars(fn.body.body, paramScope);
1495
- const result = yield* invocation.evaluateStatement(fn.body);
1496
- return result.kind === "return" ? result.value : undefined;
1497
- }
1498
- return yield* invocation.evaluateExpression(fn.body);
1499
- });
1500
- // Generators bind parameters at the call and defer only the body to the first `next()`, as in JS.
1501
- if (fn.generator)
1502
- return Effect.map(bind, () => this.createGenerator(invocation, body, fn));
1503
- const run = Effect.andThen(bind, body);
1504
- if (!fn.async)
1505
- return run;
1506
- return this.ctx.pending.createWithSelf((self) => Effect.flatMap(run, (value) => resolvePromiseValue(invocation.ctx, value, self)));
1507
- });
1508
- }
1509
- createGenerator(invocation, run, fn) {
1510
- const asynchronous = fn.async;
1511
- const state = { started: false, completed: false, draining: false, pending: [], pendingIndex: 0 };
1512
- invocation.generatorState = state;
1513
- invocation.generatorAsync = asynchronous;
1514
- const builtins = this.ctx.builtins;
1515
- const result = (value, done) => record(builtins.Object, { value, done });
1516
- const turn = this.ctx.pending.turn;
1517
- const request = (kind, value) => {
1518
- const request = { kind, value, response: Deferred.makeUnsafe() };
1519
- // A body that ran on the caller's turn has answered or suspended when it hands the turn back. An answer still
1520
- // pending can only be an async generator's: its promise settles when the body answers, without the turn.
1521
- const answer = Effect.suspend(() => Deferred.isDoneUnsafe(request.response)
1522
- ? Deferred.await(request.response)
1523
- : turn.leave(Deferred.await(request.response)));
1524
- if (!asynchronous && state.active)
1525
- return Effect.die(typeError("Generator is already running."));
1526
- if (asynchronous && (state.completed || (!state.started && kind !== "next"))) {
1527
- state.started = true;
1528
- state.completed = true;
1529
- state.pending.push(request);
1530
- if (state.draining)
1531
- return answer;
1532
- state.draining = true;
1533
- return Effect.andThen(this.ctx.pending.fork(invocation
1534
- .completeGeneratorRequests(state, true)
1535
- .pipe(Effect.ensuring(Effect.sync(() => (state.draining = false))))), answer);
1536
- }
1537
- if (state.completed) {
1538
- if (kind === "throw")
1539
- return Effect.fail(new Throw(value));
1540
- return Effect.succeed(result(kind === "return" ? value : undefined, true));
1541
- }
1542
- if (!state.started && kind !== "next") {
1543
- state.completed = true;
1544
- if (kind === "throw")
1545
- return Effect.fail(new Throw(value));
1546
- return Effect.succeed(result(value, true));
1547
- }
1548
- state.pending.push(request);
1549
- if (state.available) {
1550
- // The body is parked waiting for a request: it runs this step on the caller's turn.
1551
- const available = state.available;
1552
- state.available = undefined;
1553
- return Effect.andThen(turn.handOff(Effect.sync(() => Deferred.doneUnsafe(available, Exit.succeed(undefined)))), answer);
1554
- }
1555
- if (!state.started) {
1556
- state.started = true;
1557
- const body = Effect.gen(function* () {
1558
- state.active = yield* invocation.takeGeneratorRequest(state);
1559
- const exit = yield* Effect.exit(run.pipe(Effect.flatMap((result) => (asynchronous ? invocation.awaitValue(result) : Effect.succeed(result))), Effect.catch((error) => error instanceof GeneratorReturn
1560
- ? asynchronous
1561
- ? invocation.awaitValue(error.value)
1562
- : Effect.succeed(error.value)
1563
- : Effect.fail(error))));
1564
- const active = state.active;
1565
- state.active = undefined;
1566
- if (active) {
1567
- Deferred.doneUnsafe(active.response, Exit.isSuccess(exit) ? Exit.succeed(result(exit.value, true)) : exit);
1568
- }
1569
- yield* invocation.completeGeneratorRequests(state, asynchronous);
1570
- state.completed = true;
1571
- });
1572
- return Effect.andThen(this.ctx.pending.fork(body), answer);
1573
- }
1574
- return answer;
1575
- };
1576
- const proto = get(fn, "prototype");
1577
- return new GeneratorObj(proto instanceof Obj ? proto : builtins.Generator, asynchronous, request);
1578
- }
1579
- completeGeneratorRequests(state, asynchronous) {
1580
- const self = this;
1581
- const result = (value, done) => record(self.ctx.builtins.Object, { value, done });
1582
- return Effect.gen(function* () {
1583
- while (true) {
1584
- const pending = self.dequeueGeneratorRequest(state);
1585
- if (!pending)
1586
- return;
1587
- if (pending.kind === "throw") {
1588
- Deferred.doneUnsafe(pending.response, Exit.fail(new Throw(pending.value)));
1589
- continue;
1590
- }
1591
- if (asynchronous && pending.kind === "return") {
1592
- const resolved = yield* Effect.exit(self.awaitValue(pending.value));
1593
- Deferred.doneUnsafe(pending.response, Exit.isSuccess(resolved) ? Exit.succeed(result(resolved.value, true)) : resolved);
1745
+ }
1746
+ if (fn.generator) {
1747
+ invocation.generator = true;
1748
+ invocation.generatorAsync = fn.async;
1749
+ // The prototype is read after the parameters bind, since a default may replace it.
1750
+ const create = () => {
1751
+ const proto = get(fn, "prototype");
1752
+ return new GeneratorObj(proto instanceof Obj ? proto : fn.async ? this.ctx.builtins.AsyncGenerator : this.ctx.builtins.Generator, fn.async, generatorBody(invocation.functionBody(fn, paramScope)));
1753
+ };
1754
+ if (simple)
1755
+ return create();
1756
+ return (function* () {
1757
+ yield* invocation.bindParameters(fn, args);
1758
+ return create();
1759
+ })();
1760
+ }
1761
+ const body = simple ? invocation.functionBody(fn, paramScope) : invocation.enter(fn, args, paramScope);
1762
+ if (!fn.async)
1763
+ return new Call(body);
1764
+ const promise = runner.newPromise();
1765
+ const resolving = runner.resolving(promise);
1766
+ return new Call(body, new AsyncBoundary((completion) => completion.ok ? resolving.resolve(completion.value) : resolving.reject(completion.error), promise));
1767
+ }
1768
+ *enter(fn, args, paramScope) {
1769
+ yield* this.bindParameters(fn, args);
1770
+ return yield* this.functionBody(fn, paramScope);
1771
+ }
1772
+ *bindParameters(fn, args) {
1773
+ const parameters = fn.parameters;
1774
+ for (const [index, parameter] of parameters.entries()) {
1775
+ if (parameter.type === "RestElement") {
1776
+ yield* this.declarePattern(parameter.argument, new Arr(this.ctx.builtins.Array, args.slice(index)), true, parameter, true);
1777
+ break;
1778
+ }
1779
+ if (parameter.type === "Identifier") {
1780
+ // A sloppy simple parameter list may repeat a name; the last occurrence wins, as in JS.
1781
+ if (parameters.findLastIndex((other) => other.type === "Identifier" && other.name === parameter.name) !== index)
1594
1782
  continue;
1595
- }
1596
- Deferred.doneUnsafe(pending.response, Exit.succeed(result(pending.kind === "return" ? pending.value : undefined, true)));
1783
+ this.scopes.initialize(parameter.name, args[index], parameter);
1784
+ continue;
1597
1785
  }
1598
- });
1599
- }
1600
- takeGeneratorRequest(state) {
1601
- const next = this.dequeueGeneratorRequest(state);
1602
- if (next)
1603
- return Effect.succeed(next);
1604
- state.available = Deferred.makeUnsafe();
1605
- return Effect.andThen(this.ctx.pending.turn.park(Deferred.await(state.available)), Effect.sync(() => this.dequeueGeneratorRequest(state)));
1786
+ yield* this.declarePattern(parameter, args[index], true, parameter, true);
1787
+ }
1606
1788
  }
1607
- dequeueGeneratorRequest(state) {
1608
- const request = state.pending[state.pendingIndex];
1609
- if (!request)
1610
- return undefined;
1611
- state.pendingIndex += 1;
1612
- if (state.pendingIndex === state.pending.length) {
1613
- state.pending = [];
1614
- state.pendingIndex = 0;
1789
+ *functionBody(fn, paramScope) {
1790
+ if (fn.body.type === "BlockStatement") {
1791
+ this.scopes.push();
1792
+ this.hoistVars(fn.body.body, paramScope);
1793
+ const result = yield* this.evaluateBlock(fn.body);
1794
+ return result.kind === "return" ? result.value : undefined;
1615
1795
  }
1616
- return request;
1796
+ const result = this.evaluate(fn.body);
1797
+ return isEval(result) ? yield* result : result;
1617
1798
  }
1618
- evaluateYieldExpression(node) {
1799
+ *evaluateYieldExpression(node) {
1619
1800
  const argument = node.argument;
1620
- const self = this;
1621
- return Effect.gen(function* () {
1622
- if (!self.generatorState)
1623
- throw typeError("yield is only valid inside a generator.", node);
1624
- if (node.delegate) {
1625
- const value = argument ? yield* self.evaluateExpression(argument) : undefined;
1626
- return yield* self.delegateYield(value, node);
1627
- }
1628
- const value = argument ? yield* self.evaluateExpression(argument) : undefined;
1629
- const yielded = self.generatorAsync ? yield* self.awaitValue(value) : value;
1630
- return yield* self.suspendGenerator(yielded, node);
1631
- });
1632
- }
1633
- suspendGenerator(value, node) {
1634
- const state = this.generatorState;
1635
- if (!state?.active)
1636
- throw typeError("Generator has no active request.", node);
1637
- Deferred.doneUnsafe(state.active.response, Exit.succeed(record(this.ctx.builtins.Object, { value, done: false })));
1638
- state.active = undefined;
1639
- return Effect.flatMap(this.takeGeneratorRequest(state), (request) => {
1640
- state.active = request;
1641
- if (request.kind === "next")
1642
- return Effect.succeed(request.value);
1643
- if (request.kind === "throw")
1644
- return Effect.fail(new Throw(request.value));
1645
- return this.generatorAsync
1646
- ? Effect.flatMap(this.awaitValue(request.value), (value) => Effect.fail(new GeneratorReturn(value)))
1647
- : Effect.fail(new GeneratorReturn(request.value));
1648
- });
1649
- }
1650
- delegateYield(value, node) {
1651
- const self = this;
1652
- return Effect.gen(function* () {
1653
- const cursor = self.builtinCursor(value);
1654
- if (cursor !== undefined) {
1655
- while (true) {
1656
- const step = yield* cursor.next;
1657
- if (step.done)
1658
- return undefined;
1659
- const resumed = yield* Effect.exit(self.suspendGenerator(self.generatorAsync ? yield* self.awaitValue(step.value) : step.value, node));
1660
- if (Exit.isSuccess(resumed))
1661
- continue;
1662
- const error = Cause.squash(resumed.cause);
1801
+ if (!this.generator)
1802
+ throw typeError("yield is only valid inside a generator.", node);
1803
+ const value = argument ? yield* this.evaluateExpression(argument) : undefined;
1804
+ if (node.delegate)
1805
+ return yield* this.delegateYield(value, node);
1806
+ return yield* this.suspendGenerator(this.generatorAsync ? yield* this.awaitValue(value, node) : value);
1807
+ }
1808
+ // Yield `value` and continue with the request that resumes the body: `next` supplies the value of the `yield`,
1809
+ // `throw` throws there, and `return` unwinds through `finally` blocks (an async generator awaits the value first).
1810
+ *suspendGenerator(value) {
1811
+ const request = (yield new Yield(value));
1812
+ if (request.kind === "next")
1813
+ return request.value;
1814
+ if (request.kind === "throw")
1815
+ throw new Throw(request.value);
1816
+ throw new GeneratorReturn(this.generatorAsync ? yield* this.awaitValue(request.value) : request.value);
1817
+ }
1818
+ *delegateYield(value, node) {
1819
+ const builtin = this.builtinCursor(value);
1820
+ if (builtin !== undefined && !this.generatorAsync) {
1821
+ while (true) {
1822
+ const step = yield* builtin.next();
1823
+ if (step.done)
1824
+ return undefined;
1825
+ try {
1826
+ yield* this.suspendGenerator(step.value);
1827
+ }
1828
+ catch (error) {
1663
1829
  if (error instanceof GeneratorReturn) {
1664
- yield* cursor.close;
1665
- return yield* Effect.fail(error);
1830
+ yield* builtin.close();
1831
+ throw error;
1666
1832
  }
1667
1833
  if (error instanceof Throw) {
1668
- yield* cursor.close;
1834
+ yield* builtin.close();
1669
1835
  throw typeError("The delegated iterator does not provide a throw() method.", node);
1670
1836
  }
1671
- return yield* Effect.failCause(resumed.cause);
1837
+ throw error;
1672
1838
  }
1673
1839
  }
1674
- const iterator = yield* self.customIterator(value, node, self.generatorAsync);
1675
- if (!iterator)
1676
- throw typeError("yield* requires a compatible iterable value.", node);
1677
- let kind = "next";
1678
- let input = undefined;
1679
- while (true) {
1680
- const method = kind === "next" ? iterator.next : get(iterator.iterator, kind);
1681
- if (method === undefined || method === null) {
1682
- if (kind === "return")
1683
- return yield* Effect.fail(new GeneratorReturn(input));
1684
- yield* self.closeIterator(iterator, node, self.generatorAsync);
1685
- throw typeError("The delegated iterator does not provide a throw() method.", node);
1686
- }
1687
- const called = yield* self.call(self.requireIteratorMethod(method, `Iterator ${kind}`, node), iterator.iterator, [input], node);
1688
- const result = self.requireIteratorObject(iterator.asynchronous ? yield* self.awaitValue(called) : called, `Iterator ${kind}() result`, node);
1689
- const done = Boolean(get(result, "done"));
1690
- const resultValue = self.generatorAsync && !iterator.asynchronous
1691
- ? yield* self.awaitAsyncFromSyncValue(iterator, get(result, "value"), node, kind !== "return" && !done)
1692
- : get(result, "value");
1693
- if (done) {
1694
- if (kind === "return")
1695
- return yield* Effect.fail(new GeneratorReturn(resultValue));
1696
- return resultValue;
1697
- }
1698
- const resumed = yield* Effect.exit(self.suspendGenerator(resultValue, node));
1699
- if (Exit.isSuccess(resumed)) {
1700
- kind = "next";
1701
- input = resumed.value;
1702
- continue;
1703
- }
1704
- const error = Cause.squash(resumed.cause);
1705
- if (!(error instanceof GeneratorReturn) && !(error instanceof Throw)) {
1706
- return yield* Effect.failCause(resumed.cause);
1707
- }
1840
+ }
1841
+ const custom = builtin === undefined ? yield* this.customIterator(value, node, this.generatorAsync) : undefined;
1842
+ if (builtin === undefined && !custom)
1843
+ throw typeError("yield* requires a compatible iterable value.", node);
1844
+ // An async generator delegates to a synchronous iterator through CreateAsyncFromSyncIterator, as JS does.
1845
+ const iterator = this.generatorAsync && !custom?.asynchronous ? this.asyncFromSync(builtin, custom, node) : custom;
1846
+ let kind = "next";
1847
+ let input = undefined;
1848
+ while (true) {
1849
+ const method = kind === "next" ? iterator.next : get(iterator.iterator, kind);
1850
+ if (method === undefined || method === null) {
1851
+ if (kind === "return")
1852
+ throw new GeneratorReturn(this.generatorAsync ? yield* this.awaitValue(input, node) : input);
1853
+ yield* this.closeIterator(iterator, node);
1854
+ throw typeError("The delegated iterator does not provide a throw() method.", node);
1855
+ }
1856
+ const called = yield* this.call(this.requireIteratorMethod(method, `Iterator ${kind}`, node), iterator.iterator, [input], node);
1857
+ const result = this.requireIteratorObject(iterator.asynchronous ? yield* this.awaitValue(called, node) : called, `Iterator ${kind}() result`, node);
1858
+ const done = Boolean(get(result, "done"));
1859
+ const resultValue = get(result, "value");
1860
+ if (done) {
1861
+ if (kind === "return")
1862
+ throw new GeneratorReturn(resultValue);
1863
+ return resultValue;
1864
+ }
1865
+ try {
1866
+ // Delegated values are yielded as they are; an async generator's inner promise already settled them.
1867
+ input = yield* this.suspendGenerator(resultValue);
1868
+ kind = "next";
1869
+ }
1870
+ catch (error) {
1871
+ if (!(error instanceof GeneratorReturn) && !(error instanceof Throw))
1872
+ throw error;
1708
1873
  kind = error instanceof GeneratorReturn ? "return" : "throw";
1709
1874
  input = error.value;
1710
1875
  }
1711
- });
1876
+ }
1712
1877
  }
1713
- evaluateObjectExpression(node) {
1878
+ *evaluateObjectExpression(node) {
1714
1879
  const objectValue = new Obj(this.ctx.builtins.Object);
1715
- const self = this;
1716
- return Effect.gen(function* () {
1717
- for (const property of node.properties) {
1718
- if (property.type === "SpreadElement") {
1719
- const spread = yield* self.evaluateExpression(property.argument);
1720
- if (spread === null || spread === undefined)
1721
- continue;
1722
- assign(objectValue, enumerableSource(self.ctx, "Object spread", spread, property));
1880
+ for (const property of node.properties) {
1881
+ if (property.type === "SpreadElement") {
1882
+ const spread = yield* this.evaluateExpression(property.argument);
1883
+ if (spread === null || spread === undefined)
1723
1884
  continue;
1724
- }
1725
- if (property.kind !== "init") {
1726
- throw typeError("Only init object properties are supported.", property);
1727
- }
1728
- const keyNode = property.key;
1729
- let key;
1730
- if (property.computed) {
1731
- key = yield* self.toPropertyKey(yield* self.evaluateExpression(keyNode), keyNode);
1732
- }
1733
- else if (keyNode.type === "Identifier") {
1734
- key = keyNode.name;
1735
- }
1736
- else if (keyNode.type === "Literal") {
1737
- key = propertyKey(literal(keyNode));
1738
- }
1739
- else {
1740
- throw typeError("Unsupported object property key shape.", keyNode);
1741
- }
1742
- const name = key === IteratorSymbol
1743
- ? "[Symbol.iterator]"
1744
- : key === AsyncIteratorSymbol
1745
- ? "[Symbol.asyncIterator]"
1746
- : String(key);
1747
- define(objectValue, key, yield* self.evaluateNamed(property.value, name));
1748
- }
1749
- return objectValue;
1750
- });
1885
+ assign(objectValue, enumerableSource(this.ctx, "Object spread", spread, property));
1886
+ continue;
1887
+ }
1888
+ if (property.kind !== "init") {
1889
+ throw typeError("Only init object properties are supported.", property);
1890
+ }
1891
+ const keyNode = property.key;
1892
+ let key;
1893
+ if (property.computed) {
1894
+ key = yield* this.toPropertyKey(yield* this.evaluateExpression(keyNode), keyNode);
1895
+ }
1896
+ else if (keyNode.type === "Identifier") {
1897
+ key = keyNode.name;
1898
+ }
1899
+ else if (keyNode.type === "Literal") {
1900
+ key = propertyKey(literal(keyNode));
1901
+ }
1902
+ else {
1903
+ throw typeError("Unsupported object property key shape.", keyNode);
1904
+ }
1905
+ const name = key === IteratorSymbol
1906
+ ? "[Symbol.iterator]"
1907
+ : key === AsyncIteratorSymbol
1908
+ ? "[Symbol.asyncIterator]"
1909
+ : String(key);
1910
+ define(objectValue, key, yield* this.evaluateNamed(property.value, name));
1911
+ }
1912
+ return objectValue;
1751
1913
  }
1752
- evaluateArrayExpression(node) {
1914
+ *evaluateArrayExpression(node) {
1753
1915
  const values = [];
1754
- const self = this;
1755
- return Effect.gen(function* () {
1756
- for (const element of node.elements) {
1757
- if (element === null) {
1758
- // A literal elision is a real hole, like JS: extend length without an own index.
1759
- values.length += 1;
1760
- continue;
1761
- }
1762
- if (element.type === "SpreadElement") {
1763
- const spread = yield* self.evaluateExpression(element.argument);
1764
- const cursor = yield* self.iterate(spread, element);
1765
- if (cursor === undefined)
1766
- throw typeError("Array spread requires a synchronous iterable.", element);
1767
- while (true) {
1768
- const step = yield* cursor.next;
1769
- if (step.done)
1770
- break;
1771
- values.push(step.value);
1772
- }
1773
- }
1774
- else {
1775
- values.push(yield* self.evaluateExpression(element));
1916
+ for (const element of node.elements) {
1917
+ if (element === null) {
1918
+ // A literal elision is a real hole, like JS: extend length without an own index.
1919
+ values.length += 1;
1920
+ continue;
1921
+ }
1922
+ if (element.type === "SpreadElement") {
1923
+ const spread = yield* this.evaluateExpression(element.argument);
1924
+ const cursor = yield* this.iterate(spread, element);
1925
+ if (cursor === undefined)
1926
+ throw typeError("Array spread requires a synchronous iterable.", element);
1927
+ while (true) {
1928
+ const step = yield* cursor.next();
1929
+ if (step.done)
1930
+ break;
1931
+ values.push(step.value);
1776
1932
  }
1777
1933
  }
1778
- return new Arr(self.ctx.builtins.Array, values);
1779
- });
1934
+ else {
1935
+ values.push(yield* this.evaluateExpression(element));
1936
+ }
1937
+ }
1938
+ return new Arr(this.ctx.builtins.Array, values);
1780
1939
  }
1781
- evaluateTemplateLiteral(node) {
1940
+ *evaluateTemplateLiteral(node) {
1782
1941
  const quasis = node.quasis;
1783
1942
  const expressions = node.expressions;
1784
1943
  let output = "";
1785
- const self = this;
1786
- return Effect.gen(function* () {
1787
- for (let index = 0; index < quasis.length; index += 1) {
1788
- const quasi = quasis[index];
1789
- // acorn only omits `cooked` for invalid escapes, which are a parse error outside a tagged template.
1790
- if (typeof quasi.value.cooked !== "string") {
1791
- throw typeError("Invalid template literal quasi.", quasi);
1792
- }
1793
- output += quasi.value.cooked;
1944
+ for (let index = 0; index < quasis.length; index += 1) {
1945
+ const quasi = quasis[index];
1946
+ // acorn only omits `cooked` for invalid escapes, which are a parse error outside a tagged template.
1947
+ if (typeof quasi.value.cooked !== "string") {
1948
+ throw typeError("Invalid template literal quasi.", quasi);
1949
+ }
1950
+ output += quasi.value.cooked;
1951
+ checkStringLength(output.length);
1952
+ if (index < expressions.length) {
1953
+ const raw = yield* this.evaluateExpression(expressions[index]);
1954
+ output += coerceToString(yield* this.toPrimitive(raw, "string", expressions[index]));
1794
1955
  checkStringLength(output.length);
1795
- if (index < expressions.length) {
1796
- const raw = yield* self.evaluateExpression(expressions[index]);
1797
- output += coerceToString(yield* self.toPrimitive(raw, "string", expressions[index]));
1798
- checkStringLength(output.length);
1799
- }
1800
1956
  }
1801
- return output;
1802
- });
1957
+ }
1958
+ return output;
1803
1959
  }
1804
1960
  // `tag\`a${x}b\`` is `tag(strings, x)`: the tag is read like a callee (a member keeps its receiver), the
1805
1961
  // substitutions are evaluated in order, and `strings` carries the escaped source as `strings.raw`.
1806
- evaluateTaggedTemplate(node) {
1807
- const self = this;
1808
- return Effect.gen(function* () {
1809
- const { callable, thisValue } = node.tag.type === "MemberExpression"
1810
- ? yield* self.readMethod(node.tag)
1811
- : { callable: yield* self.evaluateExpression(node.tag), thisValue: undefined };
1812
- const strings = self.ctx.templates.get(node) ?? self.createTemplateObject(node);
1813
- const values = yield* Effect.forEach(node.quasi.expressions, (expression) => self.evaluateExpression(expression));
1814
- return yield* self.call(callable, thisValue, [strings, ...values], node, node.tag);
1815
- });
1962
+ *evaluateTaggedTemplate(node) {
1963
+ const { callable, thisValue } = node.tag.type === "MemberExpression"
1964
+ ? yield* this.readMethod(node.tag)
1965
+ : { callable: yield* this.evaluateExpression(node.tag), thisValue: undefined };
1966
+ const strings = this.ctx.templates.get(node) ?? this.createTemplateObject(node);
1967
+ const values = [];
1968
+ for (const expression of node.quasi.expressions)
1969
+ values.push(yield* this.evaluateExpression(expression));
1970
+ return yield* this.call(callable, thisValue, [strings, ...values], node, node.tag);
1816
1971
  }
1817
1972
  createTemplateObject(node) {
1818
1973
  const array = this.ctx.builtins.Array;
@@ -1822,34 +1977,51 @@ class Frame {
1822
1977
  this.ctx.templates.set(node, strings);
1823
1978
  return strings;
1824
1979
  }
1825
- evaluateConditionalExpression(node) {
1826
- return Effect.flatMap(this.evaluateExpression(node.test), (test) => this.evaluateExpression(test ? node.consequent : node.alternate));
1827
- }
1828
- getMemberReference(node) {
1980
+ *getMemberReference(node, object = unevaluated, key = unevaluated) {
1829
1981
  const objectNode = node.object;
1830
1982
  const propertyNode = node.property;
1831
1983
  if (objectNode.type === "Super")
1832
1984
  throw unsupportedSyntax(objectNode.type, objectNode);
1833
1985
  if (propertyNode.type === "PrivateIdentifier")
1834
1986
  throw unsupportedSyntax(propertyNode.type, propertyNode);
1835
- const self = this;
1836
- return Effect.gen(function* () {
1837
- const objectValue = yield* self.evaluateExpression(objectNode);
1838
- if (objectValue === OptionalShortCircuit)
1839
- return OptionalShortCircuit;
1840
- if ((objectValue === null || objectValue === undefined) && node.optional)
1841
- return OptionalShortCircuit;
1842
- const keyValue = !node.computed && propertyNode.type === "Identifier"
1987
+ const evaluated = object === unevaluated ? this.evaluate(objectNode) : object;
1988
+ const objectValue = isEval(evaluated) ? yield* evaluated : evaluated;
1989
+ if (objectValue === OptionalShortCircuit)
1990
+ return OptionalShortCircuit;
1991
+ if ((objectValue === null || objectValue === undefined) && node.optional)
1992
+ return OptionalShortCircuit;
1993
+ const computed = key !== unevaluated
1994
+ ? key
1995
+ : !node.computed && propertyNode.type === "Identifier"
1843
1996
  ? propertyNode.name
1844
- : yield* self.evaluateExpression(propertyNode);
1845
- // GetValue applies ToObject to the base before ToPropertyKey, so a nullish base throws before the key's own
1846
- // toString runs.
1847
- if (objectValue === null || objectValue === undefined) {
1848
- throw typeError(`Cannot read properties of ${objectValue} (reading '${coerceToString(keyValue)}').`, objectNode);
1849
- }
1850
- const key = yield* self.toPropertyKey(keyValue, propertyNode);
1851
- return self.resolveProperty(objectValue, key, objectNode, propertyNode);
1852
- });
1997
+ : this.evaluate(propertyNode);
1998
+ const keyValue = isEval(computed) ? yield* computed : computed;
1999
+ const reference = this.memberReference(node, objectValue, keyValue);
2000
+ return isEval(reference) ? yield* reference : reference;
2001
+ }
2002
+ // The reference once the object and key are evaluated: ToPropertyKey on an object key may run program code.
2003
+ // GetValue applies ToObject to the base before ToPropertyKey, so a nullish base throws before the key's own
2004
+ // toString runs.
2005
+ memberReference(node, objectValue, keyValue) {
2006
+ if (objectValue === null || objectValue === undefined) {
2007
+ throw typeError(`Cannot read properties of ${objectValue} (reading '${coerceToString(keyValue)}').`, node.object);
2008
+ }
2009
+ if (keyValue instanceof Obj)
2010
+ return this.resolveAfterKey(node, objectValue, keyValue);
2011
+ return this.resolveProperty(objectValue, propertyKey(keyValue), node.object, node.property);
2012
+ }
2013
+ *resolveAfterKey(node, objectValue, keyValue) {
2014
+ const key = yield* this.toPropertyKey(keyValue, node.property);
2015
+ return this.resolveProperty(objectValue, key, node.object, node.property);
2016
+ }
2017
+ readResolved(node, reference) {
2018
+ if (reference === OptionalShortCircuit)
2019
+ return OptionalShortCircuit;
2020
+ if (reference instanceof ToolReference)
2021
+ return reference;
2022
+ if ("value" in reference)
2023
+ return reference.value;
2024
+ return this.readReference(reference, node);
1853
2025
  }
1854
2026
  resolveProperty(objectValue, key, objectNode, propertyNode) {
1855
2027
  if (objectValue instanceof ToolReference) {
@@ -1901,55 +2073,47 @@ class Frame {
1901
2073
  throw locate(error, node);
1902
2074
  }
1903
2075
  }
1904
- readMember(node) {
1905
- return Effect.map(this.getMemberReference(node), (reference) => {
1906
- if (reference === OptionalShortCircuit)
1907
- return OptionalShortCircuit;
1908
- if (reference instanceof ToolReference)
1909
- return reference;
1910
- if ("value" in reference)
1911
- return reference.value;
1912
- return this.readReference(reference, node);
1913
- });
2076
+ *readMember(node, object = unevaluated, key = unevaluated) {
2077
+ return this.readResolved(node, yield* this.getMemberReference(node, object, key));
1914
2078
  }
1915
2079
  writeMember(node, value) {
1916
- return this.modifyMember(node, () => Effect.succeed({ write: true, next: value, result: value }));
2080
+ return this.modifyMember(node, function* () {
2081
+ return { write: true, next: value, result: value };
2082
+ });
1917
2083
  }
1918
- evaluateDeleteExpression(argument) {
2084
+ *evaluateDeleteExpression(argument) {
1919
2085
  const target = argument.type === "ChainExpression" ? argument.expression : argument;
1920
2086
  if (target.type === "Identifier")
1921
2087
  throw typeError("Only data fields may be deleted.", argument);
1922
2088
  // `delete <non-reference>` evaluates the operand and is true, as in JS.
1923
- if (target.type !== "MemberExpression")
1924
- return Effect.map(this.evaluateExpression(target), () => true);
1925
- return Effect.map(this.getMemberReference(target), (reference) => {
1926
- if (reference === OptionalShortCircuit)
1927
- return true;
1928
- if (reference instanceof ToolReference || "value" in reference || reference.receiver !== reference.target) {
1929
- throw invalidData("Only data fields may be deleted.", target);
1930
- }
1931
- if (remove(reference.target, reference.key))
1932
- return true;
1933
- throw typeError(`Cannot delete property '${String(reference.key)}'.`, target);
1934
- });
2089
+ if (target.type !== "MemberExpression") {
2090
+ yield* this.evaluateExpression(target);
2091
+ return true;
2092
+ }
2093
+ const reference = yield* this.getMemberReference(target);
2094
+ if (reference === OptionalShortCircuit)
2095
+ return true;
2096
+ if (reference instanceof ToolReference || "value" in reference || reference.receiver !== reference.target) {
2097
+ throw invalidData("Only data fields may be deleted.", target);
2098
+ }
2099
+ if (remove(reference.target, reference.key))
2100
+ return true;
2101
+ throw typeError(`Cannot delete property '${String(reference.key)}'.`, target);
1935
2102
  }
1936
2103
  // Resolve side-effecting object and key expressions exactly once.
1937
- modifyMember(node, compute) {
1938
- const self = this;
1939
- return Effect.gen(function* () {
1940
- const reference = yield* self.getMemberReference(node);
1941
- if (reference === OptionalShortCircuit || reference instanceof ToolReference || "value" in reference) {
1942
- throw typeError("Only data fields may be assigned.", node);
1943
- }
1944
- if (reference.receiver !== reference.target) {
1945
- throw typeError(`Cannot create property '${String(reference.key)}' on ${typeof reference.receiver} '${String(reference.receiver)}'.`, node);
1946
- }
1947
- const key = reference.key;
1948
- const { write, next, result } = yield* compute(self.readReference(reference, node));
1949
- if (write)
1950
- self.assignToReference(reference.target, key, next, node);
1951
- return result;
1952
- });
2104
+ *modifyMember(node, compute) {
2105
+ const reference = yield* this.getMemberReference(node);
2106
+ if (reference === OptionalShortCircuit || reference instanceof ToolReference || "value" in reference) {
2107
+ throw typeError("Only data fields may be assigned.", node);
2108
+ }
2109
+ if (reference.receiver !== reference.target) {
2110
+ throw typeError(`Cannot create property '${String(reference.key)}' on ${typeof reference.receiver} '${String(reference.receiver)}'.`, node);
2111
+ }
2112
+ const key = reference.key;
2113
+ const { write, next, result } = yield* compute(this.readReference(reference, node));
2114
+ if (write)
2115
+ this.assignToReference(reference.target, key, next, node);
2116
+ return result;
1953
2117
  }
1954
2118
  assignToReference(target, key, next, node) {
1955
2119
  const written = (() => {
@@ -1967,9 +2131,39 @@ class Frame {
1967
2131
  }
1968
2132
  // ToPropertyKey: a data object converts through its own `toString`/`valueOf` first; anything else becomes its
1969
2133
  // string form synchronously, so `counts[row.category]` works when the field is null.
1970
- toPropertyKey(value, node) {
2134
+ *toPropertyKey(value, node) {
1971
2135
  if (!(value instanceof Obj))
1972
- return Effect.succeed(propertyKey(value));
1973
- return Effect.map(this.toPrimitive(value, "string", node), propertyKey);
2136
+ return propertyKey(value);
2137
+ return propertyKey(yield* this.toPrimitive(value, "string", node));
2138
+ }
2139
+ }
2140
+ // The body a generator object resumes: a `return()` request ends it with the returned value.
2141
+ function* generatorBody(body) {
2142
+ try {
2143
+ return yield* body;
1974
2144
  }
2145
+ catch (error) {
2146
+ if (error instanceof GeneratorReturn)
2147
+ return error.value;
2148
+ throw error;
2149
+ }
2150
+ }
2151
+ // Rethrows inside interpreter work, so a failure already caught can pass through `preserveConsumerError`.
2152
+ function* thrower(error) {
2153
+ throw error;
2154
+ }
2155
+ // Finishes a built-in's work, locating a failure at the call that started it.
2156
+ function* located(work, node) {
2157
+ try {
2158
+ return yield* work;
2159
+ }
2160
+ catch (error) {
2161
+ throw locate(error, node);
2162
+ }
2163
+ }
2164
+ // Lets the host run first, then starts the work.
2165
+ function* afterSlice(start) {
2166
+ yield Slice;
2167
+ const result = start();
2168
+ return isEval(result) ? yield* result : result;
1975
2169
  }