@opencode/codemode 2.2.5 → 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.
- package/README.md +70 -1
- package/dist/codemode.d.ts +55 -4
- package/dist/codemode.js +63 -8
- package/dist/extension.d.ts +14 -9
- package/dist/extension.js +2 -2
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -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 +86 -2
- package/dist/interpreter/modules.d.ts +4 -0
- package/dist/interpreter/modules.js +33 -0
- package/dist/suspend-error.d.ts +23 -0
- package/dist/suspend-error.js +25 -0
- package/dist/tool-runtime.d.ts +4 -1
- 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 +103 -0
- package/dist/vm/host.js +226 -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 +58 -0
- package/dist/vm/runtime/driver.js +184 -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 +414 -0
- package/dist/vm/runtime/extensions.d.ts +16 -0
- package/dist/vm/runtime/extensions.js +270 -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 +50 -0
- package/dist/vm/runtime/interpreter.js +94 -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 +178 -0
- package/dist/vm/scheduler.js +63 -0
- package/dist/vm/snapshot/codec.d.ts +87 -0
- package/dist/vm/snapshot/codec.js +751 -0
- package/dist/vm/snapshot/snapshot.d.ts +49 -0
- package/dist/vm/snapshot/snapshot.js +70 -0
- package/dist/vm/snapshot.d.ts +32 -0
- package/dist/vm/snapshot.js +306 -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 +225 -0
- package/dist/vm/vm.js +2931 -0
- package/package.json +6 -3
|
@@ -0,0 +1,270 @@
|
|
|
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
|
+
/**
|
|
13
|
+
* The global bindings of one run's extensions. Everything crossing the boundary is converted: plain data and built-in
|
|
14
|
+
* wrappers are copied, a host function becomes a program function whose calls cross the same way, and a host Promise
|
|
15
|
+
* or Effect becomes a program promise.
|
|
16
|
+
*/
|
|
17
|
+
export const extensionGlobals = (ctx, extensions) => {
|
|
18
|
+
const builtins = ctx.builtins;
|
|
19
|
+
const toHost = (value, label, depth = 0, seen = new Set()) => {
|
|
20
|
+
if (depth > MAX_VALUE_DEPTH)
|
|
21
|
+
throw typeError(`${label} exceeds the maximum value depth of ${MAX_VALUE_DEPTH}.`);
|
|
22
|
+
if (isPrimitive(value))
|
|
23
|
+
return value;
|
|
24
|
+
if (!(value instanceof Obj) || isOpaque(value)) {
|
|
25
|
+
throw typeError(`${label} contains ${describeValue(value)}, which cannot be passed to an extension.`);
|
|
26
|
+
}
|
|
27
|
+
if (seen.has(value))
|
|
28
|
+
throw typeError(`${label} contains a circular value.`);
|
|
29
|
+
seen.add(value);
|
|
30
|
+
const next = (item) => toHost(item, label, depth + 1, seen);
|
|
31
|
+
if (value instanceof ErrorObj) {
|
|
32
|
+
const name = coerceToString(get(value, "name"));
|
|
33
|
+
const message = get(value, "message");
|
|
34
|
+
const text = message === undefined ? "" : coerceToString(message);
|
|
35
|
+
const copied = name === "AggregateError" ? new AggregateError([], text) : new (hostErrors.get(name) ?? Error)(text);
|
|
36
|
+
for (const key of new Set(["cause", ...keys(value)])) {
|
|
37
|
+
if (uncrossed.has(key) || !has(value, key))
|
|
38
|
+
continue;
|
|
39
|
+
const item = crossing(() => next(get(value, key)));
|
|
40
|
+
if (item === left)
|
|
41
|
+
continue;
|
|
42
|
+
Object.defineProperty(copied, key, {
|
|
43
|
+
value: item,
|
|
44
|
+
writable: true,
|
|
45
|
+
configurable: true,
|
|
46
|
+
enumerable: key !== "cause",
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
seen.delete(value);
|
|
50
|
+
return copied;
|
|
51
|
+
}
|
|
52
|
+
const copied = value.toHost(next);
|
|
53
|
+
seen.delete(value);
|
|
54
|
+
return copied;
|
|
55
|
+
};
|
|
56
|
+
// `extension` is set under an extension's global object, whose functions are entry points that fire the hooks.
|
|
57
|
+
const fromHost = (value, label, depth = 0, seen = new Set(), extension) => {
|
|
58
|
+
if (depth > MAX_VALUE_DEPTH)
|
|
59
|
+
throw typeError(`${label} exceeds the maximum value depth of ${MAX_VALUE_DEPTH}.`);
|
|
60
|
+
if (isPrimitive(value))
|
|
61
|
+
return value;
|
|
62
|
+
if (typeof value === "function")
|
|
63
|
+
return wrap(value, label, extension);
|
|
64
|
+
if (value !== null && typeof value === "object") {
|
|
65
|
+
const next = (item, path) => fromHost(item, path, depth + 1, seen, extension);
|
|
66
|
+
// Nothing a host value hands back is kept: results are read as primitives or copied. Where the value's own
|
|
67
|
+
// method could hand back host storage or an object (`getTime`, `slice`, `map`), its internal data is read.
|
|
68
|
+
if (value instanceof Date)
|
|
69
|
+
return new DateObj(builtins.Date, Date.prototype.getTime.call(value));
|
|
70
|
+
if (value instanceof RegExp)
|
|
71
|
+
return new RegExpObj(builtins.RegExp, value.source, value.flags);
|
|
72
|
+
if (value instanceof Uint8Array)
|
|
73
|
+
return new Bytes(builtins.Uint8Array, new Uint8Array(value));
|
|
74
|
+
if (value instanceof ArrayBuffer) {
|
|
75
|
+
const view = new Uint8Array(value);
|
|
76
|
+
// Only a real buffer has bytes to view; anything else would be read as array-like and lose them silently.
|
|
77
|
+
if (view.buffer !== value)
|
|
78
|
+
throw typeError(`${label} produced ${describeHost(value)}, which the program cannot hold.`);
|
|
79
|
+
return new Bytes(builtins.Uint8Array, new Uint8Array(view));
|
|
80
|
+
}
|
|
81
|
+
if (value instanceof Error) {
|
|
82
|
+
if (seen.has(value))
|
|
83
|
+
throw typeError(`${label} produced a circular value.`);
|
|
84
|
+
seen.add(value);
|
|
85
|
+
const copied = createErrorValue(builtins[errorType(value)], errorMessage(value));
|
|
86
|
+
const fields = value;
|
|
87
|
+
for (const key of new Set(["cause", ...Object.keys(value)])) {
|
|
88
|
+
if (uncrossed.has(key) || !(key in value))
|
|
89
|
+
continue;
|
|
90
|
+
// Read once: a getter could pass the check and then hand back a function.
|
|
91
|
+
const field = fields[key];
|
|
92
|
+
if (typeof field === "function")
|
|
93
|
+
continue;
|
|
94
|
+
const item = crossing(() => next(field, `${label}.${key}`));
|
|
95
|
+
if (item === left)
|
|
96
|
+
continue;
|
|
97
|
+
define(copied, key, item, key === "cause" ? hidden : undefined);
|
|
98
|
+
}
|
|
99
|
+
seen.delete(value);
|
|
100
|
+
return copied;
|
|
101
|
+
}
|
|
102
|
+
if (value instanceof URL)
|
|
103
|
+
return new URLObj(builtins.URL, builtins.URLSearchParams, new URL(value.href));
|
|
104
|
+
if (value instanceof URLSearchParams) {
|
|
105
|
+
return new URLSearchParamsObj(builtins.URLSearchParams, new URLSearchParams(value));
|
|
106
|
+
}
|
|
107
|
+
if (value instanceof Headers)
|
|
108
|
+
return new HeadersObj(builtins.Headers, new Headers(value));
|
|
109
|
+
if (value instanceof Map) {
|
|
110
|
+
const wrapped = new MapObj(builtins.Map);
|
|
111
|
+
for (const [key, item] of value)
|
|
112
|
+
wrapped.map.set(next(key, label), next(item, label));
|
|
113
|
+
return wrapped;
|
|
114
|
+
}
|
|
115
|
+
if (value instanceof Set) {
|
|
116
|
+
const wrapped = new SetObj(builtins.Set);
|
|
117
|
+
for (const item of value)
|
|
118
|
+
wrapped.set.add(next(item, label));
|
|
119
|
+
return wrapped;
|
|
120
|
+
}
|
|
121
|
+
if (seen.has(value))
|
|
122
|
+
throw typeError(`${label} produced a circular value.`);
|
|
123
|
+
seen.add(value);
|
|
124
|
+
if (Array.isArray(value)) {
|
|
125
|
+
const length = value.length;
|
|
126
|
+
if (length > MAX_ARRAY_LENGTH) {
|
|
127
|
+
throw rangeError(`${label} produced an array of ${length} items; at most ${MAX_ARRAY_LENGTH} can cross.`);
|
|
128
|
+
}
|
|
129
|
+
// Filled in order so the copy stays a dense array; holes stay holes, as a copy made with `map` would leave them.
|
|
130
|
+
const items = [];
|
|
131
|
+
for (let index = 0; index < length; index += 1) {
|
|
132
|
+
if (index in value)
|
|
133
|
+
items[index] = next(value[index], `${label}[${index}]`);
|
|
134
|
+
}
|
|
135
|
+
items.length = length;
|
|
136
|
+
seen.delete(value);
|
|
137
|
+
return new Arr(builtins.Array, items);
|
|
138
|
+
}
|
|
139
|
+
const prototype = Object.getPrototypeOf(value);
|
|
140
|
+
if (prototype === Object.prototype || prototype === null) {
|
|
141
|
+
const copied = new Obj(builtins.Object);
|
|
142
|
+
for (const [key, item] of Object.entries(value))
|
|
143
|
+
define(copied, key, next(item, `${label}.${key}`));
|
|
144
|
+
seen.delete(value);
|
|
145
|
+
return copied;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
throw typeError(`${label} produced ${describeHost(value)}, which the program cannot hold.`);
|
|
149
|
+
};
|
|
150
|
+
// A host function as a program function. Arguments cross in; for a global or a global object's function, the
|
|
151
|
+
// `extension.before` hook runs before the host function is called, so a call it denies never reaches the host. The
|
|
152
|
+
// host's result, or what it threw, crosses out so the program catches a copy, and `extension.after` sees how the
|
|
153
|
+
// call ended. Functions inside results are part of a value's API and skip the hooks.
|
|
154
|
+
const wrap = (value, label, extension) => {
|
|
155
|
+
// The host function's own `name` and `length` can be anything, even getters: each is read once, and only text
|
|
156
|
+
// and a count cross.
|
|
157
|
+
const name = value.name;
|
|
158
|
+
const length = value.length;
|
|
159
|
+
return native(builtins, {
|
|
160
|
+
runtime: "extension",
|
|
161
|
+
name: typeof name === "string" ? name : "",
|
|
162
|
+
length: typeof length === "number" && Number.isSafeInteger(length) && length >= 0 ? length : 0,
|
|
163
|
+
call: (_, values, site) => {
|
|
164
|
+
const args = values.map((item, index) => toHost(item, `Argument ${index + 1} to ${label}`));
|
|
165
|
+
const invocation = extension === undefined ? undefined : { extension, name: label, args };
|
|
166
|
+
// A denied call fails the way the global would: an async global rejects its promise, a sync one throws.
|
|
167
|
+
if (isAsync(value)) {
|
|
168
|
+
return pending(ctx, { stage: "run", label, invocation, host: value, args, threw: false }, site);
|
|
169
|
+
}
|
|
170
|
+
return new Push("extension call", [value, args, label, invocation]);
|
|
171
|
+
},
|
|
172
|
+
});
|
|
173
|
+
};
|
|
174
|
+
// The Effect each step of an extension call runs as, with the program's services in its requirements.
|
|
175
|
+
ctx.extensionWork = (request) => {
|
|
176
|
+
const label = request.label;
|
|
177
|
+
const call = request.invocation;
|
|
178
|
+
const cross = (reason) => new Throw(fromHost(reason, label));
|
|
179
|
+
const hooks = ctx.tools.hooks;
|
|
180
|
+
const before = call && hooks["extension.before"]?.(call).pipe(Effect.mapError(cross));
|
|
181
|
+
if (request.stage === "before")
|
|
182
|
+
return before ?? Effect.void;
|
|
183
|
+
const after = call && hooks["extension.after"];
|
|
184
|
+
const settle = (effect) => (after ? hooked(call, undefined, after, effect) : effect).pipe(Effect.mapBoth({ onFailure: cross, onSuccess: (result) => fromHost(result, label) }));
|
|
185
|
+
if (request.stage === "settle")
|
|
186
|
+
return settle(outcome(request.host, request.threw));
|
|
187
|
+
return Effect.andThen(before ?? Effect.void, settle(Effect.suspend(() => outcome(...callHost(request.host, request.args)))));
|
|
188
|
+
};
|
|
189
|
+
return extensions.flatMap((extension) => Object.entries(extension.globals).map(([name, value]) => [name, fromHost(value, name, 0, new Set(), extension.name)]));
|
|
190
|
+
};
|
|
191
|
+
// An asynchronous host call: the program holds a promise that settles when the host's work does.
|
|
192
|
+
const pending = (ctx, call, site) => {
|
|
193
|
+
const resolving = ctx.vm.scheduler.resolving(ctx.vm.scheduler.newPromise(), site);
|
|
194
|
+
ctx.vm.hosts.host({ kind: "extension", call }, { label: call.label, result: "value", resolving, site });
|
|
195
|
+
return resolving.promise;
|
|
196
|
+
};
|
|
197
|
+
/**
|
|
198
|
+
* Calls a synchronous extension function's host function, once its `extension.before` hook allowed it: a promise for
|
|
199
|
+
* a result that settles later (an Effect or a Promise), or the request that settles what it returned or threw now.
|
|
200
|
+
*/
|
|
201
|
+
export const startExtensionCall = (ctx, host, args, call, site) => {
|
|
202
|
+
const [result, threw] = callHost(host, args);
|
|
203
|
+
const request = { stage: "settle", ...call, host: result, args, threw };
|
|
204
|
+
if (!threw && (Effect.isEffect(result) || result instanceof Promise))
|
|
205
|
+
return pending(ctx, request, site);
|
|
206
|
+
return request;
|
|
207
|
+
};
|
|
208
|
+
/** Calls a host function: what it returned, or what it threw. */
|
|
209
|
+
const callHost = (value, args) => {
|
|
210
|
+
try {
|
|
211
|
+
return [value.apply(undefined, args), false];
|
|
212
|
+
}
|
|
213
|
+
catch (reason) {
|
|
214
|
+
return [reason, true];
|
|
215
|
+
}
|
|
216
|
+
};
|
|
217
|
+
/**
|
|
218
|
+
* What a host function's call settles as: a returned Effect or Promise settles later; a returned value or a throw
|
|
219
|
+
* settles now.
|
|
220
|
+
*/
|
|
221
|
+
const outcome = (result, threw) => {
|
|
222
|
+
if (threw)
|
|
223
|
+
return Effect.fail(result);
|
|
224
|
+
// Extension.Services adds an Effect global's requirements to R.
|
|
225
|
+
if (Effect.isEffect(result))
|
|
226
|
+
return result;
|
|
227
|
+
if (result instanceof Promise)
|
|
228
|
+
return Effect.tryPromise({ try: () => result, catch: (reason) => reason });
|
|
229
|
+
return Effect.succeed(result);
|
|
230
|
+
};
|
|
231
|
+
/**
|
|
232
|
+
* An error crosses as its name, message, `cause`, and own enumerable fields, such as Node's `code`, `errno`,
|
|
233
|
+
* `syscall`, and `path`. `stack` stays on its own side, `message` crosses once as text, and no field may shadow an
|
|
234
|
+
* Error method. A field that cannot cross (a socket, a handle, a function) is left behind so the error itself always
|
|
235
|
+
* arrives.
|
|
236
|
+
*/
|
|
237
|
+
const uncrossed = new Set(["stack", "message", "constructor", "toString", "__proto__"]);
|
|
238
|
+
const left = Symbol("left behind");
|
|
239
|
+
const crossing = (convert) => {
|
|
240
|
+
try {
|
|
241
|
+
return convert();
|
|
242
|
+
}
|
|
243
|
+
catch (reason) {
|
|
244
|
+
if (reason instanceof PendingThrow)
|
|
245
|
+
return left;
|
|
246
|
+
throw reason;
|
|
247
|
+
}
|
|
248
|
+
};
|
|
249
|
+
const hostErrors = new Map([
|
|
250
|
+
["TypeError", TypeError],
|
|
251
|
+
["RangeError", RangeError],
|
|
252
|
+
["SyntaxError", SyntaxError],
|
|
253
|
+
["ReferenceError", ReferenceError],
|
|
254
|
+
["EvalError", EvalError],
|
|
255
|
+
["URIError", URIError],
|
|
256
|
+
]);
|
|
257
|
+
// The primitives the interpreter operates on; symbols and BigInts are not among them.
|
|
258
|
+
const isPrimitive = (value) => value === null ||
|
|
259
|
+
value === undefined ||
|
|
260
|
+
typeof value === "string" ||
|
|
261
|
+
typeof value === "number" ||
|
|
262
|
+
typeof value === "boolean";
|
|
263
|
+
const describeHost = (value) => {
|
|
264
|
+
if (typeof value !== "object" || value === null)
|
|
265
|
+
return `a ${typeof value}`;
|
|
266
|
+
const name = value.constructor?.name;
|
|
267
|
+
if (name === undefined || name === "")
|
|
268
|
+
return "an object";
|
|
269
|
+
return `${/^[AEIO]/.test(name) ? "an" : "a"} ${name}`;
|
|
270
|
+
};
|
|
@@ -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,50 @@
|
|
|
1
|
+
import type { ToolRuntime } from "../../tool-runtime.js";
|
|
2
|
+
import type { ExtensionRequest } from "../scheduler.js";
|
|
3
|
+
import { Vm } from "../vm.js";
|
|
4
|
+
import type { Builtins } from "./intrinsics.js";
|
|
5
|
+
import { IntrinsicNames } from "./intrinsic-names.js";
|
|
6
|
+
import { type AstNode, type Binding } from "./model.js";
|
|
7
|
+
import { Obj, type Value } from "./objects.js";
|
|
8
|
+
import { Prelude } from "../prelude/prelude.js";
|
|
9
|
+
import { Push } from "./signals.js";
|
|
10
|
+
import type { NodeId, Source } from "./source.js";
|
|
11
|
+
/** One program execution: the tool bridge, the VM that runs it, captured logs, and the global scope built once. */
|
|
12
|
+
export declare class Interpreter<R> {
|
|
13
|
+
readonly tools: ToolRuntime<R>;
|
|
14
|
+
readonly builtins: Builtins;
|
|
15
|
+
readonly logs: Array<string>;
|
|
16
|
+
/** Runs program code, and keeps the job queue, promises, and host calls the program waits on. */
|
|
17
|
+
readonly vm: Vm;
|
|
18
|
+
/** Names for this runtime's intrinsics, taken before any program code can change a built-in. */
|
|
19
|
+
readonly intrinsics: IntrinsicNames;
|
|
20
|
+
/** The built-ins written in Code Mode, and the scope they close over. */
|
|
21
|
+
readonly prelude: Prelude;
|
|
22
|
+
/** Makes the Effect an extension function's host work runs as; set by the extension bridge. */
|
|
23
|
+
extensionWork: ((request: ExtensionRequest) => unknown) | undefined;
|
|
24
|
+
/** The parsed sources this execution runs, by id, so a `NodeId` resolves to its node. */
|
|
25
|
+
readonly sources: Map<string, Source>;
|
|
26
|
+
/** The global bindings: the intrinsics, the host's globals, and the program's bindings. */
|
|
27
|
+
readonly globalScope: Map<string, Binding>;
|
|
28
|
+
private readonly modules;
|
|
29
|
+
private readonly namespaces;
|
|
30
|
+
constructor(options: {
|
|
31
|
+
readonly tools: ToolRuntime<R>;
|
|
32
|
+
readonly builtins: Builtins;
|
|
33
|
+
readonly logs?: Array<string>;
|
|
34
|
+
/** The host's globals (extensions, a test harness): made again, the same way, when a saved run is restored. */
|
|
35
|
+
readonly globals?: (ctx: Interpreter<R>) => ReadonlyArray<readonly [string, Value]>;
|
|
36
|
+
/** Data bound for this program, part of its saved state; host globals of the same name win. */
|
|
37
|
+
readonly bindings?: (ctx: Interpreter<R>) => ReadonlyArray<readonly [string, Value]>;
|
|
38
|
+
});
|
|
39
|
+
/** A module, as `require` returns it and a default import binds it: a global, by its Node module name. */
|
|
40
|
+
module(specifier: string, site?: AstNode): Value;
|
|
41
|
+
/**
|
|
42
|
+
* What `import * as` and `import()` see: the module's own properties, and the module itself as `default`, the way
|
|
43
|
+
* Node presents a CommonJS module.
|
|
44
|
+
*/
|
|
45
|
+
namespace(specifier: string, site?: AstNode): Obj;
|
|
46
|
+
/** The node a `NodeId` names, in one of this execution's sources. */
|
|
47
|
+
node(id: NodeId): AstNode | undefined;
|
|
48
|
+
/** The built-in search: its result is usable directly, and can also be awaited or chained like a Promise. */
|
|
49
|
+
search(args: Array<Value>): Push;
|
|
50
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { Vm } from "../vm.js";
|
|
2
|
+
import { globals } from "./globals.js";
|
|
3
|
+
import { IntrinsicNames } from "./intrinsic-names.js";
|
|
4
|
+
import { PendingThrow } from "./model.js";
|
|
5
|
+
import { moduleName, resolveModule } from "./modules.js";
|
|
6
|
+
import { define, entries, makingIntrinsics, nativeRule, Obj } from "./objects.js";
|
|
7
|
+
import { Prelude } from "../prelude/prelude.js";
|
|
8
|
+
import { Push } from "./signals.js";
|
|
9
|
+
/** One program execution: the tool bridge, the VM that runs it, captured logs, and the global scope built once. */
|
|
10
|
+
export class Interpreter {
|
|
11
|
+
tools;
|
|
12
|
+
builtins;
|
|
13
|
+
logs;
|
|
14
|
+
/** Runs program code, and keeps the job queue, promises, and host calls the program waits on. */
|
|
15
|
+
vm;
|
|
16
|
+
/** Names for this runtime's intrinsics, taken before any program code can change a built-in. */
|
|
17
|
+
intrinsics;
|
|
18
|
+
/** The built-ins written in Code Mode, and the scope they close over. */
|
|
19
|
+
prelude;
|
|
20
|
+
/** Makes the Effect an extension function's host work runs as; set by the extension bridge. */
|
|
21
|
+
extensionWork;
|
|
22
|
+
/** The parsed sources this execution runs, by id, so a `NodeId` resolves to its node. */
|
|
23
|
+
sources = new Map();
|
|
24
|
+
/** The global bindings: the intrinsics, the host's globals, and the program's bindings. */
|
|
25
|
+
globalScope;
|
|
26
|
+
modules = new Map();
|
|
27
|
+
namespaces = new Map();
|
|
28
|
+
constructor(options) {
|
|
29
|
+
this.tools = options.tools;
|
|
30
|
+
this.builtins = options.builtins;
|
|
31
|
+
this.logs = options.logs ?? [];
|
|
32
|
+
// Program code has no receiver: top-level `this` is undefined, as in a module.
|
|
33
|
+
this.globalScope = new Map([["this", { value: undefined }]]);
|
|
34
|
+
// Everything made from here to the host globals is an intrinsic, with a static id (see `IntrinsicNames`).
|
|
35
|
+
const [[intrinsics, prelude], made] = makingIntrinsics(Object.values(this.builtins), () => {
|
|
36
|
+
const intrinsics = globals(this);
|
|
37
|
+
return [intrinsics, new Prelude(this, intrinsics)];
|
|
38
|
+
});
|
|
39
|
+
this.prelude = prelude;
|
|
40
|
+
const hosts = options.globals?.(this) ?? [];
|
|
41
|
+
this.intrinsics = new IntrinsicNames(made, {
|
|
42
|
+
globals: intrinsics,
|
|
43
|
+
builtins: this.builtins,
|
|
44
|
+
internals: [
|
|
45
|
+
["Prelude", this.prelude.functions],
|
|
46
|
+
["PreludeHelpers", this.prelude.helpers],
|
|
47
|
+
],
|
|
48
|
+
}, hosts);
|
|
49
|
+
for (const [name, value] of [...intrinsics, ...(options.bindings?.(this) ?? []), ...hosts]) {
|
|
50
|
+
this.globalScope.set(name, { value });
|
|
51
|
+
}
|
|
52
|
+
nativeRule.sealed.add(this.builtins.Function);
|
|
53
|
+
// The VM never runs host work itself, so it does not need the services that work runs with.
|
|
54
|
+
this.vm = new Vm(this);
|
|
55
|
+
}
|
|
56
|
+
/** A module, as `require` returns it and a default import binds it: a global, by its Node module name. */
|
|
57
|
+
module(specifier, site) {
|
|
58
|
+
const name = moduleName(specifier);
|
|
59
|
+
const cached = this.modules.get(name);
|
|
60
|
+
if (cached !== undefined)
|
|
61
|
+
return cached;
|
|
62
|
+
const module = resolveModule(name, (global) => this.globalScope.get(global)?.value);
|
|
63
|
+
if (module === undefined)
|
|
64
|
+
throw new PendingThrow("Error", `Cannot import "${specifier}": it isn't available in Code Mode, which can't load packages or files. Use the provided globals, or call tools through \`tools\`.`, site);
|
|
65
|
+
this.modules.set(name, module);
|
|
66
|
+
return module;
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* What `import * as` and `import()` see: the module's own properties, and the module itself as `default`, the way
|
|
70
|
+
* Node presents a CommonJS module.
|
|
71
|
+
*/
|
|
72
|
+
namespace(specifier, site) {
|
|
73
|
+
const module = this.module(specifier, site);
|
|
74
|
+
const name = moduleName(specifier);
|
|
75
|
+
const cached = this.namespaces.get(name);
|
|
76
|
+
if (cached)
|
|
77
|
+
return cached;
|
|
78
|
+
const namespace = new Obj(null);
|
|
79
|
+
if (module instanceof Obj)
|
|
80
|
+
for (const [key, value] of entries(module))
|
|
81
|
+
define(namespace, key, value);
|
|
82
|
+
define(namespace, "default", module);
|
|
83
|
+
this.namespaces.set(name, namespace);
|
|
84
|
+
return namespace;
|
|
85
|
+
}
|
|
86
|
+
/** The node a `NodeId` names, in one of this execution's sources. */
|
|
87
|
+
node(id) {
|
|
88
|
+
return this.sources.get(id.source)?.node(id);
|
|
89
|
+
}
|
|
90
|
+
/** The built-in search: its result is usable directly, and can also be awaited or chained like a Promise. */
|
|
91
|
+
search(args) {
|
|
92
|
+
return new Push("search", [args]);
|
|
93
|
+
}
|
|
94
|
+
}
|