@opencode/codemode 2.2.6 → 2.3.0

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