@opencode/codemode 2.2.5 → 2.2.7

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 (142) hide show
  1. package/README.md +164 -7
  2. package/dist/codemode.d.ts +60 -4
  3. package/dist/codemode.js +63 -8
  4. package/dist/extension.d.ts +27 -9
  5. package/dist/extension.js +7 -3
  6. package/dist/index.d.ts +1 -1
  7. package/dist/index.js +1 -1
  8. package/dist/interpreter/callback.d.ts +12 -1
  9. package/dist/interpreter/callback.js +13 -1
  10. package/dist/interpreter/execute.d.ts +1 -1
  11. package/dist/interpreter/execute.js +16 -4
  12. package/dist/interpreter/extensions.d.ts +3 -3
  13. package/dist/interpreter/extensions.js +17 -11
  14. package/dist/interpreter/globals.js +10 -0
  15. package/dist/interpreter/interpreter.d.ts +11 -1
  16. package/dist/interpreter/interpreter.js +88 -4
  17. package/dist/interpreter/modules.d.ts +4 -0
  18. package/dist/interpreter/modules.js +33 -0
  19. package/dist/interpreter/promises.js +2 -2
  20. package/dist/interpreter/runner.d.ts +1 -11
  21. package/dist/interpreter/runner.js +1 -13
  22. package/dist/stdlib/iterator.js +1 -2
  23. package/dist/suspend-error.d.ts +24 -0
  24. package/dist/suspend-error.js +25 -0
  25. package/dist/tool-runtime.d.ts +31 -7
  26. package/dist/tool-runtime.js +116 -26
  27. package/dist/tool.d.ts +45 -2
  28. package/dist/tool.js +30 -7
  29. package/dist/vm/async.d.ts +78 -0
  30. package/dist/vm/async.js +335 -0
  31. package/dist/vm/code.d.ts +122 -0
  32. package/dist/vm/code.js +407 -0
  33. package/dist/vm/compiler/compile.d.ts +13 -0
  34. package/dist/vm/compiler/compile.js +1477 -0
  35. package/dist/vm/compiler/scope.d.ts +74 -0
  36. package/dist/vm/compiler/scope.js +515 -0
  37. package/dist/vm/data.d.ts +7 -0
  38. package/dist/vm/data.js +13 -0
  39. package/dist/vm/generators.d.ts +42 -0
  40. package/dist/vm/generators.js +413 -0
  41. package/dist/vm/host.d.ts +106 -0
  42. package/dist/vm/host.js +231 -0
  43. package/dist/vm/index.d.ts +6 -0
  44. package/dist/vm/index.js +6 -0
  45. package/dist/vm/internal-prelude.d.ts +45 -0
  46. package/dist/vm/internal-prelude.js +534 -0
  47. package/dist/vm/opcodes.d.ts +222 -0
  48. package/dist/vm/opcodes.js +235 -0
  49. package/dist/vm/prelude/bytecode.d.ts +18 -0
  50. package/dist/vm/prelude/bytecode.js +31 -0
  51. package/dist/vm/prelude/bytecode.json +1 -0
  52. package/dist/vm/prelude/helpers.d.ts +8 -0
  53. package/dist/vm/prelude/helpers.js +258 -0
  54. package/dist/vm/prelude/prelude.d.ts +21 -0
  55. package/dist/vm/prelude/prelude.js +53 -0
  56. package/dist/vm/prelude/source.d.ts +1 -0
  57. package/dist/vm/prelude/source.js +652 -0
  58. package/dist/vm/runtime/callback.d.ts +25 -0
  59. package/dist/vm/runtime/callback.js +51 -0
  60. package/dist/vm/runtime/driver.d.ts +68 -0
  61. package/dist/vm/runtime/driver.js +254 -0
  62. package/dist/vm/runtime/errors.d.ts +23 -0
  63. package/dist/vm/runtime/errors.js +169 -0
  64. package/dist/vm/runtime/execute.d.ts +80 -0
  65. package/dist/vm/runtime/execute.js +442 -0
  66. package/dist/vm/runtime/extensions.d.ts +16 -0
  67. package/dist/vm/runtime/extensions.js +337 -0
  68. package/dist/vm/runtime/generators.d.ts +6 -0
  69. package/dist/vm/runtime/generators.js +44 -0
  70. package/dist/vm/runtime/globals.d.ts +6 -0
  71. package/dist/vm/runtime/globals.js +137 -0
  72. package/dist/vm/runtime/interpreter.d.ts +53 -0
  73. package/dist/vm/runtime/interpreter.js +96 -0
  74. package/dist/vm/runtime/intrinsic-names.d.ts +56 -0
  75. package/dist/vm/runtime/intrinsic-names.js +166 -0
  76. package/dist/vm/runtime/intrinsics.d.ts +15 -0
  77. package/dist/vm/runtime/intrinsics.js +111 -0
  78. package/dist/vm/runtime/limits.d.ts +10 -0
  79. package/dist/vm/runtime/limits.js +19 -0
  80. package/dist/vm/runtime/model.d.ts +58 -0
  81. package/dist/vm/runtime/model.js +57 -0
  82. package/dist/vm/runtime/modules.d.ts +4 -0
  83. package/dist/vm/runtime/modules.js +33 -0
  84. package/dist/vm/runtime/native.d.ts +19 -0
  85. package/dist/vm/runtime/native.js +41 -0
  86. package/dist/vm/runtime/objects.d.ts +403 -0
  87. package/dist/vm/runtime/objects.js +784 -0
  88. package/dist/vm/runtime/operations.d.ts +49 -0
  89. package/dist/vm/runtime/operations.js +288 -0
  90. package/dist/vm/runtime/promises.d.ts +55 -0
  91. package/dist/vm/runtime/promises.js +232 -0
  92. package/dist/vm/runtime/references.d.ts +8 -0
  93. package/dist/vm/runtime/references.js +51 -0
  94. package/dist/vm/runtime/signals.d.ts +69 -0
  95. package/dist/vm/runtime/signals.js +68 -0
  96. package/dist/vm/runtime/source.d.ts +29 -0
  97. package/dist/vm/runtime/source.js +63 -0
  98. package/dist/vm/runtime/table.d.ts +43 -0
  99. package/dist/vm/runtime/table.js +132 -0
  100. package/dist/vm/scheduler.d.ts +190 -0
  101. package/dist/vm/scheduler.js +74 -0
  102. package/dist/vm/snapshot/codec.d.ts +117 -0
  103. package/dist/vm/snapshot/codec.js +848 -0
  104. package/dist/vm/snapshot/snapshot.d.ts +53 -0
  105. package/dist/vm/snapshot/snapshot.js +74 -0
  106. package/dist/vm/snapshot.d.ts +32 -0
  107. package/dist/vm/snapshot.js +309 -0
  108. package/dist/vm/stdlib/array.d.ts +16 -0
  109. package/dist/vm/stdlib/array.js +311 -0
  110. package/dist/vm/stdlib/bytes.d.ts +11 -0
  111. package/dist/vm/stdlib/bytes.js +222 -0
  112. package/dist/vm/stdlib/collections.d.ts +7 -0
  113. package/dist/vm/stdlib/collections.js +188 -0
  114. package/dist/vm/stdlib/console.d.ts +6 -0
  115. package/dist/vm/stdlib/console.js +93 -0
  116. package/dist/vm/stdlib/date.d.ts +2 -0
  117. package/dist/vm/stdlib/date.js +123 -0
  118. package/dist/vm/stdlib/headers.d.ts +2 -0
  119. package/dist/vm/stdlib/headers.js +92 -0
  120. package/dist/vm/stdlib/iterator.d.ts +2 -0
  121. package/dist/vm/stdlib/iterator.js +30 -0
  122. package/dist/vm/stdlib/json.d.ts +3 -0
  123. package/dist/vm/stdlib/json.js +42 -0
  124. package/dist/vm/stdlib/math.d.ts +3 -0
  125. package/dist/vm/stdlib/math.js +73 -0
  126. package/dist/vm/stdlib/number.d.ts +3 -0
  127. package/dist/vm/stdlib/number.js +72 -0
  128. package/dist/vm/stdlib/object.d.ts +6 -0
  129. package/dist/vm/stdlib/object.js +201 -0
  130. package/dist/vm/stdlib/regexp.d.ts +8 -0
  131. package/dist/vm/stdlib/regexp.js +119 -0
  132. package/dist/vm/stdlib/string.d.ts +2 -0
  133. package/dist/vm/stdlib/string.js +272 -0
  134. package/dist/vm/stdlib/url.d.ts +25 -0
  135. package/dist/vm/stdlib/url.js +255 -0
  136. package/dist/vm/stdlib/value.d.ts +6 -0
  137. package/dist/vm/stdlib/value.js +32 -0
  138. package/dist/vm/stdlib/web.d.ts +5 -0
  139. package/dist/vm/stdlib/web.js +97 -0
  140. package/dist/vm/vm.d.ts +226 -0
  141. package/dist/vm/vm.js +2931 -0
  142. package/package.json +8 -5
