@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.
- package/README.md +164 -7
- package/dist/codemode.d.ts +60 -4
- package/dist/codemode.js +63 -8
- package/dist/extension.d.ts +27 -9
- package/dist/extension.js +7 -3
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/interpreter/callback.d.ts +12 -1
- package/dist/interpreter/callback.js +13 -1
- package/dist/interpreter/execute.d.ts +1 -1
- package/dist/interpreter/execute.js +16 -4
- package/dist/interpreter/extensions.d.ts +3 -3
- package/dist/interpreter/extensions.js +17 -11
- package/dist/interpreter/globals.js +10 -0
- package/dist/interpreter/interpreter.d.ts +11 -1
- package/dist/interpreter/interpreter.js +88 -4
- package/dist/interpreter/modules.d.ts +4 -0
- package/dist/interpreter/modules.js +33 -0
- package/dist/interpreter/promises.js +2 -2
- package/dist/interpreter/runner.d.ts +1 -11
- package/dist/interpreter/runner.js +1 -13
- package/dist/stdlib/iterator.js +1 -2
- package/dist/suspend-error.d.ts +24 -0
- package/dist/suspend-error.js +25 -0
- package/dist/tool-runtime.d.ts +31 -7
- package/dist/tool-runtime.js +116 -26
- package/dist/tool.d.ts +45 -2
- package/dist/tool.js +30 -7
- package/dist/vm/async.d.ts +78 -0
- package/dist/vm/async.js +335 -0
- package/dist/vm/code.d.ts +122 -0
- package/dist/vm/code.js +407 -0
- package/dist/vm/compiler/compile.d.ts +13 -0
- package/dist/vm/compiler/compile.js +1477 -0
- package/dist/vm/compiler/scope.d.ts +74 -0
- package/dist/vm/compiler/scope.js +515 -0
- package/dist/vm/data.d.ts +7 -0
- package/dist/vm/data.js +13 -0
- package/dist/vm/generators.d.ts +42 -0
- package/dist/vm/generators.js +413 -0
- package/dist/vm/host.d.ts +106 -0
- package/dist/vm/host.js +231 -0
- package/dist/vm/index.d.ts +6 -0
- package/dist/vm/index.js +6 -0
- package/dist/vm/internal-prelude.d.ts +45 -0
- package/dist/vm/internal-prelude.js +534 -0
- package/dist/vm/opcodes.d.ts +222 -0
- package/dist/vm/opcodes.js +235 -0
- package/dist/vm/prelude/bytecode.d.ts +18 -0
- package/dist/vm/prelude/bytecode.js +31 -0
- package/dist/vm/prelude/bytecode.json +1 -0
- package/dist/vm/prelude/helpers.d.ts +8 -0
- package/dist/vm/prelude/helpers.js +258 -0
- package/dist/vm/prelude/prelude.d.ts +21 -0
- package/dist/vm/prelude/prelude.js +53 -0
- package/dist/vm/prelude/source.d.ts +1 -0
- package/dist/vm/prelude/source.js +652 -0
- package/dist/vm/runtime/callback.d.ts +25 -0
- package/dist/vm/runtime/callback.js +51 -0
- package/dist/vm/runtime/driver.d.ts +68 -0
- package/dist/vm/runtime/driver.js +254 -0
- package/dist/vm/runtime/errors.d.ts +23 -0
- package/dist/vm/runtime/errors.js +169 -0
- package/dist/vm/runtime/execute.d.ts +80 -0
- package/dist/vm/runtime/execute.js +442 -0
- package/dist/vm/runtime/extensions.d.ts +16 -0
- package/dist/vm/runtime/extensions.js +337 -0
- package/dist/vm/runtime/generators.d.ts +6 -0
- package/dist/vm/runtime/generators.js +44 -0
- package/dist/vm/runtime/globals.d.ts +6 -0
- package/dist/vm/runtime/globals.js +137 -0
- package/dist/vm/runtime/interpreter.d.ts +53 -0
- package/dist/vm/runtime/interpreter.js +96 -0
- package/dist/vm/runtime/intrinsic-names.d.ts +56 -0
- package/dist/vm/runtime/intrinsic-names.js +166 -0
- package/dist/vm/runtime/intrinsics.d.ts +15 -0
- package/dist/vm/runtime/intrinsics.js +111 -0
- package/dist/vm/runtime/limits.d.ts +10 -0
- package/dist/vm/runtime/limits.js +19 -0
- package/dist/vm/runtime/model.d.ts +58 -0
- package/dist/vm/runtime/model.js +57 -0
- package/dist/vm/runtime/modules.d.ts +4 -0
- package/dist/vm/runtime/modules.js +33 -0
- package/dist/vm/runtime/native.d.ts +19 -0
- package/dist/vm/runtime/native.js +41 -0
- package/dist/vm/runtime/objects.d.ts +403 -0
- package/dist/vm/runtime/objects.js +784 -0
- package/dist/vm/runtime/operations.d.ts +49 -0
- package/dist/vm/runtime/operations.js +288 -0
- package/dist/vm/runtime/promises.d.ts +55 -0
- package/dist/vm/runtime/promises.js +232 -0
- package/dist/vm/runtime/references.d.ts +8 -0
- package/dist/vm/runtime/references.js +51 -0
- package/dist/vm/runtime/signals.d.ts +69 -0
- package/dist/vm/runtime/signals.js +68 -0
- package/dist/vm/runtime/source.d.ts +29 -0
- package/dist/vm/runtime/source.js +63 -0
- package/dist/vm/runtime/table.d.ts +43 -0
- package/dist/vm/runtime/table.js +132 -0
- package/dist/vm/scheduler.d.ts +190 -0
- package/dist/vm/scheduler.js +74 -0
- package/dist/vm/snapshot/codec.d.ts +117 -0
- package/dist/vm/snapshot/codec.js +848 -0
- package/dist/vm/snapshot/snapshot.d.ts +53 -0
- package/dist/vm/snapshot/snapshot.js +74 -0
- package/dist/vm/snapshot.d.ts +32 -0
- package/dist/vm/snapshot.js +309 -0
- package/dist/vm/stdlib/array.d.ts +16 -0
- package/dist/vm/stdlib/array.js +311 -0
- package/dist/vm/stdlib/bytes.d.ts +11 -0
- package/dist/vm/stdlib/bytes.js +222 -0
- package/dist/vm/stdlib/collections.d.ts +7 -0
- package/dist/vm/stdlib/collections.js +188 -0
- package/dist/vm/stdlib/console.d.ts +6 -0
- package/dist/vm/stdlib/console.js +93 -0
- package/dist/vm/stdlib/date.d.ts +2 -0
- package/dist/vm/stdlib/date.js +123 -0
- package/dist/vm/stdlib/headers.d.ts +2 -0
- package/dist/vm/stdlib/headers.js +92 -0
- package/dist/vm/stdlib/iterator.d.ts +2 -0
- package/dist/vm/stdlib/iterator.js +30 -0
- package/dist/vm/stdlib/json.d.ts +3 -0
- package/dist/vm/stdlib/json.js +42 -0
- package/dist/vm/stdlib/math.d.ts +3 -0
- package/dist/vm/stdlib/math.js +73 -0
- package/dist/vm/stdlib/number.d.ts +3 -0
- package/dist/vm/stdlib/number.js +72 -0
- package/dist/vm/stdlib/object.d.ts +6 -0
- package/dist/vm/stdlib/object.js +201 -0
- package/dist/vm/stdlib/regexp.d.ts +8 -0
- package/dist/vm/stdlib/regexp.js +119 -0
- package/dist/vm/stdlib/string.d.ts +2 -0
- package/dist/vm/stdlib/string.js +272 -0
- package/dist/vm/stdlib/url.d.ts +25 -0
- package/dist/vm/stdlib/url.js +255 -0
- package/dist/vm/stdlib/value.d.ts +6 -0
- package/dist/vm/stdlib/value.js +32 -0
- package/dist/vm/stdlib/web.d.ts +5 -0
- package/dist/vm/stdlib/web.js +97 -0
- package/dist/vm/vm.d.ts +226 -0
- package/dist/vm/vm.js +2931 -0
- package/package.json +8 -5
|
@@ -0,0 +1,337 @@
|
|
|
1
|
+
import { Effect } from "effect";
|
|
2
|
+
import { isAsync } from "../../extension.js";
|
|
3
|
+
import { hooked } from "../../tool-runtime.js";
|
|
4
|
+
import { errorMessage, errorType } from "./errors.js";
|
|
5
|
+
import { createErrorValue } from "./intrinsics.js";
|
|
6
|
+
import { MAX_ARRAY_LENGTH, MAX_VALUE_DEPTH } from "./limits.js";
|
|
7
|
+
import { PendingThrow, rangeError, Throw, typeError } from "./model.js";
|
|
8
|
+
import { native } from "./native.js";
|
|
9
|
+
import { define, get, has, hidden, keys, Arr, Bytes, DateObj, ErrorObj, HeadersObj, PromiseObj, MapObj, Obj, RegExpObj, SetObj, URLObj, URLSearchParamsObj, coerceToString, } from "./objects.js";
|
|
10
|
+
import { describeValue, isOpaque } from "./references.js";
|
|
11
|
+
import { Push } from "./signals.js";
|
|
12
|
+
import { SnapshotError } from "../snapshot/codec.js";
|
|
13
|
+
/**
|
|
14
|
+
* The global bindings of one run's extensions. Everything crossing the boundary is converted: plain data and built-in
|
|
15
|
+
* wrappers are copied, a host function becomes a program function whose calls cross the same way, and a host Promise
|
|
16
|
+
* or Effect becomes a program promise.
|
|
17
|
+
*/
|
|
18
|
+
export const extensionGlobals = (ctx, extensions) => {
|
|
19
|
+
const builtins = ctx.builtins;
|
|
20
|
+
const byName = new Map(extensions.map((extension) => [extension.name, extension]));
|
|
21
|
+
// The program functions wrapping functions inside values a hooked extension returned, by where they came from.
|
|
22
|
+
const origins = new WeakMap();
|
|
23
|
+
const toHost = (value, label, depth = 0, seen = new Set()) => {
|
|
24
|
+
if (depth > MAX_VALUE_DEPTH)
|
|
25
|
+
throw typeError(`${label} exceeds the maximum value depth of ${MAX_VALUE_DEPTH}.`);
|
|
26
|
+
if (isPrimitive(value))
|
|
27
|
+
return value;
|
|
28
|
+
if (!(value instanceof Obj) || isOpaque(value)) {
|
|
29
|
+
throw typeError(`${label} contains ${describeValue(value)}, which cannot be passed to an extension.`);
|
|
30
|
+
}
|
|
31
|
+
if (seen.has(value))
|
|
32
|
+
throw typeError(`${label} contains a circular value.`);
|
|
33
|
+
seen.add(value);
|
|
34
|
+
const next = (item) => toHost(item, label, depth + 1, seen);
|
|
35
|
+
if (value instanceof ErrorObj) {
|
|
36
|
+
const name = coerceToString(get(value, "name"));
|
|
37
|
+
const message = get(value, "message");
|
|
38
|
+
const text = message === undefined ? "" : coerceToString(message);
|
|
39
|
+
const copied = name === "AggregateError" ? new AggregateError([], text) : new (hostErrors.get(name) ?? Error)(text);
|
|
40
|
+
for (const key of new Set(["cause", ...keys(value)])) {
|
|
41
|
+
if (uncrossed.has(key) || !has(value, key))
|
|
42
|
+
continue;
|
|
43
|
+
const item = crossing(() => next(get(value, key)));
|
|
44
|
+
if (item === left)
|
|
45
|
+
continue;
|
|
46
|
+
Object.defineProperty(copied, key, {
|
|
47
|
+
value: item,
|
|
48
|
+
writable: true,
|
|
49
|
+
configurable: true,
|
|
50
|
+
enumerable: key !== "cause",
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
seen.delete(value);
|
|
54
|
+
return copied;
|
|
55
|
+
}
|
|
56
|
+
const copied = value.toHost(next);
|
|
57
|
+
seen.delete(value);
|
|
58
|
+
return copied;
|
|
59
|
+
};
|
|
60
|
+
// `within` says where the value is, so a function inside it fires the hooks, or can be saved; see `Within`.
|
|
61
|
+
const fromHost = (value, label, depth = 0, seen = new Set(), within) => {
|
|
62
|
+
if (depth > MAX_VALUE_DEPTH)
|
|
63
|
+
throw typeError(`${label} exceeds the maximum value depth of ${MAX_VALUE_DEPTH}.`);
|
|
64
|
+
if (isPrimitive(value))
|
|
65
|
+
return value;
|
|
66
|
+
if (typeof value === "function")
|
|
67
|
+
return wrap(value, label, within);
|
|
68
|
+
if (value !== null && typeof value === "object") {
|
|
69
|
+
const next = (item, path, key) => fromHost(item, path, depth + 1, seen, within && {
|
|
70
|
+
...within,
|
|
71
|
+
path: key === undefined || within.path === undefined ? undefined : [...within.path, key],
|
|
72
|
+
});
|
|
73
|
+
// Nothing a host value hands back is kept: results are read as primitives or copied. Where the value's own
|
|
74
|
+
// method could hand back host storage or an object (`getTime`, `slice`, `map`), its internal data is read.
|
|
75
|
+
if (value instanceof Date)
|
|
76
|
+
return new DateObj(builtins.Date, Date.prototype.getTime.call(value));
|
|
77
|
+
if (value instanceof RegExp)
|
|
78
|
+
return new RegExpObj(builtins.RegExp, value.source, value.flags);
|
|
79
|
+
if (value instanceof Uint8Array)
|
|
80
|
+
return new Bytes(builtins.Uint8Array, new Uint8Array(value));
|
|
81
|
+
if (value instanceof ArrayBuffer) {
|
|
82
|
+
const view = new Uint8Array(value);
|
|
83
|
+
// Only a real buffer has bytes to view; anything else would be read as array-like and lose them silently.
|
|
84
|
+
if (view.buffer !== value)
|
|
85
|
+
throw typeError(`${label} produced ${describeHost(value)}, which the program cannot hold.`);
|
|
86
|
+
return new Bytes(builtins.Uint8Array, new Uint8Array(view));
|
|
87
|
+
}
|
|
88
|
+
if (value instanceof Error) {
|
|
89
|
+
if (seen.has(value))
|
|
90
|
+
throw typeError(`${label} produced a circular value.`);
|
|
91
|
+
seen.add(value);
|
|
92
|
+
const copied = createErrorValue(builtins[errorType(value)], errorMessage(value));
|
|
93
|
+
const fields = value;
|
|
94
|
+
for (const key of new Set(["cause", ...Object.keys(value)])) {
|
|
95
|
+
if (uncrossed.has(key) || !(key in value))
|
|
96
|
+
continue;
|
|
97
|
+
// Read once: a getter could pass the check and then hand back a function.
|
|
98
|
+
const field = fields[key];
|
|
99
|
+
if (typeof field === "function")
|
|
100
|
+
continue;
|
|
101
|
+
const item = crossing(() => next(field, `${label}.${key}`, key));
|
|
102
|
+
if (item === left)
|
|
103
|
+
continue;
|
|
104
|
+
define(copied, key, item, key === "cause" ? hidden : undefined);
|
|
105
|
+
}
|
|
106
|
+
seen.delete(value);
|
|
107
|
+
return copied;
|
|
108
|
+
}
|
|
109
|
+
if (value instanceof URL)
|
|
110
|
+
return new URLObj(builtins.URL, builtins.URLSearchParams, new URL(value.href));
|
|
111
|
+
if (value instanceof URLSearchParams) {
|
|
112
|
+
return new URLSearchParamsObj(builtins.URLSearchParams, new URLSearchParams(value));
|
|
113
|
+
}
|
|
114
|
+
if (value instanceof Headers)
|
|
115
|
+
return new HeadersObj(builtins.Headers, new Headers(value));
|
|
116
|
+
if (value instanceof Map) {
|
|
117
|
+
const wrapped = new MapObj(builtins.Map);
|
|
118
|
+
for (const [key, item] of value)
|
|
119
|
+
wrapped.map.set(next(key, label), next(item, label));
|
|
120
|
+
return wrapped;
|
|
121
|
+
}
|
|
122
|
+
if (value instanceof Set) {
|
|
123
|
+
const wrapped = new SetObj(builtins.Set);
|
|
124
|
+
for (const item of value)
|
|
125
|
+
wrapped.set.add(next(item, label));
|
|
126
|
+
return wrapped;
|
|
127
|
+
}
|
|
128
|
+
if (seen.has(value))
|
|
129
|
+
throw typeError(`${label} produced a circular value.`);
|
|
130
|
+
seen.add(value);
|
|
131
|
+
if (Array.isArray(value)) {
|
|
132
|
+
const length = value.length;
|
|
133
|
+
if (length > MAX_ARRAY_LENGTH) {
|
|
134
|
+
throw rangeError(`${label} produced an array of ${length} items; at most ${MAX_ARRAY_LENGTH} can cross.`);
|
|
135
|
+
}
|
|
136
|
+
// Filled in order so the copy stays a dense array; holes stay holes, as a copy made with `map` would leave them.
|
|
137
|
+
const items = [];
|
|
138
|
+
for (let index = 0; index < length; index += 1) {
|
|
139
|
+
if (index in value)
|
|
140
|
+
items[index] = next(value[index], `${label}[${index}]`, index);
|
|
141
|
+
}
|
|
142
|
+
items.length = length;
|
|
143
|
+
seen.delete(value);
|
|
144
|
+
return new Arr(builtins.Array, items);
|
|
145
|
+
}
|
|
146
|
+
const prototype = Object.getPrototypeOf(value);
|
|
147
|
+
if (prototype === Object.prototype || prototype === null) {
|
|
148
|
+
const copied = new Obj(builtins.Object);
|
|
149
|
+
for (const [key, item] of Object.entries(value))
|
|
150
|
+
define(copied, key, next(item, `${label}.${key}`, key));
|
|
151
|
+
seen.delete(value);
|
|
152
|
+
return copied;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
throw typeError(`${label} produced ${describeHost(value)}, which the program cannot hold.`);
|
|
156
|
+
};
|
|
157
|
+
// A host function as a program function. Arguments cross in; for a global or a global object's function, the
|
|
158
|
+
// `extension.before` hook runs before the host function is called, so a call it denies never reaches the host. The
|
|
159
|
+
// host's result, or what it threw, crosses out so the program catches a copy, and `extension.after` sees how the
|
|
160
|
+
// call ended. Functions inside results are part of a value's API and skip the hooks; one inside a value an extension
|
|
161
|
+
// with `snapshot` hooks returned is known by where it came from, so a suspended run can save it.
|
|
162
|
+
const wrap = (value, label, within) => {
|
|
163
|
+
// The host function's own `name` and `length` can be anything, even getters: each is read once, and only text
|
|
164
|
+
// and a count cross.
|
|
165
|
+
const name = value.name;
|
|
166
|
+
const length = value.length;
|
|
167
|
+
const extension = within?.extension.name;
|
|
168
|
+
const root = within?.root;
|
|
169
|
+
const wrapped = native(builtins, {
|
|
170
|
+
runtime: "extension",
|
|
171
|
+
name: typeof name === "string" ? name : "",
|
|
172
|
+
length: typeof length === "number" && Number.isSafeInteger(length) && length >= 0 ? length : 0,
|
|
173
|
+
call: (_, values, site) => {
|
|
174
|
+
const args = values.map((item, index) => toHost(item, `Argument ${index + 1} to ${label}`));
|
|
175
|
+
const invocation = within !== undefined && root === undefined ? { extension: extension, name: label, args } : undefined;
|
|
176
|
+
// A denied call fails the way the global would: an async global rejects its promise, a sync one throws.
|
|
177
|
+
if (isAsync(value)) {
|
|
178
|
+
return pending(ctx, { stage: "run", label, extension, invocation, host: value, args, threw: false }, site);
|
|
179
|
+
}
|
|
180
|
+
return new Push("extension call", [value, args, label, invocation, extension]);
|
|
181
|
+
},
|
|
182
|
+
});
|
|
183
|
+
if (root !== undefined && within.path !== undefined) {
|
|
184
|
+
origins.set(wrapped, { extension: extension, root, path: within.path, label });
|
|
185
|
+
}
|
|
186
|
+
return wrapped;
|
|
187
|
+
};
|
|
188
|
+
ctx.hosts = {
|
|
189
|
+
extensions: extensions.map((extension) => ({ name: extension.name, hooked: extension.snapshot !== undefined })),
|
|
190
|
+
origin: (value) => origins.get(value),
|
|
191
|
+
encode: (name, root) => hostStep(name, "save", () => hooks(name).encode(root)),
|
|
192
|
+
decode: (name, data) => {
|
|
193
|
+
const root = hostStep(name, "restore", () => hooks(name).decode(data));
|
|
194
|
+
if ((typeof root !== "object" && typeof root !== "function") || root === null) {
|
|
195
|
+
throw new SnapshotError(`The extension "${name}" restored a value it returned as ${typeof root}, not an object.`);
|
|
196
|
+
}
|
|
197
|
+
return root;
|
|
198
|
+
},
|
|
199
|
+
rewrap: (target, origin) => {
|
|
200
|
+
const host = origin.path.reduce((at, key) => (typeof at === "object" && at !== null) || typeof at === "function"
|
|
201
|
+
? at[key]
|
|
202
|
+
: undefined, origin.root);
|
|
203
|
+
if (typeof host !== "function") {
|
|
204
|
+
throw new SnapshotError(`The extension "${origin.extension}" restored a value with no function at ${origin.label}, so this state can't resume.`);
|
|
205
|
+
}
|
|
206
|
+
const made = wrap(host, origin.label, {
|
|
207
|
+
extension: byName.get(origin.extension),
|
|
208
|
+
root: origin.root,
|
|
209
|
+
path: origin.path,
|
|
210
|
+
});
|
|
211
|
+
// The restored function keeps its own properties; only what calling it does comes from the new one.
|
|
212
|
+
Object.assign(target, { tag: made.tag, call: made.call, construct: made.construct, callback: made.callback });
|
|
213
|
+
origins.set(target, origin);
|
|
214
|
+
},
|
|
215
|
+
};
|
|
216
|
+
const hooks = (name) => {
|
|
217
|
+
const snapshot = byName.get(name)?.snapshot;
|
|
218
|
+
if (snapshot === undefined)
|
|
219
|
+
throw new SnapshotError(`The extension "${name}" has no snapshot hooks.`);
|
|
220
|
+
return snapshot;
|
|
221
|
+
};
|
|
222
|
+
// The Effect each step of an extension call runs as, with the program's services in its requirements.
|
|
223
|
+
ctx.extensionWork = (request) => {
|
|
224
|
+
const label = request.label;
|
|
225
|
+
const call = request.invocation;
|
|
226
|
+
const cross = (reason) => new Throw(fromHost(reason, label));
|
|
227
|
+
const hooks = ctx.tools.hooks;
|
|
228
|
+
const before = call && hooks["extension.before"]?.(call).pipe(Effect.mapError(cross));
|
|
229
|
+
if (request.stage === "before")
|
|
230
|
+
return before ?? Effect.void;
|
|
231
|
+
const after = call && hooks["extension.after"];
|
|
232
|
+
const extension = request.extension === undefined ? undefined : byName.get(request.extension);
|
|
233
|
+
// What a function returns is a value of its extension's, which its `snapshot` hooks save, when it has them.
|
|
234
|
+
const settle = (effect) => (after ? hooked(call, undefined, after, effect) : effect).pipe(Effect.mapBoth({
|
|
235
|
+
onFailure: cross,
|
|
236
|
+
onSuccess: (result) => fromHost(result, label, 0, new Set(), extension?.snapshot !== undefined &&
|
|
237
|
+
((typeof result === "object" && result !== null) || typeof result === "function")
|
|
238
|
+
? { extension, root: result, path: [] }
|
|
239
|
+
: undefined),
|
|
240
|
+
}));
|
|
241
|
+
if (request.stage === "settle")
|
|
242
|
+
return settle(outcome(request.host, request.threw));
|
|
243
|
+
return Effect.andThen(before ?? Effect.void, settle(Effect.suspend(() => outcome(...callHost(request.host, request.args)))));
|
|
244
|
+
};
|
|
245
|
+
return extensions.flatMap((extension) => Object.entries(extension.globals).map(([name, value]) => [name, fromHost(value, name, 0, new Set(), { extension, root: undefined, path: undefined })]));
|
|
246
|
+
};
|
|
247
|
+
// An asynchronous host call: the program holds a promise that settles when the host's work does.
|
|
248
|
+
const pending = (ctx, call, site) => {
|
|
249
|
+
const resolving = ctx.vm.scheduler.resolving(ctx.vm.scheduler.newPromise(), site);
|
|
250
|
+
ctx.vm.hosts.host({ kind: "extension", call }, { label: call.label, result: "value", resolving, site });
|
|
251
|
+
return resolving.promise;
|
|
252
|
+
};
|
|
253
|
+
/**
|
|
254
|
+
* Calls a synchronous extension function's host function, once its `extension.before` hook allowed it: a promise for
|
|
255
|
+
* a result that settles later (an Effect or a Promise), or the request that settles what it returned or threw now.
|
|
256
|
+
*/
|
|
257
|
+
export const startExtensionCall = (ctx, host, args, call, site) => {
|
|
258
|
+
const [result, threw] = callHost(host, args);
|
|
259
|
+
const request = { stage: "settle", ...call, host: result, args, threw };
|
|
260
|
+
if (!threw && (Effect.isEffect(result) || result instanceof Promise))
|
|
261
|
+
return pending(ctx, request, site);
|
|
262
|
+
return request;
|
|
263
|
+
};
|
|
264
|
+
// Runs an extension's `snapshot` hook; what goes wrong is the state's problem, said as such.
|
|
265
|
+
const hostStep = (extension, what, step) => {
|
|
266
|
+
try {
|
|
267
|
+
return step();
|
|
268
|
+
}
|
|
269
|
+
catch (error) {
|
|
270
|
+
if (error instanceof SnapshotError)
|
|
271
|
+
throw error;
|
|
272
|
+
throw new SnapshotError(`The extension "${extension}" couldn't ${what} a value it returned: ${error instanceof Error ? error.message : String(error)}`);
|
|
273
|
+
}
|
|
274
|
+
};
|
|
275
|
+
/** Calls a host function: what it returned, or what it threw. */
|
|
276
|
+
const callHost = (value, args) => {
|
|
277
|
+
try {
|
|
278
|
+
return [value.apply(undefined, args), false];
|
|
279
|
+
}
|
|
280
|
+
catch (reason) {
|
|
281
|
+
return [reason, true];
|
|
282
|
+
}
|
|
283
|
+
};
|
|
284
|
+
/**
|
|
285
|
+
* What a host function's call settles as: a returned Effect or Promise settles later; a returned value or a throw
|
|
286
|
+
* settles now.
|
|
287
|
+
*/
|
|
288
|
+
const outcome = (result, threw) => {
|
|
289
|
+
if (threw)
|
|
290
|
+
return Effect.fail(result);
|
|
291
|
+
// Extension.Services adds an Effect global's requirements to R.
|
|
292
|
+
if (Effect.isEffect(result))
|
|
293
|
+
return result;
|
|
294
|
+
if (result instanceof Promise)
|
|
295
|
+
return Effect.tryPromise({ try: () => result, catch: (reason) => reason });
|
|
296
|
+
return Effect.succeed(result);
|
|
297
|
+
};
|
|
298
|
+
/**
|
|
299
|
+
* An error crosses as its name, message, `cause`, and own enumerable fields, such as Node's `code`, `errno`,
|
|
300
|
+
* `syscall`, and `path`. `stack` stays on its own side, `message` crosses once as text, and no field may shadow an
|
|
301
|
+
* Error method. A field that cannot cross (a socket, a handle, a function) is left behind so the error itself always
|
|
302
|
+
* arrives.
|
|
303
|
+
*/
|
|
304
|
+
const uncrossed = new Set(["stack", "message", "constructor", "toString", "__proto__"]);
|
|
305
|
+
const left = Symbol("left behind");
|
|
306
|
+
const crossing = (convert) => {
|
|
307
|
+
try {
|
|
308
|
+
return convert();
|
|
309
|
+
}
|
|
310
|
+
catch (reason) {
|
|
311
|
+
if (reason instanceof PendingThrow)
|
|
312
|
+
return left;
|
|
313
|
+
throw reason;
|
|
314
|
+
}
|
|
315
|
+
};
|
|
316
|
+
const hostErrors = new Map([
|
|
317
|
+
["TypeError", TypeError],
|
|
318
|
+
["RangeError", RangeError],
|
|
319
|
+
["SyntaxError", SyntaxError],
|
|
320
|
+
["ReferenceError", ReferenceError],
|
|
321
|
+
["EvalError", EvalError],
|
|
322
|
+
["URIError", URIError],
|
|
323
|
+
]);
|
|
324
|
+
// The primitives the interpreter operates on; symbols and BigInts are not among them.
|
|
325
|
+
const isPrimitive = (value) => value === null ||
|
|
326
|
+
value === undefined ||
|
|
327
|
+
typeof value === "string" ||
|
|
328
|
+
typeof value === "number" ||
|
|
329
|
+
typeof value === "boolean";
|
|
330
|
+
const describeHost = (value) => {
|
|
331
|
+
if (typeof value !== "object" || value === null)
|
|
332
|
+
return `a ${typeof value}`;
|
|
333
|
+
const name = value.constructor?.name;
|
|
334
|
+
if (name === undefined || name === "")
|
|
335
|
+
return "an object";
|
|
336
|
+
return `${/^[AEIO]/.test(name) ? "an" : "a"} ${name}`;
|
|
337
|
+
};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { Interpreter } from "./interpreter.js";
|
|
2
|
+
/**
|
|
3
|
+
* `next`/`return`/`throw` on the generator prototypes (async generators answer with promises), on iterator helpers,
|
|
4
|
+
* and on the async-from-sync iterator. A generator's suspended body runs on the caller's job stack.
|
|
5
|
+
*/
|
|
6
|
+
export declare const generatorGlobals: <R>(ctx: Interpreter<R>) => void;
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { fn, methods, receiver } from "./native.js";
|
|
2
|
+
import { AsyncIteratorSymbol, IteratorSymbol, typeError } from "./model.js";
|
|
3
|
+
import { define, hidden, GeneratorObj } from "./objects.js";
|
|
4
|
+
import { Push } from "./signals.js";
|
|
5
|
+
import { AsyncFromSyncIterator, generatorRequest, generatorStep } from "../generators.js";
|
|
6
|
+
/**
|
|
7
|
+
* `next`/`return`/`throw` on the generator prototypes (async generators answer with promises), on iterator helpers,
|
|
8
|
+
* and on the async-from-sync iterator. A generator's suspended body runs on the caller's job stack.
|
|
9
|
+
*/
|
|
10
|
+
export const generatorGlobals = (ctx) => {
|
|
11
|
+
const builtins = ctx.builtins;
|
|
12
|
+
const sync = (kind, owner = "Generator.prototype") => [
|
|
13
|
+
kind,
|
|
14
|
+
1,
|
|
15
|
+
(thisValue, args) => {
|
|
16
|
+
const method = `${owner}.${kind}`;
|
|
17
|
+
const generator = receiver(GeneratorObj, thisValue, method);
|
|
18
|
+
if (generator.asynchronous)
|
|
19
|
+
throw typeError(`${method} called on incompatible receiver an async generator.`);
|
|
20
|
+
return generatorStep(ctx.vm, generator, kind, args[0]);
|
|
21
|
+
},
|
|
22
|
+
];
|
|
23
|
+
const async = (kind) => [
|
|
24
|
+
kind,
|
|
25
|
+
1,
|
|
26
|
+
(thisValue, args) => generatorRequest(ctx.vm, thisValue, kind, args[0]),
|
|
27
|
+
];
|
|
28
|
+
const adapter = (kind) => [
|
|
29
|
+
kind,
|
|
30
|
+
1,
|
|
31
|
+
(thisValue, args) => new Push("AsyncFromSyncIterator", [
|
|
32
|
+
receiver(AsyncFromSyncIterator, thisValue, `AsyncFromSyncIterator.${kind}`),
|
|
33
|
+
kind,
|
|
34
|
+
args,
|
|
35
|
+
]),
|
|
36
|
+
];
|
|
37
|
+
methods(builtins, builtins.Generator, [sync("next"), sync("return"), sync("throw")]);
|
|
38
|
+
// Iterator helpers are the prelude's generators (see prelude.ts).
|
|
39
|
+
methods(builtins, builtins.IteratorHelper, [sync("next", "%IteratorHelper%"), sync("return", "%IteratorHelper%")]);
|
|
40
|
+
methods(builtins, builtins.AsyncGenerator, [async("next"), async("return"), async("throw")]);
|
|
41
|
+
methods(builtins, builtins.AsyncFromSyncIterator, [adapter("next"), adapter("return"), adapter("throw")]);
|
|
42
|
+
define(builtins.Iterator, IteratorSymbol, fn(builtins, "[Symbol.iterator]", 0, (thisValue) => thisValue), hidden);
|
|
43
|
+
define(builtins.AsyncIterator, AsyncIteratorSymbol, fn(builtins, "[Symbol.asyncIterator]", 0, (thisValue) => thisValue), hidden);
|
|
44
|
+
};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { type Value } from "./objects.js";
|
|
2
|
+
import type { Interpreter } from "./interpreter.js";
|
|
3
|
+
/** Names bound in every program before extensions apply. */
|
|
4
|
+
export declare const globalNames: ReadonlySet<string>;
|
|
5
|
+
/** The immutable global bindings of every program, in declaration order. */
|
|
6
|
+
export declare const globals: <R>(ctx: Interpreter<R>) => ReadonlyArray<readonly [string, Value]>;
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import { Arr, BoundFn, Callable, coerceToInteger, get, Obj } from "./objects.js";
|
|
2
|
+
import { arrayGlobal } from "../stdlib/array.js";
|
|
3
|
+
import { textDecoderGlobal, textEncoderGlobal, uint8ArrayGlobal } from "../stdlib/bytes.js";
|
|
4
|
+
import { mapGlobal, setGlobal, weakMapGlobal, weakSetGlobal } from "../stdlib/collections.js";
|
|
5
|
+
import { consoleGlobal } from "../stdlib/console.js";
|
|
6
|
+
import { dateGlobal } from "../stdlib/date.js";
|
|
7
|
+
import { jsonGlobal } from "../stdlib/json.js";
|
|
8
|
+
import { mathGlobal } from "../stdlib/math.js";
|
|
9
|
+
import { booleanGlobal, numberGlobal } from "../stdlib/number.js";
|
|
10
|
+
import { objectGlobal } from "../stdlib/object.js";
|
|
11
|
+
import { regexpGlobal } from "../stdlib/regexp.js";
|
|
12
|
+
import { stringGlobal } from "../stdlib/string.js";
|
|
13
|
+
import { uriGlobal, urlGlobal, urlSearchParamsGlobal } from "../stdlib/url.js";
|
|
14
|
+
import { headersGlobal } from "../stdlib/headers.js";
|
|
15
|
+
import { iteratorGlobals } from "../stdlib/iterator.js";
|
|
16
|
+
import { coercion } from "../stdlib/value.js";
|
|
17
|
+
import { base64Global, cryptoGlobal, structuredCloneGlobal } from "../stdlib/web.js";
|
|
18
|
+
import { ToolReference } from "../../tool-runtime.js";
|
|
19
|
+
import { errorGlobal } from "./errors.js";
|
|
20
|
+
import { errorTypes } from "./intrinsics.js";
|
|
21
|
+
import { constants, constructor, methods, native, receiver } from "./native.js";
|
|
22
|
+
import { AsyncIteratorSymbol, IteratorSymbol, typeError } from "./model.js";
|
|
23
|
+
import { checkArrayLength } from "./limits.js";
|
|
24
|
+
import { generatorGlobals } from "./generators.js";
|
|
25
|
+
import { promiseGlobal } from "./promises.js";
|
|
26
|
+
import { Invoke } from "./signals.js";
|
|
27
|
+
// Function.prototype.constructor exists so `fn.constructor === Function` holds; dynamic code is unsupported.
|
|
28
|
+
const functionGlobal = (ctx) => {
|
|
29
|
+
const reject = () => {
|
|
30
|
+
throw typeError("The Function constructor is not supported; write the function inline.");
|
|
31
|
+
};
|
|
32
|
+
const target = (thisValue, method) => receiver(Callable, thisValue, `Function.prototype.${method}`);
|
|
33
|
+
methods(ctx.builtins, ctx.builtins.Function, [
|
|
34
|
+
["call", 1, (thisValue, args, site) => new Invoke(target(thisValue, "call"), args[0], args.slice(1), site)],
|
|
35
|
+
[
|
|
36
|
+
"apply",
|
|
37
|
+
2,
|
|
38
|
+
(thisValue, args, site) => new Invoke(target(thisValue, "apply"), args[0], listFromArrayLike(args[1]), site),
|
|
39
|
+
],
|
|
40
|
+
[
|
|
41
|
+
"bind",
|
|
42
|
+
1,
|
|
43
|
+
(thisValue, args) => new BoundFn(ctx.builtins.Function, target(thisValue, "bind"), args[0], args.slice(1)),
|
|
44
|
+
],
|
|
45
|
+
]);
|
|
46
|
+
return constructor(ctx.builtins, ctx.builtins.Function, {
|
|
47
|
+
name: "Function",
|
|
48
|
+
length: 1,
|
|
49
|
+
call: reject,
|
|
50
|
+
construct: reject,
|
|
51
|
+
});
|
|
52
|
+
};
|
|
53
|
+
// CreateListFromArrayLike: `apply` reads `length` and the indexed properties of any object.
|
|
54
|
+
const listFromArrayLike = (value) => {
|
|
55
|
+
if (value === undefined || value === null)
|
|
56
|
+
return [];
|
|
57
|
+
if (value instanceof Arr)
|
|
58
|
+
return [...value.items];
|
|
59
|
+
if (!(value instanceof Obj))
|
|
60
|
+
throw typeError("Function.prototype.apply expects an array-like argument list.");
|
|
61
|
+
const length = Math.max(0, coerceToInteger(get(value, "length")));
|
|
62
|
+
checkArrayLength(length);
|
|
63
|
+
return Array.from({ length }, (_, index) => get(value, String(index)));
|
|
64
|
+
};
|
|
65
|
+
const symbolGlobal = (ctx) => {
|
|
66
|
+
const symbol = native(ctx.builtins, {
|
|
67
|
+
name: "Symbol",
|
|
68
|
+
call: () => {
|
|
69
|
+
throw typeError("Symbol is not callable; only Symbol.asyncIterator and Symbol.iterator are available.");
|
|
70
|
+
},
|
|
71
|
+
callback: false,
|
|
72
|
+
});
|
|
73
|
+
constants(symbol, { asyncIterator: AsyncIteratorSymbol, iterator: IteratorSymbol });
|
|
74
|
+
return symbol;
|
|
75
|
+
};
|
|
76
|
+
// A table rather than a list so the names are known before any runtime exists.
|
|
77
|
+
const table = {
|
|
78
|
+
tools: () => new ToolReference([]),
|
|
79
|
+
search: (ctx) => native(ctx.builtins, { name: "search", call: (_, args) => ctx.search(args), callback: false }),
|
|
80
|
+
require: (ctx) => native(ctx.builtins, {
|
|
81
|
+
name: "require",
|
|
82
|
+
length: 1,
|
|
83
|
+
call: (_, args, site) => {
|
|
84
|
+
const specifier = args[0];
|
|
85
|
+
if (typeof specifier !== "string")
|
|
86
|
+
throw typeError("require expects a module name string.");
|
|
87
|
+
return ctx.module(specifier, site);
|
|
88
|
+
},
|
|
89
|
+
}),
|
|
90
|
+
undefined: () => undefined,
|
|
91
|
+
NaN: () => NaN,
|
|
92
|
+
Infinity: () => Infinity,
|
|
93
|
+
Object: (ctx) => objectGlobal(ctx),
|
|
94
|
+
Function: (ctx) => functionGlobal(ctx),
|
|
95
|
+
Array: (ctx) => arrayGlobal(ctx),
|
|
96
|
+
Math: (ctx) => mathGlobal(ctx),
|
|
97
|
+
JSON: (ctx) => jsonGlobal(ctx),
|
|
98
|
+
console: (ctx) => consoleGlobal(ctx),
|
|
99
|
+
Promise: (ctx) => promiseGlobal(ctx),
|
|
100
|
+
Symbol: (ctx) => symbolGlobal(ctx),
|
|
101
|
+
Iterator: (ctx) => iteratorGlobals(ctx),
|
|
102
|
+
Number: (ctx) => numberGlobal(ctx),
|
|
103
|
+
String: (ctx) => stringGlobal(ctx),
|
|
104
|
+
Boolean: (ctx) => booleanGlobal(ctx),
|
|
105
|
+
parseInt: (ctx) => coercion(ctx, "parseInt", 2),
|
|
106
|
+
parseFloat: (ctx) => coercion(ctx, "parseFloat"),
|
|
107
|
+
isFinite: (ctx) => coercion(ctx, "isFinite"),
|
|
108
|
+
isNaN: (ctx) => coercion(ctx, "isNaN"),
|
|
109
|
+
Date: (ctx) => dateGlobal(ctx),
|
|
110
|
+
RegExp: (ctx) => regexpGlobal(ctx),
|
|
111
|
+
Map: (ctx) => mapGlobal(ctx),
|
|
112
|
+
Set: (ctx) => setGlobal(ctx),
|
|
113
|
+
WeakMap: (ctx) => weakMapGlobal(ctx),
|
|
114
|
+
WeakSet: (ctx) => weakSetGlobal(ctx),
|
|
115
|
+
URL: (ctx) => urlGlobal(ctx),
|
|
116
|
+
URLSearchParams: (ctx) => urlSearchParamsGlobal(ctx),
|
|
117
|
+
Headers: (ctx) => headersGlobal(ctx),
|
|
118
|
+
Uint8Array: (ctx) => uint8ArrayGlobal(ctx),
|
|
119
|
+
TextEncoder: (ctx) => textEncoderGlobal(ctx),
|
|
120
|
+
TextDecoder: (ctx) => textDecoderGlobal(ctx),
|
|
121
|
+
encodeURI: (ctx) => uriGlobal(ctx, "encodeURI"),
|
|
122
|
+
encodeURIComponent: (ctx) => uriGlobal(ctx, "encodeURIComponent"),
|
|
123
|
+
decodeURI: (ctx) => uriGlobal(ctx, "decodeURI"),
|
|
124
|
+
decodeURIComponent: (ctx) => uriGlobal(ctx, "decodeURIComponent"),
|
|
125
|
+
atob: (ctx) => base64Global(ctx, "atob"),
|
|
126
|
+
btoa: (ctx) => base64Global(ctx, "btoa"),
|
|
127
|
+
crypto: (ctx) => cryptoGlobal(ctx),
|
|
128
|
+
structuredClone: (ctx) => structuredCloneGlobal(ctx),
|
|
129
|
+
...Object.fromEntries(errorTypes.map((type) => [type, (ctx) => errorGlobal(type, ctx)])),
|
|
130
|
+
};
|
|
131
|
+
/** Names bound in every program before extensions apply. */
|
|
132
|
+
export const globalNames = new Set(Object.keys(table));
|
|
133
|
+
/** The immutable global bindings of every program, in declaration order. */
|
|
134
|
+
export const globals = (ctx) => {
|
|
135
|
+
generatorGlobals(ctx);
|
|
136
|
+
return Object.entries(table).map(([name, factory]) => [name, factory(ctx)]);
|
|
137
|
+
};
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import type { ToolRuntime } from "../../tool-runtime.js";
|
|
2
|
+
import type { ExtensionRequest } from "../scheduler.js";
|
|
3
|
+
import type { HostBridge } from "../snapshot/codec.js";
|
|
4
|
+
import { Vm } from "../vm.js";
|
|
5
|
+
import type { Builtins } from "./intrinsics.js";
|
|
6
|
+
import { IntrinsicNames } from "./intrinsic-names.js";
|
|
7
|
+
import { type AstNode, type Binding } from "./model.js";
|
|
8
|
+
import { Obj, type Value } from "./objects.js";
|
|
9
|
+
import { Prelude } from "../prelude/prelude.js";
|
|
10
|
+
import { Push } from "./signals.js";
|
|
11
|
+
import type { NodeId, Source } from "./source.js";
|
|
12
|
+
/** One program execution: the tool bridge, the VM that runs it, captured logs, and the global scope built once. */
|
|
13
|
+
export declare class Interpreter<R> {
|
|
14
|
+
readonly tools: ToolRuntime<R>;
|
|
15
|
+
readonly builtins: Builtins;
|
|
16
|
+
readonly logs: Array<string>;
|
|
17
|
+
/** Runs program code, and keeps the job queue, promises, and host calls the program waits on. */
|
|
18
|
+
readonly vm: Vm;
|
|
19
|
+
/** Names for this runtime's intrinsics, taken before any program code can change a built-in. */
|
|
20
|
+
readonly intrinsics: IntrinsicNames;
|
|
21
|
+
/** The built-ins written in Code Mode, and the scope they close over. */
|
|
22
|
+
readonly prelude: Prelude;
|
|
23
|
+
/** Makes the Effect an extension function's host work runs as; set by the extension bridge. */
|
|
24
|
+
extensionWork: ((request: ExtensionRequest) => unknown) | undefined;
|
|
25
|
+
/** Saves and restores values returned by extensions with `snapshot` hooks; set by the extension bridge. */
|
|
26
|
+
hosts: HostBridge | undefined;
|
|
27
|
+
/** The parsed sources this execution runs, by id, so a `NodeId` resolves to its node. */
|
|
28
|
+
readonly sources: Map<string, Source>;
|
|
29
|
+
/** The global bindings: the intrinsics, the host's globals, and the program's bindings. */
|
|
30
|
+
readonly globalScope: Map<string, Binding>;
|
|
31
|
+
private readonly modules;
|
|
32
|
+
private readonly namespaces;
|
|
33
|
+
constructor(options: {
|
|
34
|
+
readonly tools: ToolRuntime<R>;
|
|
35
|
+
readonly builtins: Builtins;
|
|
36
|
+
readonly logs?: Array<string>;
|
|
37
|
+
/** The host's globals (extensions, a test harness): made again, the same way, when a saved run is restored. */
|
|
38
|
+
readonly globals?: (ctx: Interpreter<R>) => ReadonlyArray<readonly [string, Value]>;
|
|
39
|
+
/** Data bound for this program, part of its saved state; host globals of the same name win. */
|
|
40
|
+
readonly bindings?: (ctx: Interpreter<R>) => ReadonlyArray<readonly [string, Value]>;
|
|
41
|
+
});
|
|
42
|
+
/** A module, as `require` returns it and a default import binds it: a global, by its Node module name. */
|
|
43
|
+
module(specifier: string, site?: AstNode): Value;
|
|
44
|
+
/**
|
|
45
|
+
* What `import * as` and `import()` see: the module's own properties, and the module itself as `default`, the way
|
|
46
|
+
* Node presents a CommonJS module.
|
|
47
|
+
*/
|
|
48
|
+
namespace(specifier: string, site?: AstNode): Obj;
|
|
49
|
+
/** The node a `NodeId` names, in one of this execution's sources. */
|
|
50
|
+
node(id: NodeId): AstNode | undefined;
|
|
51
|
+
/** The built-in search: its result is usable directly, and can also be awaited or chained like a Promise. */
|
|
52
|
+
search(args: Array<Value>): Push;
|
|
53
|
+
}
|