@opencode/codemode 2.2.4 → 2.2.6

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 (133) hide show
  1. package/README.md +70 -1
  2. package/dist/codemode.d.ts +55 -4
  3. package/dist/codemode.js +63 -8
  4. package/dist/extension.d.ts +14 -9
  5. package/dist/extension.js +2 -2
  6. package/dist/index.d.ts +1 -1
  7. package/dist/index.js +1 -1
  8. package/dist/interpreter/execute.d.ts +1 -1
  9. package/dist/interpreter/execute.js +16 -4
  10. package/dist/interpreter/extensions.d.ts +3 -3
  11. package/dist/interpreter/extensions.js +17 -11
  12. package/dist/interpreter/globals.js +10 -0
  13. package/dist/interpreter/interpreter.d.ts +11 -1
  14. package/dist/interpreter/interpreter.js +86 -2
  15. package/dist/interpreter/modules.d.ts +4 -0
  16. package/dist/interpreter/modules.js +33 -0
  17. package/dist/suspend-error.d.ts +23 -0
  18. package/dist/suspend-error.js +25 -0
  19. package/dist/tool-runtime.d.ts +4 -1
  20. package/dist/vm/async.d.ts +78 -0
  21. package/dist/vm/async.js +335 -0
  22. package/dist/vm/code.d.ts +122 -0
  23. package/dist/vm/code.js +407 -0
  24. package/dist/vm/compiler/compile.d.ts +13 -0
  25. package/dist/vm/compiler/compile.js +1477 -0
  26. package/dist/vm/compiler/scope.d.ts +74 -0
  27. package/dist/vm/compiler/scope.js +515 -0
  28. package/dist/vm/data.d.ts +7 -0
  29. package/dist/vm/data.js +13 -0
  30. package/dist/vm/generators.d.ts +42 -0
  31. package/dist/vm/generators.js +413 -0
  32. package/dist/vm/host.d.ts +103 -0
  33. package/dist/vm/host.js +226 -0
  34. package/dist/vm/index.d.ts +6 -0
  35. package/dist/vm/index.js +6 -0
  36. package/dist/vm/internal-prelude.d.ts +45 -0
  37. package/dist/vm/internal-prelude.js +534 -0
  38. package/dist/vm/opcodes.d.ts +222 -0
  39. package/dist/vm/opcodes.js +235 -0
  40. package/dist/vm/prelude/bytecode.d.ts +18 -0
  41. package/dist/vm/prelude/bytecode.js +31 -0
  42. package/dist/vm/prelude/bytecode.json +1 -0
  43. package/dist/vm/prelude/helpers.d.ts +8 -0
  44. package/dist/vm/prelude/helpers.js +258 -0
  45. package/dist/vm/prelude/prelude.d.ts +21 -0
  46. package/dist/vm/prelude/prelude.js +53 -0
  47. package/dist/vm/prelude/source.d.ts +1 -0
  48. package/dist/vm/prelude/source.js +652 -0
  49. package/dist/vm/runtime/callback.d.ts +25 -0
  50. package/dist/vm/runtime/callback.js +51 -0
  51. package/dist/vm/runtime/driver.d.ts +58 -0
  52. package/dist/vm/runtime/driver.js +184 -0
  53. package/dist/vm/runtime/errors.d.ts +23 -0
  54. package/dist/vm/runtime/errors.js +169 -0
  55. package/dist/vm/runtime/execute.d.ts +80 -0
  56. package/dist/vm/runtime/execute.js +414 -0
  57. package/dist/vm/runtime/extensions.d.ts +16 -0
  58. package/dist/vm/runtime/extensions.js +270 -0
  59. package/dist/vm/runtime/generators.d.ts +6 -0
  60. package/dist/vm/runtime/generators.js +44 -0
  61. package/dist/vm/runtime/globals.d.ts +6 -0
  62. package/dist/vm/runtime/globals.js +137 -0
  63. package/dist/vm/runtime/interpreter.d.ts +50 -0
  64. package/dist/vm/runtime/interpreter.js +94 -0
  65. package/dist/vm/runtime/intrinsic-names.d.ts +56 -0
  66. package/dist/vm/runtime/intrinsic-names.js +166 -0
  67. package/dist/vm/runtime/intrinsics.d.ts +15 -0
  68. package/dist/vm/runtime/intrinsics.js +111 -0
  69. package/dist/vm/runtime/limits.d.ts +10 -0
  70. package/dist/vm/runtime/limits.js +19 -0
  71. package/dist/vm/runtime/model.d.ts +58 -0
  72. package/dist/vm/runtime/model.js +57 -0
  73. package/dist/vm/runtime/modules.d.ts +4 -0
  74. package/dist/vm/runtime/modules.js +33 -0
  75. package/dist/vm/runtime/native.d.ts +19 -0
  76. package/dist/vm/runtime/native.js +41 -0
  77. package/dist/vm/runtime/objects.d.ts +403 -0
  78. package/dist/vm/runtime/objects.js +784 -0
  79. package/dist/vm/runtime/operations.d.ts +49 -0
  80. package/dist/vm/runtime/operations.js +288 -0
  81. package/dist/vm/runtime/promises.d.ts +55 -0
  82. package/dist/vm/runtime/promises.js +232 -0
  83. package/dist/vm/runtime/references.d.ts +8 -0
  84. package/dist/vm/runtime/references.js +51 -0
  85. package/dist/vm/runtime/signals.d.ts +69 -0
  86. package/dist/vm/runtime/signals.js +68 -0
  87. package/dist/vm/runtime/source.d.ts +29 -0
  88. package/dist/vm/runtime/source.js +63 -0
  89. package/dist/vm/runtime/table.d.ts +43 -0
  90. package/dist/vm/runtime/table.js +132 -0
  91. package/dist/vm/scheduler.d.ts +178 -0
  92. package/dist/vm/scheduler.js +63 -0
  93. package/dist/vm/snapshot/codec.d.ts +87 -0
  94. package/dist/vm/snapshot/codec.js +751 -0
  95. package/dist/vm/snapshot/snapshot.d.ts +49 -0
  96. package/dist/vm/snapshot/snapshot.js +70 -0
  97. package/dist/vm/snapshot.d.ts +32 -0
  98. package/dist/vm/snapshot.js +306 -0
  99. package/dist/vm/stdlib/array.d.ts +16 -0
  100. package/dist/vm/stdlib/array.js +311 -0
  101. package/dist/vm/stdlib/bytes.d.ts +11 -0
  102. package/dist/vm/stdlib/bytes.js +222 -0
  103. package/dist/vm/stdlib/collections.d.ts +7 -0
  104. package/dist/vm/stdlib/collections.js +188 -0
  105. package/dist/vm/stdlib/console.d.ts +6 -0
  106. package/dist/vm/stdlib/console.js +93 -0
  107. package/dist/vm/stdlib/date.d.ts +2 -0
  108. package/dist/vm/stdlib/date.js +123 -0
  109. package/dist/vm/stdlib/headers.d.ts +2 -0
  110. package/dist/vm/stdlib/headers.js +92 -0
  111. package/dist/vm/stdlib/iterator.d.ts +2 -0
  112. package/dist/vm/stdlib/iterator.js +30 -0
  113. package/dist/vm/stdlib/json.d.ts +3 -0
  114. package/dist/vm/stdlib/json.js +42 -0
  115. package/dist/vm/stdlib/math.d.ts +3 -0
  116. package/dist/vm/stdlib/math.js +73 -0
  117. package/dist/vm/stdlib/number.d.ts +3 -0
  118. package/dist/vm/stdlib/number.js +72 -0
  119. package/dist/vm/stdlib/object.d.ts +6 -0
  120. package/dist/vm/stdlib/object.js +201 -0
  121. package/dist/vm/stdlib/regexp.d.ts +8 -0
  122. package/dist/vm/stdlib/regexp.js +119 -0
  123. package/dist/vm/stdlib/string.d.ts +2 -0
  124. package/dist/vm/stdlib/string.js +272 -0
  125. package/dist/vm/stdlib/url.d.ts +25 -0
  126. package/dist/vm/stdlib/url.js +255 -0
  127. package/dist/vm/stdlib/value.d.ts +6 -0
  128. package/dist/vm/stdlib/value.js +32 -0
  129. package/dist/vm/stdlib/web.d.ts +5 -0
  130. package/dist/vm/stdlib/web.js +97 -0
  131. package/dist/vm/vm.d.ts +225 -0
  132. package/dist/vm/vm.js +2931 -0
  133. package/package.json +6 -3