package/dist/vm/vm.js ADDED
@@ -0,0 +1,2931 @@
1
+ import { parse } from "acorn";
2
+ import { conversions } from "./runtime/callback.js";
3
+ import { locate, materialize } from "./runtime/errors.js";
4
+ import { checkArrayLength, checkStringLength } from "./runtime/limits.js";
5
+ import { AsyncIteratorSymbol, invalidData, IteratorSymbol, PendingThrow, rangeError, referenceError, syntaxError, Throw, typeError, } from "./runtime/model.js";
6
+ import { Arguments, Arr, assign, BoundFn, Builtin, coerceToNumber, coerceToString, define, Fn, frozen, GeneratorObj, get, getOwn, hasOwn, IteratorObj, Native, Obj, Position, PromiseObj, readonly, remove, } from "./runtime/objects.js";
7
+ import { applyBinaryOperator, assignToReference, builtinCursor, destructuredProperty, forInKeys, instanceofValue, isThenable, notAFunction, notConstructible, operatorConversion, propertyKey, readProperty, readReference, requireIteratorMethod, requireIteratorObject, requireMemberBase, resolveProperty, writableReference, } from "./runtime/operations.js";
8
+ import { capability } from "./runtime/promises.js";
9
+ import { describeValue, isOpaque, typeofValue } from "./runtime/references.js";
10
+ import { abrupt, Convert, Interruption, Invoke, MAX_CALL_DEPTH, normal, Push, Resume, } from "./runtime/signals.js";
11
+ import { Source } from "./runtime/source.js";
12
+ import { compiledPrelude } from "./prelude/prelude.js";
13
+ import { constructRegExp } from "./stdlib/regexp.js";
14
+ import { enumerableSource } from "./stdlib/object.js";
15
+ import { ToolReference } from "../tool-runtime.js";
16
+ import { registerAsyncIntrinsics, VmScheduler } from "./async.js";
17
+ import { captureVm, restoreVm } from "./snapshot.js";
18
+ import { compileSource } from "./compiler/compile.js";
19
+ import { AsyncFromSyncIterator, completeGeneratorReturn, execAwait, execGeneratorStart, execResume, execYield, execYstar, execYstarResult, handleAdapterPush, registerGeneratorIntrinsics, resumeVmGenerator, unwindGenerator, } from "./generators.js";
20
+ import { BLOCK, callExtension, callSearch, callTool, ENTERED, HostCalls, registerHostIntrinsics, VISIT_BUDGET, } from "./host.js";
21
+ import { getInternalPrelude, internalCode, registerVmIntrinsics, tryFastBoundaryOrJson, VmIntrinsic, } from "./internal-prelude.js";
22
+ import { BinOpSymbols, Cell, CheckBaseKind, CodeFlags, CondKind, EMPTY_CELLS, HOLE, ImportKind, IterContext, NotYetImplemented, Op, PutKind, UnaryOp, } from "./opcodes.js";
23
+ import { hidden } from "./runtime/objects.js";
24
+ const contiguous = () => {
25
+ const a = [""];
26
+ a.pop();
27
+ return a;
28
+ };
29
+ const INITIAL_FUEL = 10_000;
30
+ /**
31
+ * What a call to a built-in costs in fuel: one may run far longer than an instruction (describing a rejection, copying
32
+ * a value), so a loop made only of built-in calls still checks the clock every few dozen calls.
33
+ */
34
+ const NATIVE_FUEL = 50;
35
+ const SLICE_MS = 1;
36
+ export const Mode = {
37
+ CALLER: 0,
38
+ ASYNC: 1,
39
+ GENERATOR: 2,
40
+ SETTLE: 3,
41
+ REJECT_ONLY: 4,
42
+ PROGRAM: 5,
43
+ BOUNDARY_OUT: 6,
44
+ };
45
+ /** Custom synchronous/async iterator state stored in a frame's hidden `%it` slot. */
46
+ export class CustomIter {
47
+ iterator;
48
+ next;
49
+ done = false;
50
+ rawGen = false;
51
+ constructor(iterator, next) {
52
+ this.iterator = iterator;
53
+ this.next = next;
54
+ }
55
+ }
56
+ /** Single uniform activation record for the bytecode VM. */
57
+ export class Frame {
58
+ fn = null;
59
+ cells = EMPTY_CELLS;
60
+ code;
61
+ pc = 0;
62
+ sp = 0;
63
+ regs;
64
+ thisValue = undefined;
65
+ args = undefined;
66
+ mode = Mode.CALLER;
67
+ target = undefined;
68
+ answer = undefined;
69
+ origin = undefined;
70
+ counted = false;
71
+ constructor(code, regs) {
72
+ this.code = code;
73
+ this.regs = regs;
74
+ }
75
+ }
76
+ const EXEC_DONE = 0;
77
+ const EXEC_FUEL = 1;
78
+ const allocRegs = (size) => {
79
+ const regs = [];
80
+ for (let i = 0; i < size; i++)
81
+ regs.push(HOLE);
82
+ return regs;
83
+ };
84
+ /** Internal closure wrapper that does not touch `builtins.Function` or `nativeRule.sealed`. */
85
+ export class VmInternalFn {
86
+ code;
87
+ boundArgs;
88
+ constructor(code, boundArgs) {
89
+ this.code = code;
90
+ this.boundArgs = boundArgs;
91
+ }
92
+ }
93
+ /**
94
+ * Runs a runtime's program code: the job stack, the job queue, promises, and host calls. `execute.ts` and the driver
95
+ * use only its host surface:
96
+ *
97
+ * - **Starting.** Exactly one of `start(source)` (a new run) or `restore(saved, …)` (a saved one), once. Host call
98
+ * ids count up in program order.
99
+ * - **Running.** `run()` is synchronous, runs no host work, and returns a `Stop`:
100
+ * - `host(calls)`: start these queued calls now (they are `queued`; the driver marks them `running`),
101
+ * then call `run()` again; `host([])` means wait until `ready` (a blocking call or the inbox has input) and call
102
+ * `run()` again;
103
+ * - `slice`: the time slice is over; yield to the host scheduler and call `run()` again;
104
+ * - `done(completion)`: the program's body ended; host calls may still be running (`diagnostics()` reports
105
+ * unhandled rejections);
106
+ * - `stuck(node)`: nothing is queued or running, and the body awaits something that can never settle.
107
+ * - **Host calls.** `complete(id, completion)` reports how a handed-over call ended, at any time between `run()`s: a
108
+ * blocking call's outcome continues the job that made it; a concurrent call's waits in the inbox and settles its
109
+ * promise in a later job, in completion order. Unknown or completed ids are ignored. `call(id)`/`calls()` list the
110
+ * calls handed over and not completed, in the order they were made.
111
+ * - **Snapshots.** `capture` and `restore` run only between `run()`s, synchronously. A capture changes nothing a
112
+ * later `run()` sees; it fails (throws) only on a codec gap. A state holding live host values (`calls()` with an
113
+ * extension call, or `activeExtension`) can't be restored faithfully.
114
+ */
115
+ export class Vm {
116
+ ctx;
117
+ frames = contiguous();
118
+ pool = contiguous();
119
+ sourceCodes = new Map();
120
+ templates = new Map();
121
+ intrinsics = new Map();
122
+ scheduler;
123
+ /** Host calls: queued, running, completed, and the blocking one the job on the stack waits on. */
124
+ hosts;
125
+ depth = 0;
126
+ fuel = INITIAL_FUEL;
127
+ /** When the current slice began; -1 until the next `run` starts one. Host stops don't end a slice, only a yield does. */
128
+ sliceStart = -1;
129
+ sliced = false;
130
+ outcome = undefined;
131
+ /** Round-trip test mode (task C): slice after this many fuel ticks, so the run is saved and restored all through. */
132
+ tripEvery = 0;
133
+ constructor(ctx) {
134
+ this.ctx = ctx;
135
+ this.scheduler = new VmScheduler(this);
136
+ this.scheduler.intrinsicThen = get(ctx.builtins.Promise, "then");
137
+ this.hosts = new HostCalls(ctx, this.scheduler);
138
+ const internal = getInternalPrelude();
139
+ const prelude = compiledPrelude();
140
+ this.sourceCodes.set("@vm-internal", internal.codes);
141
+ this.sourceCodes.set("@prelude", prelude.codes);
142
+ for (const val of ctx.prelude.scope.values()) {
143
+ if (val instanceof Fn && val.cells.length === 0 && val.cells !== EMPTY_CELLS) {
144
+ ;
145
+ val.cells = EMPTY_CELLS;
146
+ }
147
+ }
148
+ }
149
+ initIntrinsics() {
150
+ registerVmIntrinsics(this.intrinsics, this);
151
+ registerAsyncIntrinsics(this.intrinsics, this);
152
+ registerGeneratorIntrinsics(this.intrinsics, this);
153
+ registerHostIntrinsics(this.intrinsics, this);
154
+ }
155
+ getIntrinsic(name) {
156
+ const p = this.ctx.prelude.scope.get(name);
157
+ if (p !== undefined)
158
+ return p;
159
+ if (this.intrinsics.size === 0)
160
+ this.initIntrinsics();
161
+ return this.intrinsics.get(name);
162
+ }
163
+ /** Queues the program's body as the root frame. */
164
+ start(source) {
165
+ if (!warmed)
166
+ warmupVm(this);
167
+ this.ctx.sources.set(source.id, source);
168
+ let codes;
169
+ try {
170
+ codes = compileSource(source);
171
+ }
172
+ catch (error) {
173
+ // A program nested deeper than the compiler's host stack fails the run, as running it would.
174
+ if (!(error instanceof RangeError))
175
+ throw error;
176
+ this.outcome = abrupt(error);
177
+ return;
178
+ }
179
+ this.sourceCodes.set(source.id, codes);
180
+ const progCode = codes[0];
181
+ const frame = this.acquire(progCode);
182
+ frame.fn = null;
183
+ frame.cells = EMPTY_CELLS;
184
+ frame.pc = 0;
185
+ frame.sp = progCode.locals;
186
+ frame.thisValue = undefined;
187
+ frame.args = undefined;
188
+ frame.mode = Mode.PROGRAM;
189
+ frame.origin = undefined;
190
+ frame.counted = true;
191
+ this.depth = 1;
192
+ this.frames.push(frame);
193
+ }
194
+ /**
195
+ * Runs until it has to stop (`Stop`), in this order: hand over queued host calls; a due slice; continue the job a
196
+ * completed blocking call waits on; wait while the job on the stack is blocked; continue a sliced job before any
197
+ * other; the outcome; the next job; one inbox completion; wait for running calls; stuck.
198
+ */
199
+ run() {
200
+ if (this.sliceStart < 0)
201
+ this.sliceStart = performance.now();
202
+ if (this.tripEvery > 0)
203
+ this.fuel = this.tripEvery;
204
+ const sched = this.scheduler;
205
+ const hosts = this.hosts;
206
+ while (true) {
207
+ if (hosts.queued.length > 0)
208
+ return { kind: "host", calls: hosts.handOver() };
209
+ if (this.sliced) {
210
+ this.sliced = false;
211
+ this.sliceStart = -1;
212
+ return { kind: "slice" };
213
+ }
214
+ const input = hosts.input;
215
+ if (input !== undefined) {
216
+ hosts.input = undefined;
217
+ this.resumeBlocked(input);
218
+ continue;
219
+ }
220
+ if (this.frames.length > 0) {
221
+ if (hosts.blocked !== undefined)
222
+ return { kind: "host", calls: [] };
223
+ // Fuel can run out on a call that then stopped for the host (a built-in or sync extension call costs fuel too):
224
+ // that's a slice point as well, or a loop of such calls would refill forever without yielding.
225
+ if (this.fuel <= 0) {
226
+ this.fuel = this.tripEvery || INITIAL_FUEL;
227
+ if (this.tripEvery > 0 || performance.now() - this.sliceStart >= SLICE_MS) {
228
+ this.sliced = true;
229
+ continue;
230
+ }
231
+ }
232
+ let signal = EXEC_DONE;
233
+ try {
234
+ signal = this.exec();
235
+ }
236
+ catch (error) {
237
+ if (error instanceof NotYetImplemented)
238
+ throw error;
239
+ this.unwind(error);
240
+ continue;
241
+ }
242
+ if (signal === EXEC_FUEL) {
243
+ this.fuel = this.tripEvery || INITIAL_FUEL;
244
+ if (this.tripEvery > 0 || performance.now() - this.sliceStart >= SLICE_MS) {
245
+ this.sliced = true;
246
+ }
247
+ }
248
+ continue;
249
+ }
250
+ if (this.outcome !== undefined)
251
+ return { kind: "done", completion: this.outcome };
252
+ const job = sched.dequeue();
253
+ if (job !== undefined) {
254
+ sched.beginJob(job);
255
+ if (--this.fuel <= 0) {
256
+ this.fuel = this.tripEvery || INITIAL_FUEL;
257
+ if (this.tripEvery > 0 || performance.now() - this.sliceStart >= SLICE_MS) {
258
+ this.sliced = true;
259
+ }
260
+ }
261
+ continue;
262
+ }
263
+ if (hosts.deliver())
264
+ continue;
265
+ if (hosts.running.size > 0)
266
+ return { kind: "host", calls: [] };
267
+ return { kind: "stuck", node: sched.stuckAwait() };
268
+ }
269
+ }
270
+ // Continues the job stopped at a blocking call with the call's result, or throws its failure at the call.
271
+ resumeBlocked(input) {
272
+ const frame = this.frames[this.frames.length - 1];
273
+ try {
274
+ const result = this.hosts.resume(input);
275
+ if (result === BLOCK || result === ENTERED)
276
+ return;
277
+ frame.regs[frame.sp++] = result;
278
+ frame.pc++;
279
+ }
280
+ catch (error) {
281
+ this.unwind(error);
282
+ }
283
+ }
284
+ /** Reports how host work handed over by a `host` stop ended. */
285
+ complete(id, completion) {
286
+ this.hosts.complete(id, completion);
287
+ }
288
+ /** Whether `run` has something to do: a blocking call's outcome, or one in the inbox while no job runs. */
289
+ get ready() {
290
+ const hosts = this.hosts;
291
+ return hosts.input !== undefined || (this.frames.length === 0 && (hosts.inbox.length > 0 || this.scheduler.hasJobs));
292
+ }
293
+ /** A host call handed over and not yet completed, by id. */
294
+ call(id) {
295
+ return this.hosts.running.get(id);
296
+ }
297
+ /** The host calls handed over and not yet completed, in the order they were made. */
298
+ calls() {
299
+ return [...this.hosts.running.values()];
300
+ }
301
+ compact() {
302
+ this.scheduler.compact();
303
+ }
304
+ /** Unhandled rejections, in promise creation order, once inbox completions are delivered. */
305
+ diagnostics() {
306
+ while (this.hosts.deliver())
307
+ ;
308
+ return this.scheduler.diagnostics();
309
+ }
310
+ /**
311
+ * A synchronous extension call the program is in the middle of, from its `before` hook until its result is a
312
+ * program value or its concurrent call is running: it holds live host values.
313
+ */
314
+ get activeExtension() {
315
+ return this.hosts.extension;
316
+ }
317
+ /** Saves the run's state as it is now. */
318
+ capture(options) {
319
+ if (this.intrinsics.size === 0)
320
+ this.initIntrinsics();
321
+ return captureVm(this, options);
322
+ }
323
+ /** Restores a saved state into this fresh VM, after checking it belongs to this build and runtime. */
324
+ restore(saved, options) {
325
+ if (this.intrinsics.size === 0)
326
+ this.initIntrinsics();
327
+ return restoreVm(this, saved, options);
328
+ }
329
+ deliverAnswer(frame) {
330
+ if (frame.answer !== undefined) {
331
+ const answer = frame.answer;
332
+ frame.answer = undefined;
333
+ const caller = this.frames[this.frames.length - 1];
334
+ if (caller !== undefined) {
335
+ caller.regs[caller.sp++] = answer;
336
+ caller.pc++;
337
+ }
338
+ }
339
+ }
340
+ acquire(code) {
341
+ const size = code.locals + code.maxStack;
342
+ const pool = this.pool;
343
+ if (pool.length === 0) {
344
+ return new Frame(code, allocRegs(size));
345
+ }
346
+ const f = pool.pop();
347
+ f.code = code;
348
+ const regs = f.regs;
349
+ if (regs.length < size) {
350
+ f.regs = allocRegs(size);
351
+ }
352
+ else {
353
+ for (let i = 0, n = code.locals; i < n; i++)
354
+ regs[i] = HOLE;
355
+ }
356
+ return f;
357
+ }
358
+ release(frame) {
359
+ if (frame.counted)
360
+ this.depth--;
361
+ frame.fn = null;
362
+ frame.cells = EMPTY_CELLS;
363
+ frame.thisValue = undefined;
364
+ frame.args = undefined;
365
+ frame.target = undefined;
366
+ frame.answer = undefined;
367
+ frame.origin = undefined;
368
+ frame.counted = false;
369
+ if (this.pool.length < 128)
370
+ this.pool.push(frame);
371
+ }
372
+ codesOf(code) {
373
+ return this.sourceCodes.get(code.source.id);
374
+ }
375
+ /**
376
+ * Nearest non-internal frame's AST site, or the bottom internal frame's `origin` (§3.6). A failure the host
377
+ * boundary's own walk raises (copying out the result, or a tool call's arguments) has no location: the call that
378
+ * crosses reports it.
379
+ */
380
+ currentSite() {
381
+ for (let i = this.frames.length - 1; i >= 0; i--) {
382
+ const f = this.frames[i];
383
+ if ((f.code.flags & CodeFlags.INTERNAL) === 0) {
384
+ return f.code.siteAt(f.pc);
385
+ }
386
+ if (f.mode === Mode.BOUNDARY_OUT || f.mode === Mode.REJECT_ONLY)
387
+ return undefined;
388
+ if (f.origin !== undefined)
389
+ return f.origin;
390
+ }
391
+ return undefined;
392
+ }
393
+ exec() {
394
+ const frames = this.frames;
395
+ const hole = HOLE;
396
+ const CellCtor = Cell;
397
+ const ArrCtor = Arr;
398
+ const ObjCtor = Obj;
399
+ const FnCtor = Fn;
400
+ const PositionCtor = Position;
401
+ const globalScope = this.ctx.globalScope;
402
+ const objectProto = this.ctx.builtins.Object;
403
+ let frame;
404
+ let fcode;
405
+ let code;
406
+ let regs;
407
+ let consts;
408
+ let cells;
409
+ let pc = 0;
410
+ let sp = 0;
411
+ outer: for (;;) {
412
+ if (frames.length === 0)
413
+ return 0;
414
+ frame = frames[frames.length - 1];
415
+ fcode = frame.code;
416
+ code = fcode.code;
417
+ regs = frame.regs;
418
+ consts = fcode.consts;
419
+ pc = frame.pc | 0;
420
+ cells = frame.cells;
421
+ sp = frame.sp | 0;
422
+ for (;;) {
423
+ const w = code[pc];
424
+ switch (w & 0xff) {
425
+ case 0: // Op.PUSH_UNDEF
426
+ regs[sp++] = undefined;
427
+ pc++;
428
+ continue;
429
+ case 1: // Op.PUSH_NULL
430
+ regs[sp++] = null;
431
+ pc++;
432
+ continue;
433
+ case 2: // Op.PUSH_BOOL
434
+ regs[sp++] = (w & 0xff00) === 0x0100;
435
+ pc++;
436
+ continue;
437
+ case 3: // Op.PUSH_INT
438
+ regs[sp++] = w >> 16;
439
+ pc++;
440
+ continue;
441
+ case 4: // Op.PUSH_CONST
442
+ regs[sp++] = consts[w >>> 16];
443
+ pc++;
444
+ continue;
445
+ case 5: // Op.POP
446
+ sp--;
447
+ pc++;
448
+ continue;
449
+ case 6: // Op.POPN
450
+ sp -= w >>> 16;
451
+ pc++;
452
+ continue;
453
+ case 7: // Op.DUP
454
+ regs[sp] = regs[sp - 1];
455
+ sp++;
456
+ pc++;
457
+ continue;
458
+ case 8: // Op.PICK
459
+ regs[sp] = regs[sp - 1 - ((w >>> 8) & 0xff)];
460
+ sp++;
461
+ pc++;
462
+ continue;
463
+ case 9: // Op.ROT
464
+ this.execRot(regs, (w >>> 8) & 0xff, sp);
465
+ pc++;
466
+ continue;
467
+ case 10: {
468
+ // Op.GET_LOCAL
469
+ const slot = w >>> 16;
470
+ const v = regs[slot];
471
+ if (v === hole)
472
+ this.failTdz(frame, fcode.localNames[slot], pc, sp);
473
+ regs[sp++] = v;
474
+ pc++;
475
+ continue;
476
+ }
477
+ case 11: {
478
+ // Op.PUT_LOCAL
479
+ const slot = w >>> 16;
480
+ const kind = (w >>> 8) & 0xff;
481
+ const v = regs[--sp];
482
+ if (kind !== 1 && (regs[slot] === hole || kind === 2)) {
483
+ this.failPut(frame, fcode.localNames[slot], regs[slot], pc, sp);
484
+ }
485
+ regs[slot] = v;
486
+ pc++;
487
+ continue;
488
+ }
489
+ case 12: // Op.HOLE_LOCAL
490
+ regs[w >>> 16] = hole;
491
+ pc++;
492
+ continue;
493
+ case 13: {
494
+ // Op.NEW_CELL
495
+ const slot = w >>> 16;
496
+ regs[slot] = new CellCtor((w & 0xff00) === 0x0100 ? regs[slot] : hole);
497
+ pc++;
498
+ continue;
499
+ }
500
+ case 14: {
501
+ // Op.COPY_CELL
502
+ const slot = w >>> 16;
503
+ regs[slot] = new CellCtor(regs[slot].v);
504
+ pc++;
505
+ continue;
506
+ }
507
+ case 15: {
508
+ // Op.GET_CELL
509
+ const slot = w >>> 16;
510
+ const v = regs[slot].v;
511
+ if (v === hole)
512
+ this.failTdz(frame, fcode.localNames[slot], pc, sp);
513
+ regs[sp++] = v;
514
+ pc++;
515
+ continue;
516
+ }
517
+ case 16: {
518
+ // Op.PUT_CELL
519
+ const slot = w >>> 16;
520
+ const kind = (w >>> 8) & 0xff;
521
+ const v = regs[--sp];
522
+ const cell = regs[slot];
523
+ if (kind !== 1 && (cell.v === hole || kind === 2)) {
524
+ this.failPut(frame, fcode.localNames[slot], cell.v, pc, sp);
525
+ }
526
+ cell.v = v;
527
+ pc++;
528
+ continue;
529
+ }
530
+ case 17: {
531
+ // Op.GET_UPVAL
532
+ const idx = w >>> 16;
533
+ const v = cells[idx].v;
534
+ if (v === hole)
535
+ this.failTdz(frame, fcode.upvalNames[idx], pc, sp);
536
+ regs[sp++] = v;
537
+ pc++;
538
+ continue;
539
+ }
540
+ case 18: {
541
+ // Op.PUT_UPVAL
542
+ const idx = w >>> 16;
543
+ const kind = (w >>> 8) & 0xff;
544
+ const v = regs[--sp];
545
+ const cell = cells[idx];
546
+ if (kind !== 1 && (cell.v === hole || kind === 2)) {
547
+ this.failPut(frame, fcode.upvalNames[idx], cell.v, pc, sp);
548
+ }
549
+ cell.v = v;
550
+ pc++;
551
+ continue;
552
+ }
553
+ case 19: {
554
+ // Op.GET_GLOBAL
555
+ const name = consts[w >>> 16];
556
+ if ((w & 0xff00) === 0) {
557
+ const binding = globalScope.get(name);
558
+ if (binding !== undefined) {
559
+ regs[sp++] = binding.value;
560
+ pc++;
561
+ continue;
562
+ }
563
+ }
564
+ regs[sp++] = this.execGetGlobal(frame, (w >>> 8) & 0xff, name, pc, sp);
565
+ pc++;
566
+ continue;
567
+ }
568
+ case 20: // Op.GET_INTRINSIC
569
+ regs[sp++] = this.getIntrinsic(consts[w >>> 16]);
570
+ pc++;
571
+ continue;
572
+ case 21: // Op.ARGS
573
+ regs[sp++] = this.execArgs(frame, (w >>> 8) & 0xff, w >>> 16);
574
+ pc++;
575
+ continue;
576
+ case 22: // Op.CLOSURE
577
+ regs[sp++] = this.makeClosure(fcode, w >>> 16, regs, cells);
578
+ pc++;
579
+ continue;
580
+ case 23: // Op.SET_NAME
581
+ this.execSetName(regs, consts, (w >>> 8) & 0xff, w >>> 16, sp);
582
+ pc++;
583
+ continue;
584
+ case 24: // Op.IMPORT
585
+ frame.pc = pc;
586
+ frame.sp = sp;
587
+ sp = this.execImport(frame, (w >>> 8) & 0xff, w >>> 16, pc, sp);
588
+ pc++;
589
+ continue;
590
+ case 25: {
591
+ // Op.GET_PROP
592
+ const o = regs[sp - 1];
593
+ const key = consts[w >>> 16];
594
+ const mode = (w >>> 8) & 0xff;
595
+ if (key === "length" && mode === 0) {
596
+ if (typeof o === "string") {
597
+ regs[sp - 1] = o.length;
598
+ pc++;
599
+ continue;
600
+ }
601
+ if (o instanceof ArrCtor) {
602
+ regs[sp - 1] = o.items.length;
603
+ pc++;
604
+ continue;
605
+ }
606
+ }
607
+ frame.pc = pc;
608
+ frame.sp = sp;
609
+ sp = this.execGetProp(frame, o, key, mode, pc, sp);
610
+ pc++;
611
+ continue;
612
+ }
613
+ case 26: {
614
+ // Op.GET_ELEM
615
+ const keyVal = regs[sp - 1];
616
+ const o = regs[sp - 2];
617
+ const mode = (w >>> 8) & 0xff;
618
+ if (mode === 0 &&
619
+ typeof keyVal === "number" &&
620
+ keyVal >= 0 &&
621
+ (keyVal | 0) === keyVal &&
622
+ o instanceof ArrCtor &&
623
+ keyVal in o.items) {
624
+ sp--;
625
+ regs[sp - 1] = o.items[keyVal];
626
+ pc++;
627
+ continue;
628
+ }
629
+ frame.pc = pc;
630
+ frame.sp = sp;
631
+ if (this.execGetElem(frame, o, keyVal, mode, pc, sp))
632
+ continue outer;
633
+ sp = frame.sp;
634
+ pc++;
635
+ continue;
636
+ }
637
+ case 27: {
638
+ // Op.PUT_PROP
639
+ const v = regs[--sp];
640
+ const o = regs[sp - 1];
641
+ frame.pc = pc;
642
+ frame.sp = sp;
643
+ this.execPutProp(fcode, o, consts[w >>> 16], v, pc);
644
+ regs[sp - 1] = v;
645
+ pc++;
646
+ continue;
647
+ }
648
+ case 28: {
649
+ // Op.PUT_ELEM
650
+ const v = regs[--sp];
651
+ const keyVal = regs[--sp];
652
+ const o = regs[sp - 1];
653
+ if (typeof keyVal === "number" &&
654
+ keyVal >= 0 &&
655
+ (keyVal | 0) === keyVal &&
656
+ (typeof v !== "object" || v === null) &&
657
+ o instanceof ArrCtor &&
658
+ o.elements.writable &&
659
+ o.extensible) {
660
+ const items = o.items;
661
+ if (keyVal < items.length) {
662
+ if (keyVal === 0)
663
+ items[0] = "";
664
+ items[keyVal] = v;
665
+ regs[sp - 1] = v;
666
+ pc++;
667
+ continue;
668
+ }
669
+ if (keyVal === items.length && keyVal < 10_000_000) {
670
+ items.push(v);
671
+ regs[sp - 1] = v;
672
+ pc++;
673
+ continue;
674
+ }
675
+ }
676
+ frame.pc = pc;
677
+ frame.sp = sp;
678
+ this.execPutElem(fcode, o, keyVal, v, pc);
679
+ regs[sp - 1] = v;
680
+ pc++;
681
+ continue;
682
+ }
683
+ case 29: // Op.DELETE_PROP
684
+ frame.pc = pc;
685
+ frame.sp = sp;
686
+ regs[sp - 1] = this.execDeleteProp(fcode, regs[sp - 1], consts[w >>> 16], pc);
687
+ pc++;
688
+ continue;
689
+ case 30: {
690
+ // Op.DELETE_ELEM
691
+ const keyVal = regs[--sp];
692
+ const o = regs[sp - 1];
693
+ frame.pc = pc;
694
+ frame.sp = sp;
695
+ if (this.execDeleteElem(frame, o, keyVal, pc, sp))
696
+ continue outer;
697
+ sp = frame.sp;
698
+ pc++;
699
+ continue;
700
+ }
701
+ case 31: // Op.CHECK_BASE
702
+ frame.pc = pc;
703
+ frame.sp = sp;
704
+ this.execCheckBase(fcode, (w >>> 8) & 0xff, w >>> 16, regs, sp, pc);
705
+ pc++;
706
+ continue;
707
+ case 32: {
708
+ // Op.TO_KEY
709
+ const v = regs[sp - 1];
710
+ if (typeof v === "string" || typeof v === "number" || typeof v === "symbol") {
711
+ pc++;
712
+ continue;
713
+ }
714
+ if (this.execToKey(frame, v, pc, sp))
715
+ continue outer;
716
+ pc++;
717
+ continue;
718
+ }
719
+ case 33: {
720
+ // Op.IN
721
+ const rhs = regs[--sp];
722
+ const lhs = regs[sp - 1];
723
+ if (typeof lhs === "number" && lhs >= 0 && (lhs | 0) === lhs && rhs instanceof ArrCtor) {
724
+ regs[sp - 1] = lhs in rhs.items;
725
+ pc++;
726
+ continue;
727
+ }
728
+ if (this.execIn(frame, lhs, rhs, pc, sp))
729
+ continue outer;
730
+ pc++;
731
+ continue;
732
+ }
733
+ case 34: {
734
+ // Op.INSTANCEOF
735
+ const rhs = regs[--sp];
736
+ frame.pc = pc;
737
+ frame.sp = sp;
738
+ regs[sp - 1] = this.execInstanceof(fcode, regs[sp - 1], rhs, pc);
739
+ pc++;
740
+ continue;
741
+ }
742
+ case 35: // Op.NEW_OBJECT
743
+ regs[sp++] = new ObjCtor(objectProto);
744
+ pc++;
745
+ continue;
746
+ case 36: // Op.NEW_ARRAY
747
+ sp = this.execNewArray(regs, w >>> 16, sp);
748
+ pc++;
749
+ continue;
750
+ case 37: // Op.ARRAY_APPEND
751
+ frame.pc = pc;
752
+ frame.sp = sp;
753
+ sp = this.execArrayAppend(regs, (w >>> 8) & 0xff, sp);
754
+ pc++;
755
+ continue;
756
+ case 38: // Op.DEFINE_FIELD
757
+ sp = this.execDefineField(regs, consts, (w >>> 8) & 0xff, w >>> 16, sp);
758
+ pc++;
759
+ continue;
760
+ case 39: // Op.COPY_DATA_PROPS
761
+ frame.pc = pc;
762
+ frame.sp = --sp;
763
+ this.execCopyDataProps(fcode, regs[sp - 1], regs[sp], pc);
764
+ pc++;
765
+ continue;
766
+ case 40: // Op.COPY_REST
767
+ frame.pc = pc;
768
+ frame.sp = sp;
769
+ sp = this.execCopyRest(fcode, regs, w >>> 16, pc, sp);
770
+ pc++;
771
+ continue;
772
+ case 41: // Op.TEMPLATE
773
+ regs[sp++] = this.getTemplateObject(fcode, consts[w >>> 16]);
774
+ pc++;
775
+ continue;
776
+ case 42: // Op.REGEXP
777
+ frame.pc = pc;
778
+ frame.sp = sp;
779
+ regs[sp++] = this.execRegExp(fcode, consts[w >>> 16], pc);
780
+ pc++;
781
+ continue;
782
+ case 43: {
783
+ // Op.ADD
784
+ const b = regs[--sp];
785
+ const a = regs[sp - 1];
786
+ if (typeof a === "number" && typeof b === "number") {
787
+ regs[sp - 1] = a + b;
788
+ pc++;
789
+ continue;
790
+ }
791
+ if ((typeof a === "string" || typeof b === "string") &&
792
+ (a === null || (typeof a !== "object" && typeof a !== "symbol")) &&
793
+ (b === null || (typeof b !== "object" && typeof b !== "symbol"))) {
794
+ const s = a + b;
795
+ if (s.length > 16_777_216) {
796
+ frame.pc = pc;
797
+ frame.sp = sp;
798
+ this.failStringLength(s.length);
799
+ }
800
+ regs[sp - 1] = s;
801
+ pc++;
802
+ continue;
803
+ }
804
+ frame.pc = pc;
805
+ frame.sp = sp;
806
+ if (this.execBinarySlow(frame, "+", a, b, pc, sp))
807
+ continue outer;
808
+ pc++;
809
+ continue;
810
+ }
811
+ case 44: {
812
+ // Op.SUB
813
+ const b = regs[--sp];
814
+ const a = regs[sp - 1];
815
+ if (typeof a === "number" && typeof b === "number") {
816
+ regs[sp - 1] = a - b;
817
+ pc++;
818
+ continue;
819
+ }
820
+ frame.pc = pc;
821
+ frame.sp = sp;
822
+ if (this.execBinarySlow(frame, "-", a, b, pc, sp))
823
+ continue outer;
824
+ pc++;
825
+ continue;
826
+ }
827
+ case 45: {
828
+ // Op.MUL
829
+ const b = regs[--sp];
830
+ const a = regs[sp - 1];
831
+ if (typeof a === "number" && typeof b === "number") {
832
+ regs[sp - 1] = a * b;
833
+ pc++;
834
+ continue;
835
+ }
836
+ frame.pc = pc;
837
+ frame.sp = sp;
838
+ if (this.execBinarySlow(frame, "*", a, b, pc, sp))
839
+ continue outer;
840
+ pc++;
841
+ continue;
842
+ }
843
+ case 46: {
844
+ // Op.LT
845
+ const b = regs[--sp];
846
+ const a = regs[sp - 1];
847
+ if (typeof a === "number" && typeof b === "number") {
848
+ regs[sp - 1] = a < b;
849
+ pc++;
850
+ continue;
851
+ }
852
+ frame.pc = pc;
853
+ frame.sp = sp;
854
+ if (this.execBinarySlow(frame, "<", a, b, pc, sp))
855
+ continue outer;
856
+ pc++;
857
+ continue;
858
+ }
859
+ case 47: {
860
+ // Op.LE
861
+ const b = regs[--sp];
862
+ const a = regs[sp - 1];
863
+ if (typeof a === "number" && typeof b === "number") {
864
+ regs[sp - 1] = a <= b;
865
+ pc++;
866
+ continue;
867
+ }
868
+ frame.pc = pc;
869
+ frame.sp = sp;
870
+ if (this.execBinarySlow(frame, "<=", a, b, pc, sp))
871
+ continue outer;
872
+ pc++;
873
+ continue;
874
+ }
875
+ case 48: {
876
+ // Op.GT
877
+ const b = regs[--sp];
878
+ const a = regs[sp - 1];
879
+ if (typeof a === "number" && typeof b === "number") {
880
+ regs[sp - 1] = a > b;
881
+ pc++;
882
+ continue;
883
+ }
884
+ frame.pc = pc;
885
+ frame.sp = sp;
886
+ if (this.execBinarySlow(frame, ">", a, b, pc, sp))
887
+ continue outer;
888
+ pc++;
889
+ continue;
890
+ }
891
+ case 49: {
892
+ // Op.GE
893
+ const b = regs[--sp];
894
+ const a = regs[sp - 1];
895
+ if (typeof a === "number" && typeof b === "number") {
896
+ regs[sp - 1] = a >= b;
897
+ pc++;
898
+ continue;
899
+ }
900
+ frame.pc = pc;
901
+ frame.sp = sp;
902
+ if (this.execBinarySlow(frame, ">=", a, b, pc, sp))
903
+ continue outer;
904
+ pc++;
905
+ continue;
906
+ }
907
+ case 50: {
908
+ // Op.SEQ
909
+ const b = regs[--sp];
910
+ regs[sp - 1] = regs[sp - 1] === b;
911
+ pc++;
912
+ continue;
913
+ }
914
+ case 51: {
915
+ // Op.SNE
916
+ const b = regs[--sp];
917
+ regs[sp - 1] = regs[sp - 1] !== b;
918
+ pc++;
919
+ continue;
920
+ }
921
+ case 52: {
922
+ // Op.BINOP
923
+ const b = regs[--sp];
924
+ const a = regs[sp - 1];
925
+ const sub = (w >>> 8) & 0xff;
926
+ if (typeof a === "number" && typeof b === "number") {
927
+ regs[sp - 1] = sub === 1 ? a % b : this.execBinopNum(sub, a, b);
928
+ pc++;
929
+ continue;
930
+ }
931
+ frame.pc = pc;
932
+ frame.sp = sp;
933
+ if (this.execBinopSlow(frame, sub, a, b, pc, sp))
934
+ continue outer;
935
+ pc++;
936
+ continue;
937
+ }
938
+ case 53: {
939
+ // Op.UNARY
940
+ const sub = (w >>> 8) & 0xff;
941
+ const v = regs[sp - 1];
942
+ if (typeof v === "number" && sub < 3) {
943
+ regs[sp - 1] = sub === 0 ? -v : sub === 1 ? +v : ~v;
944
+ pc++;
945
+ continue;
946
+ }
947
+ frame.pc = pc;
948
+ frame.sp = sp;
949
+ if (this.execUnarySlow(frame, sub, v, pc, sp))
950
+ continue outer;
951
+ pc++;
952
+ continue;
953
+ }
954
+ case 54: // Op.NOT
955
+ regs[sp - 1] = !regs[sp - 1];
956
+ pc++;
957
+ continue;
958
+ case 55: {
959
+ // Op.TO_NUMERIC
960
+ const v = regs[sp - 1];
961
+ if (typeof v === "number") {
962
+ pc++;
963
+ continue;
964
+ }
965
+ if (this.execToNumericSlow(frame, (w >>> 8) & 0xff, v, pc, sp))
966
+ continue outer;
967
+ pc++;
968
+ continue;
969
+ }
970
+ case 56: {
971
+ // Op.INC
972
+ const v = regs[sp - 1];
973
+ if (typeof v === "number") {
974
+ regs[sp - 1] = (w & 0xff00) === 0 ? v + 1 : v - 1;
975
+ pc++;
976
+ continue;
977
+ }
978
+ if (this.execIncSlow(frame, (w >>> 8) & 0xff, v, pc, sp))
979
+ continue outer;
980
+ pc++;
981
+ continue;
982
+ }
983
+ case 57: {
984
+ // Op.TO_STRING
985
+ const v = regs[sp - 1];
986
+ if (typeof v === "string") {
987
+ pc++;
988
+ continue;
989
+ }
990
+ if (typeof v === "number") {
991
+ regs[sp - 1] = "" + v;
992
+ pc++;
993
+ continue;
994
+ }
995
+ if (this.execToStringSlow(frame, (w >>> 8) & 0xff, v, pc, sp))
996
+ continue outer;
997
+ pc++;
998
+ continue;
999
+ }
1000
+ case 58: {
1001
+ // Op.CONCAT
1002
+ const n = w >>> 16;
1003
+ if (n === 2) {
1004
+ const b = regs[--sp];
1005
+ const s = regs[sp - 1] + b;
1006
+ if (s.length > 16_777_216) {
1007
+ frame.pc = pc;
1008
+ frame.sp = sp;
1009
+ this.failStringLength(s.length);
1010
+ }
1011
+ regs[sp - 1] = s;
1012
+ pc++;
1013
+ continue;
1014
+ }
1015
+ frame.pc = pc;
1016
+ frame.sp = sp;
1017
+ sp = this.execConcat(regs, n, sp);
1018
+ pc++;
1019
+ continue;
1020
+ }
1021
+ case 59: // Op.JUMP
1022
+ pc = w >>> 16;
1023
+ continue;
1024
+ case 60: // Op.LOOP
1025
+ pc = w >>> 16;
1026
+ if (--this.fuel <= 0) {
1027
+ frame.pc = pc;
1028
+ frame.sp = sp;
1029
+ return 1;
1030
+ }
1031
+ continue;
1032
+ case 61: // Op.JUMP_IF_FALSE
1033
+ if (regs[--sp])
1034
+ pc++;
1035
+ else
1036
+ pc = w >>> 16;
1037
+ continue;
1038
+ case 62: // Op.JUMP_IF_TRUE
1039
+ if (regs[--sp])
1040
+ pc = w >>> 16;
1041
+ else
1042
+ pc++;
1043
+ continue;
1044
+ case 63: {
1045
+ // Op.JUMP_COND
1046
+ const v = regs[sp - 1];
1047
+ const sub = (w >>> 8) & 0xff;
1048
+ if (sub >= 4) {
1049
+ if (v === null || v === undefined) {
1050
+ if (sub === 5)
1051
+ sp--;
1052
+ regs[sp - 1] = undefined;
1053
+ pc = w >>> 16;
1054
+ }
1055
+ else {
1056
+ pc++;
1057
+ }
1058
+ continue;
1059
+ }
1060
+ const jump = sub === 0 ? !!v : sub === 1 ? !v : sub === 2 ? v !== null && v !== undefined : v !== undefined;
1061
+ if (jump) {
1062
+ pc = w >>> 16;
1063
+ }
1064
+ else {
1065
+ sp--;
1066
+ pc++;
1067
+ }
1068
+ continue;
1069
+ }
1070
+ case 64: // Op.THROW
1071
+ this.execThrow(frame, regs[--sp], pc, sp);
1072
+ case 65: // Op.THROW_ERROR
1073
+ this.execThrowError(frame, w >>> 16, pc, sp);
1074
+ case 66: // Op.END_FINALLY
1075
+ pc = this.execEndFinally(frame, w >>> 16, pc, sp);
1076
+ continue;
1077
+ case 67: // Op.RETURN
1078
+ case 87: {
1079
+ // Op.END_PROGRAM
1080
+ const v = regs[sp - 1];
1081
+ if (frame.mode === 0) {
1082
+ frames.pop();
1083
+ if (frame.counted)
1084
+ this.depth--;
1085
+ if (this.pool.length < 128)
1086
+ this.pool.push(frame);
1087
+ const caller = frames[frames.length - 1];
1088
+ caller.regs[caller.sp++] = v;
1089
+ caller.pc++;
1090
+ continue outer;
1091
+ }
1092
+ if (this.execReturnSlow(frame, v, pc, sp))
1093
+ continue outer;
1094
+ return 0;
1095
+ }
1096
+ case 68: // Op.NOP
1097
+ pc++;
1098
+ continue;
1099
+ case 69: {
1100
+ // Op.EXTRA
1101
+ const nextPc = this.execExtra(frame, w, pc, sp);
1102
+ if (nextPc < 0) {
1103
+ if (nextPc === -1)
1104
+ continue outer;
1105
+ return -2 - nextPc;
1106
+ }
1107
+ sp = frame.sp;
1108
+ pc = nextPc;
1109
+ continue;
1110
+ }
1111
+ case 70: {
1112
+ // Op.CALL
1113
+ const n = (w >>> 8) & 0xff;
1114
+ const base = sp - n;
1115
+ const callee = regs[base - 1];
1116
+ if (callee instanceof FnCtor) {
1117
+ const c = callee.code;
1118
+ if ((c.flags & 518) === 0) {
1119
+ const counted = (c.flags & 64) === 0;
1120
+ if (counted && this.depth > 10_000) {
1121
+ this.failCallDepth(frame, fcode, pc, sp);
1122
+ }
1123
+ if (counted)
1124
+ this.depth++;
1125
+ const f = this.acquire(c);
1126
+ f.fn = callee;
1127
+ f.cells = callee.cells;
1128
+ f.counted = counted;
1129
+ const r = f.regs;
1130
+ const p = c.params;
1131
+ if (p === 1) {
1132
+ r[0] = n > 0 ? regs[base] : undefined;
1133
+ }
1134
+ else if (p === 2) {
1135
+ r[0] = n > 0 ? regs[base] : undefined;
1136
+ r[1] = n > 1 ? regs[base + 1] : undefined;
1137
+ }
1138
+ else if (p > 2) {
1139
+ this.copyParams(r, regs, base, n, p);
1140
+ }
1141
+ f.thisValue = regs[base - 2];
1142
+ f.origin = counted ? undefined : (fcode.flags & 64) === 0 ? fcode.siteAt(pc) : frame.origin;
1143
+ frame.pc = pc;
1144
+ frame.sp = base - 2;
1145
+ f.pc = 0;
1146
+ f.sp = c.locals;
1147
+ f.mode = 0;
1148
+ frames.push(f);
1149
+ if (--this.fuel <= 0)
1150
+ return 1;
1151
+ continue outer;
1152
+ }
1153
+ }
1154
+ frame.pc = pc;
1155
+ frame.sp = sp;
1156
+ const called = this.execCallSlow(frame, n, pc, sp);
1157
+ if (called === 1) {
1158
+ if (this.fuel <= 0)
1159
+ return 1;
1160
+ continue outer;
1161
+ }
1162
+ if (called === 2)
1163
+ return 2;
1164
+ sp = frame.sp;
1165
+ pc++;
1166
+ frame.pc = pc;
1167
+ if (this.fuel <= 0)
1168
+ return 1;
1169
+ continue;
1170
+ }
1171
+ case 71: {
1172
+ // Op.CALL_SPREAD
1173
+ const called = this.execCallSpread(frame, pc, sp);
1174
+ if (called === 1) {
1175
+ if (this.fuel <= 0)
1176
+ return 1;
1177
+ continue outer;
1178
+ }
1179
+ if (called === 2)
1180
+ return 2;
1181
+ sp = frame.sp;
1182
+ pc++;
1183
+ frame.pc = pc;
1184
+ if (this.fuel <= 0)
1185
+ return 1;
1186
+ continue;
1187
+ }
1188
+ case 72: // Op.NEW
1189
+ if (this.execNew(frame, (w >>> 8) & 0xff, pc, sp))
1190
+ continue outer;
1191
+ sp = frame.sp;
1192
+ pc++;
1193
+ continue;
1194
+ case 73: // Op.NEW_SPREAD
1195
+ if (this.execNewSpread(frame, pc, sp))
1196
+ continue outer;
1197
+ sp = frame.sp;
1198
+ pc++;
1199
+ continue;
1200
+ case 74: // Op.ITER_OPEN
1201
+ frame.pc = pc;
1202
+ frame.sp = sp;
1203
+ pc = this.execIterOpen(frame, (w >>> 8) & 0xff, pc, sp);
1204
+ sp = frame.sp;
1205
+ continue;
1206
+ case 75: // Op.ITER_INIT
1207
+ frame.pc = pc;
1208
+ frame.sp = sp;
1209
+ this.execIterInit(frame, (w >>> 8) & 0xff, pc, sp);
1210
+ pc++;
1211
+ continue;
1212
+ case 76: {
1213
+ // Op.ITER_STEP
1214
+ const rec = regs[(w >>> 8) & 0xff];
1215
+ if (rec instanceof PositionCtor) {
1216
+ const step = rec.step();
1217
+ if (!step.done) {
1218
+ regs[sp++] = step.value;
1219
+ pc += 2;
1220
+ }
1221
+ else {
1222
+ pc = w >>> 16;
1223
+ }
1224
+ continue;
1225
+ }
1226
+ if (this.execIterStepSlow(frame, rec, w >>> 16, pc, sp))
1227
+ continue outer;
1228
+ sp = frame.sp;
1229
+ pc = frame.pc;
1230
+ continue;
1231
+ }
1232
+ case 77: // Op.ITER_RESULT
1233
+ pc = this.execIterResult(frame, (w >>> 8) & 0xff, w >>> 16, pc, sp);
1234
+ sp = frame.sp;
1235
+ continue;
1236
+ case 78: // Op.ITER_CLOSE
1237
+ pc = this.execIterClose(frame, (w >>> 8) & 0xff, w >>> 16, pc, sp);
1238
+ sp = frame.sp;
1239
+ continue;
1240
+ case 79: // Op.ITER_APPEND_ALL
1241
+ pc = this.execIterAppendAll(frame, (w >>> 8) & 0xff, w >>> 16, pc, sp);
1242
+ continue;
1243
+ case 80: // Op.FOR_IN
1244
+ frame.pc = pc;
1245
+ frame.sp = sp;
1246
+ regs[sp - 1] = this.execForIn(fcode, regs[sp - 1], pc);
1247
+ pc++;
1248
+ continue;
1249
+ case 81: // Op.GENERATOR_START
1250
+ this.onGeneratorStart(frame, pc, sp);
1251
+ continue outer;
1252
+ case 82: // Op.YIELD
1253
+ if (this.onYield(frame, pc, sp))
1254
+ continue outer;
1255
+ sp = frame.sp;
1256
+ pc = frame.pc;
1257
+ continue;
1258
+ case 83: // Op.RESUME
1259
+ if (regs[sp - 1] === 0) {
1260
+ sp--;
1261
+ pc = w >>> 16;
1262
+ continue;
1263
+ }
1264
+ pc = this.onResume(frame, w >>> 16, pc, sp);
1265
+ sp = frame.sp;
1266
+ continue;
1267
+ case 84: // Op.AWAIT
1268
+ this.onAwait(frame, (w >>> 8) & 0xff, pc, sp);
1269
+ continue outer;
1270
+ case 85: // Op.YSTAR
1271
+ frame.pc = pc;
1272
+ frame.sp = sp;
1273
+ pc = this.onYstar(frame, (w >>> 8) & 0xff, w >>> 16, pc, sp);
1274
+ sp = frame.sp;
1275
+ continue;
1276
+ case 86: // Op.YSTAR_RESULT
1277
+ frame.pc = pc;
1278
+ frame.sp = sp;
1279
+ pc = this.onYstarResult(frame, (w >>> 8) & 0xff, w >>> 16, pc, sp);
1280
+ sp = frame.sp;
1281
+ continue;
1282
+ default:
1283
+ this.failOpcode(w & 0xff);
1284
+ }
1285
+ }
1286
+ }
1287
+ }
1288
+ copyParams(r, regs, base, n, p) {
1289
+ for (let i = 0; i < p; i++)
1290
+ r[i] = i < n ? regs[base + i] : undefined;
1291
+ }
1292
+ failCallDepth(frame, fcode, pc, sp) {
1293
+ frame.pc = pc;
1294
+ frame.sp = sp;
1295
+ throw rangeError("Maximum call stack size exceeded", fcode.siteAt(pc));
1296
+ }
1297
+ failStringLength(len) {
1298
+ checkStringLength(len);
1299
+ }
1300
+ execInstanceof(fcode, lhs, rhs, pc) {
1301
+ return instanceofValue(lhs, rhs, fcode.siteAt(pc));
1302
+ }
1303
+ execBinopSlow(frame, sub, a, b, pc, sp) {
1304
+ return this.execBinarySlow(frame, BinOpSymbols[sub], a, b, pc, sp);
1305
+ }
1306
+ execThrow(frame, val, pc, sp) {
1307
+ frame.pc = pc;
1308
+ frame.sp = sp;
1309
+ throw new Throw(val);
1310
+ }
1311
+ execForIn(fcode, val, pc) {
1312
+ return new Position(forInKeys(this.ctx, val, fcode.siteAt(pc)), "values", this.ctx.builtins.Array);
1313
+ }
1314
+ onGeneratorStart(frame, pc, sp) {
1315
+ execGeneratorStart(this, frame, pc, sp);
1316
+ }
1317
+ onYield(frame, pc, sp) {
1318
+ return execYield(this, frame, pc, sp);
1319
+ }
1320
+ onResume(frame, bx, pc, sp) {
1321
+ return execResume(frame, bx, pc, sp);
1322
+ }
1323
+ onAwait(frame, flag, pc, sp) {
1324
+ execAwait(this, frame, flag, pc, sp);
1325
+ }
1326
+ onYstar(frame, slot, bx, pc, sp) {
1327
+ return execYstar(frame, slot, bx, pc, sp);
1328
+ }
1329
+ onYstarResult(frame, slot, bx, pc, sp) {
1330
+ return execYstarResult(frame, slot, bx, pc, sp);
1331
+ }
1332
+ failOpcode(op) {
1333
+ throw new NotYetImplemented(`opcode ${op}`);
1334
+ }
1335
+ execRot(regs, n, sp) {
1336
+ const top = regs[sp - 1];
1337
+ for (let i = sp - 1; i > sp - 1 - n; i--)
1338
+ regs[i] = regs[i - 1];
1339
+ regs[sp - 1 - n] = top;
1340
+ }
1341
+ failTdz(frame, name, pc, sp) {
1342
+ frame.pc = pc;
1343
+ frame.sp = sp;
1344
+ throw referenceError(`Cannot access '${name}' before initialization.`, frame.code.siteAt(pc));
1345
+ }
1346
+ failPut(frame, name, current, pc, sp) {
1347
+ frame.pc = pc;
1348
+ frame.sp = sp;
1349
+ if (current === HOLE) {
1350
+ throw referenceError(`Cannot access '${name}' before initialization.`, frame.code.siteAt(pc));
1351
+ }
1352
+ throw typeError(`Cannot assign to constant '${name}'.`, frame.code.siteAt(pc));
1353
+ }
1354
+ execGetGlobal(frame, mode, name, pc, sp) {
1355
+ const fcode = frame.code;
1356
+ const binding = this.ctx.globalScope.get(name);
1357
+ if (mode === 2) {
1358
+ frame.pc = pc;
1359
+ frame.sp = sp - 1;
1360
+ if (binding === undefined)
1361
+ throw referenceError(`Unknown identifier '${name}'.`, fcode.siteAt(pc));
1362
+ throw typeError(`Cannot assign to constant '${name}'.`, fcode.siteAt(pc));
1363
+ }
1364
+ if (binding === undefined) {
1365
+ if (mode === 1)
1366
+ return "undefined";
1367
+ frame.pc = pc;
1368
+ frame.sp = sp;
1369
+ throw referenceError(`Unknown identifier '${name}'.`, fcode.siteAt(pc));
1370
+ }
1371
+ return mode === 1 ? typeofValue(binding.value) : binding.value;
1372
+ }
1373
+ execArgs(frame, kind, bx) {
1374
+ if (kind === 0)
1375
+ return new Arguments(this.ctx.builtins.Object, frame.args ?? []);
1376
+ if (kind === 1)
1377
+ return new Arr(this.ctx.builtins.Array, (frame.args ?? []).slice(bx));
1378
+ if (kind === 2)
1379
+ return frame.fn;
1380
+ if (kind === 3)
1381
+ return frame.thisValue;
1382
+ return frame.args?.[bx];
1383
+ }
1384
+ execSetName(regs, consts, mode, bx, sp) {
1385
+ const fn = regs[sp - 1];
1386
+ if (!(fn instanceof Fn))
1387
+ return;
1388
+ if (mode === 0) {
1389
+ define(fn, "name", consts[bx], readonly);
1390
+ return;
1391
+ }
1392
+ const key = regs[sp - 2];
1393
+ const name = key === IteratorSymbol
1394
+ ? "[Symbol.iterator]"
1395
+ : key === AsyncIteratorSymbol
1396
+ ? "[Symbol.asyncIterator]"
1397
+ : String(key);
1398
+ define(fn, "name", name, readonly);
1399
+ }
1400
+ execToKey(frame, v, pc, sp) {
1401
+ if (!(v instanceof Obj) || isOpaque(v)) {
1402
+ frame.regs[sp - 1] = coerceToString(v);
1403
+ return false;
1404
+ }
1405
+ frame.pc = pc;
1406
+ frame.sp = sp - 1;
1407
+ this.pushInternalCall("$vmToKey", [v], frame.code.siteAt(pc) ?? frame.origin);
1408
+ return true;
1409
+ }
1410
+ execIn(frame, lhs, rhs, pc, sp) {
1411
+ frame.pc = pc;
1412
+ frame.sp = sp;
1413
+ return this.execBinarySlow(frame, "in", lhs, rhs, pc, sp);
1414
+ }
1415
+ execNewArray(regs, n, sp) {
1416
+ if (n === 0) {
1417
+ regs[sp] = new Arr(this.ctx.builtins.Array, contiguous());
1418
+ return sp + 1;
1419
+ }
1420
+ const items = regs.slice(sp - n, sp);
1421
+ sp -= n;
1422
+ regs[sp] = new Arr(this.ctx.builtins.Array, items);
1423
+ return sp + 1;
1424
+ }
1425
+ execArrayAppend(regs, isHole, sp) {
1426
+ if (isHole === 1) {
1427
+ const arr = regs[sp - 1];
1428
+ checkArrayLength(arr.items.length + 1);
1429
+ arr.items.length += 1;
1430
+ return sp;
1431
+ }
1432
+ const v = regs[--sp];
1433
+ const arr = regs[sp - 1];
1434
+ checkArrayLength(arr.items.length + 1);
1435
+ arr.items.push(v);
1436
+ return sp;
1437
+ }
1438
+ execDefineField(regs, consts, computed, bx, sp) {
1439
+ if (computed === 0) {
1440
+ const v = regs[--sp];
1441
+ define(regs[sp - 1], consts[bx], v);
1442
+ return sp;
1443
+ }
1444
+ const v = regs[--sp];
1445
+ const k = regs[--sp];
1446
+ define(regs[sp - 1], k, v);
1447
+ return sp;
1448
+ }
1449
+ execCopyDataProps(fcode, o, src, pc) {
1450
+ if (src !== null && src !== undefined) {
1451
+ assign(o, enumerableSource(this.ctx, "Object spread", src, fcode.siteAt(pc)));
1452
+ }
1453
+ }
1454
+ execCopyRest(fcode, regs, n, pc, sp) {
1455
+ const consumed = new Set();
1456
+ for (let i = sp - n; i < sp; i++) {
1457
+ const k = regs[i];
1458
+ consumed.add(typeof k === "symbol" ? k : String(k));
1459
+ }
1460
+ sp -= n;
1461
+ const src = regs[sp - 1];
1462
+ const rest = new Obj(this.ctx.builtins.Object);
1463
+ assign(rest, enumerableSource(this.ctx, "Object destructuring", src, fcode.siteAt(pc)), consumed);
1464
+ regs[sp - 1] = rest;
1465
+ return sp;
1466
+ }
1467
+ execRegExp(fcode, site, pc) {
1468
+ try {
1469
+ return constructRegExp(this.ctx.builtins, [site.pattern, site.flags]);
1470
+ }
1471
+ catch (err) {
1472
+ throw locate(err, fcode.siteAt(pc));
1473
+ }
1474
+ }
1475
+ execBinopNum(sub, a, b) {
1476
+ switch (sub) {
1477
+ case 0:
1478
+ return a / b;
1479
+ case 1:
1480
+ return a % b;
1481
+ case 2:
1482
+ return a ** b;
1483
+ case 3:
1484
+ return a & b;
1485
+ case 4:
1486
+ return a | b;
1487
+ case 5:
1488
+ return a ^ b;
1489
+ case 6:
1490
+ return a << b;
1491
+ case 7:
1492
+ return a >> b;
1493
+ case 8:
1494
+ return a >>> b;
1495
+ case 9:
1496
+ return a == b;
1497
+ default:
1498
+ return a != b;
1499
+ }
1500
+ }
1501
+ // `helper` converts an object in the prelude: `$vmToNumeric`, or `$vmInc` for `INC`.
1502
+ execToNumericSlow(frame, flag, v, pc, sp, helper = "$vmToNumeric") {
1503
+ const fcode = frame.code;
1504
+ frame.pc = pc;
1505
+ frame.sp = sp;
1506
+ if (v instanceof Obj && !isOpaque(v)) {
1507
+ frame.sp = sp - 1;
1508
+ this.pushInternalCall(helper, [flag, v], fcode.siteAt(pc) ?? frame.origin);
1509
+ return true;
1510
+ }
1511
+ if (isOpaque(v)) {
1512
+ throw invalidData(`'${flag === 0 ? "++" : "--"}' requires a data value.`, fcode.siteAt(pc));
1513
+ }
1514
+ frame.regs[sp - 1] = coerceToNumber(v);
1515
+ return false;
1516
+ }
1517
+ execIncSlow(frame, flag, v, pc, sp) {
1518
+ if (this.execToNumericSlow(frame, flag, v, pc, sp, "$vmInc"))
1519
+ return true;
1520
+ const n = frame.regs[sp - 1];
1521
+ frame.regs[sp - 1] = flag === 0 ? n + 1 : n - 1;
1522
+ return false;
1523
+ }
1524
+ execToStringSlow(frame, flag, v, pc, sp) {
1525
+ if (flag === 1 || !(v instanceof Obj) || isOpaque(v)) {
1526
+ frame.regs[sp - 1] = coerceToString(v);
1527
+ return false;
1528
+ }
1529
+ frame.pc = pc;
1530
+ frame.sp = sp - 1;
1531
+ this.pushInternalCall("$vmToString", [v], frame.code.siteAt(pc) ?? frame.origin);
1532
+ return true;
1533
+ }
1534
+ execConcat(regs, n, sp) {
1535
+ let out = "";
1536
+ for (let i = sp - n; i < sp; i++) {
1537
+ out += regs[i];
1538
+ if (out.length > 16_777_216)
1539
+ checkStringLength(out.length);
1540
+ }
1541
+ sp -= n;
1542
+ regs[sp] = out;
1543
+ return sp + 1;
1544
+ }
1545
+ execThrowError(frame, bx, pc, sp) {
1546
+ frame.pc = pc;
1547
+ frame.sp = sp;
1548
+ const site = frame.code.consts[bx];
1549
+ throw new PendingThrow(site.type, site.message, frame.code.siteAt(pc), site.kind, site.suggestions);
1550
+ }
1551
+ execEndFinally(frame, level, pc, sp) {
1552
+ const fcode = frame.code;
1553
+ const offset = fcode.finallyOffsets[level];
1554
+ const fin = fcode.finallies;
1555
+ const tag = frame.regs[fin[offset]];
1556
+ if (tag === 1) {
1557
+ frame.pc = pc;
1558
+ frame.sp = sp;
1559
+ throw new Throw(frame.regs[fin[offset + 1]]);
1560
+ }
1561
+ return fin[offset + 4 + tag];
1562
+ }
1563
+ execReturnSlow(frame, v, pc, sp) {
1564
+ const frames = this.frames;
1565
+ if (frame.mode === Mode.ASYNC || frame.mode === Mode.SETTLE) {
1566
+ frames.pop();
1567
+ const target = frame.target;
1568
+ this.deliverAnswer(frame);
1569
+ this.release(frame);
1570
+ target.resolve(v);
1571
+ return true;
1572
+ }
1573
+ if (frame.mode === Mode.GENERATOR) {
1574
+ completeGeneratorReturn(this, frame, v);
1575
+ return true;
1576
+ }
1577
+ if (frame.mode === Mode.REJECT_ONLY) {
1578
+ frames.pop();
1579
+ this.deliverAnswer(frame);
1580
+ this.release(frame);
1581
+ return true;
1582
+ }
1583
+ if (frame.mode === Mode.BOUNDARY_OUT) {
1584
+ frames.pop();
1585
+ this.release(frame);
1586
+ this.outcome = normal(v);
1587
+ return false;
1588
+ }
1589
+ if (frame.mode === Mode.PROGRAM) {
1590
+ frame.pc = pc;
1591
+ frame.sp = sp;
1592
+ return this.finishProgram(frame, v);
1593
+ }
1594
+ frames.pop();
1595
+ this.release(frame);
1596
+ return true;
1597
+ }
1598
+ execCallSpread(frame, pc, sp) {
1599
+ const regs = frame.regs;
1600
+ const argsArr = regs[--sp];
1601
+ frame.pc = pc;
1602
+ const callee = regs[sp - 1];
1603
+ const thisVal = regs[sp - 2];
1604
+ frame.sp = sp - 2;
1605
+ return this.invokeCallable(frame, callee, thisVal, [...argsArr.items], callSiteOf(frame, pc), pc);
1606
+ }
1607
+ execNew(frame, n, pc, sp) {
1608
+ const fcode = frame.code;
1609
+ const regs = frame.regs;
1610
+ if (n === 255) {
1611
+ const callee = regs[sp - 1];
1612
+ if (!(callee instanceof Builtin) || callee.construct === undefined) {
1613
+ frame.pc = pc;
1614
+ frame.sp = sp;
1615
+ throw notConstructible(callee, fcode.siteAt(pc));
1616
+ }
1617
+ frame.sp = sp;
1618
+ return false;
1619
+ }
1620
+ frame.pc = pc;
1621
+ const base = sp - n;
1622
+ const callee = regs[base - 1];
1623
+ const args = regs.slice(base, sp);
1624
+ frame.sp = base - 1;
1625
+ return this.execConstruct(frame, callee, args, callSiteOf(frame, pc));
1626
+ }
1627
+ execNewSpread(frame, pc, sp) {
1628
+ const regs = frame.regs;
1629
+ const argsArr = regs[--sp];
1630
+ const callee = regs[--sp];
1631
+ frame.pc = pc;
1632
+ frame.sp = sp;
1633
+ return this.execConstruct(frame, callee, [...argsArr.items], callSiteOf(frame, pc));
1634
+ }
1635
+ execIterStepSlow(frame, custom, bx, pc, sp) {
1636
+ const regs = frame.regs;
1637
+ custom.done = true;
1638
+ if (custom.rawGen) {
1639
+ const gen = custom.iterator;
1640
+ if (gen.state === "completed") {
1641
+ frame.sp = sp;
1642
+ frame.pc = bx;
1643
+ return false;
1644
+ }
1645
+ if (gen.state === "suspendedStart" || gen.state === "suspendedYield") {
1646
+ gen.state = "executing";
1647
+ frame.pc = pc;
1648
+ frame.sp = sp;
1649
+ resumeVmGenerator(this, gen, NEXT);
1650
+ return true;
1651
+ }
1652
+ }
1653
+ regs[sp++] = custom.iterator;
1654
+ regs[sp++] = custom.next;
1655
+ frame.sp = sp;
1656
+ frame.pc = pc + 1;
1657
+ return false;
1658
+ }
1659
+ execIterResult(frame, slot, bx, pc, sp) {
1660
+ const regs = frame.regs;
1661
+ const res = regs[--sp];
1662
+ frame.pc = pc;
1663
+ frame.sp = sp;
1664
+ if (!(res instanceof Obj)) {
1665
+ throw typeError("Iterator next() result must be an object.", frame.code.siteAt(pc));
1666
+ }
1667
+ const done = Boolean(this.readObjProp(res, "done", frame.code, pc));
1668
+ if (done)
1669
+ return bx;
1670
+ regs[slot].done = false;
1671
+ regs[sp] = this.readObjProp(res, "value", frame.code, pc);
1672
+ frame.sp = sp + 1;
1673
+ return pc + 1;
1674
+ }
1675
+ execIterClose(frame, slot, bx, pc, sp) {
1676
+ const regs = frame.regs;
1677
+ const rec = regs[slot];
1678
+ if (!(rec instanceof CustomIter) || rec.done) {
1679
+ frame.sp = sp;
1680
+ return bx;
1681
+ }
1682
+ frame.pc = pc;
1683
+ frame.sp = sp;
1684
+ rec.done = true;
1685
+ const ret = this.readObjProp(rec.iterator, "return", frame.code, pc);
1686
+ if (ret === undefined || ret === null)
1687
+ return bx;
1688
+ const method = requireIteratorMethod(ret, "Iterator return", frame.code.siteAt(pc));
1689
+ regs[sp++] = rec.iterator;
1690
+ regs[sp++] = method;
1691
+ frame.sp = sp;
1692
+ return pc + 1;
1693
+ }
1694
+ execIterAppendAll(frame, slot, bx, pc, sp) {
1695
+ const rec = frame.regs[slot];
1696
+ if (!(rec instanceof Position))
1697
+ return bx;
1698
+ const arr = frame.regs[sp - 1];
1699
+ frame.pc = pc;
1700
+ frame.sp = sp;
1701
+ for (let step = rec.step(); !step.done; step = rec.step()) {
1702
+ checkArrayLength(arr.items.length + 1);
1703
+ arr.items.push(step.value);
1704
+ }
1705
+ return pc + 1;
1706
+ }
1707
+ readObjProp(target, key, fcode, pc) {
1708
+ for (let cur = target; cur !== null; cur = cur.proto) {
1709
+ if (cur.props.size === 0)
1710
+ continue;
1711
+ const slot = cur.props.get(key);
1712
+ if (slot !== undefined) {
1713
+ if ("value" in slot)
1714
+ return slot.value;
1715
+ if (slot.get === undefined)
1716
+ return undefined;
1717
+ try {
1718
+ return slot.get(target);
1719
+ }
1720
+ catch (err) {
1721
+ throw locate(err, fcode.siteAt(pc));
1722
+ }
1723
+ }
1724
+ }
1725
+ return undefined;
1726
+ }
1727
+ unwind(rawError) {
1728
+ // An interruption skips every handler, but still completes each frame by its mode: a frame that settles a
1729
+ // promise rejects it, so whatever awaits that promise is interrupted in turn.
1730
+ const interrupted = rawError instanceof Interruption;
1731
+ const error = interrupted ? rawError : locate(rawError, this.currentSite());
1732
+ if (this.frames.length === 0) {
1733
+ this.outcome = abrupt(error);
1734
+ return false;
1735
+ }
1736
+ while (this.frames.length > 0) {
1737
+ const frame = this.frames[this.frames.length - 1];
1738
+ const fcode = frame.code;
1739
+ const handlers = fcode.handlers;
1740
+ const faultPc = frame.pc;
1741
+ for (let i = 0; !interrupted && i < handlers.length; i += 4) {
1742
+ const start = handlers[i];
1743
+ const end = handlers[i + 1];
1744
+ if (faultPc >= start && faultPc < end) {
1745
+ const target = handlers[i + 2];
1746
+ const depth = handlers[i + 3];
1747
+ const sp = fcode.locals + depth;
1748
+ frame.regs[sp] = materialize(this.ctx, error);
1749
+ frame.sp = sp + 1;
1750
+ frame.pc = target;
1751
+ return true;
1752
+ }
1753
+ }
1754
+ this.frames.pop();
1755
+ const mode = frame.mode;
1756
+ if (mode === Mode.CALLER) {
1757
+ this.release(frame);
1758
+ continue;
1759
+ }
1760
+ if (mode === Mode.GENERATOR) {
1761
+ if (unwindGenerator(this, frame, error)) {
1762
+ return this.frames.length > 0;
1763
+ }
1764
+ continue;
1765
+ }
1766
+ if (mode === Mode.ASYNC || mode === Mode.SETTLE || mode === Mode.REJECT_ONLY) {
1767
+ const target = frame.target;
1768
+ this.deliverAnswer(frame);
1769
+ this.release(frame);
1770
+ target.reject(error);
1771
+ return this.frames.length > 0;
1772
+ }
1773
+ this.release(frame);
1774
+ if (mode === Mode.PROGRAM || mode === Mode.BOUNDARY_OUT) {
1775
+ this.outcome = abrupt(error);
1776
+ return false;
1777
+ }
1778
+ }
1779
+ return false;
1780
+ }
1781
+ finishProgram(frame, value) {
1782
+ if (!isThenable(value)) {
1783
+ let fast;
1784
+ try {
1785
+ fast = tryFastBoundaryOrJson(this.ctx.builtins, value, true, VISIT_BUDGET);
1786
+ }
1787
+ catch (error) {
1788
+ this.frames.pop();
1789
+ this.release(frame);
1790
+ this.outcome = abrupt(error);
1791
+ return false;
1792
+ }
1793
+ if (fast.ok) {
1794
+ this.frames.pop();
1795
+ this.release(frame);
1796
+ this.outcome = normal(fast.json);
1797
+ return false;
1798
+ }
1799
+ }
1800
+ this.frames.pop();
1801
+ this.release(frame);
1802
+ this.pushInternal(internalCode("$vmCross"), [new Arr(this.ctx.builtins.Array, [value])], undefined, Mode.BOUNDARY_OUT);
1803
+ return true;
1804
+ }
1805
+ makeClosure(parentCode, fnIndex, regs, cells) {
1806
+ const childCode = this.codesOf(parentCode)[fnIndex];
1807
+ const caps = childCode.captures;
1808
+ let childCells;
1809
+ if (caps.length === 0) {
1810
+ childCells = EMPTY_CELLS;
1811
+ }
1812
+ else {
1813
+ const arr = contiguous();
1814
+ for (let i = 0; i < caps.length; i += 2) {
1815
+ arr.push(caps[i] === 0 ? regs[caps[i + 1]] : cells[caps[i + 1]]);
1816
+ }
1817
+ childCells = arr;
1818
+ }
1819
+ const fn = new Fn(this.ctx.builtins.Function, childCode, childCells);
1820
+ if ((childCode.flags & CodeFlags.GENERATOR) !== 0) {
1821
+ const isAsync = (childCode.flags & CodeFlags.ASYNC) !== 0;
1822
+ define(fn, "prototype", new Obj(isAsync ? this.ctx.builtins.AsyncGenerator : this.ctx.builtins.Generator), hidden);
1823
+ }
1824
+ return fn;
1825
+ }
1826
+ getTemplateObject(fcode, site) {
1827
+ const key = `${fcode.source.id}:${site.nodeIndex}`;
1828
+ const cached = this.templates.get(key);
1829
+ if (cached !== undefined)
1830
+ return cached;
1831
+ const arrayProto = this.ctx.builtins.Array;
1832
+ const strings = new Arr(arrayProto, [...site.cooked]);
1833
+ define(strings, "raw", new Arr(arrayProto, [...site.raw]), frozen);
1834
+ this.templates.set(key, strings);
1835
+ return strings;
1836
+ }
1837
+ execImport(frame, kind, k, pc, sp) {
1838
+ const fcode = frame.code;
1839
+ const siteNode = fcode.siteAt(pc);
1840
+ if (kind === ImportKind.DYNAMIC) {
1841
+ const specifier = frame.regs[sp - 1];
1842
+ const promise = capability(this.ctx, siteNode);
1843
+ try {
1844
+ promise.resolve(this.ctx.namespace(specifier, siteNode));
1845
+ }
1846
+ catch (err) {
1847
+ if (!(err instanceof PendingThrow))
1848
+ throw err;
1849
+ promise.reject(err);
1850
+ }
1851
+ frame.regs[sp - 1] = promise.promise;
1852
+ return sp;
1853
+ }
1854
+ const site = fcode.consts[k];
1855
+ if (kind === ImportKind.SIDE_EFFECT) {
1856
+ this.ctx.module(site.specifier, siteNode);
1857
+ return sp;
1858
+ }
1859
+ if (kind === ImportKind.DEFAULT) {
1860
+ frame.regs[sp] = this.ctx.module(site.specifier, siteNode);
1861
+ return sp + 1;
1862
+ }
1863
+ const ns = this.ctx.namespace(site.specifier, siteNode);
1864
+ if (kind === ImportKind.NAMESPACE) {
1865
+ frame.regs[sp] = ns;
1866
+ return sp + 1;
1867
+ }
1868
+ const imported = site.imported;
1869
+ if (!hasOwn(ns, imported)) {
1870
+ throw syntaxError(`"${site.specifier}" has no export named "${imported}".`, siteNode);
1871
+ }
1872
+ frame.regs[sp] = getOwn(ns, imported);
1873
+ return sp + 1;
1874
+ }
1875
+ execGetProp(frame, o, key, mode, pc, sp) {
1876
+ const regs = frame.regs;
1877
+ if (mode !== 2 && o instanceof Obj && !(o instanceof PromiseObj)) {
1878
+ const v = key === "length" && o instanceof Arr ? o.items.length : this.readObjProp(o, key, frame.code, pc);
1879
+ return writeRead(regs, sp - 1, mode, o, v);
1880
+ }
1881
+ if (mode !== 2 && typeof o === "string") {
1882
+ const v = key === "length" ? o.length : this.readObjProp(this.ctx.builtins.String, key, frame.code, pc);
1883
+ return writeRead(regs, sp - 1, mode, o, v);
1884
+ }
1885
+ if (o instanceof ToolReference)
1886
+ return writeRead(regs, sp - 1, mode, undefined, new ToolReference([...o.path, key]));
1887
+ const site = frame.code.siteAt(pc);
1888
+ if (mode === 2) {
1889
+ regs[sp - 1] = destructuredProperty(this.ctx.builtins, o, key, site);
1890
+ return sp;
1891
+ }
1892
+ return this.readMember(regs, sp - 1, mode, o, key, site);
1893
+ }
1894
+ execGetElem(frame, o, keyVal, mode, pc, sp) {
1895
+ if (mode === 0) {
1896
+ if (typeof o === "string" && typeof keyVal === "number" && keyVal >= 0 && (keyVal | 0) === keyVal) {
1897
+ frame.regs[sp - 2] = o[keyVal];
1898
+ frame.sp = sp - 1;
1899
+ return false;
1900
+ }
1901
+ if (o instanceof Obj && !(o instanceof PromiseObj)) {
1902
+ if (typeof keyVal === "number" && !(o instanceof Arr)) {
1903
+ if (o.constructor === Obj &&
1904
+ (o.props.size === 0 || (o.props.size === 1 && o.props.has("length"))) &&
1905
+ o.proto === this.ctx.builtins.Object &&
1906
+ o.proto.intrinsic > 0) {
1907
+ frame.regs[sp - 2] = undefined;
1908
+ frame.sp = sp - 1;
1909
+ return false;
1910
+ }
1911
+ }
1912
+ if (typeof keyVal === "string" && o.constructor === Obj) {
1913
+ frame.regs[sp - 2] = this.readObjProp(o, keyVal, frame.code, pc);
1914
+ frame.sp = sp - 1;
1915
+ return false;
1916
+ }
1917
+ }
1918
+ }
1919
+ const site = frame.code.siteAt(pc);
1920
+ const memberNode = site;
1921
+ if (mode !== 2)
1922
+ requireMemberBase(memberNode, o, keyVal);
1923
+ if (keyVal instanceof Obj && !isOpaque(keyVal)) {
1924
+ frame.sp = sp - 2;
1925
+ this.pushInternalCall("$vmGetElem", [o, keyVal], memberNode.property ?? site);
1926
+ return true;
1927
+ }
1928
+ const key = propertyKey(keyVal);
1929
+ if (mode === 2) {
1930
+ frame.regs[sp - 2] = destructuredProperty(this.ctx.builtins, o, key, site);
1931
+ frame.sp = sp - 1;
1932
+ return false;
1933
+ }
1934
+ frame.sp = this.readMember(frame.regs, sp - 2, mode, o, key, site);
1935
+ return false;
1936
+ }
1937
+ // Reads `o[key]` for the member expression at `site` into `regs` at `at`; see `writeRead`.
1938
+ readMember(regs, at, mode, o, key, site) {
1939
+ const ref = this.resolveMember(o, key, site);
1940
+ if (ref instanceof ToolReference)
1941
+ return writeRead(regs, at, mode, undefined, ref);
1942
+ if ("value" in ref)
1943
+ return writeRead(regs, at, mode, undefined, ref.value);
1944
+ return writeRead(regs, at, mode, ref.receiver, readReference(ref, site));
1945
+ }
1946
+ // The reference `o[key]` that the member expression at `site` names.
1947
+ resolveMember(o, key, site) {
1948
+ const member = site;
1949
+ return resolveProperty(this.ctx.builtins, o, key, member.object ?? site, member.property ?? site);
1950
+ }
1951
+ execPutProp(fcode, o, key, v, pc) {
1952
+ if (!(o instanceof Obj)) {
1953
+ const site = fcode.siteAt(pc);
1954
+ const ref = resolveProperty(this.ctx.builtins, o, key, site, site);
1955
+ writableReference(ref, site);
1956
+ return;
1957
+ }
1958
+ try {
1959
+ assignToReference(o, key, v, undefined);
1960
+ }
1961
+ catch (err) {
1962
+ throw locate(err, fcode.siteAt(pc));
1963
+ }
1964
+ }
1965
+ execPutElem(fcode, o, keyVal, v, pc) {
1966
+ this.execPutProp(fcode, o, propertyKey(keyVal), v, pc);
1967
+ }
1968
+ execDeleteProp(fcode, o, key, pc) {
1969
+ const site = fcode.siteAt(pc);
1970
+ const ref = this.resolveMember(o, key, site);
1971
+ if (ref instanceof ToolReference || "value" in ref || ref.receiver !== ref.target) {
1972
+ throw invalidData("Only data fields may be deleted.", site);
1973
+ }
1974
+ if (remove(ref.target, ref.key))
1975
+ return true;
1976
+ throw typeError(`Cannot delete property '${String(ref.key)}'.`, site);
1977
+ }
1978
+ execDeleteElem(frame, o, keyVal, pc, sp) {
1979
+ const site = frame.code.siteAt(pc);
1980
+ requireMemberBase(site, o, keyVal);
1981
+ if (keyVal instanceof Obj && !isOpaque(keyVal)) {
1982
+ frame.sp = sp - 1;
1983
+ this.pushInternalCall("$vmDeleteElem", [o, keyVal], site);
1984
+ return true;
1985
+ }
1986
+ frame.regs[sp - 1] = this.execDeleteProp(frame.code, o, propertyKey(keyVal), pc);
1987
+ frame.sp = sp;
1988
+ return false;
1989
+ }
1990
+ execCheckBase(fcode, kind, bx, regs, sp, pc) {
1991
+ const base = regs[kind === CheckBaseKind.READ || kind === CheckBaseKind.WRITE_ELEM ? sp - 2 : sp - 1];
1992
+ if (base instanceof Obj && !(base instanceof PromiseObj))
1993
+ return;
1994
+ const site = fcode.siteAt(pc);
1995
+ if (kind === CheckBaseKind.DESTRUCTURE) {
1996
+ if (base === null || base === undefined) {
1997
+ throw typeError(`Cannot destructure ${describeValue(base)} as it is ${base}.`, site);
1998
+ }
1999
+ return;
2000
+ }
2001
+ const memberNode = site;
2002
+ if (kind === CheckBaseKind.READ) {
2003
+ requireMemberBase(memberNode, base, regs[sp - 1]);
2004
+ return;
2005
+ }
2006
+ const key = kind === CheckBaseKind.WRITE_PROP ? fcode.consts[bx] : propertyKey(regs[sp - 1]);
2007
+ readReference(writableReference(this.resolveMember(base, key, site), memberNode), memberNode);
2008
+ }
2009
+ execBinarySlow(frame, op, a, b, pc, sp) {
2010
+ const fcode = frame.code;
2011
+ const site = fcode.siteAt(pc) ?? frame.origin;
2012
+ if (a instanceof Obj || b instanceof Obj) {
2013
+ const conv = operatorConversion(op, a, b);
2014
+ if (conv !== undefined) {
2015
+ frame.sp = sp - 1;
2016
+ this.pushInternalCall("$vmBinary", [op, a, b], site);
2017
+ return true;
2018
+ }
2019
+ }
2020
+ frame.regs[sp - 1] = applyBinaryOperator(op, a, b, site);
2021
+ return false;
2022
+ }
2023
+ execUnarySlow(frame, sub, v, pc, sp) {
2024
+ if (sub === 3) {
2025
+ frame.regs[sp - 1] = typeofValue(v);
2026
+ return false;
2027
+ }
2028
+ if (sub === 4) {
2029
+ frame.regs[sp - 1] = undefined;
2030
+ return false;
2031
+ }
2032
+ const fcode = frame.code;
2033
+ const site = fcode.siteAt(pc) ?? frame.origin;
2034
+ if (v instanceof Obj && !isOpaque(v)) {
2035
+ frame.sp = sp - 1;
2036
+ this.pushInternalCall("$vmUnary", [sub, v], site);
2037
+ return true;
2038
+ }
2039
+ if (isOpaque(v))
2040
+ throw invalidData("Unary operators require data values.", site);
2041
+ const n = coerceToNumber(v);
2042
+ frame.regs[sp - 1] = sub === UnaryOp.NEG ? -n : sub === UnaryOp.PLUS ? +n : ~n;
2043
+ return false;
2044
+ }
2045
+ execCallSlow(frame, n, pc, sp) {
2046
+ const regs = frame.regs;
2047
+ const base = sp - n;
2048
+ const callee = regs[base - 1];
2049
+ const thisVal = regs[base - 2];
2050
+ if (callee instanceof Native) {
2051
+ conversions.count = 0;
2052
+ const args = n === 0
2053
+ ? []
2054
+ : n === 1
2055
+ ? [regs[base]]
2056
+ : n === 2
2057
+ ? [regs[base], regs[base + 1]]
2058
+ : regs.slice(base, sp);
2059
+ frame.pc = pc;
2060
+ frame.sp = base - 2;
2061
+ const site = callee.callback && callee.call.length < 3 ? undefined : callSiteOf(frame, pc);
2062
+ const res = callee.call(thisVal, args, site);
2063
+ if (this.tripEvery === 0)
2064
+ this.fuel -= NATIVE_FUEL;
2065
+ if (res === null || typeof res !== "object" || res instanceof Obj) {
2066
+ normalizeItems(res);
2067
+ regs[base - 2] = res;
2068
+ frame.sp = base - 1;
2069
+ return 0;
2070
+ }
2071
+ return this.settleNativeResult(frame, res, callee, thisVal, args, false, site ?? callSiteOf(frame, pc), pc);
2072
+ }
2073
+ const args = regs.slice(base, sp);
2074
+ frame.sp = base - 2;
2075
+ return this.invokeCallable(frame, callee, thisVal, args, callSiteOf(frame, pc), pc);
2076
+ }
2077
+ /**
2078
+ * Dispatches a call to `callee`. Returns `0` if synchronous value pushed, `1` if a frame was entered, `2` if the job
2079
+ * blocks on a host call.
2080
+ */
2081
+ invokeCallable(callerFrame, callee, thisVal, args, site, pc) {
2082
+ while (callee instanceof BoundFn) {
2083
+ thisVal = callee.boundThis;
2084
+ args = [...callee.boundArgs, ...args];
2085
+ callee = callee.target;
2086
+ }
2087
+ if (callee instanceof VmIntrinsic) {
2088
+ let res;
2089
+ try {
2090
+ res = callee.call(args);
2091
+ }
2092
+ catch (err) {
2093
+ throw locate(err, site ?? this.currentSite());
2094
+ }
2095
+ if (res instanceof Convert) {
2096
+ callerFrame.regs[callerFrame.sp++] = res;
2097
+ return 0;
2098
+ }
2099
+ return this.settleNativeResult(callerFrame, res, undefined, thisVal, args, false, site, pc);
2100
+ }
2101
+ if (callee instanceof VmInternalFn) {
2102
+ const callArgs = callee.boundArgs !== undefined ? [...callee.boundArgs, ...args] : args;
2103
+ const f = this.pushInternal(callee.code, callArgs, site ?? callerFrame.origin);
2104
+ if ((callee.code.flags & CodeFlags.NEEDS_ARGS) !== 0)
2105
+ f.args = callArgs;
2106
+ f.thisValue = thisVal;
2107
+ this.fuel--;
2108
+ return 1;
2109
+ }
2110
+ if (callee instanceof Fn) {
2111
+ const code = callee.code;
2112
+ const counted = (code.flags & CodeFlags.INTERNAL) === 0;
2113
+ if (counted && this.depth > MAX_CALL_DEPTH) {
2114
+ throw rangeError("Maximum call stack size exceeded", site ?? this.currentSite());
2115
+ }
2116
+ const isGenerator = (code.flags & CodeFlags.GENERATOR) !== 0;
2117
+ const isAsync = (code.flags & CodeFlags.ASYNC) !== 0;
2118
+ const origin = site ?? callerFrame.origin;
2119
+ if (isAsync && !isGenerator) {
2120
+ const resolving = this.scheduler.resolving(this.scheduler.newPromise(), site ?? this.currentSite());
2121
+ this.pushFn(callee, thisVal, args, origin, Mode.ASYNC, resolving, resolving.promise);
2122
+ }
2123
+ else
2124
+ this.pushFn(callee, thisVal, args, origin, Mode.CALLER);
2125
+ this.fuel--;
2126
+ return 1;
2127
+ }
2128
+ if (callee instanceof Builtin) {
2129
+ conversions.count = 0;
2130
+ let res;
2131
+ try {
2132
+ res = callee.invoke(thisVal, args, site ?? this.currentSite());
2133
+ }
2134
+ catch (err) {
2135
+ throw locate(err, site ?? this.currentSite());
2136
+ }
2137
+ if (this.tripEvery === 0)
2138
+ this.fuel -= NATIVE_FUEL;
2139
+ return this.settleNativeResult(callerFrame, res, callee, thisVal, args, false, site, pc);
2140
+ }
2141
+ if (callee instanceof ToolReference) {
2142
+ if (callee.path.length === 0) {
2143
+ const callNode = site;
2144
+ throw typeError("The tools root is not callable.", callNode?.callee ?? site);
2145
+ }
2146
+ return this.hostResult(callerFrame, callTool(this, this.hosts, callee.path, args, site ?? this.currentSite()));
2147
+ }
2148
+ const callNode = site;
2149
+ throw notAFunction(callNode?.callee, site ?? this.currentSite());
2150
+ }
2151
+ execConstruct(callerFrame, ctor, args, site) {
2152
+ conversions.count = 0;
2153
+ let res;
2154
+ try {
2155
+ res = ctor.construct(args, ctor, site ?? this.currentSite());
2156
+ }
2157
+ catch (err) {
2158
+ throw locate(err, site ?? this.currentSite());
2159
+ }
2160
+ return this.settleNativeResult(callerFrame, res, ctor, ctor, args, true, site, callerFrame.pc) === 1;
2161
+ }
2162
+ settleNativeResult(callerFrame, res, callable, thisOrNewTarget, args, constructing, site, pc) {
2163
+ if (res instanceof Invoke) {
2164
+ normalizeItems(res.thisValue);
2165
+ for (let i = 0; i < res.args.length; i++)
2166
+ normalizeItems(res.args[i]);
2167
+ return this.invokeCallable(callerFrame, res.callable, res.thisValue, res.args, res.site ?? site, pc);
2168
+ }
2169
+ if (res instanceof Resume) {
2170
+ resumeVmGenerator(this, res.generator, res.request);
2171
+ return 1;
2172
+ }
2173
+ if (res === BLOCK)
2174
+ return 2;
2175
+ if (res instanceof Convert) {
2176
+ const builtins = this.ctx.builtins;
2177
+ this.pushInternalCall("$vmConvert", [
2178
+ callable,
2179
+ thisOrNewTarget,
2180
+ new Arr(builtins.Array, args),
2181
+ constructing,
2182
+ new Arr(builtins.Array, []),
2183
+ res,
2184
+ ], site ?? callerFrame.origin);
2185
+ return 1;
2186
+ }
2187
+ if (res instanceof Push) {
2188
+ const kindName = res.kind;
2189
+ const slots = res.slots;
2190
+ const builtins = this.ctx.builtins;
2191
+ if (kindName === "JSON.stringify") {
2192
+ const [value, replacer, properties, indent] = slots;
2193
+ if (replacer === undefined && properties === undefined) {
2194
+ const fast = tryFastBoundaryOrJson(builtins, value, false, VISIT_BUDGET);
2195
+ if (fast.ok) {
2196
+ const text = JSON.stringify(fast.json, null, indent);
2197
+ if (text !== undefined)
2198
+ checkStringLength(text.length);
2199
+ callerFrame.regs[callerFrame.sp++] = text;
2200
+ return 0;
2201
+ }
2202
+ }
2203
+ this.pushInternalCall("$vmJsonWalk", [replacer, value, properties !== undefined ? new Arr(builtins.Array, properties) : null, indent], site ?? callerFrame.origin);
2204
+ return 1;
2205
+ }
2206
+ if (kindName === "AsyncFromSyncIterator") {
2207
+ return handleAdapterPush(this, callerFrame, slots);
2208
+ }
2209
+ const promiseHandled = this.scheduler.handlePromisePush(callerFrame, kindName, slots, site ?? callerFrame.origin);
2210
+ if (promiseHandled !== undefined)
2211
+ return promiseHandled;
2212
+ if (kindName === "search") {
2213
+ return this.hostResult(callerFrame, callSearch(this, this.hosts, slots[0], site ?? callerFrame.origin));
2214
+ }
2215
+ if (kindName === "extension call") {
2216
+ return this.hostResult(callerFrame, callExtension(this.ctx, this.hosts, slots, site ?? callerFrame.origin));
2217
+ }
2218
+ throw new NotYetImplemented(`Push kind: ${kindName}`);
2219
+ }
2220
+ callerFrame.regs[callerFrame.sp++] = res;
2221
+ return 0;
2222
+ }
2223
+ // A host operation's answer, by `invokeCallable`'s convention: a value is pushed (0), a frame entered (1), or the job
2224
+ // blocks (2).
2225
+ hostResult(callerFrame, result) {
2226
+ if (result === ENTERED)
2227
+ return 1;
2228
+ if (result === BLOCK)
2229
+ return 2;
2230
+ callerFrame.regs[callerFrame.sp++] = result;
2231
+ return 0;
2232
+ }
2233
+ /**
2234
+ * Enters the program function `fn`, from the call at `origin`. A frame in another `mode` than `CALLER` settles
2235
+ * `target`, and hands the caller `answer` when it ends.
2236
+ */
2237
+ pushFn(fn, thisValue, args, origin, mode, target, answer) {
2238
+ const code = fn.code;
2239
+ const counted = (code.flags & CodeFlags.INTERNAL) === 0;
2240
+ if (counted)
2241
+ this.depth++;
2242
+ const f = this.acquire(code);
2243
+ f.fn = fn;
2244
+ f.cells = fn.cells.length === 0 ? EMPTY_CELLS : fn.cells;
2245
+ f.counted = counted;
2246
+ if ((code.flags & CodeFlags.SIMPLE_PARAMS) !== 0) {
2247
+ for (let i = 0; i < code.params; i++)
2248
+ f.regs[i] = i < args.length ? args[i] : undefined;
2249
+ }
2250
+ f.args = (code.flags & CodeFlags.NEEDS_ARGS) !== 0 ? args : undefined;
2251
+ f.thisValue = thisValue;
2252
+ f.origin = counted ? undefined : origin;
2253
+ f.pc = 0;
2254
+ f.sp = code.locals;
2255
+ f.mode = mode;
2256
+ f.target = target;
2257
+ f.answer = answer;
2258
+ this.frames.push(f);
2259
+ }
2260
+ pushInternalCall(name, args, origin) {
2261
+ this.pushInternal(internalCode(name), args, origin);
2262
+ }
2263
+ /** Runs an internal prelude function at the call `origin`; see `HostVm.pushInternal`. */
2264
+ pushInternal(code, args, origin, mode = Mode.CALLER, target, answer) {
2265
+ const f = this.acquire(code);
2266
+ f.fn = null;
2267
+ f.cells = EMPTY_CELLS;
2268
+ for (let i = 0; i < code.params; i++)
2269
+ f.regs[i] = i < args.length ? args[i] : undefined;
2270
+ f.thisValue = undefined;
2271
+ f.args = undefined;
2272
+ f.origin = origin;
2273
+ f.pc = 0;
2274
+ f.sp = code.locals;
2275
+ f.mode = mode;
2276
+ f.target = target;
2277
+ f.answer = answer;
2278
+ f.counted = false;
2279
+ this.frames.push(f);
2280
+ return f;
2281
+ }
2282
+ execIterOpen(frame, context, pc, sp) {
2283
+ const v = frame.regs[sp - 1];
2284
+ const fcode = frame.code;
2285
+ if (context !== IterContext.FOR_AWAIT &&
2286
+ context !== IterContext.ASYNC_DELEGATE &&
2287
+ context !== IterContext.DELEGATE) {
2288
+ const cursor = builtinCursor(this.ctx.builtins, v);
2289
+ if (cursor !== undefined) {
2290
+ if (cursor instanceof Position) {
2291
+ frame.regs[sp - 1] = cursor;
2292
+ }
2293
+ else {
2294
+ frame.regs[sp - 1] = this.customIter(cursor.iterator, cursor.next);
2295
+ }
2296
+ return skipJump(fcode.code, pc);
2297
+ }
2298
+ }
2299
+ const site = fcode.siteAt(pc) ?? frame.origin;
2300
+ if (context === IterContext.FOR_AWAIT || context === IterContext.ASYNC_DELEGATE) {
2301
+ if (this.openWithMethod(frame, v, AsyncIteratorSymbol, site, sp))
2302
+ return pc + 1;
2303
+ const cursor = builtinCursor(this.ctx.builtins, v);
2304
+ if (cursor !== undefined) {
2305
+ const adapter = new AsyncFromSyncIterator(this.ctx.builtins.AsyncFromSyncIterator, cursor, site);
2306
+ frame.regs[sp - 1] = new CustomIter(adapter, get(adapter, "next"));
2307
+ return skipJump(fcode.code, pc);
2308
+ }
2309
+ if (v instanceof Obj) {
2310
+ const syncMethod = readProperty(v, IteratorSymbol, site);
2311
+ if (syncMethod !== undefined && syncMethod !== null) {
2312
+ const callable = requireIteratorMethod(syncMethod, "Iterator method", site);
2313
+ const openCode = internalCode("$vmOpenSyncForAsync");
2314
+ frame.regs[sp - 1] = undefined;
2315
+ frame.regs[sp] = new VmInternalFn(openCode, [v, callable]);
2316
+ frame.sp = sp + 1;
2317
+ return pc + 1;
2318
+ }
2319
+ }
2320
+ if (context === IterContext.FOR_AWAIT) {
2321
+ throw invalidData(`for await...of requires an iterable value, received ${describeValue(v)}.`, site);
2322
+ }
2323
+ throw typeError("yield* requires a compatible iterable value.", site);
2324
+ }
2325
+ if (context === IterContext.DELEGATE) {
2326
+ if (this.openWithMethod(frame, v, IteratorSymbol, site, sp))
2327
+ return pc + 1;
2328
+ const cursor = builtinCursor(this.ctx.builtins, v);
2329
+ if (cursor !== undefined) {
2330
+ const iterObj = cursor instanceof Position ? new IteratorObj(this.ctx.builtins.Iterator, cursor) : cursor.iterator;
2331
+ frame.regs[sp - 1] = new CustomIter(iterObj, get(iterObj, "next"));
2332
+ return skipJump(fcode.code, pc);
2333
+ }
2334
+ throw typeError("yield* requires a compatible iterable value.", site);
2335
+ }
2336
+ if (this.openWithMethod(frame, v, IteratorSymbol, site, sp))
2337
+ return pc + 1;
2338
+ if (context === IterContext.FOR_OF) {
2339
+ throw invalidData(`for...of requires an iterable value, received ${describeValue(v)}.`, site);
2340
+ }
2341
+ if (context === IterContext.DESTRUCTURE) {
2342
+ throw typeError("Array destructuring requires a supported iterable value.", site);
2343
+ }
2344
+ throw typeError(site?.type === "SpreadElement" && (fcode.sourceObj?.nodes.includes(site) ?? false)
2345
+ ? "Spread requires a synchronous iterable."
2346
+ : "Value is not iterable.", site);
2347
+ }
2348
+ execIterInit(frame, context, pc, sp) {
2349
+ const site = frame.code.siteAt(pc) ?? frame.origin;
2350
+ const v = frame.regs[sp - 1];
2351
+ if (context === IterContext.CHECK_OBJECT) {
2352
+ requireIteratorObject(v, "Iterator return() result", site);
2353
+ return;
2354
+ }
2355
+ const obj = requireIteratorObject(v, "Iterator method result", site);
2356
+ const next = requireIteratorMethod(readProperty(obj, "next", site), "Iterator next", site);
2357
+ frame.regs[sp - 1] = this.customIter(obj, next);
2358
+ }
2359
+ // Opens `v` with its own `symbol` method, when it has one: the next instruction calls it.
2360
+ openWithMethod(frame, v, symbol, site, sp) {
2361
+ if (!(v instanceof Obj))
2362
+ return false;
2363
+ const method = readProperty(v, symbol, site);
2364
+ if (method === undefined || method === null)
2365
+ return false;
2366
+ frame.regs[sp - 1] = v;
2367
+ frame.regs[sp] = requireIteratorMethod(method, "Iterator method", site);
2368
+ frame.sp = sp + 1;
2369
+ return true;
2370
+ }
2371
+ // A synchronous generator's (or iterator helper's) own `next` is stepped without a call to it.
2372
+ customIter(iterator, next) {
2373
+ const custom = new CustomIter(iterator, next);
2374
+ const builtins = this.ctx.builtins;
2375
+ custom.rawGen =
2376
+ iterator instanceof GeneratorObj &&
2377
+ !iterator.asynchronous &&
2378
+ (next === get(builtins.Generator, "next") || next === get(builtins.IteratorHelper, "next"));
2379
+ return custom;
2380
+ }
2381
+ // Decodes one or two `EXTRA` prefix words and dispatches the widened instruction.
2382
+ // Negative returns encode outer control: `-1` = `continue outer`, `-2` = `return 0`, `-3` = `return 1`, `-4` = `return 2`.
2383
+ execExtra(frame, w, pc, sp) {
2384
+ const code = frame.code.code;
2385
+ const w1 = code[pc + 1];
2386
+ const op1 = w1 & 0xff;
2387
+ if (op1 === Op.EXTRA) {
2388
+ const w2 = code[pc + 2];
2389
+ const wideA = ((w >>> 16) << 16) | (w1 & 0xff00) | ((w2 >>> 8) & 0xff);
2390
+ const wideBx = ((w1 >>> 16) << 16) | (w2 >>> 16);
2391
+ frame.pc = pc + 2;
2392
+ frame.sp = sp;
2393
+ return this.execWide(frame, w2 & 0xff, wideA, wideBx, pc + 2);
2394
+ }
2395
+ const wideA = (w & 0xff00) | ((w1 >>> 8) & 0xff);
2396
+ const wideBx = ((w >>> 16) << 16) | (w1 >>> 16);
2397
+ frame.pc = pc + 1;
2398
+ frame.sp = sp;
2399
+ return this.execWide(frame, op1, wideA, wideBx, pc + 1);
2400
+ }
2401
+ // An instruction after its `EXTRA` prefix: the same work as in `exec`, with wide `a` and `bx`.
2402
+ execWide(frame, op, a, bx, pc) {
2403
+ const fcode = frame.code;
2404
+ const regs = frame.regs;
2405
+ const consts = fcode.consts;
2406
+ const cells = frame.cells;
2407
+ let sp = frame.sp;
2408
+ switch (op) {
2409
+ case Op.PUSH_UNDEF:
2410
+ regs[sp++] = undefined;
2411
+ frame.sp = sp;
2412
+ return pc + 1;
2413
+ case Op.PUSH_NULL:
2414
+ regs[sp++] = null;
2415
+ frame.sp = sp;
2416
+ return pc + 1;
2417
+ case Op.PUSH_BOOL:
2418
+ regs[sp++] = a === 1;
2419
+ frame.sp = sp;
2420
+ return pc + 1;
2421
+ case Op.PUSH_CONST:
2422
+ regs[sp++] = consts[bx];
2423
+ frame.sp = sp;
2424
+ return pc + 1;
2425
+ case Op.POP:
2426
+ frame.sp = sp - 1;
2427
+ return pc + 1;
2428
+ case Op.POPN:
2429
+ frame.sp = sp - bx;
2430
+ return pc + 1;
2431
+ case Op.DUP:
2432
+ regs[sp] = regs[sp - 1];
2433
+ frame.sp = sp + 1;
2434
+ return pc + 1;
2435
+ case Op.PICK:
2436
+ regs[sp] = regs[sp - 1 - a];
2437
+ frame.sp = sp + 1;
2438
+ return pc + 1;
2439
+ case Op.ROT:
2440
+ this.execRot(regs, a, sp);
2441
+ return pc + 1;
2442
+ case Op.GET_LOCAL:
2443
+ case Op.GET_CELL: {
2444
+ const v = op === Op.GET_LOCAL ? regs[bx] : regs[bx].v;
2445
+ if (v === HOLE)
2446
+ this.failTdz(frame, fcode.localNames[bx], pc, sp);
2447
+ regs[sp++] = v;
2448
+ frame.sp = sp;
2449
+ return pc + 1;
2450
+ }
2451
+ case Op.PUT_LOCAL: {
2452
+ const v = regs[--sp];
2453
+ frame.sp = sp;
2454
+ if (a !== PutKind.INIT && (regs[bx] === HOLE || a === PutKind.CONST)) {
2455
+ this.failPut(frame, fcode.localNames[bx], regs[bx], pc, sp);
2456
+ }
2457
+ regs[bx] = v;
2458
+ return pc + 1;
2459
+ }
2460
+ case Op.PUT_CELL:
2461
+ case Op.PUT_UPVAL: {
2462
+ const v = regs[--sp];
2463
+ frame.sp = sp;
2464
+ const cell = op === Op.PUT_CELL ? regs[bx] : cells[bx];
2465
+ if (a !== PutKind.INIT && (cell.v === HOLE || a === PutKind.CONST)) {
2466
+ this.failPut(frame, (op === Op.PUT_CELL ? fcode.localNames : fcode.upvalNames)[bx], cell.v, pc, sp);
2467
+ }
2468
+ cell.v = v;
2469
+ return pc + 1;
2470
+ }
2471
+ case Op.HOLE_LOCAL:
2472
+ regs[bx] = HOLE;
2473
+ return pc + 1;
2474
+ case Op.NEW_CELL:
2475
+ regs[bx] = new Cell(a === 1 ? regs[bx] : HOLE);
2476
+ return pc + 1;
2477
+ case Op.COPY_CELL:
2478
+ regs[bx] = new Cell(regs[bx].v);
2479
+ return pc + 1;
2480
+ case Op.GET_UPVAL: {
2481
+ const v = cells[bx].v;
2482
+ if (v === HOLE)
2483
+ this.failTdz(frame, fcode.upvalNames[bx], pc, sp);
2484
+ regs[sp++] = v;
2485
+ frame.sp = sp;
2486
+ return pc + 1;
2487
+ }
2488
+ case Op.GET_GLOBAL:
2489
+ regs[sp] = this.execGetGlobal(frame, a, consts[bx], pc, sp);
2490
+ frame.sp = sp + 1;
2491
+ return pc + 1;
2492
+ case Op.GET_INTRINSIC:
2493
+ regs[sp++] = this.getIntrinsic(consts[bx]);
2494
+ frame.sp = sp;
2495
+ return pc + 1;
2496
+ case Op.ARGS:
2497
+ regs[sp++] = this.execArgs(frame, a, bx);
2498
+ frame.sp = sp;
2499
+ return pc + 1;
2500
+ case Op.CLOSURE:
2501
+ regs[sp++] = this.makeClosure(fcode, bx, regs, cells);
2502
+ frame.sp = sp;
2503
+ return pc + 1;
2504
+ case Op.SET_NAME:
2505
+ this.execSetName(regs, consts, a, bx, sp);
2506
+ return pc + 1;
2507
+ case Op.IMPORT:
2508
+ frame.sp = this.execImport(frame, a, bx, pc, sp);
2509
+ return pc + 1;
2510
+ case Op.GET_PROP:
2511
+ frame.sp = this.execGetProp(frame, regs[sp - 1], consts[bx], a, pc, sp);
2512
+ return pc + 1;
2513
+ case Op.GET_ELEM:
2514
+ if (this.execGetElem(frame, regs[sp - 2], regs[sp - 1], a, pc, sp))
2515
+ return -1;
2516
+ return pc + 1;
2517
+ case Op.PUT_PROP: {
2518
+ const v = regs[--sp];
2519
+ frame.sp = sp;
2520
+ this.execPutProp(fcode, regs[sp - 1], consts[bx], v, pc);
2521
+ regs[sp - 1] = v;
2522
+ return pc + 1;
2523
+ }
2524
+ case Op.PUT_ELEM: {
2525
+ const v = regs[--sp];
2526
+ const keyVal = regs[--sp];
2527
+ frame.sp = sp;
2528
+ this.execPutElem(fcode, regs[sp - 1], keyVal, v, pc);
2529
+ regs[sp - 1] = v;
2530
+ return pc + 1;
2531
+ }
2532
+ case Op.DELETE_PROP:
2533
+ regs[sp - 1] = this.execDeleteProp(fcode, regs[sp - 1], consts[bx], pc);
2534
+ return pc + 1;
2535
+ case Op.DELETE_ELEM: {
2536
+ const keyVal = regs[--sp];
2537
+ frame.sp = sp;
2538
+ if (this.execDeleteElem(frame, regs[sp - 1], keyVal, pc, sp))
2539
+ return -1;
2540
+ return pc + 1;
2541
+ }
2542
+ case Op.CHECK_BASE:
2543
+ this.execCheckBase(fcode, a, bx, regs, sp, pc);
2544
+ return pc + 1;
2545
+ case Op.TO_KEY: {
2546
+ const v = regs[sp - 1];
2547
+ if (typeof v !== "string" && typeof v !== "number" && typeof v !== "symbol") {
2548
+ if (this.execToKey(frame, v, pc, sp))
2549
+ return -1;
2550
+ }
2551
+ return pc + 1;
2552
+ }
2553
+ case Op.IN: {
2554
+ const rhs = regs[--sp];
2555
+ frame.sp = sp;
2556
+ if (this.execIn(frame, regs[sp - 1], rhs, pc, sp))
2557
+ return -1;
2558
+ return pc + 1;
2559
+ }
2560
+ case Op.INSTANCEOF: {
2561
+ const rhs = regs[--sp];
2562
+ frame.sp = sp;
2563
+ regs[sp - 1] = this.execInstanceof(fcode, regs[sp - 1], rhs, pc);
2564
+ return pc + 1;
2565
+ }
2566
+ case Op.NEW_OBJECT:
2567
+ regs[sp++] = new Obj(this.ctx.builtins.Object);
2568
+ frame.sp = sp;
2569
+ return pc + 1;
2570
+ case Op.NEW_ARRAY:
2571
+ frame.sp = this.execNewArray(regs, bx, sp);
2572
+ return pc + 1;
2573
+ case Op.ARRAY_APPEND:
2574
+ frame.sp = this.execArrayAppend(regs, a, sp);
2575
+ return pc + 1;
2576
+ case Op.DEFINE_FIELD:
2577
+ frame.sp = this.execDefineField(regs, consts, a, bx, sp);
2578
+ return pc + 1;
2579
+ case Op.COPY_DATA_PROPS:
2580
+ frame.sp = --sp;
2581
+ this.execCopyDataProps(fcode, regs[sp - 1], regs[sp], pc);
2582
+ return pc + 1;
2583
+ case Op.COPY_REST:
2584
+ frame.sp = this.execCopyRest(fcode, regs, bx, pc, sp);
2585
+ return pc + 1;
2586
+ case Op.TEMPLATE:
2587
+ regs[sp++] = this.getTemplateObject(fcode, consts[bx]);
2588
+ frame.sp = sp;
2589
+ return pc + 1;
2590
+ case Op.REGEXP:
2591
+ regs[sp] = this.execRegExp(fcode, consts[bx], pc);
2592
+ frame.sp = sp + 1;
2593
+ return pc + 1;
2594
+ case Op.ADD:
2595
+ case Op.SUB:
2596
+ case Op.MUL:
2597
+ case Op.LT:
2598
+ case Op.LE:
2599
+ case Op.GT:
2600
+ case Op.GE: {
2601
+ const b = regs[--sp];
2602
+ const lhs = regs[sp - 1];
2603
+ frame.sp = sp;
2604
+ const sym = op === Op.ADD
2605
+ ? "+"
2606
+ : op === Op.SUB
2607
+ ? "-"
2608
+ : op === Op.MUL
2609
+ ? "*"
2610
+ : op === Op.LT
2611
+ ? "<"
2612
+ : op === Op.LE
2613
+ ? "<="
2614
+ : op === Op.GT
2615
+ ? ">"
2616
+ : ">=";
2617
+ if (this.execBinarySlow(frame, sym, lhs, b, pc, sp))
2618
+ return -1;
2619
+ return pc + 1;
2620
+ }
2621
+ case Op.SEQ: {
2622
+ const b = regs[--sp];
2623
+ frame.sp = sp;
2624
+ regs[sp - 1] = regs[sp - 1] === b;
2625
+ return pc + 1;
2626
+ }
2627
+ case Op.SNE: {
2628
+ const b = regs[--sp];
2629
+ frame.sp = sp;
2630
+ regs[sp - 1] = regs[sp - 1] !== b;
2631
+ return pc + 1;
2632
+ }
2633
+ case Op.BINOP: {
2634
+ const b = regs[--sp];
2635
+ const lhs = regs[sp - 1];
2636
+ frame.sp = sp;
2637
+ if (typeof lhs === "number" && typeof b === "number") {
2638
+ regs[sp - 1] = this.execBinopNum(a, lhs, b);
2639
+ return pc + 1;
2640
+ }
2641
+ if (this.execBinopSlow(frame, a, lhs, b, pc, sp))
2642
+ return -1;
2643
+ return pc + 1;
2644
+ }
2645
+ case Op.UNARY: {
2646
+ const v = regs[sp - 1];
2647
+ if (typeof v === "number" && a < 3) {
2648
+ regs[sp - 1] = a === 0 ? -v : a === 1 ? +v : ~v;
2649
+ return pc + 1;
2650
+ }
2651
+ if (this.execUnarySlow(frame, a, v, pc, sp))
2652
+ return -1;
2653
+ return pc + 1;
2654
+ }
2655
+ case Op.NOT:
2656
+ regs[sp - 1] = !regs[sp - 1];
2657
+ return pc + 1;
2658
+ case Op.TO_NUMERIC: {
2659
+ const v = regs[sp - 1];
2660
+ if (typeof v !== "number" && this.execToNumericSlow(frame, a, v, pc, sp))
2661
+ return -1;
2662
+ return pc + 1;
2663
+ }
2664
+ case Op.INC: {
2665
+ const v = regs[sp - 1];
2666
+ if (typeof v === "number") {
2667
+ regs[sp - 1] = a === 0 ? v + 1 : v - 1;
2668
+ return pc + 1;
2669
+ }
2670
+ if (this.execIncSlow(frame, a, v, pc, sp))
2671
+ return -1;
2672
+ return pc + 1;
2673
+ }
2674
+ case Op.TO_STRING: {
2675
+ const v = regs[sp - 1];
2676
+ if (typeof v !== "string" && this.execToStringSlow(frame, a, v, pc, sp))
2677
+ return -1;
2678
+ return pc + 1;
2679
+ }
2680
+ case Op.CONCAT:
2681
+ frame.sp = this.execConcat(regs, bx, sp);
2682
+ return pc + 1;
2683
+ case Op.JUMP:
2684
+ return bx;
2685
+ case Op.LOOP:
2686
+ frame.pc = bx;
2687
+ if (--this.fuel <= 0)
2688
+ return -3;
2689
+ return bx;
2690
+ case Op.JUMP_IF_FALSE:
2691
+ frame.sp = sp - 1;
2692
+ return regs[sp - 1] ? pc + 1 : bx;
2693
+ case Op.JUMP_IF_TRUE:
2694
+ frame.sp = sp - 1;
2695
+ return regs[sp - 1] ? bx : pc + 1;
2696
+ case Op.JUMP_COND: {
2697
+ const v = regs[sp - 1];
2698
+ if (a === CondKind.NULLISH) {
2699
+ if (v === null || v === undefined) {
2700
+ regs[sp - 1] = undefined;
2701
+ return bx;
2702
+ }
2703
+ return pc + 1;
2704
+ }
2705
+ if (a === CondKind.NULLISH_METHOD) {
2706
+ if (v === null || v === undefined) {
2707
+ frame.sp = sp - 1;
2708
+ regs[sp - 2] = undefined;
2709
+ return bx;
2710
+ }
2711
+ return pc + 1;
2712
+ }
2713
+ const jump = a === CondKind.TRUTHY_KEEP
2714
+ ? Boolean(v)
2715
+ : a === CondKind.FALSY_KEEP
2716
+ ? !v
2717
+ : a === CondKind.NOT_NULLISH_KEEP
2718
+ ? v !== null && v !== undefined
2719
+ : v !== undefined;
2720
+ if (jump)
2721
+ return bx;
2722
+ frame.sp = sp - 1;
2723
+ return pc + 1;
2724
+ }
2725
+ case Op.THROW:
2726
+ return this.execThrow(frame, regs[--sp], pc, sp);
2727
+ case Op.THROW_ERROR:
2728
+ return this.execThrowError(frame, bx, pc, sp);
2729
+ case Op.END_FINALLY:
2730
+ return this.execEndFinally(frame, bx, pc, sp);
2731
+ case Op.RETURN:
2732
+ case Op.END_PROGRAM: {
2733
+ const v = regs[sp - 1];
2734
+ if (frame.mode === 0) {
2735
+ this.frames.pop();
2736
+ if (frame.counted)
2737
+ this.depth--;
2738
+ if (this.pool.length < 128)
2739
+ this.pool.push(frame);
2740
+ const caller = this.frames[this.frames.length - 1];
2741
+ caller.regs[caller.sp++] = v;
2742
+ caller.pc++;
2743
+ return -1;
2744
+ }
2745
+ return this.execReturnSlow(frame, v, pc, sp) ? -1 : -2;
2746
+ }
2747
+ case Op.NOP:
2748
+ return pc + 1;
2749
+ case Op.CALL: {
2750
+ const called = this.execCallSlow(frame, a, pc, sp);
2751
+ if (called === 1)
2752
+ return this.fuel <= 0 ? -3 : -1;
2753
+ if (called === 2)
2754
+ return -4;
2755
+ frame.pc = pc + 1;
2756
+ return this.fuel <= 0 ? -3 : pc + 1;
2757
+ }
2758
+ case Op.CALL_SPREAD: {
2759
+ const called = this.execCallSpread(frame, pc, sp);
2760
+ if (called === 1)
2761
+ return this.fuel <= 0 ? -3 : -1;
2762
+ if (called === 2)
2763
+ return -4;
2764
+ frame.pc = pc + 1;
2765
+ return this.fuel <= 0 ? -3 : pc + 1;
2766
+ }
2767
+ case Op.NEW:
2768
+ if (this.execNew(frame, a, pc, sp))
2769
+ return -1;
2770
+ return pc + 1;
2771
+ case Op.NEW_SPREAD:
2772
+ if (this.execNewSpread(frame, pc, sp))
2773
+ return -1;
2774
+ return pc + 1;
2775
+ case Op.ITER_OPEN:
2776
+ return this.execIterOpen(frame, a, pc, sp);
2777
+ case Op.ITER_INIT:
2778
+ this.execIterInit(frame, a, pc, sp);
2779
+ return pc + 1;
2780
+ case Op.ITER_STEP: {
2781
+ const rec = regs[a];
2782
+ if (rec instanceof Position) {
2783
+ const step = rec.step();
2784
+ if (!step.done) {
2785
+ regs[sp++] = step.value;
2786
+ frame.sp = sp;
2787
+ return skipJump(fcode.code, pc);
2788
+ }
2789
+ return bx;
2790
+ }
2791
+ if (this.execIterStepSlow(frame, rec, bx, pc, sp))
2792
+ return -1;
2793
+ return frame.pc;
2794
+ }
2795
+ case Op.ITER_RESULT:
2796
+ return this.execIterResult(frame, a, bx, pc, sp);
2797
+ case Op.ITER_CLOSE:
2798
+ return this.execIterClose(frame, a, bx, pc, sp);
2799
+ case Op.ITER_APPEND_ALL:
2800
+ return this.execIterAppendAll(frame, a, bx, pc, sp);
2801
+ case Op.FOR_IN:
2802
+ regs[sp - 1] = this.execForIn(fcode, regs[sp - 1], pc);
2803
+ return pc + 1;
2804
+ case Op.GENERATOR_START:
2805
+ execGeneratorStart(this, frame, pc, sp);
2806
+ return -1;
2807
+ case Op.YIELD:
2808
+ if (execYield(this, frame, pc, sp))
2809
+ return -1;
2810
+ return frame.pc;
2811
+ case Op.RESUME:
2812
+ return execResume(frame, bx, pc, sp);
2813
+ case Op.AWAIT:
2814
+ execAwait(this, frame, a, pc, sp);
2815
+ return -1;
2816
+ case Op.YSTAR:
2817
+ return execYstar(frame, a, bx, pc, sp);
2818
+ case Op.YSTAR_RESULT:
2819
+ return execYstarResult(frame, a, bx, pc, sp);
2820
+ default:
2821
+ throw new Error(`Unexpected wide op ${op}`);
2822
+ }
2823
+ }
2824
+ }
2825
+ // Skips the `JUMP slow` instruction following a test-and-skip `ITER_OPEN` or `ITER_STEP`.
2826
+ const skipJump = (code, pc) => ((code[pc + 1] & 0xff) === Op.EXTRA ? pc + 3 : pc + 2);
2827
+ // A member read's result replaces its base at `at`; a method read (mode 1) keeps the receiver under the value.
2828
+ const writeRead = (regs, at, mode, receiver, value) => {
2829
+ if (mode !== 1) {
2830
+ regs[at] = value;
2831
+ return at + 1;
2832
+ }
2833
+ regs[at] = receiver;
2834
+ regs[at + 1] = value;
2835
+ return at + 2;
2836
+ };
2837
+ const NEXT = { kind: "next", value: undefined };
2838
+ // Where the call at `pc` is located: its own node, or inside the VM's internal code, the call that entered it.
2839
+ const callSiteOf = (frame, pc) => (frame.code.flags & CodeFlags.INTERNAL) === 0 ? frame.code.siteAt(pc) : frame.origin;
2840
+ // Rewrites an array's first item in place, so arrays a native returns share the item shape JSC sees in the VM's own.
2841
+ const normalizeItems = (value) => {
2842
+ if (!(value instanceof Arr) || !(0 in value.items))
2843
+ return;
2844
+ const first = value.items[0];
2845
+ value.items[0] = "";
2846
+ value.items[0] = first;
2847
+ };
2848
+ let warmed = false;
2849
+ const WARMUP_SOURCE = [
2850
+ "return (async () => {",
2851
+ " let totalSum = 0",
2852
+ " const fib = (n) => (n < 2 ? n : fib(n - 1) + fib(n - 2))",
2853
+ " const restFn = (a, b, ...r) => r.length",
2854
+ " const fiveFn = (a, b, c, d, e) => (a === b ? c : d) !== e ? 1 : 0",
2855
+ " const work = async (i) => { await null; return i * 2 }",
2856
+ " function* range(n) { for (let i = 0; i < n; i++) yield i }",
2857
+ " for (let r = 0; r < 12; r++) {",
2858
+ " let sum = 0",
2859
+ " for (let i = 0; i < 6; i++) sum = (sum + i * 3 + (i === 2 ? 1 : 0)) % 1000003",
2860
+ " sum += fib(3) + restFn(1, 2, 3) + fiveFn(r & 1, 1, 2, work, fib)",
2861
+ " for (const x of range(3)) sum += x",
2862
+ ' let out = ""',
2863
+ " for (let i = 0; i < 3; i++) out += String.fromCharCode(97 + (i % 26))",
2864
+ " const parts = []",
2865
+ " for (let i = 0; i < 3; i++) parts.push(`item-${i}`)",
2866
+ " const map = new Map(), set = new Set()",
2867
+ ' for (let i = 0; i < 4; i++) { map.set("k" + (i % 2), i); set.add(i % 2) }',
2868
+ " for (const [k, v] of map) sum += v",
2869
+ " for (const v of set) sum += v",
2870
+ ' map.delete("k0"); set.delete(0)',
2871
+ " const items = Array.from({ length: 4 }, (_, i) => (i * 7919) % 4)",
2872
+ " const mapped = items.map((x) => x * 2).filter((x) => x % 3 !== 0)",
2873
+ " const total = mapped.reduce((a, b) => a + b, 0)",
2874
+ " const sorted = mapped.slice(0, 4).sort((a, b) => a - b)",
2875
+ ' const obj = { a: 1, b: "two", c: [1, r], d: null, e: sorted }',
2876
+ " if (r >= 2) sum += JSON.stringify(JSON.parse(JSON.stringify(obj))).length",
2877
+ " const pres = await Promise.all(Array.from({ length: 2 }, (_, i) => work(i)))",
2878
+ " const tres = await Promise.all(Array.from({ length: 2 }, (_, i) => tools.echo({ id: i })))",
2879
+ ' totalSum += sum + total + sorted.length + pres.length + tres.length + out.length + parts.join(",").length + map.size + set.size',
2880
+ " }",
2881
+ " return totalSum",
2882
+ "})()",
2883
+ ].join("\n");
2884
+ const warmupVm = (vm) => {
2885
+ warmed = true;
2886
+ const savedTripEvery = vm.tripEvery;
2887
+ vm.tripEvery = 0;
2888
+ try {
2889
+ const ast = parse(WARMUP_SOURCE, {
2890
+ ecmaVersion: "latest",
2891
+ sourceType: "script",
2892
+ allowReturnOutsideFunction: true,
2893
+ });
2894
+ const source = new Source("<warmup>", WARMUP_SOURCE, ast);
2895
+ vm.start(source);
2896
+ for (;;) {
2897
+ const stop = vm.run();
2898
+ if (stop.kind === "done" || stop.kind === "stuck")
2899
+ break;
2900
+ if (stop.kind === "host") {
2901
+ for (const call of stop.calls)
2902
+ vm.complete(call.id, normal(1));
2903
+ }
2904
+ }
2905
+ vm.sourceCodes.delete(source.id);
2906
+ vm.ctx.sources.delete(source.id);
2907
+ }
2908
+ catch {
2909
+ }
2910
+ finally {
2911
+ vm.frames.length = 0;
2912
+ vm.templates.clear();
2913
+ vm.scheduler.parked.clear();
2914
+ vm.scheduler.queue.length = 0;
2915
+ vm.scheduler.head = 0;
2916
+ vm.scheduler.pending = 0;
2917
+ vm.scheduler.nextID = 0;
2918
+ vm.scheduler.unhandled.clear();
2919
+ vm.hosts.queued.length = 0;
2920
+ vm.hosts.running.clear();
2921
+ vm.hosts.inbox.length = 0;
2922
+ vm.hosts.nextID = 0;
2923
+ vm.hosts.blocked = undefined;
2924
+ vm.hosts.input = undefined;
2925
+ vm.depth = 0;
2926
+ vm.fuel = INITIAL_FUEL;
2927
+ vm.sliced = false;
2928
+ vm.outcome = undefined;
2929
+ vm.tripEvery = savedTripEvery;
2930
+ }
2931
+ };