@mark1russell7/vex 0.0.0-stage → 0.2.0
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/LICENSE +21 -0
- package/build/index.d.ts +884 -0
- package/build/index.d.ts.map +1 -0
- package/build/index.js +1839 -0
- package/build/index.js.map +1 -0
- package/package.json +44 -3
- package/src/builder.ts +649 -0
- package/src/deps.ts +33 -0
- package/src/domain.ts +135 -0
- package/src/errors.ts +102 -0
- package/src/evaluate.ts +628 -0
- package/src/index.ts +16 -0
- package/src/ir.ts +212 -0
- package/src/json.ts +76 -0
- package/src/list.ts +35 -0
- package/src/result.ts +44 -0
- package/src/sheet.ts +141 -0
- package/src/space.ts +322 -0
- package/src/trace.ts +37 -0
- package/src/traversal.ts +126 -0
- package/README.md +0 -3
package/src/evaluate.ts
ADDED
|
@@ -0,0 +1,628 @@
|
|
|
1
|
+
import { liftsAt, resolveOp, type AnyDomain, type ParamKind, type ResolvedOp } from "./domain.ts";
|
|
2
|
+
import { formatError, vexError, type ErrorKind, type VexError } from "./errors.ts";
|
|
3
|
+
import { children, type Axis, type Expr, type ExprOf } from "./ir.ts";
|
|
4
|
+
import { isListOp, isVexList, vexList, type ListItem, type ListOp, type ListOptions, type VexList } from "./list.ts";
|
|
5
|
+
import { fail, ok, type Result } from "./result.ts";
|
|
6
|
+
import { axisTargets, resolveAddr, type Position, type Space } from "./space.ts";
|
|
7
|
+
import type { Read, Trace, TraceEvent, TraceSink } from "./trace.ts";
|
|
8
|
+
|
|
9
|
+
/** A free function op. The interpreter gives it the values of all arguments. */
|
|
10
|
+
export type FreeFn = (...args: readonly unknown[]) => unknown;
|
|
11
|
+
|
|
12
|
+
/** The context of an extension handler. */
|
|
13
|
+
export interface ExtContext {
|
|
14
|
+
readonly space: Space;
|
|
15
|
+
readonly position: Position;
|
|
16
|
+
readonly path: readonly number[];
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** The handler of an extension expression kind. */
|
|
20
|
+
export type ExtHandler = (data: unknown, ctx: ExtContext) => Result<unknown>;
|
|
21
|
+
|
|
22
|
+
/** The options of an evaluation. */
|
|
23
|
+
export interface EvalOptions {
|
|
24
|
+
/** The space that the program reads. */
|
|
25
|
+
readonly space: Space;
|
|
26
|
+
/** The key where the evaluation starts. Relative references read here. */
|
|
27
|
+
readonly origin: string;
|
|
28
|
+
/** The domains. The interpreter finds the op of a value in the first domain that accepts the value. */
|
|
29
|
+
readonly domains?: readonly AnyDomain[];
|
|
30
|
+
/** Free function ops, for ops that are not domain ops. */
|
|
31
|
+
readonly fns?: Readonly<Record<string, FreeFn>>;
|
|
32
|
+
/** The handlers of extension expression kinds. */
|
|
33
|
+
readonly extensions?: Readonly<Record<string, ExtHandler>>;
|
|
34
|
+
/** Variables that the program can read with `v(name)`. */
|
|
35
|
+
readonly vars?: Readonly<Record<string, unknown>>;
|
|
36
|
+
/** A receiver of trace events. */
|
|
37
|
+
readonly trace?: TraceSink;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
type Env = ReadonlyMap<string, Result<unknown>>;
|
|
41
|
+
|
|
42
|
+
interface Frame {
|
|
43
|
+
readonly pos: Position;
|
|
44
|
+
readonly env: Env;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** The name of a special form. */
|
|
48
|
+
export type SpecialForm = "if" | "and" | "or" | "ifError";
|
|
49
|
+
|
|
50
|
+
/** The names of the special forms. Their arguments are not evaluated before the call. */
|
|
51
|
+
export const SPECIAL_FORMS: ReadonlySet<string> = new Set<SpecialForm>(["if", "and", "or", "ifError"]);
|
|
52
|
+
|
|
53
|
+
const isSpecialForm = (op: string): op is SpecialForm => SPECIAL_FORMS.has(op);
|
|
54
|
+
|
|
55
|
+
/** The options that a compiled program keeps: the domains, the free functions and the extension handlers. */
|
|
56
|
+
export type CompileOptions = Pick<EvalOptions, "domains" | "fns" | "extensions">;
|
|
57
|
+
|
|
58
|
+
/** The options of one run of a compiled program. */
|
|
59
|
+
export type RunOptions = Pick<EvalOptions, "space" | "origin" | "vars" | "trace">;
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* A compiled program: the expression as a tree of functions. A program evaluates many times at different origins,
|
|
63
|
+
* and over different spaces, without a new walk of the expression.
|
|
64
|
+
*/
|
|
65
|
+
export interface Program {
|
|
66
|
+
/** The expression of the program. */
|
|
67
|
+
readonly expr: Expr;
|
|
68
|
+
/** This method evaluates the program at an origin. It does not throw. */
|
|
69
|
+
run(opts: RunOptions): Result<unknown>;
|
|
70
|
+
/** This method evaluates the program at an origin, with a trace of each node. */
|
|
71
|
+
explain(opts: Omit<RunOptions, "trace">): Trace;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* This function compiles an expression. The result gives the same results and the same traces as `evaluate`,
|
|
76
|
+
* because `evaluate` uses it too.
|
|
77
|
+
*/
|
|
78
|
+
export function compile(expr: Expr, opts: CompileOptions = {}): Program {
|
|
79
|
+
const root = new Compiler(opts).node(expr, []);
|
|
80
|
+
const run = (r: RunOptions): Result<unknown> => {
|
|
81
|
+
const { space, origin } = r;
|
|
82
|
+
if (!space.has(origin)) return fail(vexError("unknown-key", `the space has no key "${origin}"`, { origin, focus: origin }));
|
|
83
|
+
const env = new Map<string, Result<unknown>>(Object.entries(r.vars ?? {}).map(([k, val]) => [k, ok(val)]));
|
|
84
|
+
try {
|
|
85
|
+
return root({ pos: { origin, focus: origin }, env }, { space, trace: r.trace });
|
|
86
|
+
} catch (thrown) {
|
|
87
|
+
// A defect in an extension handler or in a test of the interpreter itself. Totality still holds.
|
|
88
|
+
return fail(vexError("threw", "the evaluation threw an exception", { origin, focus: origin, thrown }));
|
|
89
|
+
}
|
|
90
|
+
};
|
|
91
|
+
return {
|
|
92
|
+
expr,
|
|
93
|
+
run,
|
|
94
|
+
explain: (r) => {
|
|
95
|
+
const sink: TraceSink = { events: [] };
|
|
96
|
+
const result = run({ ...r, trace: sink });
|
|
97
|
+
return { events: sink.events, result };
|
|
98
|
+
},
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// The cache of compiled programs: one entry for each expression object, for the last options.
|
|
103
|
+
const CACHE = new WeakMap<Expr, { readonly domains: unknown; readonly fns: unknown; readonly extensions: unknown; readonly program: Program }>();
|
|
104
|
+
|
|
105
|
+
function compiled(expr: Expr, opts: CompileOptions): Program {
|
|
106
|
+
const hit = CACHE.get(expr);
|
|
107
|
+
if (hit !== undefined && hit.domains === opts.domains && hit.fns === opts.fns && hit.extensions === opts.extensions) return hit.program;
|
|
108
|
+
const program = compile(expr, opts);
|
|
109
|
+
CACHE.set(expr, { domains: opts.domains, fns: opts.fns, extensions: opts.extensions, program });
|
|
110
|
+
return program;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** This function evaluates an expression at the origin of a space. It does not throw. */
|
|
114
|
+
export function evaluate(expr: Expr, opts: EvalOptions): Result<unknown> {
|
|
115
|
+
return compiled(expr, opts).run(opts);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** This function evaluates an expression and records a trace of each node. */
|
|
119
|
+
export function explain(expr: Expr, opts: Omit<EvalOptions, "trace">): Trace {
|
|
120
|
+
return compiled(expr, opts).explain(opts);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** The state of one run that the nodes read: the space and the trace sink. */
|
|
124
|
+
interface Ctx {
|
|
125
|
+
readonly space: Space;
|
|
126
|
+
readonly trace: TraceSink | undefined;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** A compiled node: it evaluates in a frame of a run. */
|
|
130
|
+
type Node = (f: Frame, c: Ctx) => Result<unknown>;
|
|
131
|
+
|
|
132
|
+
/** The static facts of a node for its trace events. */
|
|
133
|
+
interface Info {
|
|
134
|
+
readonly path: readonly number[];
|
|
135
|
+
readonly tag: Expr["tag"];
|
|
136
|
+
readonly label: string;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
class Compiler {
|
|
140
|
+
readonly #domains: readonly AnyDomain[];
|
|
141
|
+
readonly #fns: Readonly<Record<string, FreeFn>> | undefined;
|
|
142
|
+
readonly #extensions: Readonly<Record<string, ExtHandler>> | undefined;
|
|
143
|
+
|
|
144
|
+
constructor(opts: CompileOptions) {
|
|
145
|
+
this.#domains = opts.domains ?? [];
|
|
146
|
+
this.#fns = opts.fns;
|
|
147
|
+
this.#extensions = opts.extensions;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
#err(kind: ErrorKind, message: string, f: Frame, path: readonly number[], extra: { op?: string; causes?: readonly VexError[]; thrown?: unknown } = {}): Result<never> {
|
|
151
|
+
return fail(vexError(kind, message, { path, origin: f.pos.origin, focus: f.pos.focus, ...extra }));
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
#emit(c: Ctx, info: Info, f: Frame, result: Result<unknown>, reads?: readonly Read[]): Result<unknown> {
|
|
155
|
+
if (c.trace !== undefined) {
|
|
156
|
+
const event: TraceEvent = {
|
|
157
|
+
path: info.path,
|
|
158
|
+
tag: info.tag,
|
|
159
|
+
label: info.label,
|
|
160
|
+
origin: f.pos.origin,
|
|
161
|
+
focus: f.pos.focus,
|
|
162
|
+
...(reads === undefined ? {} : { reads }),
|
|
163
|
+
result,
|
|
164
|
+
};
|
|
165
|
+
c.trace.events.push(event);
|
|
166
|
+
}
|
|
167
|
+
return result;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** This method compiles the expression `e` at the position `path` of the tree. */
|
|
171
|
+
node(e: Expr, path: readonly number[]): Node {
|
|
172
|
+
const info: Info = { path, tag: e.tag, label: labelOf(e) };
|
|
173
|
+
switch (e.tag) {
|
|
174
|
+
case "lit": {
|
|
175
|
+
const r = ok(e.value);
|
|
176
|
+
return (f, c) => this.#emit(c, info, f, r);
|
|
177
|
+
}
|
|
178
|
+
case "ref":
|
|
179
|
+
return this.#ref(e, info);
|
|
180
|
+
case "var": {
|
|
181
|
+
const name = e.name;
|
|
182
|
+
return (f, c) => this.#emit(c, info, f, f.env.get(name) ?? this.#err("unbound", `the name "${name}" has no binding`, f, path));
|
|
183
|
+
}
|
|
184
|
+
case "let": {
|
|
185
|
+
const binds = Object.entries(e.bind).map(([name, be], i): readonly [string, Node] => [name, this.node(be, [...path, i])]);
|
|
186
|
+
const body = this.node(e.body, [...path, binds.length]);
|
|
187
|
+
return (f, c) => {
|
|
188
|
+
const env = new Map(f.env);
|
|
189
|
+
for (const [name, n] of binds) env.set(name, n(f, c));
|
|
190
|
+
return this.#emit(c, info, f, body({ pos: f.pos, env }, c));
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
case "rec": {
|
|
194
|
+
const names = Object.keys(e.fields);
|
|
195
|
+
const fields = this.#nodes(Object.values(e.fields), path);
|
|
196
|
+
return (f, c) => {
|
|
197
|
+
const values = this.#all(fields, f, c, path, "fields");
|
|
198
|
+
if (!values.ok) return this.#emit(c, info, f, values);
|
|
199
|
+
const out: Record<string, unknown> = {};
|
|
200
|
+
names.forEach((n, i) => {
|
|
201
|
+
out[n] = values.value[i];
|
|
202
|
+
});
|
|
203
|
+
return this.#emit(c, info, f, ok(Object.freeze(out)));
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
case "app":
|
|
207
|
+
return isSpecialForm(e.op) ? this.#special(e.op, this.#nodes(e.args, path), info) : this.#app(e.op, this.#nodes(e.args, path), info);
|
|
208
|
+
case "each":
|
|
209
|
+
return this.#each(e, info);
|
|
210
|
+
case "ext": {
|
|
211
|
+
const handler = Object.hasOwn(this.#extensions ?? {}, e.kind) ? this.#extensions?.[e.kind] : undefined;
|
|
212
|
+
const { kind, data } = e;
|
|
213
|
+
if (handler === undefined) return (f, c) => this.#emit(c, info, f, this.#err("unknown-op", `no handler for the extension kind "${kind}"`, f, path));
|
|
214
|
+
return (f, c) =>
|
|
215
|
+
this.#emit(c, info, f, this.#locate(this.#guard(() => handler(data, { space: c.space, position: f.pos, path }), f, path, kind), f, path));
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
#nodes(es: readonly Expr[], path: readonly number[]): readonly Node[] {
|
|
221
|
+
return es.map((x, i) => this.node(x, [...path, i]));
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** This method gives an error of a handler the path, the origin and the focus of its node, if it has no origin. */
|
|
225
|
+
#locate(r: Result<unknown>, f: Frame, path: readonly number[]): Result<unknown> {
|
|
226
|
+
if (r.ok || r.error.origin !== undefined) return r;
|
|
227
|
+
return fail({ ...r.error, path, origin: f.pos.origin, focus: f.pos.focus });
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
#guard(run: () => Result<unknown>, f: Frame, path: readonly number[], op: string): Result<unknown> {
|
|
231
|
+
try {
|
|
232
|
+
return run();
|
|
233
|
+
} catch (thrown) {
|
|
234
|
+
return this.#err("threw", `"${op}" threw an exception`, f, path, { op, thrown });
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
#ref(e: ExprOf<"ref">, info: Info): Node {
|
|
239
|
+
const { path } = info;
|
|
240
|
+
const segs = e.path;
|
|
241
|
+
const at = e.at ?? [];
|
|
242
|
+
const label = segs.join(".");
|
|
243
|
+
const steps = segs.map((seg, i) => ({ seg, where: segs.slice(0, i + 1).join("."), valid: isFieldName(seg) }));
|
|
244
|
+
return (f, c) => {
|
|
245
|
+
let key = f.pos.focus;
|
|
246
|
+
if (at.length > 0) {
|
|
247
|
+
const where = resolveAddr(c.space, f.pos, at);
|
|
248
|
+
if (!where.ok) return this.#emit(c, info, f, fail({ ...where.error, path }));
|
|
249
|
+
key = where.value;
|
|
250
|
+
}
|
|
251
|
+
const failed = (r: Result<unknown>): Result<unknown> => this.#emit(c, info, f, r, [{ key, path: segs, ok: false }]);
|
|
252
|
+
const missing = (where: string): Result<unknown> => failed(this.#err("missing-field", `the record at "${key}" has no value at "${where}"`, f, path));
|
|
253
|
+
let value: unknown = c.space.get(key);
|
|
254
|
+
if (value === undefined || value === null) return missing(label === "" ? "(record)" : label);
|
|
255
|
+
for (const { seg, where, valid } of steps) {
|
|
256
|
+
if ((typeof value !== "object" && typeof value !== "function") || !valid) return missing(where);
|
|
257
|
+
try {
|
|
258
|
+
value = Reflect.get(value, seg);
|
|
259
|
+
} catch (thrown) {
|
|
260
|
+
return failed(this.#err("threw", `reading "${where}" at "${key}" threw an exception`, f, path, { thrown }));
|
|
261
|
+
}
|
|
262
|
+
if (value === undefined || value === null) return missing(where);
|
|
263
|
+
}
|
|
264
|
+
return this.#emit(c, info, f, ok(value), [{ key, path: segs, ok: true }]);
|
|
265
|
+
};
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/** This method evaluates nodes applicatively. One failure stays as it is. Two or more give `#ARGS`. */
|
|
269
|
+
#all(nodes: readonly Node[], f: Frame, c: Ctx, path: readonly number[], what: string): Result<readonly unknown[]> {
|
|
270
|
+
const values: unknown[] = [];
|
|
271
|
+
let first: VexError | undefined;
|
|
272
|
+
let errors: VexError[] | undefined;
|
|
273
|
+
for (const n of nodes) {
|
|
274
|
+
const r = n(f, c);
|
|
275
|
+
if (r.ok) values.push(r.value);
|
|
276
|
+
else if (first === undefined) first = r.error;
|
|
277
|
+
else (errors ??= [first]).push(r.error);
|
|
278
|
+
}
|
|
279
|
+
if (first === undefined) return ok(values);
|
|
280
|
+
return errors === undefined ? fail(first) : this.#err("args", `${errors.length} ${what} failed`, f, path, { causes: errors });
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
#each(e: ExprOf<"each">, info: Info): Node {
|
|
284
|
+
const { path } = info;
|
|
285
|
+
const targets = this.#targets(e.axis, path, { next: 1 });
|
|
286
|
+
const body = this.node(e.body, [...path, 0]);
|
|
287
|
+
return (f, c) => {
|
|
288
|
+
const ts = targets(f, c);
|
|
289
|
+
if (!ts.ok) return this.#emit(c, info, f, ts);
|
|
290
|
+
const items: ListItem[] = ts.value.map(({ key, test }) => {
|
|
291
|
+
if (test !== undefined && !test.ok) return { key, result: test };
|
|
292
|
+
return { key, result: body({ pos: { origin: f.pos.origin, focus: key }, env: f.env }, c) };
|
|
293
|
+
});
|
|
294
|
+
return this.#emit(c, info, f, ok(vexList(items)));
|
|
295
|
+
};
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/** This method compiles the targets of an axis. For `where`, a failed test keeps the target with its error. */
|
|
299
|
+
#targets(a: Axis, path: readonly number[], counter: { next: number }): (f: Frame, c: Ctx) => Result<readonly { readonly key: string; readonly test?: Result<unknown> }[]> {
|
|
300
|
+
if (a.t !== "where") {
|
|
301
|
+
return (f, c) => {
|
|
302
|
+
const keys = axisTargets(c.space, f.pos, a);
|
|
303
|
+
return keys.ok ? ok(keys.value.map((key) => ({ key }))) : fail({ ...keys.error, path });
|
|
304
|
+
};
|
|
305
|
+
}
|
|
306
|
+
const inner = this.#targets(a.axis, path, counter);
|
|
307
|
+
const testPath = [...path, counter.next++];
|
|
308
|
+
const test = this.node(a.test, testPath);
|
|
309
|
+
return (f, c) => {
|
|
310
|
+
const ts = inner(f, c);
|
|
311
|
+
if (!ts.ok) return ts;
|
|
312
|
+
const out: { key: string; test?: Result<unknown> }[] = [];
|
|
313
|
+
for (const t of ts.value) {
|
|
314
|
+
if (t.test !== undefined && !t.test.ok) {
|
|
315
|
+
out.push(t);
|
|
316
|
+
continue;
|
|
317
|
+
}
|
|
318
|
+
const at: Frame = { pos: { origin: f.pos.origin, focus: t.key }, env: f.env };
|
|
319
|
+
const r = test(at, c);
|
|
320
|
+
if (!r.ok) out.push({ key: t.key, test: r });
|
|
321
|
+
else if (r.value === true) out.push({ key: t.key });
|
|
322
|
+
else if (r.value !== false) {
|
|
323
|
+
out.push({ key: t.key, test: this.#err("kind-mismatch", `the test of "where" gave a ${typeof r.value}, not a boolean`, at, testPath) });
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
return ok(out);
|
|
327
|
+
};
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
#app(op: string, args: readonly Node[], info: Info): Node {
|
|
331
|
+
const { path } = info;
|
|
332
|
+
const listOp = isListOp(op) ? op : undefined;
|
|
333
|
+
const fn = this.#fns !== undefined && Object.hasOwn(this.#fns, op) ? this.#fns[op] : undefined;
|
|
334
|
+
return (f, c) => {
|
|
335
|
+
const all = this.#all(args, f, c, path, "arguments");
|
|
336
|
+
if (!all.ok) return this.#emit(c, info, f, all);
|
|
337
|
+
const values = all.value;
|
|
338
|
+
const self = values[0];
|
|
339
|
+
if (listOp !== undefined && isVexList(self)) return this.#emit(c, info, f, this.#listOp(listOp, self, values.slice(1), f, path));
|
|
340
|
+
let accepted: AnyDomain | undefined;
|
|
341
|
+
if (values.length > 0) {
|
|
342
|
+
for (const d of this.#domains) {
|
|
343
|
+
if (!safeIs(d, self)) continue;
|
|
344
|
+
accepted ??= d;
|
|
345
|
+
const resolved = resolveOp(d, self, op);
|
|
346
|
+
if (resolved !== undefined) return this.#emit(c, info, f, this.#call(resolved, op, values.slice(1), f, path));
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
if (fn !== undefined) return this.#emit(c, info, f, this.#checkResult(this.#invoke(() => fn(...values), op, f, path), f, path, op));
|
|
350
|
+
if (accepted !== undefined) return this.#emit(c, info, f, this.#err("unknown-op", `the domain "${accepted.name}" has no op "${op}"`, f, path, { op }));
|
|
351
|
+
if (values.length === 0) return this.#emit(c, info, f, this.#err("unknown-op", `there is no function "${op}"`, f, path, { op }));
|
|
352
|
+
return this.#emit(c, info, f, this.#err("not-instance", `no domain accepts the receiver of "${op}" (${describeType(self)})`, f, path, { op }));
|
|
353
|
+
};
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
#special(op: SpecialForm, args: readonly Node[], info: Info): Node {
|
|
357
|
+
const { path } = info;
|
|
358
|
+
const arg = (i: number, f: Frame, c: Ctx): Result<unknown> => {
|
|
359
|
+
const n = args[i];
|
|
360
|
+
return n === undefined ? this.#err("bad-expression", `"${op}" needs argument ${i + 1}`, f, path, { op }) : n(f, c);
|
|
361
|
+
};
|
|
362
|
+
const bool = (i: number, f: Frame, c: Ctx): Result<boolean> => {
|
|
363
|
+
const r = arg(i, f, c);
|
|
364
|
+
if (!r.ok) return r;
|
|
365
|
+
return typeof r.value === "boolean" ? ok(r.value) : this.#err("kind-mismatch", `argument ${i + 1} of "${op}" is a ${describeType(r.value)}, not a boolean`, f, path, { op });
|
|
366
|
+
};
|
|
367
|
+
switch (op) {
|
|
368
|
+
case "if":
|
|
369
|
+
return (f, c) => {
|
|
370
|
+
const cond = bool(0, f, c);
|
|
371
|
+
return this.#emit(c, info, f, cond.ok ? arg(cond.value ? 1 : 2, f, c) : cond);
|
|
372
|
+
};
|
|
373
|
+
case "and":
|
|
374
|
+
case "or": {
|
|
375
|
+
const stop = op === "or";
|
|
376
|
+
return (f, c) => {
|
|
377
|
+
if (args.length === 0) return this.#emit(c, info, f, this.#err("bad-expression", `"${op}" needs at least 1 argument`, f, path, { op }));
|
|
378
|
+
for (let i = 0; i < args.length; i++) {
|
|
379
|
+
const b = bool(i, f, c);
|
|
380
|
+
if (!b.ok) return this.#emit(c, info, f, b);
|
|
381
|
+
if (b.value === stop) return this.#emit(c, info, f, ok(b.value));
|
|
382
|
+
}
|
|
383
|
+
return this.#emit(c, info, f, ok(!stop));
|
|
384
|
+
};
|
|
385
|
+
}
|
|
386
|
+
case "ifError":
|
|
387
|
+
return (f, c) => {
|
|
388
|
+
const first = arg(0, f, c);
|
|
389
|
+
return this.#emit(c, info, f, first.ok ? first : arg(1, f, c));
|
|
390
|
+
};
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
#call(op: ResolvedOp, name: string, rest: readonly unknown[], f: Frame, path: readonly number[]): Result<unknown> {
|
|
395
|
+
const { domain, spec } = op;
|
|
396
|
+
const lift = spec.liftScalar;
|
|
397
|
+
const from = domain.fromScalar;
|
|
398
|
+
let callArgs: readonly unknown[] = rest;
|
|
399
|
+
if (lift !== undefined && lift !== false && from !== undefined) {
|
|
400
|
+
const lifted = this.#invoke(() => rest.map((a, i): unknown => (typeof a === "number" && liftsAt(lift, i) ? from(a) : a)), `${domain.name}.fromScalar`, f, path);
|
|
401
|
+
if (!lifted.ok) return lifted;
|
|
402
|
+
callArgs = lifted.value as readonly unknown[];
|
|
403
|
+
}
|
|
404
|
+
if (spec.params !== undefined) {
|
|
405
|
+
for (let i = 0; i < callArgs.length; i++) {
|
|
406
|
+
const kind = spec.params[i] ?? "any";
|
|
407
|
+
if (!matchesKind(kind, callArgs[i], domain)) {
|
|
408
|
+
const k: ErrorKind = kind === "domain" ? "not-instance" : "kind-mismatch";
|
|
409
|
+
return this.#err(k, `argument ${i + 1} of "${name}" is a ${describeType(callArgs[i])}, not a ${kind === "domain" ? domain.name : kind}`, f, path, { op: name });
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
return this.#checkResult(this.#invoke(() => op.call(callArgs), name, f, path), f, path, name);
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
#invoke(run: () => unknown, op: string, f: Frame, path: readonly number[]): Result<unknown> {
|
|
417
|
+
try {
|
|
418
|
+
return ok(run());
|
|
419
|
+
} catch (thrown) {
|
|
420
|
+
return this.#err("threw", `"${op}" threw an exception`, f, path, { op, thrown });
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
/** This method checks the value that an op gave: no `undefined`, finite numbers, and valid domain values. */
|
|
425
|
+
#checkResult(r: Result<unknown>, f: Frame, path: readonly number[], op: string): Result<unknown> {
|
|
426
|
+
if (!r.ok) return r;
|
|
427
|
+
const value = r.value;
|
|
428
|
+
const extra = { op };
|
|
429
|
+
if (value === undefined || value === null) return this.#err("undefined-result", `"${op}" gave no value`, f, path, extra);
|
|
430
|
+
if (typeof value === "number" && !Number.isFinite(value)) return this.#err("not-finite", `"${op}" gave ${value}`, f, path, extra);
|
|
431
|
+
const d = this.#domains.find((dom) => safeIs(dom, value));
|
|
432
|
+
if (d?.valid !== undefined) {
|
|
433
|
+
let valid: boolean;
|
|
434
|
+
try {
|
|
435
|
+
valid = d.valid(value);
|
|
436
|
+
} catch (thrown) {
|
|
437
|
+
return this.#err("threw", `the "valid" check of "${d.name}" threw an exception`, f, path, { ...extra, thrown });
|
|
438
|
+
}
|
|
439
|
+
if (!valid) return this.#err("invalid-value", `"${op}" gave a value that is not a valid ${d.name}`, f, path, extra);
|
|
440
|
+
}
|
|
441
|
+
return r;
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
#listOp(op: ListOp, list: VexList, rest: readonly unknown[], f: Frame, path: readonly number[]): Result<unknown> {
|
|
445
|
+
const optsArg = op === "reduce" ? rest[1] : rest[0];
|
|
446
|
+
const strict = isOptions(optsArg) && optsArg.strict === true;
|
|
447
|
+
const firstError = list.items.find((it) => !it.result.ok)?.result;
|
|
448
|
+
if (strict && firstError !== undefined && !firstError.ok) return fail(firstError.error);
|
|
449
|
+
const okValues = list.items.flatMap((it) => (it.result.ok ? [it.result.value] : []));
|
|
450
|
+
const numbers = (): Result<readonly number[]> => {
|
|
451
|
+
const bad = okValues.find((x) => typeof x !== "number");
|
|
452
|
+
return bad === undefined ? ok(okValues as readonly number[]) : this.#err("kind-mismatch", `"${op}" needs numbers, but an item is a ${describeType(bad)}`, f, path, { op });
|
|
453
|
+
};
|
|
454
|
+
const booleans = (): Result<readonly boolean[]> => {
|
|
455
|
+
const bad = okValues.find((x) => typeof x !== "boolean");
|
|
456
|
+
return bad === undefined ? ok(okValues as readonly boolean[]) : this.#err("kind-mismatch", `"${op}" needs booleans, but an item is a ${describeType(bad)}`, f, path, { op });
|
|
457
|
+
};
|
|
458
|
+
const empty = (): Result<never> => this.#err("empty", `"${op}" has no values to work with`, f, path, { op });
|
|
459
|
+
switch (op) {
|
|
460
|
+
case "count":
|
|
461
|
+
return ok(okValues.length);
|
|
462
|
+
case "values":
|
|
463
|
+
return ok(Object.freeze([...okValues]));
|
|
464
|
+
case "keys":
|
|
465
|
+
return ok(Object.freeze(list.items.filter((it) => it.result.ok).map((it) => it.key)));
|
|
466
|
+
case "errors":
|
|
467
|
+
return ok(Object.freeze(list.items.flatMap((it) => (it.result.ok ? [] : [it.result.error]))));
|
|
468
|
+
case "first":
|
|
469
|
+
return okValues.length > 0 ? ok(okValues[0]) : empty();
|
|
470
|
+
case "sum": {
|
|
471
|
+
const n = numbers();
|
|
472
|
+
return n.ok ? this.#checkResult(ok(n.value.reduce((s, x) => s + x, 0)), f, path, op) : n;
|
|
473
|
+
}
|
|
474
|
+
case "mean": {
|
|
475
|
+
const n = numbers();
|
|
476
|
+
if (!n.ok) return n;
|
|
477
|
+
return n.value.length === 0 ? empty() : this.#checkResult(ok(n.value.reduce((s, x) => s + x, 0) / n.value.length), f, path, op);
|
|
478
|
+
}
|
|
479
|
+
case "min":
|
|
480
|
+
case "max": {
|
|
481
|
+
const n = numbers();
|
|
482
|
+
if (!n.ok) return n;
|
|
483
|
+
if (n.value.length === 0) return empty();
|
|
484
|
+
return ok(n.value.reduce((best, x) => (op === "min" ? Math.min(best, x) : Math.max(best, x))));
|
|
485
|
+
}
|
|
486
|
+
case "any":
|
|
487
|
+
case "all":
|
|
488
|
+
case "none": {
|
|
489
|
+
const b = booleans();
|
|
490
|
+
if (!b.ok) return b;
|
|
491
|
+
if (op === "any") return ok(b.value.some((x) => x));
|
|
492
|
+
if (op === "all") return ok(b.value.every((x) => x));
|
|
493
|
+
return ok(!b.value.some((x) => x));
|
|
494
|
+
}
|
|
495
|
+
case "reduce":
|
|
496
|
+
return this.#reduce(rest[0], okValues, f, path);
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
/** This method folds the values with a domain op, from the left. An empty list gives the identity of the op. */
|
|
501
|
+
#reduce(opName: unknown, values: readonly unknown[], f: Frame, path: readonly number[]): Result<unknown> {
|
|
502
|
+
if (typeof opName !== "string") return this.#err("kind-mismatch", `"reduce" needs an op name, but got a ${describeType(opName)}`, f, path, { op: "reduce" });
|
|
503
|
+
if (values.length === 0) {
|
|
504
|
+
for (const d of this.#domains) {
|
|
505
|
+
const id = (d.ops[opName] as { identity?: () => unknown } | undefined)?.identity;
|
|
506
|
+
if (id !== undefined && Object.hasOwn(d.ops, opName)) return this.#invoke(id, opName, f, path);
|
|
507
|
+
}
|
|
508
|
+
return this.#err("empty", `"reduce" with "${opName}" has no values and the op has no identity`, f, path, { op: opName });
|
|
509
|
+
}
|
|
510
|
+
let acc: unknown = values[0];
|
|
511
|
+
for (let i = 1; i < values.length; i++) {
|
|
512
|
+
const d = this.#domains.find((dom) => safeIs(dom, acc) && resolveOp(dom, acc, opName) !== undefined);
|
|
513
|
+
const op = d === undefined ? undefined : resolveOp(d, acc, opName);
|
|
514
|
+
if (op === undefined) return this.#err("unknown-op", `no domain gives "${opName}" for a ${describeType(acc)}`, f, path, { op: opName });
|
|
515
|
+
const r = this.#call(op, opName, [values[i]], f, path);
|
|
516
|
+
if (!r.ok) return r;
|
|
517
|
+
acc = r.value;
|
|
518
|
+
}
|
|
519
|
+
return ok(acc);
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
const FORBIDDEN_FIELDS = new Set(["__proto__", "constructor", "prototype"]);
|
|
524
|
+
const isFieldName = (seg: string): boolean => seg.length > 0 && !FORBIDDEN_FIELDS.has(seg);
|
|
525
|
+
|
|
526
|
+
/** This function runs the `is` test of a domain. A test that throws counts as `false`. */
|
|
527
|
+
function safeIs(d: AnyDomain, value: unknown): boolean {
|
|
528
|
+
try {
|
|
529
|
+
return d.is(value);
|
|
530
|
+
} catch {
|
|
531
|
+
return false;
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
const isOptions = (u: unknown): u is ListOptions => typeof u === "object" && u !== null && !Array.isArray(u) && !isVexList(u);
|
|
536
|
+
|
|
537
|
+
function matchesKind(kind: ParamKind, value: unknown, domain: AnyDomain): boolean {
|
|
538
|
+
switch (kind) {
|
|
539
|
+
case "domain":
|
|
540
|
+
return safeIs(domain, value);
|
|
541
|
+
case "number":
|
|
542
|
+
return typeof value === "number";
|
|
543
|
+
case "boolean":
|
|
544
|
+
return typeof value === "boolean";
|
|
545
|
+
case "string":
|
|
546
|
+
return typeof value === "string";
|
|
547
|
+
case "any":
|
|
548
|
+
return true;
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
/** This function gives a short name for the type of a value, for error messages. */
|
|
553
|
+
export function describeType(u: unknown): string {
|
|
554
|
+
if (u === null) return "null";
|
|
555
|
+
if (Array.isArray(u)) return "array";
|
|
556
|
+
if (isVexList(u)) return "list";
|
|
557
|
+
if (typeof u === "object") {
|
|
558
|
+
const name = (Object.getPrototypeOf(u) as { constructor?: { name?: unknown } } | null)?.constructor?.name;
|
|
559
|
+
return typeof name === "string" && name !== "Object" ? name : "object";
|
|
560
|
+
}
|
|
561
|
+
return typeof u;
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
/** This function gives the label of a node, for traces. */
|
|
565
|
+
export function labelOf(e: Expr): string {
|
|
566
|
+
switch (e.tag) {
|
|
567
|
+
case "lit":
|
|
568
|
+
return previewValue(e.value);
|
|
569
|
+
case "ref":
|
|
570
|
+
return e.path.length === 0 ? "(record)" : e.path.join(".");
|
|
571
|
+
case "app":
|
|
572
|
+
return e.op;
|
|
573
|
+
case "let":
|
|
574
|
+
return `let ${Object.keys(e.bind).join(", ")}`;
|
|
575
|
+
case "var":
|
|
576
|
+
return e.name;
|
|
577
|
+
case "rec":
|
|
578
|
+
return `{ ${Object.keys(e.fields).join(", ")} }`;
|
|
579
|
+
case "each":
|
|
580
|
+
return `each ${e.axis.t}`;
|
|
581
|
+
case "ext":
|
|
582
|
+
return e.kind;
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
/** This function gives a short text for a value. */
|
|
587
|
+
export function previewValue(u: unknown): string {
|
|
588
|
+
if (typeof u === "string") return JSON.stringify(u);
|
|
589
|
+
if (typeof u === "number" || typeof u === "boolean" || u === null || u === undefined) return String(u);
|
|
590
|
+
if (isVexList(u)) return `list(${u.items.length})`;
|
|
591
|
+
try {
|
|
592
|
+
const json = JSON.stringify(u);
|
|
593
|
+
if (json !== undefined) return json.length > 60 ? `${json.slice(0, 57)}...` : json;
|
|
594
|
+
} catch {
|
|
595
|
+
// A value with cycles has no JSON form.
|
|
596
|
+
}
|
|
597
|
+
return describeType(u);
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
// The reads of a reference show the key and the path, for example "read B.position" or "no value at A.mass".
|
|
601
|
+
const formatRead = (r: Read): string => `${r.ok ? "read" : "no value at"} ${r.key}.${r.path.length === 0 ? "(record)" : r.path.join(".")}`;
|
|
602
|
+
|
|
603
|
+
/**
|
|
604
|
+
* This function gives a text form of a trace. Each event has one line, in finish order. The indent of a line
|
|
605
|
+
* shows the depth of the node. A domain with `show` gives the text of its values. The golden tests compare this text.
|
|
606
|
+
*/
|
|
607
|
+
export function formatTrace(trace: Trace, domains: readonly AnyDomain[] = []): string {
|
|
608
|
+
const show = (u: unknown): string => {
|
|
609
|
+
if (isVexList(u)) return `[${u.items.map((it) => `${it.key}: ${result(it.result)}`).join(", ")}]`;
|
|
610
|
+
const d = domains.find((dom) => dom.show !== undefined && safeIs(dom, u));
|
|
611
|
+
try {
|
|
612
|
+
if (d?.show !== undefined) return d.show(u);
|
|
613
|
+
} catch {
|
|
614
|
+
// A show function that throws gives the default text.
|
|
615
|
+
}
|
|
616
|
+
return previewValue(u);
|
|
617
|
+
};
|
|
618
|
+
const result = (r: Result<unknown>): string => (r.ok ? show(r.value) : formatError(r.error));
|
|
619
|
+
const line = (e: TraceEvent): string => {
|
|
620
|
+
const reads = e.reads === undefined ? "" : ` [${e.reads.map(formatRead).join(", ")}]`;
|
|
621
|
+
return `${" ".repeat(e.path.length)}${e.label} @${e.focus}${reads} = ${result(e.result)}`;
|
|
622
|
+
};
|
|
623
|
+
const lines = trace.events.map(line);
|
|
624
|
+
return [...lines, `result = ${result(trace.result)}`, ""].join("\n");
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
/** This function gives the number of nodes of an expression. */
|
|
628
|
+
export const sizeOf = (e: Expr): number => 1 + children(e).reduce((s, c) => s + sizeOf(c), 0);
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The kernel of Vex: spaces, addresses, the expression IR, domains, the interpreter and its folds.
|
|
3
|
+
*/
|
|
4
|
+
export * from "./result.ts";
|
|
5
|
+
export * from "./errors.ts";
|
|
6
|
+
export * from "./ir.ts";
|
|
7
|
+
export * from "./space.ts";
|
|
8
|
+
export * from "./domain.ts";
|
|
9
|
+
export * from "./list.ts";
|
|
10
|
+
export * from "./trace.ts";
|
|
11
|
+
export * from "./evaluate.ts";
|
|
12
|
+
export * from "./deps.ts";
|
|
13
|
+
export * from "./json.ts";
|
|
14
|
+
export * from "./traversal.ts";
|
|
15
|
+
export * from "./sheet.ts";
|
|
16
|
+
export * from "./builder.ts";
|