@@ -0,0 +1,74 @@
1
+ import type { AnyNode, ArrowFunctionExpression, FunctionDeclaration, FunctionExpression, Identifier, Pattern, Program } from "acorn";
2
+ import type { Source } from "../runtime/source.js";
3
+ type FunctionNode = Program | FunctionDeclaration | FunctionExpression | ArrowFunctionExpression;
4
+ type DeclKind = "var" | "let" | "const" | "function" | "param" | "catch" | "import" | "self" | "this" | "arguments";
5
+ export type Decl = {
6
+ readonly name: string;
7
+ readonly kind: DeclKind;
8
+ readonly fnIndex: number;
9
+ mutable: boolean;
10
+ captured: boolean;
11
+ used: boolean;
12
+ slot: number;
13
+ /** When a body `var` shares a name with a parameter or `arguments` in a separate `paramScope`. */
14
+ copyFromParam?: Decl | undefined;
15
+ };
16
+ export declare class Scope {
17
+ readonly parent: Scope | undefined;
18
+ readonly decls: Map<string, Decl>;
19
+ readonly hoistedFunctions: Array<{
20
+ readonly node: FunctionDeclaration;
21
+ fnIndex: number;
22
+ readonly decl: Decl;
23
+ }>;
24
+ constructor(parent: Scope | undefined);
25
+ }
26
+ type UpvalueInfo = {
27
+ /** `0` = parent's local cell slot, `1` = parent's upvalue index. */
28
+ readonly from: 0 | 1;
29
+ index: number;
30
+ readonly decl: Decl;
31
+ };
32
+ export type FunctionInfo = {
33
+ readonly index: number;
34
+ readonly node: FunctionNode;
35
+ readonly parentIndex: number;
36
+ readonly name: string;
37
+ flags: number;
38
+ readonly length: number;
39
+ readonly params: ReadonlyArray<Pattern>;
40
+ readonly selfScope: Scope | undefined;
41
+ readonly paramScope: Scope;
42
+ readonly bodyScope: Scope;
43
+ readonly allDecls: Array<Decl>;
44
+ readonly upvalues: Array<UpvalueInfo>;
45
+ readonly upvalueMap: Map<Decl, number>;
46
+ thisDecl: Decl | undefined;
47
+ argumentsDecl: Decl | undefined;
48
+ locals: number;
49
+ readonly localNames: Array<string>;
50
+ };
51
+ export type ResolvedRef = {
52
+ readonly kind: "local";
53
+ readonly decl: Decl;
54
+ } | {
55
+ readonly kind: "upval";
56
+ readonly upvalIndex: number;
57
+ readonly decl: Decl;
58
+ } | {
59
+ readonly kind: "global";
60
+ readonly name: string;
61
+ };
62
+ export type ScopeAnalysis = {
63
+ readonly functions: ReadonlyArray<FunctionInfo>;
64
+ readonly nodeToFunction: ReadonlyMap<FunctionNode, FunctionInfo>;
65
+ readonly scopeOfNode: ReadonlyMap<AnyNode, Scope>;
66
+ readonly refs: ReadonlyMap<Identifier, ResolvedRef>;
67
+ readonly thisRefs: ReadonlyMap<AnyNode, ResolvedRef>;
68
+ };
69
+ /**
70
+ * Pass 1: walks the AST to build lexical/var scopes, assign pre-order function indices,
71
+ * resolve all identifier and `this` references, mark captured bindings, and assign local/upvalue slots.
72
+ */
73
+ export declare const analyzeScopes: (source: Source, internal?: boolean) => ScopeAnalysis;
74
+ export {};
@@ -0,0 +1,515 @@
1
+ import { CodeFlags } from "../opcodes.js";
2
+ export class Scope {
3
+ parent;
4
+ decls = new Map();
5
+ hoistedFunctions = [];
6
+ constructor(parent) {
7
+ this.parent = parent;
8
+ }
9
+ }
10
+ /**
11
+ * Pass 1: walks the AST to build lexical/var scopes, assign pre-order function indices,
12
+ * resolve all identifier and `this` references, mark captured bindings, and assign local/upvalue slots.
13
+ */
14
+ export const analyzeScopes = (source, internal = false) => {
15
+ const functions = [];
16
+ const nodeToFunction = new Map();
17
+ const scopeOfNode = new Map();
18
+ const unresolved = [];
19
+ const addDecl = (scope, fnInfo, name, kind, mutable) => {
20
+ const existing = scope.decls.get(name);
21
+ if (existing !== undefined) {
22
+ if (mutable)
23
+ existing.mutable = true;
24
+ return existing;
25
+ }
26
+ const decl = { name, kind, fnIndex: fnInfo.index, mutable, captured: false, used: false, slot: -1 };
27
+ scope.decls.set(name, decl);
28
+ fnInfo.allDecls.push(decl);
29
+ return decl;
30
+ };
31
+ const declareLexical = (node, scope, fnInfo) => {
32
+ if (node.kind === "var")
33
+ return;
34
+ for (const d of node.declarations) {
35
+ for (const name of collectPatternNames(d.id))
36
+ addDecl(scope, fnInfo, name, node.kind === "let" ? "let" : "const", node.kind === "let");
37
+ }
38
+ };
39
+ const visitFunction = (node, parentScope, parentFnIndex) => {
40
+ const index = functions.length;
41
+ const isProgram = node.type === "Program";
42
+ const isArrow = node.type === "ArrowFunctionExpression";
43
+ const params = isProgram ? [] : node.params;
44
+ const simple = params.every((p) => p.type === "Identifier");
45
+ let flags = 0;
46
+ if (isArrow)
47
+ flags |= CodeFlags.ARROW;
48
+ if (isProgram || node.async)
49
+ flags |= CodeFlags.ASYNC;
50
+ if (!isProgram && node.generator)
51
+ flags |= CodeFlags.GENERATOR;
52
+ if (simple)
53
+ flags |= CodeFlags.SIMPLE_PARAMS;
54
+ if (internal)
55
+ flags |= CodeFlags.INTERNAL;
56
+ if (isProgram)
57
+ flags |= CodeFlags.PROGRAM;
58
+ const selfScope = node.type === "FunctionExpression" && node.id ? new Scope(parentScope) : undefined;
59
+ const paramScope = new Scope(selfScope ?? parentScope);
60
+ const bodyScope = simple ? paramScope : new Scope(paramScope);
61
+ const lengthEnd = params.findIndex((p) => p.type === "AssignmentPattern" || p.type === "RestElement");
62
+ const fnInfo = {
63
+ index,
64
+ node,
65
+ parentIndex: parentFnIndex,
66
+ name: isProgram ? "<program>" : isArrow ? "" : (node.id?.name ?? ""),
67
+ flags,
68
+ length: lengthEnd === -1 ? params.length : lengthEnd,
69
+ params,
70
+ selfScope,
71
+ paramScope,
72
+ bodyScope,
73
+ allDecls: [],
74
+ upvalues: [],
75
+ upvalueMap: new Map(),
76
+ thisDecl: undefined,
77
+ argumentsDecl: undefined,
78
+ locals: 0,
79
+ localNames: [],
80
+ };
81
+ functions.push(fnInfo);
82
+ nodeToFunction.set(node, fnInfo);
83
+ scopeOfNode.set(node, bodyScope);
84
+ if (selfScope && node.type === "FunctionExpression")
85
+ addDecl(selfScope, fnInfo, node.id.name, "self", false);
86
+ if (!isArrow)
87
+ fnInfo.thisDecl = addDecl(paramScope, fnInfo, "this", "this", false);
88
+ const paramNames = params.flatMap((param) => collectPatternNames(param));
89
+ if (!isProgram && !isArrow && !paramNames.includes("arguments")) {
90
+ fnInfo.argumentsDecl = addDecl(paramScope, fnInfo, "arguments", "arguments", true);
91
+ }
92
+ for (const name of paramNames)
93
+ addDecl(paramScope, fnInfo, name, "param", true);
94
+ for (const param of params)
95
+ visitPattern(param, paramScope, fnInfo);
96
+ if (node.type !== "Program" && node.body.type !== "BlockStatement")
97
+ visitExpression(node.body, bodyScope, fnInfo);
98
+ else {
99
+ if (node.type !== "Program")
100
+ scopeOfNode.set(node.body, bodyScope);
101
+ const stmts = node.type === "Program" ? node.body : node.body.body;
102
+ hoistStatementList(stmts, bodyScope, bodyScope, fnInfo, isProgram);
103
+ for (const stmt of stmts)
104
+ visitStatement(stmt, bodyScope, bodyScope, fnInfo);
105
+ }
106
+ if (!simple) {
107
+ for (const [varName, decl] of bodyScope.decls) {
108
+ const paramDecl = decl.kind === "var" ? paramScope.decls.get(varName) : undefined;
109
+ if (paramDecl?.kind !== "param" && paramDecl?.kind !== "arguments")
110
+ continue;
111
+ decl.copyFromParam = paramDecl;
112
+ paramDecl.used = true;
113
+ if (paramDecl.kind === "arguments")
114
+ fnInfo.flags |= CodeFlags.USES_ARGUMENTS | CodeFlags.NEEDS_ARGS;
115
+ }
116
+ }
117
+ return fnInfo;
118
+ };
119
+ const hoistStatementList = (stmts, lexicalScope, varScope, fnInfo, isProgram) => {
120
+ if (isProgram) {
121
+ for (const stmt of stmts) {
122
+ if (stmt.type !== "ImportDeclaration")
123
+ continue;
124
+ for (const spec of stmt.specifiers)
125
+ addDecl(lexicalScope, fnInfo, spec.local.name, "import", false);
126
+ }
127
+ }
128
+ for (const stmt of stmts)
129
+ if (stmt.type === "VariableDeclaration")
130
+ declareLexical(stmt, lexicalScope, fnInfo);
131
+ for (const stmt of stmts) {
132
+ if (stmt.type !== "FunctionDeclaration" || !stmt.id || (internal && isProgram))
133
+ continue;
134
+ const decl = addDecl(lexicalScope, fnInfo, stmt.id.name, "function", true);
135
+ lexicalScope.hoistedFunctions.push({ node: stmt, fnIndex: -1, decl });
136
+ }
137
+ if (lexicalScope === varScope)
138
+ for (const stmt of stmts)
139
+ collectVars(stmt, varScope, fnInfo);
140
+ };
141
+ const collectVars = (stmt, varScope, fnInfo) => {
142
+ switch (stmt?.type) {
143
+ case "VariableDeclaration":
144
+ if (stmt.kind !== "var")
145
+ break;
146
+ for (const d of stmt.declarations) {
147
+ for (const name of collectPatternNames(d.id)) {
148
+ if (!varScope.decls.has(name))
149
+ addDecl(varScope, fnInfo, name, "var", true);
150
+ }
151
+ }
152
+ break;
153
+ case "BlockStatement":
154
+ for (const s of stmt.body)
155
+ collectVars(s, varScope, fnInfo);
156
+ break;
157
+ case "IfStatement":
158
+ collectVars(stmt.consequent, varScope, fnInfo);
159
+ collectVars(stmt.alternate, varScope, fnInfo);
160
+ break;
161
+ case "WhileStatement":
162
+ case "DoWhileStatement":
163
+ case "LabeledStatement":
164
+ collectVars(stmt.body, varScope, fnInfo);
165
+ break;
166
+ case "ForStatement":
167
+ if (stmt.init?.type === "VariableDeclaration")
168
+ collectVars(stmt.init, varScope, fnInfo);
169
+ collectVars(stmt.body, varScope, fnInfo);
170
+ break;
171
+ case "ForInStatement":
172
+ case "ForOfStatement":
173
+ if (stmt.left.type === "VariableDeclaration")
174
+ collectVars(stmt.left, varScope, fnInfo);
175
+ collectVars(stmt.body, varScope, fnInfo);
176
+ break;
177
+ case "SwitchStatement":
178
+ for (const c of stmt.cases)
179
+ for (const s of c.consequent)
180
+ collectVars(s, varScope, fnInfo);
181
+ break;
182
+ case "TryStatement":
183
+ collectVars(stmt.block, varScope, fnInfo);
184
+ collectVars(stmt.handler?.body, varScope, fnInfo);
185
+ collectVars(stmt.finalizer, varScope, fnInfo);
186
+ break;
187
+ }
188
+ };
189
+ const visitStatement = (stmt, scope, varScope, fnInfo) => {
190
+ switch (stmt.type) {
191
+ case "ExpressionStatement":
192
+ visitExpression(stmt.expression, scope, fnInfo);
193
+ break;
194
+ case "VariableDeclaration":
195
+ for (const d of stmt.declarations) {
196
+ visitPattern(d.id, scope, fnInfo);
197
+ if (d.init)
198
+ visitExpression(d.init, scope, fnInfo);
199
+ }
200
+ break;
201
+ case "ReturnStatement":
202
+ case "ThrowStatement":
203
+ if (stmt.argument)
204
+ visitExpression(stmt.argument, scope, fnInfo);
205
+ break;
206
+ case "BlockStatement":
207
+ visitBlock(stmt, new Scope(scope), varScope, fnInfo);
208
+ break;
209
+ case "IfStatement":
210
+ visitExpression(stmt.test, scope, fnInfo);
211
+ visitStatement(stmt.consequent, scope, varScope, fnInfo);
212
+ if (stmt.alternate)
213
+ visitStatement(stmt.alternate, scope, varScope, fnInfo);
214
+ break;
215
+ case "WhileStatement":
216
+ case "DoWhileStatement":
217
+ visitExpression(stmt.test, scope, fnInfo);
218
+ visitStatement(stmt.body, scope, varScope, fnInfo);
219
+ break;
220
+ case "ForStatement": {
221
+ const forScope = new Scope(scope);
222
+ scopeOfNode.set(stmt, forScope);
223
+ if (stmt.init?.type === "VariableDeclaration") {
224
+ declareLexical(stmt.init, forScope, fnInfo);
225
+ visitStatement(stmt.init, forScope, varScope, fnInfo);
226
+ }
227
+ else if (stmt.init)
228
+ visitExpression(stmt.init, forScope, fnInfo);
229
+ if (stmt.test)
230
+ visitExpression(stmt.test, forScope, fnInfo);
231
+ if (stmt.update)
232
+ visitExpression(stmt.update, forScope, fnInfo);
233
+ visitStatement(stmt.body, forScope, varScope, fnInfo);
234
+ break;
235
+ }
236
+ case "ForInStatement":
237
+ case "ForOfStatement": {
238
+ const forScope = new Scope(scope);
239
+ scopeOfNode.set(stmt, forScope);
240
+ if (stmt.left.type === "VariableDeclaration") {
241
+ declareLexical(stmt.left, forScope, fnInfo);
242
+ for (const d of stmt.left.declarations)
243
+ visitPattern(d.id, forScope, fnInfo);
244
+ }
245
+ else
246
+ visitPattern(stmt.left, forScope, fnInfo);
247
+ visitExpression(stmt.right, forScope, fnInfo);
248
+ visitStatement(stmt.body, forScope, varScope, fnInfo);
249
+ break;
250
+ }
251
+ case "SwitchStatement": {
252
+ visitExpression(stmt.discriminant, scope, fnInfo);
253
+ const switchScope = new Scope(scope);
254
+ scopeOfNode.set(stmt, switchScope);
255
+ hoistStatementList(stmt.cases.flatMap((c) => c.consequent), switchScope, varScope, fnInfo, false);
256
+ for (const c of stmt.cases) {
257
+ if (c.test)
258
+ visitExpression(c.test, switchScope, fnInfo);
259
+ for (const s of c.consequent)
260
+ visitStatement(s, switchScope, varScope, fnInfo);
261
+ }
262
+ break;
263
+ }
264
+ case "LabeledStatement":
265
+ visitStatement(stmt.body, scope, varScope, fnInfo);
266
+ break;
267
+ case "TryStatement":
268
+ visitBlock(stmt.block, new Scope(scope), varScope, fnInfo);
269
+ if (stmt.handler)
270
+ visitCatchClause(stmt.handler, scope, varScope, fnInfo);
271
+ if (stmt.finalizer)
272
+ visitBlock(stmt.finalizer, new Scope(scope), varScope, fnInfo);
273
+ break;
274
+ case "FunctionDeclaration": {
275
+ const childFn = visitFunction(stmt, scope, fnInfo.index);
276
+ const hoisted = scope.hoistedFunctions.find((h) => h.node === stmt);
277
+ if (hoisted)
278
+ hoisted.fnIndex = childFn.index;
279
+ break;
280
+ }
281
+ }
282
+ };
283
+ const visitBlock = (block, blockScope, varScope, fnInfo) => {
284
+ scopeOfNode.set(block, blockScope);
285
+ hoistStatementList(block.body, blockScope, varScope, fnInfo, false);
286
+ for (const s of block.body)
287
+ visitStatement(s, blockScope, varScope, fnInfo);
288
+ };
289
+ const visitCatchClause = (handler, scope, varScope, fnInfo) => {
290
+ const catchScope = new Scope(scope);
291
+ scopeOfNode.set(handler, catchScope);
292
+ if (handler.param) {
293
+ for (const name of collectPatternNames(handler.param))
294
+ addDecl(catchScope, fnInfo, name, "catch", true);
295
+ visitPattern(handler.param, catchScope, fnInfo);
296
+ }
297
+ visitBlock(handler.body, new Scope(catchScope), varScope, fnInfo);
298
+ };
299
+ const visitPattern = (pattern, scope, fnInfo) => {
300
+ switch (pattern.type) {
301
+ case "Identifier":
302
+ unresolved.push({ node: pattern, name: pattern.name, scope, fnIndex: fnInfo.index });
303
+ break;
304
+ case "AssignmentPattern":
305
+ visitPattern(pattern.left, scope, fnInfo);
306
+ visitExpression(pattern.right, scope, fnInfo);
307
+ break;
308
+ case "RestElement":
309
+ visitPattern(pattern.argument, scope, fnInfo);
310
+ break;
311
+ case "ArrayPattern":
312
+ for (const el of pattern.elements)
313
+ if (el)
314
+ visitPattern(el, scope, fnInfo);
315
+ break;
316
+ case "ObjectPattern":
317
+ for (const prop of pattern.properties) {
318
+ if (prop.type === "RestElement")
319
+ visitPattern(prop.argument, scope, fnInfo);
320
+ else {
321
+ if (prop.computed)
322
+ visitExpression(prop.key, scope, fnInfo);
323
+ visitPattern(prop.value, scope, fnInfo);
324
+ }
325
+ }
326
+ break;
327
+ case "MemberExpression":
328
+ visitExpression(pattern, scope, fnInfo);
329
+ break;
330
+ }
331
+ };
332
+ const visitExpression = (expr, scope, fnInfo) => {
333
+ const visit = (child) => visitExpression(child, scope, fnInfo);
334
+ switch (expr.type) {
335
+ case "Identifier":
336
+ unresolved.push({ node: expr, name: expr.name, scope, fnIndex: fnInfo.index });
337
+ break;
338
+ case "ThisExpression":
339
+ unresolved.push({ node: expr, name: "this", scope, fnIndex: fnInfo.index });
340
+ break;
341
+ case "FunctionExpression":
342
+ case "ArrowFunctionExpression":
343
+ visitFunction(expr, scope, fnInfo.index);
344
+ break;
345
+ case "BinaryExpression":
346
+ case "LogicalExpression":
347
+ visit(expr.left);
348
+ visit(expr.right);
349
+ break;
350
+ case "UnaryExpression":
351
+ case "UpdateExpression":
352
+ case "AwaitExpression":
353
+ case "SpreadElement":
354
+ visit(expr.argument);
355
+ break;
356
+ case "YieldExpression":
357
+ if (expr.argument)
358
+ visit(expr.argument);
359
+ break;
360
+ case "AssignmentExpression":
361
+ visitPattern(expr.left, scope, fnInfo);
362
+ visit(expr.right);
363
+ break;
364
+ case "SequenceExpression":
365
+ case "TemplateLiteral":
366
+ for (const e of expr.expressions)
367
+ visit(e);
368
+ break;
369
+ case "ConditionalExpression":
370
+ visit(expr.test);
371
+ visit(expr.consequent);
372
+ visit(expr.alternate);
373
+ break;
374
+ case "CallExpression":
375
+ case "NewExpression":
376
+ if (expr.callee.type !== "Super")
377
+ visit(expr.callee);
378
+ for (const arg of expr.arguments)
379
+ visit(arg);
380
+ break;
381
+ case "MemberExpression":
382
+ if (expr.object.type !== "Super")
383
+ visit(expr.object);
384
+ if (expr.computed)
385
+ visit(expr.property);
386
+ break;
387
+ case "ChainExpression":
388
+ visit(expr.expression);
389
+ break;
390
+ case "ArrayExpression":
391
+ for (const el of expr.elements)
392
+ if (el)
393
+ visit(el);
394
+ break;
395
+ case "ObjectExpression":
396
+ for (const prop of expr.properties) {
397
+ if (prop.type === "SpreadElement")
398
+ visit(prop.argument);
399
+ else {
400
+ if (prop.computed)
401
+ visit(prop.key);
402
+ visit(prop.value);
403
+ }
404
+ }
405
+ break;
406
+ case "TaggedTemplateExpression":
407
+ visit(expr.tag);
408
+ for (const e of expr.quasi.expressions)
409
+ visit(e);
410
+ break;
411
+ case "ImportExpression":
412
+ visit(expr.source);
413
+ if (expr.options)
414
+ visit(expr.options);
415
+ break;
416
+ }
417
+ };
418
+ visitFunction(source.program, undefined, -1);
419
+ const ensureUpvalue = (fnIndex, decl) => {
420
+ const fnInfo = functions[fnIndex];
421
+ const existing = fnInfo.upvalueMap.get(decl);
422
+ if (existing !== undefined)
423
+ return existing;
424
+ const upvalIndex = fnInfo.upvalues.length;
425
+ if (fnInfo.parentIndex === decl.fnIndex)
426
+ fnInfo.upvalues.push({ from: 0, index: -1, decl });
427
+ else
428
+ fnInfo.upvalues.push({ from: 1, index: ensureUpvalue(fnInfo.parentIndex, decl), decl });
429
+ fnInfo.upvalueMap.set(decl, upvalIndex);
430
+ return upvalIndex;
431
+ };
432
+ const lookupDecl = (scope, name) => scope === undefined ? undefined : (scope.decls.get(name) ?? lookupDecl(scope.parent, name));
433
+ const refs = new Map();
434
+ const thisRefs = new Map();
435
+ // Identifiers resolve first, then `this`, so upvalues keep their order.
436
+ const resolve = (item) => {
437
+ const decl = lookupDecl(item.scope, item.name);
438
+ if (decl === undefined)
439
+ return { kind: "global", name: item.name };
440
+ decl.used = true;
441
+ const owner = functions[decl.fnIndex];
442
+ if (decl.kind === "arguments")
443
+ owner.flags |= CodeFlags.USES_ARGUMENTS | CodeFlags.NEEDS_ARGS;
444
+ if (decl.kind === "this")
445
+ owner.flags |= CodeFlags.USES_THIS;
446
+ if (decl.fnIndex === item.fnIndex)
447
+ return { kind: "local", decl };
448
+ decl.captured = true;
449
+ return { kind: "upval", upvalIndex: ensureUpvalue(item.fnIndex, decl), decl };
450
+ };
451
+ for (const item of unresolved)
452
+ if (item.node.type !== "ThisExpression")
453
+ refs.set(item.node, resolve(item));
454
+ for (const item of unresolved)
455
+ if (item.node.type === "ThisExpression")
456
+ thisRefs.set(item.node, resolve(item));
457
+ // Assign dense local slots per function. A call copies its arguments into the leading slots, so with simple
458
+ // parameters each position gets a slot; an earlier duplicate name (`function f(a, a)`) gets a dummy one.
459
+ for (const fnInfo of functions) {
460
+ const assignSlot = (decl) => {
461
+ if (decl.slot >= 0)
462
+ return;
463
+ decl.slot = fnInfo.localNames.length;
464
+ fnInfo.localNames.push(decl.name);
465
+ };
466
+ if ((fnInfo.flags & CodeFlags.SIMPLE_PARAMS) !== 0) {
467
+ fnInfo.params.forEach((p, i) => {
468
+ const name = p.name;
469
+ const last = fnInfo.params.findLastIndex((q) => q.name === name);
470
+ if (last === i)
471
+ assignSlot(fnInfo.paramScope.decls.get(name));
472
+ else
473
+ fnInfo.localNames.push(name);
474
+ });
475
+ }
476
+ else
477
+ fnInfo.flags |= CodeFlags.NEEDS_ARGS;
478
+ for (const decl of fnInfo.allDecls) {
479
+ if ((decl.kind === "this" || decl.kind === "arguments") && !decl.used)
480
+ continue;
481
+ assignSlot(decl);
482
+ }
483
+ fnInfo.locals = fnInfo.localNames.length;
484
+ }
485
+ // Patch `from === 0` upvalue indices now that parent local slots are assigned
486
+ for (const fnInfo of functions)
487
+ for (const u of fnInfo.upvalues)
488
+ if (u.from === 0)
489
+ u.index = u.decl.slot;
490
+ return { functions, nodeToFunction, scopeOfNode, refs, thisRefs };
491
+ };
492
+ const collectPatternNames = (pattern, out = []) => {
493
+ switch (pattern.type) {
494
+ case "Identifier":
495
+ out.push(pattern.name);
496
+ break;
497
+ case "AssignmentPattern":
498
+ collectPatternNames(pattern.left, out);
499
+ break;
500
+ case "RestElement":
501
+ collectPatternNames(pattern.argument, out);
502
+ break;
503
+ case "ArrayPattern":
504
+ for (const element of pattern.elements)
505
+ if (element !== null)
506
+ collectPatternNames(element, out);
507
+ break;
508
+ case "ObjectPattern":
509
+ for (const prop of pattern.properties) {
510
+ collectPatternNames(prop.type === "RestElement" ? prop.argument : prop.value, out);
511
+ }
512
+ break;
513
+ }
514
+ return out;
515
+ };
@@ -0,0 +1,7 @@
1
+ export * as Data from "./data.js";
2
+ import type { Json } from "../data.js";
3
+ import type { Interpreter } from "./runtime/interpreter.js";
4
+ import { type Value } from "./runtime/objects.js";
5
+ export type { Json };
6
+ /** Host JSON as program values: objects and arrays are copied, primitives pass through. */
7
+ export declare const fromJson: <R>(ctx: Interpreter<R>, value: Json | undefined) => Value;
@@ -0,0 +1,13 @@
1
+ export * as Data from "./data.js";
2
+ import { Arr, define, Obj } from "./runtime/objects.js";
3
+ /** Host JSON as program values: objects and arrays are copied, primitives pass through. */
4
+ export const fromJson = (ctx, value) => {
5
+ if (value === null || typeof value !== "object")
6
+ return value;
7
+ if (Array.isArray(value))
8
+ return new Arr(ctx.builtins.Array, value.map((item) => fromJson(ctx, item)));
9
+ const copied = new Obj(ctx.builtins.Object);
10
+ for (const [key, item] of Object.entries(value))
11
+ define(copied, key, fromJson(ctx, item));
12
+ return copied;
13
+ };
@@ -0,0 +1,42 @@
1
+ import { type AstNode, type GeneratorRequestKind } from "./runtime/model.js";
2
+ import { type Cursor, GeneratorObj, Obj, Opaque, type Value } from "./runtime/objects.js";
3
+ import { type Completion, type GeneratorRequest, Resume } from "./runtime/signals.js";
4
+ import { type Frame, type Vm } from "./vm.js";
5
+ /**
6
+ * CreateAsyncFromSyncIterator's object: an async iterator over a synchronous one, for `for await` and an async
7
+ * generator's `yield*`. Its methods are the `%AsyncFromSyncIterator%` intrinsics, so it is plain data.
8
+ */
9
+ export declare class AsyncFromSyncIterator extends Opaque {
10
+ /** The synchronous iterator it drives. */
11
+ readonly sync: Cursor;
12
+ /** Where it was made, so a failure that rejects one of its promises is located there. */
13
+ readonly site: AstNode;
14
+ readonly tag = "AsyncFromSyncIterator";
15
+ constructor(proto: Obj,
16
+ /** The synchronous iterator it drives. */
17
+ sync: Cursor,
18
+ /** Where it was made, so a failure that rejects one of its promises is located there. */
19
+ site: AstNode);
20
+ get describe(): string;
21
+ }
22
+ /** Generator.prototype.next/return/throw: the body runs on the caller's job stack until it yields, returns, or throws. */
23
+ export declare const generatorStep: (vm: Vm, generator: GeneratorObj, kind: GeneratorRequestKind, value: Value) => Value | Resume;
24
+ /**
25
+ * AsyncGenerator.prototype.next/return/throw: queue the request with its promise, and run the body now if it is
26
+ * waiting for one. A request that arrives while the body runs is answered when the body reaches it.
27
+ */
28
+ export declare const generatorRequest: (vm: Vm, thisValue: Value, kind: GeneratorRequestKind, value: Value) => Value | Resume;
29
+ /** The `awaitReturn` reaction: answers the `return` request with how its value settled, then drains the queue. */
30
+ export declare const finishAwaitReturn: (vm: Vm, generator: GeneratorObj, completion: Completion) => void;
31
+ export declare const execGeneratorStart: (vm: Vm, frame: Frame, pc: number, sp: number) => void;
32
+ export declare const execYield: (vm: Vm, frame: Frame, pc: number, sp: number) => boolean;
33
+ export declare const execResume: (frame: Frame, bx: number, pc: number, sp: number) => number;
34
+ export declare const execAwait: (vm: Vm, frame: Frame, a: number, pc: number, sp: number) => void;
35
+ export declare const execYstar: (frame: Frame, itSlot: number, bx: number, pc: number, sp: number) => number;
36
+ export declare const execYstarResult: (frame: Frame, kindSlot: number, bx: number, pc: number, sp: number) => number;
37
+ /** Puts a suspended generator's body back on the job stack, handing it `request` unless it has not started yet. */
38
+ export declare const resumeVmGenerator: (vm: Vm, gen: GeneratorObj, request: GeneratorRequest) => void;
39
+ export declare const completeGeneratorReturn: (vm: Vm, frame: Frame, v: Value) => void;
40
+ export declare const unwindGenerator: (vm: Vm, frame: Frame, error: unknown) => boolean;
41
+ export declare const handleAdapterPush: (vm: Vm, callerFrame: Frame, slots: Array<unknown>) => number;
42
+ export declare const registerGeneratorIntrinsics: (map: Map<string, unknown>, vm: Vm) => void;