@opencode/codemode 0.0.0-dev-98 → 0.0.0-dev-106
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/dist/data.d.ts +5 -4
- package/dist/data.js +7 -4
- package/dist/interpreter/callback.d.ts +10 -10
- package/dist/interpreter/callback.js +43 -31
- package/dist/interpreter/errors.d.ts +1 -1
- package/dist/interpreter/errors.js +9 -13
- package/dist/interpreter/execute.js +24 -21
- package/dist/interpreter/extensions.js +12 -4
- package/dist/interpreter/generators.js +162 -19
- package/dist/interpreter/globals.js +11 -8
- package/dist/interpreter/interpreter.d.ts +18 -13
- package/dist/interpreter/interpreter.js +1325 -1147
- package/dist/interpreter/intrinsics.js +1 -2
- package/dist/interpreter/model.d.ts +0 -6
- package/dist/interpreter/model.js +0 -5
- package/dist/interpreter/native.d.ts +7 -8
- package/dist/interpreter/native.js +4 -10
- package/dist/interpreter/objects.d.ts +47 -21
- package/dist/interpreter/objects.js +33 -12
- package/dist/interpreter/promises.d.ts +10 -53
- package/dist/interpreter/promises.js +196 -402
- package/dist/interpreter/runner.d.ts +184 -0
- package/dist/interpreter/runner.js +472 -0
- package/dist/stdlib/array.d.ts +3 -3
- package/dist/stdlib/array.js +106 -102
- package/dist/stdlib/bytes.d.ts +3 -3
- package/dist/stdlib/bytes.js +46 -41
- package/dist/stdlib/collections.d.ts +5 -5
- package/dist/stdlib/collections.js +160 -165
- package/dist/stdlib/date.d.ts +1 -1
- package/dist/stdlib/date.js +28 -20
- package/dist/stdlib/headers.d.ts +1 -1
- package/dist/stdlib/headers.js +14 -19
- package/dist/stdlib/iterator.d.ts +1 -1
- package/dist/stdlib/iterator.js +140 -122
- package/dist/stdlib/json.js +9 -12
- package/dist/stdlib/math.js +10 -10
- package/dist/stdlib/number.d.ts +2 -2
- package/dist/stdlib/object.d.ts +1 -1
- package/dist/stdlib/object.js +21 -22
- package/dist/stdlib/regexp.d.ts +1 -1
- package/dist/stdlib/regexp.js +2 -3
- package/dist/stdlib/string.d.ts +1 -1
- package/dist/stdlib/string.js +18 -20
- package/dist/stdlib/url.d.ts +5 -5
- package/dist/stdlib/url.js +32 -33
- package/dist/stdlib/value.d.ts +2 -2
- package/dist/stdlib/web.d.ts +2 -2
- package/package.json +1 -1
package/dist/data.d.ts
CHANGED
|
@@ -1,20 +1,21 @@
|
|
|
1
1
|
export * as Data from "./data.js";
|
|
2
|
-
import {
|
|
2
|
+
import type { Schema } from "effect";
|
|
3
3
|
import type { Interpreter } from "./interpreter/interpreter.js";
|
|
4
4
|
import { Obj, type Value } from "./interpreter/objects.js";
|
|
5
|
+
import { type Eval } from "./interpreter/runner.js";
|
|
5
6
|
export type Json = Schema.Json;
|
|
6
|
-
type Replacer
|
|
7
|
+
type Replacer = (args: Array<Value>, holder: Obj) => Eval<Value>;
|
|
7
8
|
/**
|
|
8
9
|
* What `JSON.stringify` would serialize for a program value, as host JSON: `toJSON` is honored, functions and
|
|
9
10
|
* `undefined` vanish, non-finite numbers become null, and everything else is copied. Two departures from JS
|
|
10
11
|
* so a mistake is not a silent `{}`: an Error serializes as `{ name, message, ...own }`, and a promise throws.
|
|
11
12
|
*/
|
|
12
|
-
export declare const toJson: <R>(ctx: Interpreter<R>, value: Value, replacer?: Replacer
|
|
13
|
+
export declare const toJson: <R>(ctx: Interpreter<R>, value: Value, replacer?: Replacer) => Eval<Schema.Json | undefined>;
|
|
13
14
|
/**
|
|
14
15
|
* The host boundary: `toJson`, plus what a program most likely meant when a value cannot be JSON. A promise is
|
|
15
16
|
* awaited, a Set crosses as an array, a URLSearchParams as its query string, a Uint8Array asks to be encoded as
|
|
16
17
|
* text first, and a `__proto__` key is dropped so host code can never receive one.
|
|
17
18
|
*/
|
|
18
|
-
export declare const toBoundary: <R>(ctx: Interpreter<R>, value: Value) =>
|
|
19
|
+
export declare const toBoundary: <R>(ctx: Interpreter<R>, value: Value) => Eval<Schema.Json | undefined>;
|
|
19
20
|
/** Host JSON as program values: objects and arrays are copied, primitives pass through. */
|
|
20
21
|
export declare const fromJson: <R>(ctx: Interpreter<R>, value: Json | undefined) => Value;
|
package/dist/data.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
export * as Data from "./data.js";
|
|
2
|
-
import { Effect } from "effect";
|
|
3
2
|
import { MAX_VALUE_DEPTH } from "./interpreter/limits.js";
|
|
4
3
|
import { invalidData, rangeError, typeError } from "./interpreter/model.js";
|
|
5
4
|
import { Arr, Bytes, Callable, define, ErrorObj, get, keys, Obj, PromiseObj, record, SetObj, URLSearchParamsObj, HeadersObj, } from "./interpreter/objects.js";
|
|
6
5
|
import { typeofValue } from "./interpreter/references.js";
|
|
6
|
+
import { Slice } from "./interpreter/runner.js";
|
|
7
7
|
/**
|
|
8
8
|
* What `JSON.stringify` would serialize for a program value, as host JSON: `toJSON` is honored, functions and
|
|
9
9
|
* `undefined` vanish, non-finite numbers become null, and everything else is copied. Two departures from JS
|
|
@@ -18,14 +18,17 @@ export const toJson = (ctx, value, replacer) => walk(ctx, value, replacer, false
|
|
|
18
18
|
export const toBoundary = (ctx, value) => walk(ctx, value, undefined, true);
|
|
19
19
|
const walk = (ctx, value, replacer, boundary) => {
|
|
20
20
|
const stack = new Set();
|
|
21
|
-
const visit = (holder, key, depth)
|
|
21
|
+
const visit = function* (holder, key, depth) {
|
|
22
|
+
// Shared references expand into a tree, so the work is not bounded by the value's size or depth.
|
|
23
|
+
if (ctx.runner.tick())
|
|
24
|
+
yield Slice;
|
|
22
25
|
if (depth > MAX_VALUE_DEPTH)
|
|
23
26
|
throw rangeError(`Value exceeds the maximum depth of ${MAX_VALUE_DEPTH}.`);
|
|
24
27
|
const raw = get(holder, key);
|
|
25
28
|
if (raw instanceof PromiseObj && !boundary) {
|
|
26
29
|
throw invalidData("JSON.stringify received an un-awaited Promise; await it first - e.g. `const result = await tools.ns.tool(...)`.");
|
|
27
30
|
}
|
|
28
|
-
const settled = raw instanceof PromiseObj ? yield* ctx.
|
|
31
|
+
const settled = raw instanceof PromiseObj ? yield* ctx.awaitValue(raw) : raw;
|
|
29
32
|
const toJSON = settled instanceof Obj ? get(settled, "toJSON") : undefined;
|
|
30
33
|
const own = toJSON instanceof Callable ? yield* ctx.call(toJSON, settled, [key]) : settled;
|
|
31
34
|
const value = replacer === undefined ? own : yield* replacer([key, own], holder);
|
|
@@ -74,7 +77,7 @@ const walk = (ctx, value, replacer, boundary) => {
|
|
|
74
77
|
}
|
|
75
78
|
stack.delete(target);
|
|
76
79
|
return copied;
|
|
77
|
-
}
|
|
80
|
+
};
|
|
78
81
|
return visit(record(ctx.builtins.Object, { "": value }), "", 0);
|
|
79
82
|
};
|
|
80
83
|
/** Host JSON as program values: objects and arrays are copied, primitives pass through. */
|
|
@@ -1,24 +1,24 @@
|
|
|
1
|
-
import { Effect } from "effect";
|
|
2
1
|
import type { Interpreter } from "./interpreter.js";
|
|
3
|
-
import { Callable, type Cursor, type Value } from "./objects.js";
|
|
2
|
+
import { Callable, type Cursor, type NativeResult, type Value } from "./objects.js";
|
|
3
|
+
import { type Eval } from "./runner.js";
|
|
4
4
|
/** IteratorClose: a consumer failure closes the iterator and wins over any close failure, except that a generator's
|
|
5
5
|
* return() is a return completion, so a failing close wins over it, as after `break`. */
|
|
6
|
-
export declare
|
|
6
|
+
export declare function preserveConsumerError<A>(close: Cursor["close"], body: Eval<A>): Eval<A>;
|
|
7
7
|
export type Hint = "number" | "string" | "default";
|
|
8
8
|
/**
|
|
9
9
|
* ToPrimitive: calls `valueOf`/`toString` in hint order and returns the first primitive result. Dates treat the
|
|
10
10
|
* default hint as "string", like their `Symbol.toPrimitive`. Opaque values (functions, promises, generators, tool
|
|
11
11
|
* references) pass through unchanged so callers reject or describe them in their built-in form.
|
|
12
12
|
*/
|
|
13
|
-
export declare
|
|
13
|
+
export declare function toPrimitive<R>(ctx: Interpreter<R>, value: Value, hint: Hint): Eval<Value>;
|
|
14
14
|
/** Invoke(value, name): calls the method the value would find through its prototype. */
|
|
15
|
-
export declare const invoke: <R>(ctx: Interpreter<R>, value: Value, name: string, label: string) =>
|
|
16
|
-
export declare
|
|
17
|
-
export declare
|
|
15
|
+
export declare const invoke: <R>(ctx: Interpreter<R>, value: Value, name: string, label: string) => Eval<Value>;
|
|
16
|
+
export declare function toPrimitiveString<R>(ctx: Interpreter<R>, value: Value): Eval<string>;
|
|
17
|
+
export declare function toPrimitiveNumber<R>(ctx: Interpreter<R>, value: Value): Eval<number>;
|
|
18
18
|
/**
|
|
19
19
|
* Runs a native body on its arguments after ToPrimitive, in order, with one hint for all positions or one per
|
|
20
|
-
* position. Primitive arguments skip the
|
|
20
|
+
* position. Primitive arguments skip the conversion entirely.
|
|
21
21
|
*/
|
|
22
|
-
export declare const withPrimitives: <R>(ctx: Interpreter<R>, hints: Hint | ReadonlyArray<Hint>, values: Array<Value>, body: (primitives: Array<Value>) =>
|
|
22
|
+
export declare const withPrimitives: <R>(ctx: Interpreter<R>, hints: Hint | ReadonlyArray<Hint>, values: Array<Value>, body: (primitives: Array<Value>) => NativeResult) => NativeResult;
|
|
23
23
|
export declare const isSupportedCallback: (value: Value) => value is Callable;
|
|
24
|
-
export declare const applyCollectionCallback: <R>(ctx: Interpreter<R>, callback: Value, name: string) => ((args: Array<Value>, thisValue?: Value) =>
|
|
24
|
+
export declare const applyCollectionCallback: <R>(ctx: Interpreter<R>, callback: Value, name: string) => ((args: Array<Value>, thisValue?: Value) => Eval<Value>);
|
|
@@ -1,42 +1,46 @@
|
|
|
1
|
-
import { Cause, Effect, Exit } from "effect";
|
|
2
1
|
import { primitivePrototype } from "./intrinsics.js";
|
|
3
2
|
import { GeneratorReturn, typeError } from "./model.js";
|
|
4
3
|
import { Callable, get, Native, DateObj, Obj, coerceToNumber, coerceToString, } from "./objects.js";
|
|
5
4
|
import { isOpaque, typeofValue } from "./references.js";
|
|
5
|
+
import { Interruption, isEval } from "./runner.js";
|
|
6
6
|
/** IteratorClose: a consumer failure closes the iterator and wins over any close failure, except that a generator's
|
|
7
7
|
* return() is a return completion, so a failing close wins over it, as after `break`. */
|
|
8
|
-
export
|
|
9
|
-
|
|
10
|
-
return
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
8
|
+
export function* preserveConsumerError(close, body) {
|
|
9
|
+
try {
|
|
10
|
+
return yield* body;
|
|
11
|
+
}
|
|
12
|
+
catch (error) {
|
|
13
|
+
if (error instanceof Interruption)
|
|
14
|
+
throw error;
|
|
15
|
+
try {
|
|
16
|
+
yield* close();
|
|
17
|
+
}
|
|
18
|
+
catch (closed) {
|
|
19
|
+
if (error instanceof GeneratorReturn)
|
|
20
|
+
throw closed;
|
|
14
21
|
}
|
|
15
|
-
|
|
16
|
-
}
|
|
17
|
-
}
|
|
22
|
+
throw error;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
18
25
|
/**
|
|
19
26
|
* ToPrimitive: calls `valueOf`/`toString` in hint order and returns the first primitive result. Dates treat the
|
|
20
27
|
* default hint as "string", like their `Symbol.toPrimitive`. Opaque values (functions, promises, generators, tool
|
|
21
28
|
* references) pass through unchanged so callers reject or describe them in their built-in form.
|
|
22
29
|
*/
|
|
23
|
-
export
|
|
30
|
+
export function* toPrimitive(ctx, value, hint) {
|
|
24
31
|
if (!(value instanceof Obj) || isOpaque(value))
|
|
25
|
-
return
|
|
32
|
+
return value;
|
|
26
33
|
const asString = hint === "string" || (hint === "default" && value instanceof DateObj);
|
|
27
|
-
const
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
throw typeError("Cannot convert object to primitive value.");
|
|
38
|
-
});
|
|
39
|
-
};
|
|
34
|
+
for (const method of asString ? ["toString", "valueOf"] : ["valueOf", "toString"]) {
|
|
35
|
+
const callable = get(value, method);
|
|
36
|
+
if (!(callable instanceof Callable))
|
|
37
|
+
continue;
|
|
38
|
+
const result = yield* ctx.call(callable, value, []);
|
|
39
|
+
if (result === null || (typeof result !== "object" && typeof result !== "function"))
|
|
40
|
+
return result;
|
|
41
|
+
}
|
|
42
|
+
throw typeError("Cannot convert object to primitive value.");
|
|
43
|
+
}
|
|
40
44
|
/** Invoke(value, name): calls the method the value would find through its prototype. */
|
|
41
45
|
export const invoke = (ctx, value, name, label) => {
|
|
42
46
|
const target = value instanceof Obj ? value : primitivePrototype(ctx.builtins, value);
|
|
@@ -44,19 +48,27 @@ export const invoke = (ctx, value, name, label) => {
|
|
|
44
48
|
throw typeError(`${label} called on null or undefined.`);
|
|
45
49
|
return ctx.call(get(target, name), value, []);
|
|
46
50
|
};
|
|
47
|
-
export
|
|
48
|
-
|
|
51
|
+
export function* toPrimitiveString(ctx, value) {
|
|
52
|
+
return coerceToString(yield* toPrimitive(ctx, value, "string"));
|
|
53
|
+
}
|
|
54
|
+
export function* toPrimitiveNumber(ctx, value) {
|
|
55
|
+
return coerceToNumber(yield* toPrimitive(ctx, value, "number"));
|
|
56
|
+
}
|
|
49
57
|
/**
|
|
50
58
|
* Runs a native body on its arguments after ToPrimitive, in order, with one hint for all positions or one per
|
|
51
|
-
* position. Primitive arguments skip the
|
|
59
|
+
* position. Primitive arguments skip the conversion entirely.
|
|
52
60
|
*/
|
|
53
61
|
export const withPrimitives = (ctx, hints, values, body) => {
|
|
54
62
|
if (!values.some((value) => value instanceof Obj))
|
|
55
63
|
return body(values);
|
|
56
|
-
return
|
|
64
|
+
return (function* () {
|
|
65
|
+
const primitives = [];
|
|
66
|
+
for (const [index, value] of values.entries()) {
|
|
67
|
+
primitives.push(yield* toPrimitive(ctx, value, typeof hints === "string" ? hints : hints[index]));
|
|
68
|
+
}
|
|
57
69
|
const result = body(primitives);
|
|
58
|
-
return
|
|
59
|
-
});
|
|
70
|
+
return isEval(result) ? yield* result : result;
|
|
71
|
+
})();
|
|
60
72
|
};
|
|
61
73
|
// The single acceptance list for callbacks: collections, sort, string replacers,
|
|
62
74
|
// Array.from mappers, and promise reactions all admit exactly these callables.
|
|
@@ -13,4 +13,4 @@ export declare const locate: (error: unknown, node?: AstNode) => unknown;
|
|
|
13
13
|
export declare const materialize: <R>(ctx: Interpreter<R>, thrown: unknown) => Value;
|
|
14
14
|
export declare const createAggregateErrorValue: <R>(ctx: Interpreter<R>, errors: Array<Value>, message: string, proto?: Obj) => ErrorObj;
|
|
15
15
|
/** An error constructor such as `Error` or `TypeError`; callable with or without `new`, like JS. */
|
|
16
|
-
export declare const errorGlobal: <R>(type: ErrorType, ctx: Interpreter<R>) => Native
|
|
16
|
+
export declare const errorGlobal: <R>(type: ErrorType, ctx: Interpreter<R>) => Native;
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { Effect } from "effect";
|
|
2
1
|
import { ToolError } from "../tool-error.js";
|
|
3
2
|
import { ToolRuntimeError } from "../tool-runtime.js";
|
|
4
3
|
import { formatLocation, PendingThrow, Throw, sourceLocation, typeError } from "./model.js";
|
|
@@ -109,36 +108,33 @@ export const createAggregateErrorValue = (ctx, errors, message, proto = ctx.buil
|
|
|
109
108
|
define(value, "errors", new Arr(ctx.builtins.Array, errors), { ...hidden });
|
|
110
109
|
return value;
|
|
111
110
|
};
|
|
112
|
-
|
|
111
|
+
function* constructAggregateErrorValue(ctx, args, proto) {
|
|
113
112
|
const message = args[1] === undefined ? "" : yield* toPrimitiveString(ctx, args[1]);
|
|
114
113
|
const cursor = yield* ctx.iterate(args[0]);
|
|
115
114
|
if (cursor === undefined)
|
|
116
115
|
throw typeError("new AggregateError(...) expects a synchronous iterable of errors.");
|
|
117
116
|
const errors = [];
|
|
118
117
|
while (true) {
|
|
119
|
-
const step = yield* cursor.next;
|
|
118
|
+
const step = yield* cursor.next();
|
|
120
119
|
if (step.done)
|
|
121
120
|
return createAggregateErrorValue(ctx, errors, message, proto);
|
|
122
121
|
errors.push(step.value);
|
|
123
122
|
}
|
|
124
|
-
}
|
|
123
|
+
}
|
|
125
124
|
/** An error constructor such as `Error` or `TypeError`; callable with or without `new`, like JS. */
|
|
126
125
|
export const errorGlobal = (type, ctx) => {
|
|
127
126
|
const builtins = ctx.builtins;
|
|
128
127
|
const prototype = builtins[type];
|
|
129
|
-
const construct = (args, newTarget)
|
|
128
|
+
const construct = function* (args, newTarget) {
|
|
130
129
|
const proto = prototypeFrom(newTarget, prototype);
|
|
131
130
|
const created = type === "AggregateError"
|
|
132
|
-
? constructAggregateErrorValue(ctx, args, proto)
|
|
133
|
-
:
|
|
131
|
+
? yield* constructAggregateErrorValue(ctx, args, proto)
|
|
132
|
+
: createErrorValue(proto, args[0] === undefined ? undefined : yield* toPrimitiveString(ctx, args[0]));
|
|
134
133
|
// ES2022 `new Error(message, { cause })`: installed only when the options object has the property at all.
|
|
135
134
|
const options = args[type === "AggregateError" ? 2 : 1];
|
|
136
|
-
if (
|
|
137
|
-
|
|
138
|
-
return
|
|
139
|
-
define(value, "cause", get(options, "cause"), hidden);
|
|
140
|
-
return value;
|
|
141
|
-
});
|
|
135
|
+
if (options instanceof Obj && has(options, "cause"))
|
|
136
|
+
define(created, "cause", get(options, "cause"), hidden);
|
|
137
|
+
return created;
|
|
142
138
|
};
|
|
143
139
|
const ctor = constructor(builtins, prototype, {
|
|
144
140
|
name: type,
|
|
@@ -1,10 +1,8 @@
|
|
|
1
1
|
import { parse } from "acorn";
|
|
2
|
-
import { Cause, Effect
|
|
3
|
-
import { toBoundary } from "../data.js";
|
|
2
|
+
import { Cause, Effect } from "effect";
|
|
4
3
|
import { ToolRuntime } from "../tool-runtime.js";
|
|
5
4
|
import { normalizeError } from "./errors.js";
|
|
6
5
|
import { createBuiltins } from "./intrinsics.js";
|
|
7
|
-
import { Pending } from "./promises.js";
|
|
8
6
|
import { Interpreter } from "./interpreter.js";
|
|
9
7
|
export const executeProgram = (code, prepared, limits, hooks, globals) => {
|
|
10
8
|
if (code.trim().length === 0) {
|
|
@@ -22,24 +20,29 @@ export const executeProgram = (code, prepared, limits, hooks, globals) => {
|
|
|
22
20
|
const logged = () => (logs.length > 0 ? { logs: [...logs] } : {});
|
|
23
21
|
// Set only after copy-out so timeouts cannot report invalid values as completed.
|
|
24
22
|
let returned;
|
|
25
|
-
|
|
23
|
+
let runner;
|
|
24
|
+
const base = Effect.gen(function* () {
|
|
26
25
|
const program = parseProgram(code);
|
|
27
|
-
const
|
|
28
|
-
const ctx = new Interpreter({ tools,
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
26
|
+
const services = yield* Effect.context();
|
|
27
|
+
const ctx = new Interpreter({ tools, services, builtins, logs, globals });
|
|
28
|
+
runner = ctx.runner;
|
|
29
|
+
const outcome = yield* runner.run(ctx.main(program));
|
|
30
|
+
if (!outcome.ok) {
|
|
31
|
+
return { ok: false, error: normalizeError(outcome.error), ...logged(), toolCalls: tools.calls };
|
|
32
|
+
}
|
|
33
|
+
const result = outcome.value ?? null;
|
|
34
|
+
returned = { value: result, runner };
|
|
35
|
+
// Host work the program left running is interrupted, not awaited.
|
|
36
|
+
yield* runner.interrupt();
|
|
37
|
+
const warnings = runner.diagnostics();
|
|
38
|
+
return {
|
|
39
|
+
ok: true,
|
|
40
|
+
value: result,
|
|
41
|
+
...(warnings.length > 0 ? { warnings } : {}),
|
|
42
|
+
...logged(),
|
|
43
|
+
toolCalls: tools.calls,
|
|
44
|
+
};
|
|
45
|
+
}).pipe(Effect.ensuring(Effect.suspend(() => runner?.interrupt() ?? Effect.void)));
|
|
43
46
|
const timeoutMs = limits.timeoutMs;
|
|
44
47
|
const operation = timeoutMs === undefined
|
|
45
48
|
? base
|
|
@@ -63,7 +66,7 @@ export const executeProgram = (code, prepared, limits, hooks, globals) => {
|
|
|
63
66
|
kind: "TimeoutExceeded",
|
|
64
67
|
message: `The program returned, but background work was still running at the ${timeoutMs}ms timeout and was interrupted. Await all started promises.`,
|
|
65
68
|
},
|
|
66
|
-
...returned.
|
|
69
|
+
...returned.runner.diagnostics(),
|
|
67
70
|
],
|
|
68
71
|
...logged(),
|
|
69
72
|
toolCalls: tools.calls,
|
|
@@ -125,7 +125,7 @@ export const extensionGlobals = (ctx, extensions) => {
|
|
|
125
125
|
// A host function as a program function. Arguments cross in; a global's call runs inside the host's extension
|
|
126
126
|
// hooks, which see the host's own error on failure; then whatever came back, or was thrown, crosses out so the
|
|
127
127
|
// program catches a copy. Functions inside results are part of a value's API and skip the hooks.
|
|
128
|
-
const wrap = (value, label, describe) => fn(builtins, value.name, value.length, (_, values) => {
|
|
128
|
+
const wrap = (value, label, describe) => fn(builtins, value.name, value.length, (_, values, site) => {
|
|
129
129
|
const args = values.map((item, index) => toHost(item, `Argument ${index + 1} to ${label}`));
|
|
130
130
|
const hooks = ctx.tools.hooks;
|
|
131
131
|
const settle = (run) => (describe === undefined
|
|
@@ -136,14 +136,22 @@ export const extensionGlobals = (ctx, extensions) => {
|
|
|
136
136
|
result = value.apply(undefined, args);
|
|
137
137
|
}
|
|
138
138
|
catch (reason) {
|
|
139
|
-
return settle(Effect.fail(reason));
|
|
139
|
+
return blocking(ctx.runner.blocking(settle(Effect.fail(reason))));
|
|
140
140
|
}
|
|
141
141
|
if (!(result instanceof Promise))
|
|
142
|
-
return settle(Effect.succeed(result));
|
|
143
|
-
|
|
142
|
+
return blocking(ctx.runner.blocking(settle(Effect.succeed(result))));
|
|
143
|
+
const runner = ctx.runner;
|
|
144
|
+
const promise = runner.newPromise();
|
|
145
|
+
const resolving = runner.resolving(promise, site);
|
|
146
|
+
runner.host(settle(Effect.tryPromise({ try: () => result, catch: (reason) => reason })), (settled) => (settled.ok ? resolving.resolve(settled.value) : resolving.reject(settled.error)), site);
|
|
147
|
+
return promise;
|
|
144
148
|
});
|
|
145
149
|
return extensions.flatMap((extension) => Object.entries(extension.globals).map(([name, value]) => [name, wrap(value, name, (args) => ({ extension: extension.name, name, args }))]));
|
|
146
150
|
};
|
|
151
|
+
// A synchronous host call: its hooks run before any other job, as the call itself did.
|
|
152
|
+
function* blocking(host) {
|
|
153
|
+
return (yield host);
|
|
154
|
+
}
|
|
147
155
|
/**
|
|
148
156
|
* An error crosses as its name, message, `cause`, and own enumerable fields, such as Node's `code`, `errno`,
|
|
149
157
|
* `syscall`, and `path`. `stack` stays on its own side, and no field may shadow an Error method. A field that cannot
|
|
@@ -1,25 +1,168 @@
|
|
|
1
|
-
import { Effect } from "effect";
|
|
2
1
|
import { fn, methods, receiver } from "./native.js";
|
|
3
|
-
import { AsyncIteratorSymbol, IteratorSymbol } from "./model.js";
|
|
4
|
-
import { define, hidden, GeneratorObj } from "./objects.js";
|
|
2
|
+
import { AsyncIteratorSymbol, IteratorSymbol, Throw, typeError } from "./model.js";
|
|
3
|
+
import { define, hidden, GeneratorObj, iteratorResult } from "./objects.js";
|
|
4
|
+
import { abrupt, Enter, normal, } from "./runner.js";
|
|
5
5
|
/** `next`/`return`/`throw` on the generator prototypes; async generators answer with promises. */
|
|
6
6
|
export const generatorGlobals = (ctx) => {
|
|
7
7
|
const builtins = ctx.builtins;
|
|
8
|
-
const
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
kind
|
|
13
|
-
|
|
14
|
-
(
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
8
|
+
const sync = (kind) => [
|
|
9
|
+
kind,
|
|
10
|
+
1,
|
|
11
|
+
(thisValue, args) => {
|
|
12
|
+
const method = `Generator.prototype.${kind}`;
|
|
13
|
+
const generator = receiver(GeneratorObj, thisValue, method);
|
|
14
|
+
if (generator.asynchronous)
|
|
15
|
+
throw typeError(`${method} called on incompatible receiver an async generator.`);
|
|
16
|
+
return step(ctx, generator, kind, args[0]);
|
|
17
|
+
},
|
|
18
|
+
];
|
|
19
|
+
const async = (kind) => [
|
|
20
|
+
kind,
|
|
21
|
+
1,
|
|
22
|
+
(thisValue, args) => request(ctx, thisValue, kind, args[0]),
|
|
23
|
+
];
|
|
24
|
+
methods(builtins, builtins.Generator, [sync("next"), sync("return"), sync("throw")]);
|
|
25
|
+
methods(builtins, builtins.AsyncGenerator, [async("next"), async("return"), async("throw")]);
|
|
26
|
+
define(builtins.Iterator, IteratorSymbol, fn(builtins, "[Symbol.iterator]", 0, (thisValue) => thisValue), hidden);
|
|
27
|
+
define(builtins.AsyncIterator, AsyncIteratorSymbol, fn(builtins, "[Symbol.asyncIterator]", 0, (thisValue) => thisValue), hidden);
|
|
28
|
+
};
|
|
29
|
+
const result = (ctx, value, done) => iteratorResult(ctx.builtins.Object, value, done);
|
|
30
|
+
// Puts the suspended body back on the stack and continues it with `request`; the boundary answers the caller when
|
|
31
|
+
// the body next yields or ends.
|
|
32
|
+
const resume = (ctx, generator, request) => {
|
|
33
|
+
const started = generator.state !== "suspendedStart";
|
|
34
|
+
generator.state = "executing";
|
|
35
|
+
if (!started) {
|
|
36
|
+
return new Enter([{ body: generator.body, boundary: new GeneratorBoundary(ctx, generator) }], normal(undefined));
|
|
37
|
+
}
|
|
38
|
+
const entries = generator.entries;
|
|
39
|
+
generator.entries = undefined;
|
|
40
|
+
return new Enter(entries, normal(request));
|
|
41
|
+
};
|
|
42
|
+
// A synchronous generator step: the body runs on the caller's stack until it yields, returns, or throws.
|
|
43
|
+
function* step(ctx, generator, kind, value) {
|
|
44
|
+
if (generator.state === "executing")
|
|
45
|
+
throw typeError("Generator is already running.");
|
|
46
|
+
if (generator.state === "suspendedStart" && kind !== "next")
|
|
47
|
+
generator.state = "completed";
|
|
48
|
+
if (generator.state === "completed") {
|
|
49
|
+
if (kind === "throw")
|
|
50
|
+
throw new Throw(value);
|
|
51
|
+
return result(ctx, kind === "return" ? value : undefined, true);
|
|
52
|
+
}
|
|
53
|
+
return (yield resume(ctx, generator, { kind, value }));
|
|
54
|
+
}
|
|
55
|
+
// AsyncGenerator.prototype.next/return/throw: queue the request with its promise, and run the body now if it is
|
|
56
|
+
// waiting for one. A request that arrives while the body runs is answered when the body reaches it.
|
|
57
|
+
function* request(ctx, thisValue, kind, value) {
|
|
58
|
+
const runner = ctx.runner;
|
|
59
|
+
const promise = runner.newPromise();
|
|
60
|
+
const resolving = runner.resolving(promise);
|
|
61
|
+
if (!(thisValue instanceof GeneratorObj) || !thisValue.asynchronous) {
|
|
62
|
+
resolving.reject(typeError(`AsyncGenerator.prototype.${kind} called on incompatible receiver.`));
|
|
63
|
+
return promise;
|
|
64
|
+
}
|
|
65
|
+
const generator = thisValue;
|
|
66
|
+
const state = generator.state;
|
|
67
|
+
if (kind === "next" && state === "completed") {
|
|
68
|
+
resolving.resolve(result(ctx, undefined, true));
|
|
69
|
+
return promise;
|
|
70
|
+
}
|
|
71
|
+
if (kind === "throw") {
|
|
72
|
+
if (state === "suspendedStart")
|
|
73
|
+
generator.state = "completed";
|
|
74
|
+
if (generator.state === "completed") {
|
|
75
|
+
resolving.reject(new Throw(value));
|
|
76
|
+
return promise;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
const queued = { kind, value };
|
|
80
|
+
generator.queue.push({ request: queued, resolving });
|
|
81
|
+
if (kind === "return" && (state === "suspendedStart" || state === "completed")) {
|
|
82
|
+
generator.state = "awaiting-return";
|
|
83
|
+
awaitReturn(ctx, generator);
|
|
84
|
+
return promise;
|
|
85
|
+
}
|
|
86
|
+
if (state === "suspendedStart" || state === "suspendedYield")
|
|
87
|
+
yield resume(ctx, generator, queued);
|
|
88
|
+
return promise;
|
|
89
|
+
}
|
|
90
|
+
// AsyncGeneratorCompleteStep: answer the oldest request.
|
|
91
|
+
const completeStep = (ctx, generator, completion, done) => {
|
|
92
|
+
const next = generator.queue.shift();
|
|
93
|
+
if (completion.ok)
|
|
94
|
+
next.resolving.resolve(result(ctx, completion.value, done));
|
|
95
|
+
else
|
|
96
|
+
next.resolving.reject(completion.error);
|
|
97
|
+
};
|
|
98
|
+
// AsyncGeneratorDrainQueue: once the body has ended, answer the remaining requests in order.
|
|
99
|
+
const drainQueue = (ctx, generator) => {
|
|
100
|
+
generator.state = "draining";
|
|
101
|
+
while (true) {
|
|
102
|
+
const next = generator.queue[0];
|
|
103
|
+
if (next === undefined) {
|
|
104
|
+
generator.state = "completed";
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
if (next.request.kind === "return") {
|
|
108
|
+
generator.state = "awaiting-return";
|
|
109
|
+
return awaitReturn(ctx, generator);
|
|
110
|
+
}
|
|
111
|
+
completeStep(ctx, generator, next.request.kind === "throw" ? abrupt(new Throw(next.request.value)) : normal(undefined), true);
|
|
112
|
+
}
|
|
113
|
+
};
|
|
114
|
+
// AsyncGeneratorAwaitReturn: a `return(value)` on an ended or unstarted generator settles once `value` does.
|
|
115
|
+
const awaitReturn = (ctx, generator) => {
|
|
116
|
+
const runner = ctx.runner;
|
|
117
|
+
const finish = (completion) => {
|
|
118
|
+
completeStep(ctx, generator, completion, true);
|
|
119
|
+
drainQueue(ctx, generator);
|
|
22
120
|
};
|
|
23
|
-
|
|
24
|
-
|
|
121
|
+
try {
|
|
122
|
+
runner.then(runner.promiseResolve(generator.queue[0].request.value), finish);
|
|
123
|
+
}
|
|
124
|
+
catch (error) {
|
|
125
|
+
finish(abrupt(error));
|
|
126
|
+
}
|
|
25
127
|
};
|
|
128
|
+
/** Where a generator body splits off the stack when it yields, and how its end answers the request that ran it. */
|
|
129
|
+
class GeneratorBoundary {
|
|
130
|
+
ctx;
|
|
131
|
+
target;
|
|
132
|
+
generator = true;
|
|
133
|
+
async;
|
|
134
|
+
constructor(ctx, target) {
|
|
135
|
+
this.ctx = ctx;
|
|
136
|
+
this.target = target;
|
|
137
|
+
this.async = target.asynchronous;
|
|
138
|
+
}
|
|
139
|
+
finish(completion) {
|
|
140
|
+
const generator = this.target;
|
|
141
|
+
if (!generator.asynchronous) {
|
|
142
|
+
generator.state = "completed";
|
|
143
|
+
return completion.ok ? normal(result(this.ctx, completion.value, true)) : completion;
|
|
144
|
+
}
|
|
145
|
+
completeStep(this.ctx, generator, completion, true);
|
|
146
|
+
drainQueue(this.ctx, generator);
|
|
147
|
+
return normal(undefined);
|
|
148
|
+
}
|
|
149
|
+
suspended() {
|
|
150
|
+
return normal(undefined);
|
|
151
|
+
}
|
|
152
|
+
yielded(value, split) {
|
|
153
|
+
const generator = this.target;
|
|
154
|
+
if (!generator.asynchronous) {
|
|
155
|
+
generator.entries = split();
|
|
156
|
+
generator.state = "suspendedYield";
|
|
157
|
+
return normal(result(this.ctx, value, false));
|
|
158
|
+
}
|
|
159
|
+
// AsyncGeneratorYield: answer the oldest request, and keep running if another is already waiting.
|
|
160
|
+
completeStep(this.ctx, generator, normal(value), false);
|
|
161
|
+
const next = generator.queue[0];
|
|
162
|
+
if (next !== undefined)
|
|
163
|
+
return normal(next.request);
|
|
164
|
+
generator.entries = split();
|
|
165
|
+
generator.state = "suspendedYield";
|
|
166
|
+
return normal(undefined);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { Effect } from "effect";
|
|
2
1
|
import { Arr, Callable, coerceToInteger, coerceToString, get, Obj } from "./objects.js";
|
|
3
2
|
import { arrayGlobal } from "../stdlib/array.js";
|
|
4
3
|
import { textDecoderGlobal, textEncoderGlobal, uint8ArrayGlobal } from "../stdlib/bytes.js";
|
|
@@ -26,13 +25,17 @@ import { generatorGlobals } from "./generators.js";
|
|
|
26
25
|
import { promiseGlobal } from "./promises.js";
|
|
27
26
|
// Function.prototype.constructor exists so `fn.constructor === Function` holds; dynamic code is unsupported.
|
|
28
27
|
const functionGlobal = (ctx) => {
|
|
29
|
-
const reject = () =>
|
|
28
|
+
const reject = () => {
|
|
30
29
|
throw typeError("The Function constructor is not supported; write the function inline.");
|
|
31
|
-
}
|
|
30
|
+
};
|
|
32
31
|
const target = (thisValue, method) => receiver(Callable, thisValue, `Function.prototype.${method}`);
|
|
33
32
|
methods(ctx.builtins, ctx.builtins.Function, [
|
|
34
|
-
["call", 1, (thisValue, args) => ctx.call(target(thisValue, "call"), args[0], args.slice(1))],
|
|
35
|
-
[
|
|
33
|
+
["call", 1, (thisValue, args, site) => ctx.call(target(thisValue, "call"), args[0], args.slice(1), site)],
|
|
34
|
+
[
|
|
35
|
+
"apply",
|
|
36
|
+
2,
|
|
37
|
+
(thisValue, args, site) => ctx.call(target(thisValue, "apply"), args[0], listFromArrayLike(args[1]), site),
|
|
38
|
+
],
|
|
36
39
|
[
|
|
37
40
|
"bind",
|
|
38
41
|
1,
|
|
@@ -42,7 +45,7 @@ const functionGlobal = (ctx) => {
|
|
|
42
45
|
return native(ctx.builtins, {
|
|
43
46
|
name: `bound ${coerceToString(get(fn, "name"))}`,
|
|
44
47
|
length: Math.max(0, fn.length - bound.length),
|
|
45
|
-
call: (_, rest) => ctx.call(fn, args[0], [...bound, ...rest]),
|
|
48
|
+
call: (_, rest, site) => ctx.call(fn, args[0], [...bound, ...rest], site),
|
|
46
49
|
});
|
|
47
50
|
},
|
|
48
51
|
],
|
|
@@ -69,9 +72,9 @@ const listFromArrayLike = (value) => {
|
|
|
69
72
|
const symbolGlobal = (ctx) => {
|
|
70
73
|
const symbol = native(ctx.builtins, {
|
|
71
74
|
name: "Symbol",
|
|
72
|
-
call: () =>
|
|
75
|
+
call: () => {
|
|
73
76
|
throw typeError("Symbol is not callable; only Symbol.asyncIterator and Symbol.iterator are available.");
|
|
74
|
-
}
|
|
77
|
+
},
|
|
75
78
|
callback: false,
|
|
76
79
|
});
|
|
77
80
|
constants(symbol, { asyncIterator: AsyncIteratorSymbol, iterator: IteratorSymbol });
|