@mark1russell7/vex-compiler 0.0.0-stage → 0.8.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/src/module.ts ADDED
@@ -0,0 +1,1723 @@
1
+ /**
2
+ * Standalone modules (docs/COMPILER.md §4.4 and §6). `emitModule` prints a program as an ES module that has no import of
3
+ * Vex. A host that guarantees the kinds of its input uses it without the interpreter, for example ireko at build time.
4
+ *
5
+ * The module gives the results of the interpreter for each input that keeps the schema. It checks the schema once, at
6
+ * the start of a run, and an input against the schema throws a `VexContractError`. An error of Vex is a value too:
7
+ * the run gives `VEX_ERROR` at its key.
8
+ *
9
+ * The printer gives statements and loops, as a person writes them. A binding is a variable, and a list op is a `for`
10
+ * loop with a running value. An error of Vex is a thrown sentinel. A binding, `ifError` and an item of a list op catch
11
+ * it, as in the interpreter. A node of the memo and the key of the run catch it too. Each op is the function of its
12
+ * domain, as text, so it has the bits of the interpreter (§4.2).
13
+ *
14
+ * A part of the program that depends on no key of the space is a constant of the run. The module evaluates it once,
15
+ * before the loop over the keys. A node of the memo is one function of its other keys, with a map of its values. The
16
+ * nodes with the same expression share the function.
17
+ *
18
+ * The printer takes a part of the language. It takes an array space of records, the fields and the variables of the
19
+ * schema, and the axes `all`, `others` and `window`. The kinds of each op site must decide its op. Another construct
20
+ * gives a reason, not code.
21
+ */
22
+ import { addrExprs, children, isFieldName, lit, moveExpr, shapeError, type AnyDomain, type Axis, type Expr, type ExprOf, type Move, type Names, type PrimitiveKind } from "@mark1russell7/vex";
23
+ import { factsOf, kindOfDomain, primitiveOf, type Facts, type Kind, type Schema } from "./facts.ts";
24
+ import { memoNodes } from "./memo.ts";
25
+
26
+ /** The options of a standalone module. */
27
+ export interface ModuleOptions {
28
+ readonly domains?: readonly AnyDomain[];
29
+ /** The kinds of the fields of the records and of the variables. A module reads only the names of its schema. */
30
+ readonly schema: Schema;
31
+ /** The name of the function that the module exports. The default is `run`. */
32
+ readonly name?: string;
33
+ }
34
+
35
+ /** The source of a standalone module, or the reason that the program cannot be one. */
36
+ export type Emitted = { readonly ok: true; readonly source: string } | { readonly ok: false; readonly reason: string };
37
+
38
+ /** The error of a construct that a standalone module does not have. */
39
+ class NotStandalone extends Error {}
40
+
41
+ /**
42
+ * A value of the printer: its code, its kind if the printer knows it, and true when its code cannot throw. A literal,
43
+ * a variable of the schema and a field of the schema at the focus or at the origin cannot throw.
44
+ */
45
+ interface Value {
46
+ readonly code: string;
47
+ readonly kind: Kind | undefined;
48
+ readonly safe: boolean;
49
+ /** For the read of a name that can hold the error sentinel: the name itself, which holds the value or the sentinel. */
50
+ readonly held?: string;
51
+ /**
52
+ * The levels of the keys that the value depends on: 1 for the key of the run, and one more for each axis around it.
53
+ * A value with no levels is a constant of the run.
54
+ */
55
+ readonly deps: ReadonlySet<number>;
56
+ /** True for a literal and for the read of a name: a constant of the run with such code needs no variable of its own. */
57
+ readonly plain?: boolean;
58
+ /** For a list (LIST.VALUE): the kind of its items. The code is an array of pairs of a key and a value or the sentinel. */
59
+ readonly list?: ListInfo | undefined;
60
+ }
61
+
62
+ /** The facts of a list of the code: the kind of the values of its items, if the printer knows it. */
63
+ interface ListInfo {
64
+ readonly item: Kind | undefined;
65
+ }
66
+
67
+ /** The code of a node: the statements before its value, and its value. `safe` covers the statements too. */
68
+ interface Code {
69
+ readonly s: readonly string[];
70
+ readonly v: Value;
71
+ }
72
+
73
+ /** A name of the program in the code: its variable, its kind, true when it can hold the error sentinel, and its levels. */
74
+ interface Name {
75
+ readonly code: string;
76
+ readonly kind: Kind | undefined;
77
+ readonly lazy: boolean;
78
+ readonly deps: ReadonlySet<number>;
79
+ readonly list?: ListInfo | undefined;
80
+ }
81
+
82
+ /** An argument of a call: its code, its kind and its levels. */
83
+ interface Arg {
84
+ readonly code: string;
85
+ readonly kind: Kind | undefined;
86
+ readonly deps: ReadonlySet<number>;
87
+ }
88
+
89
+ /** The levels of a constant of the run. */
90
+ const NO_DEPS: ReadonlySet<number> = new Set();
91
+
92
+ /** This function gives the levels of some codes together. */
93
+ const depsOf = (...xs: readonly Code[]): ReadonlySet<number> => new Set(xs.flatMap((x) => [...x.v.deps]));
94
+
95
+ /** This function gives the statements of some codes, in order. */
96
+ const stmtsOf = (...xs: readonly Code[]): string[] => xs.flatMap((x) => x.s);
97
+
98
+ /** This function indents some statements by one level. */
99
+ const ind = (xs: readonly string[]): string[] => xs.map((x) => ` ${x}`);
100
+
101
+ /**
102
+ * The lexical position of a node: the code of the index of its origin and of its focus, and its names. It also has the
103
+ * keys of its node of the memo. A node of the memo reads neither its origin nor its focus, so these are undefined there.
104
+ */
105
+ interface Ctx {
106
+ readonly origin: string | undefined;
107
+ readonly focus: string | undefined;
108
+ /** The level of the focus: 1 at the key of the run, and one more in each axis. */
109
+ readonly level: number;
110
+ /** The level of the origin: 1 at the key of the run, and the marker of the origin in the body of a function. */
111
+ readonly originLevel: number;
112
+ readonly env: ReadonlyMap<string, Name>;
113
+ readonly keys: ReadonlyMap<Expr, Name>;
114
+ /** The bound functions (FN.BIND), with the context of their binding. */
115
+ readonly fns: ReadonlyMap<string, BoundFn>;
116
+ }
117
+
118
+ /**
119
+ * A bound function of the printer (FN.BIND): its node and the context of its binding. It also has one printed
120
+ * JavaScript function for each signature of the arguments of its calls.
121
+ */
122
+ interface BoundFn {
123
+ /** The number of the binding. Two functions with one name are two functions, so a key of a constant needs it. */
124
+ readonly id: number;
125
+ readonly fn: ExprOf<"fn">;
126
+ readonly ctx: Ctx;
127
+ /** The printed function for each signature: the kind of each argument. */
128
+ readonly specs: Map<string, Spec>;
129
+ /** The declarations of the printed functions that read names of the place of the binding. The let prints them. */
130
+ readonly decls: string[];
131
+ /** True when a printed function of the binding is at the place of the binding, not at the start of a run. */
132
+ local: boolean;
133
+ }
134
+
135
+ /**
136
+ * A printed function. The levels of the value of its body have a marker for the origin, for the focus and for each
137
+ * parameter. A call replaces each marker with the levels at the call.
138
+ */
139
+ interface Spec {
140
+ readonly name: string;
141
+ readonly kind: Kind | undefined;
142
+ readonly safe: boolean;
143
+ readonly deps: ReadonlySet<number>;
144
+ readonly origin: number;
145
+ readonly focus: number;
146
+ readonly param: number;
147
+ /** True when the body reads only constants of the run, its parameters and its position, so it is at the start of a run. */
148
+ readonly global: boolean;
149
+ }
150
+
151
+ /** The name of a helper of the generated code. */
152
+ type Helper = "F" | "C" | "T" | "L" | "Q" | "G" | "B" | "U" | "X" | "I" | "K" | "M" | "M1" | "S" | "V" | "SB" | "TK" | "NT";
153
+
154
+ /** The helpers of the generated code. A module has only the helpers that it uses. */
155
+ const HELPERS: Readonly<Record<Exclude<Helper, "S">, string>> = {
156
+ F: "function F() { throw E; }",
157
+ C: "function C(m) { throw new VexContractError(m); }",
158
+ // An exception of an op is an error of Vex too, as in the interpreter. Only the checks of the contract throw a
159
+ // VexContractError, and they come before the run, so each catch of the run gives the sentinel.
160
+ T: "function T(f) { try { return f(); } catch { return E; } }",
161
+ // A constant of the run with a loop evaluates on its first read, so a loop in a branch that no run takes costs nothing.
162
+ L: "function L(f) { let done = false, v; return () => { if (!done) { done = true; try { v = f(); } catch { v = E; } } return v; }; }",
163
+ // A column of the run: the value of an expression at each record, on its first read.
164
+ Q: "function Q(f) { const m = []; return (j) => { let v = m[j]; if (v === undefined) { try { v = f(j); } catch { v = E; } m[j] = v; } return v; }; }",
165
+ G: "function G(x) { return x === E ? F() : x; }",
166
+ B: 'function B(x) { return typeof x === "boolean" ? x : F(); }',
167
+ U: 'function U(x) { return typeof x === "number" ? x : F(); }',
168
+ X: "function X(t, n) { return t >= 0 && t < n ? t : F(); }",
169
+ // The index of a computed position, and of a computed key: a key of an array space is the text of its index.
170
+ I: "function I(t, n) { return Number.isInteger(t) && t >= 0 && t < n ? t : F(); }",
171
+ K: 'function K(k, n) { return typeof k === "string" && /^(0|[1-9]\\d*)$/.test(k) && +k < n ? +k : F(); }',
172
+ // The ops on the order of a list (LIST.SORT, LIST.TAKE, LIST.NTH) work on the items with values. With strict, an
173
+ // error item is the error of the op. A sort is stable, and the values are numbers without NaN or texts of one kind.
174
+ V: "function V(l, s) { if (s && l.some((x) => x[1] === E)) F(); return l.filter((x) => x[1] !== E); }",
175
+ SB: [
176
+ "function SB(l, s) {",
177
+ " const o = V(l, s);",
178
+ " const t = o.length > 0 ? typeof o[0][1] : \"number\";",
179
+ " for (const [, v] of o) if (typeof v !== t || (t !== \"number\" && t !== \"string\") || v !== v) F();",
180
+ " return o.sort((a, b) => (a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0));",
181
+ "}",
182
+ ].join("\n"),
183
+ TK: "function TK(l, n, s) { const o = V(l, s); return Number.isSafeInteger(n) && n >= 0 ? o.slice(0, n) : F(); }",
184
+ NT: "function NT(l, i, s) { const o = V(l, s); return Number.isSafeInteger(i) && i >= 0 && i < o.length ? o[i][1] : F(); }",
185
+ // The memo of a function of one key, and of more keys. -0 has its own entry, because an op can tell it from 0.
186
+ M1: [
187
+ "function M1(f) {",
188
+ " const m = new Map();",
189
+ " return (k) => {",
190
+ " const s = Object.is(k, -0) ? Z : k;",
191
+ " let r = m.get(s);",
192
+ " if (r === undefined) {",
193
+ " try { r = f(k); } catch { r = E; }",
194
+ " m.set(s, r);",
195
+ " }",
196
+ " return G(r);",
197
+ " };",
198
+ "}",
199
+ ].join("\n"),
200
+ M: [
201
+ "function M(f) {",
202
+ " const root = new Map();",
203
+ " return (...k) => {",
204
+ " let m = root;",
205
+ " for (const x of k.slice(0, -1)) {",
206
+ " const s = Object.is(x, -0) ? Z : x;",
207
+ " let c = m.get(s);",
208
+ " if (c === undefined) m.set(s, (c = new Map()));",
209
+ " m = c;",
210
+ " }",
211
+ " const last = k.at(-1);",
212
+ " const s = Object.is(last, -0) ? Z : last;",
213
+ " let r = m.get(s);",
214
+ " if (r === undefined) {",
215
+ " try { r = f(...k); } catch { r = E; }",
216
+ " m.set(s, r);",
217
+ " }",
218
+ " return G(r);",
219
+ " };",
220
+ "}",
221
+ ].join("\n"),
222
+ };
223
+
224
+ /** A part of the helper S that only some nodes need (helperS). */
225
+ type Feature = "group" | "prefix" | "strict" | "ok" | "pre";
226
+
227
+ /**
228
+ * This function gives the code of the helper S, a node of the memo that keeps its items (Printer.#cached). The helper
229
+ * has only the parts that the nodes of the module need:
230
+ *
231
+ * - `group`: the groups of the values of the key (mode 1).
232
+ * - `prefix`: the prefixes of the items (mode 2).
233
+ * - `strict`: the option strict of a list op.
234
+ * - `ok`: the check of the kind of a value.
235
+ * - `pre`: the tests before the test of the key.
236
+ *
237
+ * The node gives `key` for the value of each item, and `val` for the value of an item from its index. It gives `test`
238
+ * for the test of the key.
239
+ */
240
+ const helperS = (has: ReadonlySet<Feature>): string => {
241
+ const on = (f: Feature, ...lines: readonly string[]): readonly string[] => (has.has(f) ? lines : []);
242
+ const strict = has.has("strict");
243
+ const ok = has.has("ok");
244
+ // The items that end the lookup with an error, and the items that the lookup skips.
245
+ const fails = [...(strict ? ["x === E"] : []), ...(ok ? ["x === W"] : [])].join(" || ");
246
+ const skips = strict ? "x === N || (x === E && !strict)" : "x === N || x === E";
247
+ return [
248
+ "function S(n, mode, strict, a0, step, result, key, val, test, pre, ok) {",
249
+ " let ts, js, xs, bad, reach, gs, mono, pa, pc, pe;",
250
+ " const value = (i) => {",
251
+ " let x = xs[i];",
252
+ " if (x === undefined) {",
253
+ " x = val(js[i]);",
254
+ ...on("ok", " if (ok && x !== E && x !== N && !ok(x)) x = W;"),
255
+ " xs[i] = x;",
256
+ " }",
257
+ " return x;",
258
+ " };",
259
+ " return M1((q) => {",
260
+ " if (ts === undefined) {",
261
+ " ts = [];",
262
+ " js = [];",
263
+ " xs = [];",
264
+ ...on("strict", " bad = false;", " reach = 0;"),
265
+ " for (let j = 0; j < n; j++) {",
266
+ " try {",
267
+ ...on("pre", " if (pre && !pre(j)) continue;"),
268
+ ...on("strict", " reach++;"),
269
+ " const t = key(j);",
270
+ // NaN satisfies no test of a group or of a prefix, so its item is in none.
271
+ " if (mode && t !== t) continue;",
272
+ " ts.push(t);",
273
+ " js.push(j);",
274
+ " } catch {",
275
+ ...on("strict", " bad = true;"),
276
+ " }",
277
+ " }",
278
+ ...on("group", " if (mode === 1) {", " gs = new Map();", " for (let i = 0; i < ts.length; i++) {", " let g = gs.get(ts[i]);", " if (g === undefined) gs.set(ts[i], (g = []));", " g.push(i);", " }", " }"),
279
+ ...on("prefix", " if (mode === 2) {", " mono = true;", " for (let i = 1; i < ts.length; i++) if (!(ts[i - 1] <= ts[i])) mono = false;", " pa = [a0];", " pc = [0];", " pe = [false];", " }"),
280
+ " }",
281
+ // A key with an error makes an error item of each item that reaches the test of the key.
282
+ strict ? " if (q === E) return strict && (bad || reach > 0) ? F() : result(a0, 0);" : " if (q === E) return result(a0, 0);",
283
+ ...on("strict", " if (strict && bad) F();"),
284
+ " let a = a0, c = 0;",
285
+ " const add = (i) => {",
286
+ " const x = value(i);",
287
+ ` if (${skips}) return;`,
288
+ ...(fails === "" ? [] : [` if (${fails}) F();`]),
289
+ " a = step(a, c, x);",
290
+ " c++;",
291
+ " };",
292
+ ...on("group", " if (mode === 1) {", " const g = gs.get(q);", " if (g !== undefined) for (const i of g) add(i);", " return result(a, c);", " }"),
293
+ // The values t do not decrease, so the items whose test is true are a prefix. Each prefix keeps its running value.
294
+ ...on(
295
+ "prefix",
296
+ " if (mode === 2 && mono) {",
297
+ " let lo = 0, hi = ts.length;",
298
+ " while (lo < hi) {",
299
+ " const h = (lo + hi) >> 1;",
300
+ " if (test(ts[h], q)) lo = h + 1;",
301
+ " else hi = h;",
302
+ " }",
303
+ " for (let i = pa.length - 1; i < lo; i++) {",
304
+ " let x = value(i), b = pa[i], d = pc[i], err = pe[i];",
305
+ ...(fails === "" ? [" if (x !== N && x !== E) {"] : [` if (${fails.replace("x === E", "(x === E && strict)")}) err = true;`, " else if (x !== N && x !== E) {"]),
306
+ " b = step(b, d, x);",
307
+ " d++;",
308
+ " }",
309
+ " pa.push(b);",
310
+ " pc.push(d);",
311
+ " pe.push(err);",
312
+ " }",
313
+ " if (pe[lo]) F();",
314
+ " return result(pa[lo], pc[lo]);",
315
+ " }",
316
+ ),
317
+ " for (let i = 0; i < ts.length; i++) if (test(ts[i], q)) add(i);",
318
+ " return result(a, c);",
319
+ " });",
320
+ "}",
321
+ ].join("\n");
322
+ };
323
+
324
+ /** The step of the running value of first and of count: the name of its function in a module, and its code. */
325
+ const FIRST_STEP: readonly [string, string] = ["s_first", "(a, c, x) => (c === 0 ? x : a)"];
326
+
327
+ /** The step of the running value of each list op: the name of its function in a module, and its code. */
328
+ const STEPS: Readonly<Record<string, readonly [string, string]>> = {
329
+ count: FIRST_STEP,
330
+ first: FIRST_STEP,
331
+ sum: ["s_add", "(a, c, x) => a + x"],
332
+ mean: ["s_add", "(a, c, x) => a + x"],
333
+ min: ["s_min", "(a, c, x) => (c === 0 ? x : Math.min(a, x))"],
334
+ max: ["s_max", "(a, c, x) => (c === 0 ? x : Math.max(a, x))"],
335
+ any: ["s_or", "(a, c, x) => a || x"],
336
+ none: ["s_or", "(a, c, x) => a || x"],
337
+ all: ["s_and", "(a, c, x) => a && x"],
338
+ };
339
+
340
+ /** The helpers that each helper uses. */
341
+ const NEEDS: Readonly<Record<Helper, readonly Helper[]>> = {
342
+ F: [], C: [], T: [], L: [], Q: [], G: ["F"], B: ["F"], U: ["F"], X: ["F"], I: ["F"], K: ["F"], M: ["G"], M1: ["G"], S: ["M1", "F"],
343
+ // Only SB, TK and NT use V, and they need F too, so the need of V only completes the list.
344
+ // Stryker disable next-line ArrayDeclaration: see the comment above
345
+ V: ["F"],
346
+ SB: ["V", "F"], TK: ["V", "F"], NT: ["V", "F"],
347
+ };
348
+
349
+ /** The list ops of a standalone module. */
350
+ const LIST_OPS: ReadonlySet<string> = new Set(["count", "sum", "mean", "min", "max", "any", "all", "none", "first"]);
351
+ const NUMBER_LIST_OPS: ReadonlySet<string> = new Set(["count", "sum", "mean", "min", "max"]);
352
+ const BOOLEAN_LIST_OPS: ReadonlySet<string> = new Set(["any", "all", "none"]);
353
+
354
+ /** This function gives the kind of the result of a list op: first gives the kind of its items. */
355
+ const listKind = (op: string, item: Kind | undefined): Kind | undefined => (NUMBER_LIST_OPS.has(op) ? "number" : BOOLEAN_LIST_OPS.has(op) ? "boolean" : item);
356
+
357
+ const LOOPS = new WeakMap<Expr, boolean>();
358
+
359
+ /** This function gives the names that an expression reads, also the names that it binds itself. */
360
+ function namesOf(e: Expr, out = new Set<string>()): Set<string> {
361
+ if (e.tag === "var") out.add(e.name);
362
+ for (const x of children(e)) namesOf(x, out);
363
+ return out;
364
+ }
365
+
366
+ /**
367
+ * The smallest work of an expression in a column of the run. The work is the number of nodes. A node of the memo and a
368
+ * constant of the run count as one node each. A part with less work costs less than the read of its column.
369
+ */
370
+ const COLUMN_WORK = 10;
371
+
372
+ /** This function gives the head of a loop over targets: from `lo` up to `hi`, or from `hi` down to `lo` in the reverse order. */
373
+ const forHead = (j: string, lo: string, hi: string, reverse: boolean): string => (reverse ? `for (let ${j} = ${hi} - 1; ${j} >= ${lo}; ${j}--) {` : `for (let ${j} = ${lo}; ${j} < ${hi}; ${j}++) {`);
374
+
375
+ /** This function tells if an expression has a loop of names: a fold or an iteration. */
376
+ function hasLoop(e: Expr): boolean {
377
+ let found = LOOPS.get(e);
378
+ if (found === undefined) {
379
+ found = e.tag === "fold" || e.tag === "iterate" || children(e).some(hasLoop);
380
+ LOOPS.set(e, found);
381
+ }
382
+ return found;
383
+ }
384
+
385
+ /**
386
+ * This function tells if a node of the memo has a loop of its own. Such a loop is outside its keys and outside the nodes
387
+ * of the memo in it. A node without one combines the values of other nodes, and a function of its own only costs time.
388
+ */
389
+ function ownLoop(e: Expr, root: Expr, memo: ReadonlyMap<Expr, readonly Expr[]>, keys: ReadonlySet<Expr>): boolean {
390
+ if (e !== root && (memo.has(e) || keys.has(e))) return false;
391
+ return e.tag === "each" || children(e).some((x) => ownLoop(x, root, memo, keys));
392
+ }
393
+
394
+ /** This function gives the nodes of the memo of an expression that have a loop of their own, with their keys. */
395
+ function memoOf(expr: Expr): ReadonlyMap<Expr, readonly Expr[]> {
396
+ const all = memoNodes(expr);
397
+ return new Map([...all].filter(([e, keys]) => ownLoop(e, e, all, new Set(keys))));
398
+ }
399
+
400
+ /** This function tells if an expression contains the expression `x`, the same object. */
401
+ function contains(e: Expr, x: Expr): boolean {
402
+ return e === x || children(e).some((c) => contains(c, x));
403
+ }
404
+
405
+ /** This function gives the base of an axis and its tests in the order of evaluation. */
406
+ function testsOf(axis: Axis): { readonly base: Axis; readonly tests: readonly Expr[] } {
407
+ const tests: Expr[] = [];
408
+ let base = axis;
409
+ while (base.t === "where") {
410
+ tests.unshift(base.test);
411
+ base = base.axis;
412
+ }
413
+ return { base, tests };
414
+ }
415
+
416
+ /**
417
+ * This function gives the parts of a test `and`, and of each part that is a test `and` too. `and` stops at the first
418
+ * `false`, as a chain of tests does, and each part must be a boolean.
419
+ */
420
+ function partsOf(t: Expr): readonly Expr[] {
421
+ return t.tag === "app" && t.op === "and" && t.args.length > 0 ? t.args.flatMap(partsOf) : [t];
422
+ }
423
+
424
+ /** This function gives the kind of two values in the branches of a form, if they have the same kind. */
425
+ const join = (a: Kind | undefined, b: Kind | undefined): Kind | undefined => (a === b ? a : undefined);
426
+
427
+ /** This function gives a value that is a constant of the run, with plain code. */
428
+ const plainValue = (code: string, kind: Kind | undefined): Value => ({ code, kind, safe: true, deps: NO_DEPS, plain: true });
429
+
430
+ /** This function gives the code of a value with no statements. */
431
+ const bare = (v: Value): Code => ({ s: [], v });
432
+
433
+ /** This function gives the code of a literal. A value that is not a finite number, a text, a boolean or null has no code. */
434
+ function literal(value: unknown): Value {
435
+ if (typeof value === "number") {
436
+ if (!Number.isFinite(value)) throw new NotStandalone("a literal is a number that is not finite");
437
+ return plainValue(Object.is(value, -0) ? "-0" : String(value), "number");
438
+ }
439
+ if (typeof value === "string") return plainValue(JSON.stringify(value), "string");
440
+ if (typeof value === "boolean") return plainValue(String(value), "boolean");
441
+ if (value === null) return plainValue("null", undefined);
442
+ throw new NotStandalone("a literal is not a number, a text, a boolean or null");
443
+ }
444
+
445
+ /**
446
+ * This function gives a text that is the same for two expressions with the same structure. -0 is not 0. A part with a
447
+ * token gives the token, so the text does not depend on that part. A token is an object, and a literal of a module is
448
+ * not, so a token is not the text of a literal.
449
+ */
450
+ function canonical(e: Expr, token: (x: unknown) => object | undefined): string {
451
+ return JSON.stringify(e, (_name, x: unknown) => token(x) ?? (Object.is(x, -0) ? { "-0": 0 } : x));
452
+ }
453
+
454
+ /** The values of each kind that `copied` gives to a function and to its copy. */
455
+ const SAMPLES: Readonly<Record<PrimitiveKind, readonly unknown[]>> = {
456
+ number: [0, 1, -1, 2.5, -0, 1e300, -7],
457
+ string: ["", "a", "ab c"],
458
+ boolean: [true, false],
459
+ };
460
+
461
+ /** This function gives each list of arguments with one sample of each parameter, from the samples of each parameter. */
462
+ function samples(each: readonly (readonly unknown[])[]): readonly (readonly unknown[])[] {
463
+ return each.reduce<readonly (readonly unknown[])[]>((acc, values) => acc.flatMap((xs) => values.map((x) => [...xs, x])), [[]]);
464
+ }
465
+
466
+ /** This function gives the text of plain data, with -0 apart from 0. */
467
+ const dataText = (x: unknown): string => canonical(x as Expr, () => undefined);
468
+
469
+ /** This function tells if two values are the same: the same primitive, or plain data with the same structure. */
470
+ function same(a: unknown, b: unknown): boolean {
471
+ if (Object.is(a, b)) return true;
472
+ if (typeof a !== "object" || a === null || typeof b !== "object" || b === null || Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) return false;
473
+ return dataText(a) === dataText(b);
474
+ }
475
+
476
+ /** This function gives the value of a call, or that it threw. */
477
+ function call(f: () => unknown): { readonly threw: boolean; readonly value?: unknown } {
478
+ try {
479
+ return { threw: false, value: f() };
480
+ } catch {
481
+ return { threw: true };
482
+ }
483
+ }
484
+
485
+ /** This function tells if two calls give the same: the same value, or an exception in both. */
486
+ function sameCall(a: () => unknown, b: () => unknown): boolean {
487
+ const x = call(a);
488
+ const y = call(b);
489
+ return x.threw === y.threw && same(x.value, y.value);
490
+ }
491
+
492
+ /**
493
+ * This function gives the source of a function of a domain, for a copy in a module. The source must be an expression:
494
+ * the source of a native function or of a method does not compile as one. A copy must give the values of the function:
495
+ * a function that reads a name outside itself gives an exception in the copy. Thus the copy and the function must give
496
+ * the same for the samples of their kinds.
497
+ */
498
+ function copied(f: (...a: never[]) => unknown, each: readonly (readonly unknown[])[], what: string): string {
499
+ const src = Function.prototype.toString.call(f);
500
+ let copy: (...a: unknown[]) => unknown;
501
+ try {
502
+ // oxlint-disable-next-line typescript/no-implied-eval -- the source is the source of a function of a domain.
503
+ const make = new Function(`"use strict"; return (${src});`) as () => (...a: unknown[]) => unknown;
504
+ copy = make();
505
+ } catch {
506
+ throw new NotStandalone(`${what} has no source that a module can copy`);
507
+ }
508
+ const fn = f as (...a: unknown[]) => unknown;
509
+ if (!samples(each).every((xs) => sameCall(() => fn(...xs), () => copy(...xs)))) throw new NotStandalone(`${what} reads a name outside itself, so a module cannot copy it`);
510
+ return src;
511
+ }
512
+
513
+ /** The functions that an inline form can use. They do not throw for numbers. */
514
+ const CALLS: ReadonlySet<string> = new Set([
515
+ "Math.abs",
516
+ "Math.ceil",
517
+ "Math.floor",
518
+ "Math.round",
519
+ "Math.trunc",
520
+ "Math.sign",
521
+ "Math.sqrt",
522
+ "Math.cbrt",
523
+ "Math.exp",
524
+ "Math.log",
525
+ "Math.log10",
526
+ "Math.log2",
527
+ "Math.min",
528
+ "Math.max",
529
+ "Math.pow",
530
+ "Math.hypot",
531
+ "Math.sin",
532
+ "Math.cos",
533
+ "Math.tan",
534
+ "Math.atan2",
535
+ "Number.isFinite",
536
+ ]);
537
+
538
+ /** The inline form of a function of an op: its parameters, and its body with a hole for each use of a parameter. */
539
+ interface InlineForm {
540
+ readonly params: readonly string[];
541
+ /** The parts of the body, and between two parts the index of a parameter. */
542
+ readonly parts: readonly (string | number)[];
543
+ /** The number of uses of each parameter. */
544
+ readonly uses: readonly number[];
545
+ }
546
+
547
+ /**
548
+ * This function gives the inline form of the source of an arrow function. The body of the function must be an
549
+ * expression of operators, numbers, its parameters and the functions of `CALLS`. Such a body cannot throw for primitive
550
+ * values (§7.1). The inline form is the text of the function itself, so it has its bits.
551
+ */
552
+ function inlineForm(src: string): InlineForm | undefined {
553
+ const m = /^\(?\s*((?:[A-Za-z_$][\w$]*\s*,\s*)*[A-Za-z_$][\w$]*)\s*\)?\s*=>\s*([\s\S]*)/.exec(src);
554
+ if (m === null) return undefined;
555
+ const params = (m[1] as string).split(",").map((x) => x.trim());
556
+ const parts: (string | number)[] = [];
557
+ const uses = params.map(() => 0);
558
+ let text = "";
559
+ // The even parts are the text between the names: numbers, operators and parentheses. An assignment, a call of a value
560
+ // and another character, for example a quote, stop the inline form.
561
+ const split = (m[2] as string).split(/([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)?)/);
562
+ for (const [i, t] of split.entries()) {
563
+ if (i % 2 === 0) {
564
+ if (!/^(?:\d|\.\d|\s|===?|!==?|<=|>=|[+\-*/%<>!?:(),&|^~])*$/.test(t) || /\+\+|--|\)\s*\(/.test(t)) return undefined;
565
+ text += t;
566
+ } else if (CALLS.has(t)) text += t;
567
+ else {
568
+ const p = params.indexOf(t);
569
+ if (p < 0 || /^\s*\(/.test(split[i + 1] as string)) return undefined;
570
+ parts.push(text, p);
571
+ text = "";
572
+ uses[p] = (uses[p] as number) + 1;
573
+ }
574
+ }
575
+ parts.push(text);
576
+ return { params, parts, uses };
577
+ }
578
+
579
+ /** This function gives the text of an inline form without spaces, with `#i` for the parameter `at(i)`. */
580
+ const patternOf = (form: InlineForm, at: (p: number) => number): string => form.parts.map((p) => (typeof p === "number" ? `#${at(p)}` : p.replaceAll(/\s/g, ""))).join("");
581
+
582
+ class Printer {
583
+ readonly #facts: Facts;
584
+ readonly #domains: readonly AnyDomain[];
585
+ readonly #schema: Schema;
586
+ readonly #memo: ReadonlyMap<Expr, readonly Expr[]>;
587
+ readonly helpers = new Set<Helper>();
588
+ /** The declarations at the top of the module: the functions of the domains and the checks of the results. */
589
+ readonly top = new Map<string, string>();
590
+ /** The statements at the start of a run: the constants of the run and the functions of the memo. */
591
+ readonly run: string[] = [];
592
+ /** The variables of the schema that the program reads. */
593
+ readonly vars = new Map<string, string>();
594
+ /** True when the module has a node of the memo, so it needs the key of -0. */
595
+ memos = false;
596
+ /** The parts of the helper S that the nodes of the memo that keep their items need (helperS). */
597
+ readonly features = new Set<Feature>();
598
+ #names = 0;
599
+ /** The number of the next bound function, and of the next printed function. */
600
+ #fnIds = 0;
601
+ #printed = 0;
602
+ /** The level of the names of the next loop. It is far above the levels of the axes, so the two do not meet. */
603
+ #loops = 1_000_000;
604
+ /** The node of the memo whose function the printer prints, so it prints the node itself. */
605
+ #inside: Expr | undefined;
606
+ readonly #structures = new Map<string, string>();
607
+ readonly #kinds = new Map<string, Kind | undefined>();
608
+ readonly #ops = new Map<string, number>();
609
+ /** The inline form of each function of an op, or undefined for a function that the module calls. */
610
+ readonly #forms = new Map<string, InlineForm | undefined>();
611
+ /** The functions of ops that the module calls, not in an inline form. */
612
+ readonly #called = new Set<string>();
613
+ /** The key of the expression of each code that is a constant of the run, and the read of each hoisted constant by key. */
614
+ readonly #keyOf = new WeakMap<Code, string>();
615
+ readonly #constants = new Map<string, Code>();
616
+ /** The columns of the run, by the structure of their expression. */
617
+ readonly #columns = new Map<string, string>();
618
+ /** The expressions whose code is a constant of the run. */
619
+ readonly #constant = new WeakSet<Expr>();
620
+ /** The expressions at a place that takes a list: a binding, the head of a list op and the list of an axis. */
621
+ readonly #wantList = new WeakSet<Expr>();
622
+ /** The facts of the list of each function of the memo whose value is a list. */
623
+ readonly #lists = new Map<string, ListInfo | undefined>();
624
+
625
+ constructor(expr: Expr, options: ModuleOptions) {
626
+ this.#domains = options.domains ?? [];
627
+ this.#facts = factsOf({ domains: this.#domains });
628
+ this.#schema = options.schema;
629
+ this.#memo = memoOf(expr);
630
+ }
631
+
632
+ use(name: Helper): string {
633
+ this.helpers.add(name);
634
+ return name;
635
+ }
636
+
637
+ /**
638
+ * This method gives the check of a result of a kind, or undefined for a result that needs no check. A number must be
639
+ * finite, and the domain of the kind can check the value with valid. The law checker of the test kit checks the
640
+ * declaration `returns` of each op (KIND.RETURNS), so the module trusts the kind itself.
641
+ */
642
+ check(kind: Kind): string | undefined {
643
+ const name = `k_${kind.replace(":", "_")}`;
644
+ // Stryker disable next-line ConditionalExpression: a check of a kind is always the same, so the map only saves time
645
+ if (!this.top.has(name)) {
646
+ const d = this.#facts.checkOf(kind);
647
+ // The kind is primitive here. A static site on a value of a domain has no domain without a primitive type before it.
648
+ if (d === undefined) throw new NotStandalone(`a domain without a primitive type comes before the domain of a ${kind}`);
649
+ const domain = this.#domains[d];
650
+ const valid = domain?.valid === undefined ? undefined : this.#valid(d, domain.name, kind, domain.valid);
651
+ const conds = [...(kind === "number" ? ["Number.isFinite(x)"] : []), ...(valid === undefined ? [] : [`${valid}(x)`])];
652
+ if (conds.length === 0) return undefined;
653
+ this.top.set(name, `const ${name} = (x) => (${conds.join(" && ")} ? x : ${this.use("F")}());`);
654
+ }
655
+ return name;
656
+ }
657
+
658
+ /** This method gives the code of a result with its check, if it needs one. */
659
+ #checked(kind: Kind, code: string): string {
660
+ const k = this.check(kind);
661
+ return k === undefined ? code : `${k}(${code})`;
662
+ }
663
+
664
+ #valid(d: number, domain: string, kind: Kind, valid: (x: never) => boolean): string | undefined {
665
+ const name = `v_${d}`;
666
+ const src = copied(valid, [this.#samples(kind)], `the check "valid" of the domain ${domain}`);
667
+ // A check that is Number.isFinite of a number adds nothing to the check of the result.
668
+ const form = inlineForm(src);
669
+ if (kind === "number" && form !== undefined && patternOf(form, (p) => p) === "Number.isFinite(#0)") return undefined;
670
+ this.top.set(name, `const ${name} = ${src};`);
671
+ return name;
672
+ }
673
+
674
+ /** This method gives the samples of a kind: the samples of a primitive type, or the samples of a domain (KIND.DOMAIN). */
675
+ #samples(kind: Kind): readonly unknown[] {
676
+ const primitive = primitiveOf(kind);
677
+ if (primitive !== undefined) return SAMPLES[primitive];
678
+ const d = this.#domains.find((x) => kindOfDomain(x) === kind) as AnyDomain;
679
+ if (d.samples === undefined) throw new NotStandalone(`the domain ${d.name} gives no samples, so a module cannot check a copy of its op`);
680
+ return d.samples();
681
+ }
682
+
683
+ /**
684
+ * This method gives the code of a check of the kind of an input. The check is a test of its JavaScript type, or the
685
+ * copy of `is` of a domain. The code is true for an input against the kind.
686
+ */
687
+ against(kind: Kind, input: string): string {
688
+ const primitive = primitiveOf(kind);
689
+ if (primitive !== undefined) return `typeof ${input} !== "${primitive}"`;
690
+ const d = this.#domains.findIndex((x) => kindOfDomain(x) === kind);
691
+ const domain = this.#domains[d];
692
+ if (domain === undefined) throw new NotStandalone(`the schema has the kind ${kind}, and no domain has it`);
693
+ const name = `is_${String(d)}`;
694
+ if (!this.top.has(name)) {
695
+ const src = copied(domain.is, [[...SAMPLES.number, ...SAMPLES.string, ...SAMPLES.boolean, null, {}, [], ...this.#samples(kind)]], `the test "is" of the domain ${domain.name}`);
696
+ this.top.set(name, `const ${name} = ${src};`);
697
+ }
698
+ return `!${name}(${input})`;
699
+ }
700
+
701
+ /** This method gives a new name for the code. */
702
+ fresh(prefix: string): string {
703
+ return `${prefix}${this.#names++}`;
704
+ }
705
+
706
+ /** This method gives the code of a name: a read that throws the error of its value, if it can hold an error. */
707
+ #read(name: Name): Value {
708
+ const base = { kind: name.kind, deps: name.deps, plain: true, list: name.list };
709
+ return name.lazy ? { ...base, code: `${this.use("G")}(${name.code})`, safe: false, held: name.code } : { ...base, code: name.code, safe: true };
710
+ }
711
+
712
+ /** This method gives the name of a constant of the run, from the read of its value. */
713
+ #nameOf(v: Value): Name {
714
+ return { code: v.held ?? v.code, kind: v.kind, lazy: v.held !== undefined, deps: NO_DEPS, list: v.list };
715
+ }
716
+
717
+ /**
718
+ * This method gives the statements that put the value of a code, or the error sentinel, into a new variable `name`.
719
+ * A constant of the run without statements uses the helper `T`: it evaluates once, so its closure costs little.
720
+ */
721
+ #store(name: string, c: Code, run = false): string[] {
722
+ if (c.v.safe) return [...c.s, `const ${name} = ${c.v.code};`];
723
+ if (c.s.length === 0 && c.v.held !== undefined) return [`const ${name} = ${c.v.held};`];
724
+ if (run && c.s.length === 0) return [`const ${name} = ${this.use("T")}(() => ${c.v.code});`];
725
+ return [`let ${name};`, "try {", ...ind(c.s), ` ${name} = ${c.v.code};`, "} catch {", ` ${name} = E;`, "}"];
726
+ }
727
+
728
+ /**
729
+ * This method evaluates a constant of the run once, before the loop over the keys, and gives the read of its value. A
730
+ * constant with a loop (`lazy`) evaluates on its first read instead, as a branch of the interpreter does.
731
+ */
732
+ #hoist(c: Code, lazy = false): Code {
733
+ if (c.v.deps.size > 0 || (c.v.plain === true && c.s.length === 0)) return c;
734
+ const key = this.#keyOf.get(c);
735
+ const hit = key === undefined ? undefined : this.#constants.get(key);
736
+ if (hit !== undefined) return hit;
737
+ const name = this.fresh("c");
738
+ if (lazy) this.run.push(`const ${name} = ${this.use("L")}(() => {`, ...ind(c.s), ` return ${c.v.code};`, "});");
739
+ else this.run.push(...this.#store(name, c, true));
740
+ const { list } = c.v;
741
+ const read = bare(this.#read(lazy ? { code: `${name}()`, kind: c.v.kind, lazy: true, deps: NO_DEPS, list } : { code: name, kind: c.v.kind, lazy: !c.v.safe, deps: NO_DEPS, list }));
742
+ if (key !== undefined) this.#constants.set(key, read);
743
+ return read;
744
+ }
745
+
746
+ /**
747
+ * This method gives the parts of a node with levels `deps`. When the node is not a constant of the run, each part that
748
+ * is a constant evaluates once, before the loop. A node that is a constant keeps its parts, and its parent decides.
749
+ */
750
+ #settle(parts: readonly Code[], deps: ReadonlySet<number>, exprs: readonly Expr[] = []): readonly Code[] {
751
+ return deps.size === 0 ? parts : parts.map((x, i) => this.#hoist(x, exprs[i] !== undefined && hasLoop(exprs[i])));
752
+ }
753
+
754
+ expr(e: Expr, ctx: Ctx): Code {
755
+ const key = ctx.keys.get(e);
756
+ if (key !== undefined) return bare(this.#read(key));
757
+ const keys = this.#memo.get(e);
758
+ const c = keys !== undefined && this.#inside !== e ? this.#memoized(e, keys, ctx) : this.#node(e, ctx);
759
+ if (c.v.deps.size === 0) {
760
+ // A constant of the run with the structure of an earlier one is that constant.
761
+ this.#keyOf.set(c, this.#constKey(e, ctx));
762
+ this.#constant.add(e);
763
+ }
764
+ // A list is a value only at a place that takes a list. A result, an argument and a field take no list.
765
+ if (c.v.list !== undefined && !this.#wantList.has(e)) throw new NotStandalone("a list is a value of the program");
766
+ return this.#columnar(e, c, ctx) ? this.#column(e, c, ctx) : c;
767
+ }
768
+
769
+ /** This method gives the code of a list at a place that takes a list (LIST.VALUE): an each, a name, sortBy or take. */
770
+ #listOf(e: Expr, ctx: Ctx): Code {
771
+ this.#wantList.add(e);
772
+ const c = this.expr(e, ctx);
773
+ if (c.v.list === undefined) throw new NotStandalone("a list op on a value that is not a list");
774
+ return c;
775
+ }
776
+
777
+ /** This method tells if an expression gives a list at a place that takes one: an each, sortBy, take or a name of a list. */
778
+ #isList(e: Expr, ctx: Ctx): boolean {
779
+ if (e.tag === "each") return true;
780
+ if (e.tag === "app") return e.op === "sortBy" || e.op === "take";
781
+ return e.tag === "var" && ctx.env.get(e.name)?.list !== undefined;
782
+ }
783
+
784
+ /**
785
+ * This method tells if a part of a loop over the targets is a column of the run. Its value depends only on the
786
+ * target and on the constants of the run, so each run computes it once for each record. Each name that it reads
787
+ * from outside is a constant of the run, so its code can be outside the loop.
788
+ */
789
+ #columnar(e: Expr, c: Code, ctx: Ctx): boolean {
790
+ // A node of the memo has the level 1, so a column has a focus.
791
+ if (ctx.level < 2 || c.v.deps.size !== 1 || !c.v.deps.has(ctx.level) || this.#work(e) < COLUMN_WORK) return false;
792
+ // A node of the memo with keys keeps its costly part for each value of its keys already.
793
+ if (this.#keyed(e)) return false;
794
+ return [...namesOf(e)].every((name) => (ctx.env.get(name)?.deps.size ?? 0) === 0) && !this.#callsLocal(e, ctx);
795
+ }
796
+
797
+ /** This method tells if an expression calls a function that is at the place of its binding, not at the start of a run. */
798
+ #callsLocal(e: Expr, ctx: Ctx): boolean {
799
+ // Stryker disable next-line ConditionalExpression: a node that is not a call has no field fn, so the map gives undefined
800
+ if (e.tag === "call" && ctx.fns.get(e.fn)?.local === true) return true;
801
+ return children(e).some((x) => this.#callsLocal(x, ctx));
802
+ }
803
+
804
+ /** This method tells if an expression has a node of the memo with keys in it. */
805
+ #keyed(e: Expr): boolean {
806
+ return (this.#memo.get(e)?.length ?? 0) > 0 || children(e).some((x) => this.#keyed(x));
807
+ }
808
+
809
+ /** This method gives the work of an expression: a node of the memo and a constant of the run are one read each. */
810
+ #work(e: Expr): number {
811
+ if (this.#memo.has(e) || this.#constant.has(e)) return 1;
812
+ return children(e).reduce((sum, x) => sum + this.#work(x), 1);
813
+ }
814
+
815
+ /** This method gives the read of a column of the run. Two parts with the same structure share one column. */
816
+ #column(e: Expr, c: Code, ctx: Ctx): Code {
817
+ const key = this.#constKey(e, ctx);
818
+ let name = this.#columns.get(key);
819
+ if (name === undefined) {
820
+ name = this.fresh("col");
821
+ this.run.push(`const ${name} = ${this.use("Q")}((${ctx.focus as string}) => {`, ...ind(c.s), ` return ${c.v.code};`, "});");
822
+ this.#columns.set(key, name);
823
+ }
824
+ return bare({ code: `${this.use("G")}(${name}(${ctx.focus as string}))`, kind: c.v.kind, safe: false, deps: c.v.deps, list: c.v.list });
825
+ }
826
+
827
+ #node(e: Expr, ctx: Ctx): Code {
828
+ switch (e.tag) {
829
+ case "lit":
830
+ return bare(literal(e.value));
831
+ case "ref":
832
+ return this.#ref(e, ctx);
833
+ case "var":
834
+ return bare(this.#var(e.name, ctx));
835
+ case "let":
836
+ return this.#let(e, ctx);
837
+ // A function is only a binding of let, so the check of the shape stops this node first.
838
+ // Stryker disable next-line all: see the comment above
839
+ /* v8 ignore next -- @preserve */
840
+ case "fn": throw new NotStandalone("a function outside the bindings of a let");
841
+ case "call":
842
+ return this.#call(e, ctx);
843
+ case "rec": {
844
+ const names = Object.keys(e.fields);
845
+ const raw = Object.values(e.fields).map((x) => this.expr(x, ctx));
846
+ const deps = depsOf(...raw);
847
+ const fields = this.#settle(raw, deps, Object.values(e.fields));
848
+ // A record of a module is a new object, so it needs no freeze.
849
+ const code = `({ ${fields.map((x, i) => `${JSON.stringify(names[i])}: ${x.v.code}`).join(", ")} })`;
850
+ return { s: stmtsOf(...fields), v: { code, kind: undefined, safe: fields.every((x) => x.v.safe), deps } };
851
+ }
852
+ case "app":
853
+ return this.#app(e, ctx);
854
+ case "each":
855
+ return this.#eachList(e, ctx);
856
+ case "fold":
857
+ return this.#fold(e, ctx);
858
+ case "iterate":
859
+ return this.#iterate(e, ctx);
860
+ case "ext":
861
+ throw new NotStandalone(`the extension "${e.kind}"`);
862
+ }
863
+ }
864
+
865
+ /**
866
+ * This method gives the code of the index of an address from the focus. `values` has the code of the value of each
867
+ * computed move, in order (NAV.COMPUTED).
868
+ */
869
+ #address(at: readonly Move[], ctx: Ctx, values: readonly Code[]): string {
870
+ let index = ctx.focus;
871
+ let next = 0;
872
+ // A move that can fail keeps its check when a later fixed key, index or origin replaces its index (V-052). The focus
873
+ // and the origin cannot fail, and the code of a move from an index has the code of that index in it.
874
+ let fails = false;
875
+ const checks: string[] = [];
876
+ for (const m of at) {
877
+ if (fails && index !== undefined && m.t !== "offset" && m.t !== "other") checks.push(index);
878
+ index = moveExpr(m) === undefined ? this.#move(m, index, ctx.origin) : this.#computed(m, values[next++] as Code);
879
+ fails = m.t !== "origin";
880
+ }
881
+ // A node of the memo reads neither its origin nor its focus (memo.ts), so the guards of this method do not fail.
882
+ // Stryker disable next-line ConditionalExpression,StringLiteral: see the comment above
883
+ /* v8 ignore next -- @preserve */
884
+ if (index === undefined) throw new NotStandalone("a node of the memo reads its focus");
885
+ return checks.length === 0 ? index : `(${[...checks, index].join(", ")})`;
886
+ }
887
+
888
+ /** This method gives the code of the index of a computed move, from the code of its value. */
889
+ #computed(m: Move, value: Code): string {
890
+ return `${this.use(m.t === "key" ? "K" : "I")}(${value.v.code}, n)`;
891
+ }
892
+
893
+ #move(m: Move, focus: string | undefined, origin: string | undefined): string {
894
+ const F = this.use("F");
895
+ switch (m.t) {
896
+ case "origin":
897
+ // Stryker disable next-line ConditionalExpression,StringLiteral: see #address
898
+ /* v8 ignore next -- @preserve */
899
+ if (origin === undefined) throw new NotStandalone("a node of the memo reads its origin");
900
+ return origin;
901
+ case "key":
902
+ // A key of an array space is the text of its index.
903
+ return typeof m.key === "string" && /^(0|[1-9]\d*)$/.test(m.key) ? `(${m.key} < n ? ${m.key} : ${F}())` : `${F}()`;
904
+ case "index":
905
+ return typeof m.i === "number" && Number.isInteger(m.i) && m.i >= 0 ? `(${m.i} < n ? ${m.i} : ${F}())` : `${F}()`;
906
+ case "offset": {
907
+ const [d, ...more] = m.d;
908
+ // Stryker disable next-line ConditionalExpression,StringLiteral: see #address
909
+ /* v8 ignore next -- @preserve */
910
+ if (focus === undefined) throw new NotStandalone("a node of the memo reads its focus");
911
+ if (d === undefined || more.length > 0 || !Number.isInteger(d)) return `${F}()`;
912
+ return `${this.use("X")}(${focus} + ${d}, n)`;
913
+ }
914
+ case "other":
915
+ // Stryker disable next-line ConditionalExpression,StringLiteral: see #address
916
+ /* v8 ignore next -- @preserve */
917
+ if (focus === undefined) throw new NotStandalone("a node of the memo reads its focus");
918
+ return `(n === 2 ? 1 - ${focus} : ${F}())`;
919
+ case "parent":
920
+ return `${F}()`;
921
+ }
922
+ }
923
+
924
+ #ref(e: ExprOf<"ref">, ctx: Ctx): Code {
925
+ const [field, ...more] = e.path;
926
+ const kind = field === undefined ? undefined : this.#schema.fields?.[field];
927
+ if (field === undefined || more.length > 0 || !isFieldName(field) || kind === undefined) throw new NotStandalone(`a read of a field that is not in the schema: "${e.path.join(".")}"`);
928
+ // A move to the origin cannot fail, and the schema has the field in each record.
929
+ const at = e.at ?? [];
930
+ const safe = at.every((m) => m.t === "origin");
931
+ const values = this.#addressValues(at, ctx);
932
+ const deps = this.#addressDeps(at, ctx, values);
933
+ const parts = this.#settle(values, deps);
934
+ return { s: stmtsOf(...parts), v: { code: `R[${this.#address(at, ctx, parts)}][${JSON.stringify(field)}]`, kind, safe, deps } };
935
+ }
936
+
937
+ /** This method gives the code of the expressions of the computed moves of an address. They evaluate at the node. */
938
+ #addressValues(at: readonly Move[], ctx: Ctx): readonly Code[] {
939
+ return addrExprs(at).map((x) => this.expr(x, ctx));
940
+ }
941
+
942
+ /**
943
+ * This method gives the levels of the key of an address. The focus and the origin have their level, and a fixed key
944
+ * has no level. A computed move has the levels of its value.
945
+ */
946
+ #addressDeps(at: readonly Move[], ctx: Ctx, values: readonly Code[]): ReadonlySet<number> {
947
+ let deps: ReadonlySet<number> = new Set([ctx.level]);
948
+ let next = 0;
949
+ // A move that can fail keeps the levels of its index when a later move replaces the index (V-052). An offset and
950
+ // other keep the index, so their levels stay.
951
+ let fails = false;
952
+ const kept = new Set<number>();
953
+ for (const m of at) {
954
+ if (fails) for (const d of deps) kept.add(d);
955
+ if (moveExpr(m) !== undefined) deps = (values[next++] as Code).v.deps;
956
+ else if (m.t === "origin") deps = new Set([ctx.originLevel]);
957
+ else if (m.t === "key" || m.t === "index" || m.t === "parent") deps = NO_DEPS;
958
+ fails = m.t !== "origin";
959
+ }
960
+ return new Set([...deps, ...kept]);
961
+ }
962
+
963
+ #var(name: string, ctx: Ctx): Value {
964
+ const bound = ctx.env.get(name);
965
+ if (bound !== undefined) return this.#read(bound);
966
+ // A name of a loop hides a function with its name, so this check comes after the names of the scope.
967
+ if (ctx.fns.has(name)) throw new NotStandalone(`the name "${name}" is a function, not a value`);
968
+ const kind = this.#schema.vars?.[name];
969
+ if (kind === undefined) throw new NotStandalone(`a variable that is not in the schema: "${name}"`);
970
+ let code = this.vars.get(name);
971
+ if (code === undefined) {
972
+ code = `v${this.vars.size}`;
973
+ this.vars.set(name, code);
974
+ }
975
+ return plainValue(code, kind);
976
+ }
977
+
978
+ /**
979
+ * A binding is a variable. A binding with an error is an error only where the body reads its name, so the variable
980
+ * can hold the sentinel. A binding that is a constant of the run is the variable of that constant.
981
+ */
982
+ #let(e: ExprOf<"let">, ctx: Ctx): Code {
983
+ const env = new Map(ctx.env);
984
+ const fns = new Map(ctx.fns);
985
+ const s: string[] = [];
986
+ let deps = new Set<number>();
987
+ const bound: BoundFn[] = [];
988
+ for (const [name, x] of Object.entries(e.bind)) {
989
+ // A binding sees the context of the let, so a function cannot call itself.
990
+ if (x.tag === "fn") {
991
+ // Stryker disable next-line UpdateOperator: the numbers of the bindings only need to be distinct
992
+ const b: BoundFn = { id: this.#fnIds++, fn: x, ctx, specs: new Map(), decls: [], local: false };
993
+ bound.push(b);
994
+ fns.set(name, b);
995
+ env.delete(name);
996
+ continue;
997
+ }
998
+ // A binding takes a list (LIST.VALUE). A value hides a function of its name, because a read looks at the values first.
999
+ this.#wantList.add(x);
1000
+ const c = this.#hoist(this.expr(x, ctx), hasLoop(x));
1001
+ if (c.v.deps.size === 0) {
1002
+ env.set(name, this.#nameOf(c.v));
1003
+ continue;
1004
+ }
1005
+ const b = this.fresh("b");
1006
+ s.push(...this.#store(b, c));
1007
+ env.set(name, { code: b, kind: c.v.kind, lazy: !c.v.safe, deps: c.v.deps, list: c.v.list });
1008
+ // The statements of the binding read its keys, so the let is not a constant of the run.
1009
+ deps = new Set([...deps, ...c.v.deps]);
1010
+ }
1011
+ const body = this.expr(e.body, { ...ctx, env, fns });
1012
+ // A function that reads names of the place of the binding comes after them, before the body.
1013
+ return { s: [...s, ...bound.flatMap((b) => b.decls), ...body.s], v: { ...body.v, deps: new Set([...deps, ...body.v.deps]) } };
1014
+ }
1015
+
1016
+ /**
1017
+ * This method prints a call (FN.CALL). Each argument evaluates at the place of the call, as a binding of a let. The
1018
+ * call goes to the printed function of the signature of its arguments, with the focus and the origin if it reads them.
1019
+ */
1020
+ #call(e: ExprOf<"call">, ctx: Ctx): Code {
1021
+ const bound = ctx.env.has(e.fn) ? undefined : ctx.fns.get(e.fn);
1022
+ if (bound === undefined) throw new NotStandalone(`a call of "${e.fn}", which is not a function`);
1023
+ if (bound.fn.params.length !== e.args.length) throw new NotStandalone(`a call of "${e.fn}" with ${String(e.args.length)} arguments, not ${String(bound.fn.params.length)}`);
1024
+ const s: string[] = [];
1025
+ const args = e.args.map((x): Arg => {
1026
+ const c = this.#hoist(this.expr(x, ctx), hasLoop(x));
1027
+ // A value that cannot throw is the argument itself. A read of a name that can hold the error passes the name.
1028
+ if (c.v.safe) {
1029
+ s.push(...c.s);
1030
+ return { code: c.v.code, kind: c.v.kind, deps: c.v.deps };
1031
+ }
1032
+ // Stryker disable next-line ConditionalExpression: the statements with a read of a name bind other names and do not throw, so the read alone has the same value
1033
+ if (c.s.length === 0 && c.v.held !== undefined) return { code: c.v.held, kind: c.v.kind, deps: c.v.deps };
1034
+ const b = this.fresh("b");
1035
+ s.push(...this.#store(b, c));
1036
+ return { code: b, kind: c.v.kind, deps: c.v.deps };
1037
+ });
1038
+ // Each parameter can hold the error of its argument, so one function serves the arguments of one kind.
1039
+ const sig = JSON.stringify(args.map((a) => a.kind ?? null));
1040
+ const spec = bound.specs.get(sig) ?? this.#printFn(bound, args, sig);
1041
+ // Each marker becomes the levels at the call. The levels of the arguments count for each call, because their
1042
+ // statements read their keys, so the marker of the parameters gives no level.
1043
+ const levels = (d: number): readonly number[] => (d === spec.origin ? [ctx.originLevel] : d === spec.focus ? [ctx.level] : d === spec.param ? [] : [d]);
1044
+ const deps = new Set([...args.flatMap((a) => [...a.deps]), ...[...spec.deps].flatMap(levels)]);
1045
+ const position = spec.deps.has(spec.origin) ? [ctx.focus, ctx.origin] : spec.deps.has(spec.focus) ? [ctx.focus] : [];
1046
+ return { s, v: { code: `${spec.name}(${[...args.map((a) => a.code), ...position].join(", ")})`, kind: spec.kind, safe: spec.safe, deps } };
1047
+ }
1048
+
1049
+ /**
1050
+ * This method prints a bound function for one signature of its arguments, as one JavaScript function. Its parameters
1051
+ * are the arguments, then the focus and the origin, if the body reads them. A function that reads a name of the place
1052
+ * of its binding is at that place. Each other function is at the start of a run, so a constant of the run can call it.
1053
+ */
1054
+ #printFn(bound: BoundFn, args: readonly Arg[], sig: string): Spec {
1055
+ // The markers are far from the levels of the axes and of the loops, so they do not meet them. They only need to be
1056
+ // distinct.
1057
+ // Stryker disable next-line ArithmeticOperator,UpdateOperator: see the comment above
1058
+ const origin = 2_000_000 + 1000 * this.#printed++;
1059
+ const focus = origin + 1;
1060
+ const param = -origin;
1061
+ const names = args.map(() => this.fresh("p"));
1062
+ const k = this.fresh("k");
1063
+ const o = this.fresh("o");
1064
+ const env = new Map(bound.ctx.env);
1065
+ // A parameter hides a function of its name, because a read looks at the values first.
1066
+ bound.fn.params.forEach((p, i) => env.set(p, { code: names[i] as string, kind: (args[i] as Arg).kind, lazy: true, deps: new Set([param]) }));
1067
+ const body = this.expr(bound.fn.body, { origin: o, focus: k, level: focus, originLevel: origin, env, fns: bound.ctx.fns, keys: new Map() });
1068
+ const markers = new Set([origin, focus, param]);
1069
+ const global = [...body.v.deps].every((d) => markers.has(d));
1070
+ const name = this.fresh("fn");
1071
+ const position = body.v.deps.has(origin) ? [k, o] : body.v.deps.has(focus) ? [k] : [];
1072
+ const head = `const ${name} = (${[...names, ...position].join(", ")}) =>`;
1073
+ const decl = body.s.length === 0 ? [`${head} ${body.v.code};`] : [`${head} {`, ...ind(body.s), ` return ${body.v.code};`, "};"];
1074
+ (global ? this.run : bound.decls).push(...decl);
1075
+ if (!global) bound.local = true;
1076
+ const spec: Spec = { name, kind: body.v.kind, safe: body.v.safe, deps: body.v.deps, origin, focus, param, global };
1077
+ bound.specs.set(sig, spec);
1078
+ return spec;
1079
+ }
1080
+
1081
+ #boolean(v: Value): string {
1082
+ return v.kind === "boolean" ? v.code : `${this.use("B")}(${v.code})`;
1083
+ }
1084
+
1085
+ /** A condition is safe when it is a safe boolean. */
1086
+ #safeBoolean(v: Value): boolean {
1087
+ return v.safe && v.kind === "boolean";
1088
+ }
1089
+
1090
+ #app(e: ExprOf<"app">, ctx: Ctx): Code {
1091
+ const { op, args } = e;
1092
+ if (op === "if") return this.#if(args, ctx);
1093
+ if (op === "and" || op === "or") return this.#andOr(op === "and", args, ctx);
1094
+ if (op === "ifError") return this.#ifError(args, ctx);
1095
+ const [head] = args;
1096
+ if (LIST_OPS.has(op) && head?.tag === "each") return this.#list(op, head, args.slice(1), ctx);
1097
+ if (head !== undefined && (op === "sortBy" || op === "take")) return this.#order(op, head, args.slice(1), ctx);
1098
+ if (head !== undefined && (LIST_OPS.has(op) || op === "nth") && this.#isList(head, ctx)) return this.#overList(op, head, args.slice(1), ctx);
1099
+ const raw = args.map((x) => this.expr(x, ctx));
1100
+ const deps = depsOf(...raw);
1101
+ const values = this.#settle(raw, deps, args);
1102
+ const site = this.#facts.staticSite(op, values.map((x) => x.v.kind));
1103
+ if (site?.t !== "fn") throw new NotStandalone(`the kinds of the values of "${op}" do not decide its op`);
1104
+ if (site.bad) return { s: stmtsOf(...values), v: { code: `${this.use("F")}()`, kind: site.returns, safe: false, deps } };
1105
+ if (site.returns === undefined) throw new NotStandalone(`the op "${op}" does not declare the kind of its result`);
1106
+ const d = this.#domains[site.domain] as AnyDomain;
1107
+ const name = `op_${site.domain}_${this.#opIndex(op)}`;
1108
+ // Stryker disable next-line ConditionalExpression: the form of an op is always the same, so the map only saves time
1109
+ if (!this.#forms.has(name)) {
1110
+ // A static site of a domain has the function of the op of that domain.
1111
+ const fn = (d.ops[op] as { fn: (...a: never[]) => unknown }).fn;
1112
+ const kinds = values.map((x) => x.v.kind).filter((k): k is Kind => k !== undefined);
1113
+ const src = copied(fn, kinds.map((k) => this.#samples(k)), `the op "${op}" of the domain ${d.name}`);
1114
+ // An inline form cannot throw for primitive values only.
1115
+ this.#forms.set(name, kinds.every((k) => primitiveOf(k) !== undefined) ? inlineForm(src) : undefined);
1116
+ this.top.set(name, `const ${name} = ${src};`);
1117
+ }
1118
+ const form = this.#forms.get(name);
1119
+ // An inline form takes each argument once, or a plain argument more often, so each argument evaluates once.
1120
+ const inline = form !== undefined && form.params.length === values.length && values.every((x, i) => form.uses[i] === 1 || (x.v.plain === true && x.v.safe && (form.uses[i] as number) > 0));
1121
+ if (inline) {
1122
+ const text = form.parts.map((x) => (typeof x === "number" ? `(${(values[x] as Code).v.code})` : x)).join("");
1123
+ const checked = this.check(site.returns);
1124
+ const code = checked === undefined ? `(${text})` : `${checked}(${text})`;
1125
+ return { s: stmtsOf(...values), v: { code, kind: site.returns, safe: checked === undefined && values.every((x) => x.v.safe), deps } };
1126
+ }
1127
+ this.#called.add(name);
1128
+ // An exception of the op is an error of Vex: the boundary around the op catches it.
1129
+ const code = this.#checked(site.returns, `${name}(${values.map((x) => x.v.code).join(", ")})`);
1130
+ return { s: stmtsOf(...values), v: { code, kind: site.returns, safe: false, deps } };
1131
+ }
1132
+
1133
+ /** The condition must be a boolean. Only the branch that the condition selects is evaluated. */
1134
+ #if(args: readonly Expr[], ctx: Ctx): Code {
1135
+ if (args.length !== 3) throw new NotStandalone("an if without three arguments");
1136
+ const [c, a, b] = args as [Expr, Expr, Expr];
1137
+ const raw = [this.expr(c, ctx), this.expr(a, ctx), this.expr(b, ctx)];
1138
+ const deps = depsOf(...raw);
1139
+ const [cond, yes, no] = this.#settle(raw, deps, [c, a, b]) as [Code, Code, Code];
1140
+ const v = { kind: join(yes.v.kind, no.v.kind), safe: this.#safeBoolean(cond.v) && yes.v.safe && no.v.safe, deps };
1141
+ if (yes.s.length === 0 && no.s.length === 0) return { s: cond.s, v: { ...v, code: `(${this.#boolean(cond.v)} ? ${yes.v.code} : ${no.v.code})` } };
1142
+ const t = this.fresh("t");
1143
+ const s = [...cond.s, `let ${t};`, `if (${this.#boolean(cond.v)}) {`, ...ind(yes.s), ` ${t} = ${yes.v.code};`, "} else {", ...ind(no.s), ` ${t} = ${no.v.code};`, "}"];
1144
+ return { s, v: { ...v, code: t } };
1145
+ }
1146
+
1147
+ /** `and` stops at the first `false`, and `or` at the first `true`. Each argument before the stop must be a boolean. */
1148
+ #andOr(and: boolean, args: readonly Expr[], ctx: Ctx): Code {
1149
+ if (args.length === 0) throw new NotStandalone(`an ${and ? "and" : "or"} without arguments`);
1150
+ const raw = args.map((x) => this.expr(x, ctx));
1151
+ const deps = depsOf(...raw);
1152
+ const parts = this.#settle(raw, deps, args);
1153
+ const v = { kind: "boolean" as const, safe: parts.every((x) => this.#safeBoolean(x.v)), deps };
1154
+ const [first, ...rest] = parts as [Code, ...Code[]];
1155
+ if (rest.every((x) => x.s.length === 0)) return { s: first.s, v: { ...v, code: `(${parts.map((x) => this.#boolean(x.v)).join(and ? " && " : " || ")})` } };
1156
+ const t = this.fresh("t");
1157
+ const s = [...first.s, `let ${t} = ${this.#boolean(first.v)};`];
1158
+ for (const x of rest) s.push(`if (${and ? "" : "!"}${t}) {`, ...ind(x.s), ` ${t} = ${this.#boolean(x.v)};`, "}");
1159
+ return { s, v: { ...v, code: t } };
1160
+ }
1161
+
1162
+ /** The value of the first argument, or else the value of the second argument. */
1163
+ #ifError(args: readonly Expr[], ctx: Ctx): Code {
1164
+ if (args.length !== 2) throw new NotStandalone("an ifError without two arguments");
1165
+ const [a, b] = args as [Expr, Expr];
1166
+ const raw = [this.expr(a, ctx), this.expr(b, ctx)];
1167
+ const deps = depsOf(...raw);
1168
+ const [first, second] = this.#settle(raw, deps, [a, b]) as [Code, Code];
1169
+ if (first.v.safe) return first;
1170
+ const t = this.fresh("t");
1171
+ const s = [`let ${t};`, "try {", ...ind(first.s), ` ${t} = ${first.v.code};`, "} catch {", ...ind(second.s), ` ${t} = ${second.v.code};`, "}"];
1172
+ return { s, v: { code: t, kind: join(first.v.kind, second.v.kind), safe: second.v.safe, deps } };
1173
+ }
1174
+
1175
+ #opIndex(op: string): number {
1176
+ let i = this.#ops.get(op);
1177
+ if (i === undefined) {
1178
+ i = this.#ops.size;
1179
+ this.#ops.set(op, i);
1180
+ }
1181
+ return i;
1182
+ }
1183
+
1184
+ /**
1185
+ * This method gives the option strict of a list op. The options must be one literal with only strict. Only a literal
1186
+ * has a value, so another expression gives the reason too.
1187
+ */
1188
+ #strict(op: string, rest: readonly Expr[]): boolean {
1189
+ const [options, ...more] = rest;
1190
+ if (more.length > 0) throw new NotStandalone(`"${op}" with more than one option`);
1191
+ if (options === undefined) return false;
1192
+ const opts = (options as { readonly value?: unknown }).value;
1193
+ if (typeof opts !== "object" || opts === null || Object.keys(opts).some((k) => k !== "strict")) throw new NotStandalone(`the options of "${op}" are not a literal with strict`);
1194
+ return (opts as { readonly strict?: unknown }).strict === true;
1195
+ }
1196
+
1197
+ /**
1198
+ * A list op over an axis: one `for` loop with a running value. An item with an error is skipped, and with `strict` it
1199
+ * is an error of the list op. A value of the wrong kind is an error of the list op, as in the interpreter.
1200
+ */
1201
+ /**
1202
+ * This method gives the loop over the targets of an axis: the statements before it, its bounds and the key that it
1203
+ * skips. `start` has the levels of the address, and `inner` is the position at a target. The axes all, others and
1204
+ * window have a loop.
1205
+ */
1206
+ #targetLoop(axis: Axis, at: readonly Move[], ctx: Ctx): {
1207
+ readonly s: string[];
1208
+ readonly j: string;
1209
+ /** The head of the loop, and the statements at the start of each item before the try and inside it. */
1210
+ readonly head: string;
1211
+ readonly key: readonly string[];
1212
+ readonly check: readonly string[];
1213
+ readonly skip: string | undefined;
1214
+ readonly fixed: boolean;
1215
+ readonly start: ReadonlySet<number>;
1216
+ /** True when the statements before the loop cannot throw. */
1217
+ readonly startSafe: boolean;
1218
+ readonly tests: readonly Expr[];
1219
+ readonly inner: Ctx;
1220
+ } {
1221
+ const { base: outer, tests } = testsOf(axis);
1222
+ // The reverse order of an axis is a loop from its end (AXIS.REVERSE). The validation keeps a base axis inside.
1223
+ const reverse = outer.t === "reverse";
1224
+ const base = outer.t === "reverse" ? outer.axis : outer;
1225
+ const j = this.fresh("j");
1226
+ const inner: Ctx = { ...ctx, focus: j, level: ctx.level + 1 };
1227
+ // The axis list goes over the array of its list (AXIS.LIST). The list evaluates at the node, before the loop, and an
1228
+ // error item is an item that fails.
1229
+ if (base.t === "list") {
1230
+ if (at.length > 0) throw new NotStandalone('the axis "list" with an address');
1231
+ const list = this.#hoist(this.#listOf(base.list, ctx), hasLoop(base.list));
1232
+ const a = this.fresh("A");
1233
+ const q = this.fresh("q");
1234
+ const head = reverse ? `for (let ${q} = ${a}.length - 1; ${q} >= 0; ${q}--) {` : `for (let ${q} = 0; ${q} < ${a}.length; ${q}++) {`;
1235
+ const key = [`const ${j} = ${a}[${q}][0];`];
1236
+ const check = [`if (${a}[${q}][1] === E) ${this.use("F")}();`];
1237
+ return { s: [...list.s, `const ${a} = ${list.v.code};`], j, head, key, check, skip: undefined, fixed: false, start: list.v.deps, startSafe: list.v.safe, tests, inner };
1238
+ }
1239
+ const s: string[] = [];
1240
+ let lo = "0";
1241
+ let hi = "n";
1242
+ let skip: string | undefined;
1243
+ // The targets of the axis all depend on no key, but its address can fail (V-051). The other axes start at their
1244
+ // address.
1245
+ let start: ReadonlySet<number> = NO_DEPS;
1246
+ const f = base.t === "all" && at.length === 0 ? undefined : this.fresh("f");
1247
+ if (f !== undefined) {
1248
+ const values = this.#addressValues(at, ctx);
1249
+ start = this.#addressDeps(at, ctx, values);
1250
+ const parts = this.#settle(values, start);
1251
+ s.push(...stmtsOf(...parts), `const ${f} = ${this.#address(at, ctx, parts)};`);
1252
+ }
1253
+ if (base.t === "others") skip = f;
1254
+ else if (base.t === "window") {
1255
+ if (!Number.isInteger(base.from) || !Number.isInteger(base.to)) throw new NotStandalone('the axis "window" with a bound that is not an integer');
1256
+ const h = this.fresh("h");
1257
+ lo = `Math.max(0, ${f as string} + Math.max(${base.from}, -n))`;
1258
+ s.push(`const ${h} = Math.min(n, ${f as string} + Math.min(${base.to}, n) + 1);`);
1259
+ hi = h;
1260
+ } else if (base.t !== "all") throw new NotStandalone(`the axis "${base.t}"`);
1261
+ const startSafe = at.every((m) => m.t === "origin");
1262
+ return { s, j, head: forHead(j, lo, hi, reverse), key: [], check: [], skip, fixed: f === undefined, start, startSafe, tests, inner };
1263
+ }
1264
+
1265
+ #list(op: string, target: ExprOf<"each">, rest: readonly Expr[], ctx: Ctx): Code {
1266
+ const strict = this.#strict(op, rest);
1267
+ const at = target.at ?? [];
1268
+ const { s, j, head, key, check, skip, fixed, start, startSafe, tests, inner } = this.#targetLoop(target.axis, at, ctx);
1269
+ const { level } = inner;
1270
+ // Inside the loop, a constant of the run evaluates once, before the loop over the keys of the run.
1271
+ const testCodes = tests.map((t) => this.#hoist(this.expr(t, inner), hasLoop(t)));
1272
+ const body = this.#hoist(this.expr(target.body, inner), hasLoop(target.body));
1273
+ // A count of all the items, whose body cannot fail, is the count of the records. A safe body covers its statements.
1274
+ if (op === "count" && fixed && tests.length === 0 && body.v.safe) return bare(plainValue("n", "number"));
1275
+ const deps = new Set([...start, ...[body, ...testCodes].flatMap((x) => [...x.v.deps])].filter((d) => d !== level));
1276
+ const r = this.#reduction(op, body.v.kind);
1277
+ const { v } = r;
1278
+ s.push(r.init);
1279
+ const item = [...check, ...testCodes.flatMap((t) => [...t.s, `if (!${this.#boolean(t.v)}) continue;`]), ...body.s];
1280
+ // An item whose tests and body cannot fail needs no try.
1281
+ const safeItem = check.length === 0 && body.v.safe && testCodes.every((t) => this.#safeBoolean(t.v));
1282
+ const loop = [
1283
+ ...key,
1284
+ ...(skip === undefined ? [] : [`if (${j} === ${skip}) continue;`]),
1285
+ ...(safeItem
1286
+ ? [...item, `const ${v} = ${body.v.code};`]
1287
+ : [`let ${v};`, "try {", ...ind(item), ` ${v} = ${body.v.code};`, "} catch {", strict ? ` ${this.use("F")}();` : " continue;", "}"]),
1288
+ r.step,
1289
+ ];
1290
+ s.push(head, ...ind(loop), "}");
1291
+ // A count without strict, and any, all and none over booleans without strict, cannot fail. The address of the axis
1292
+ // can fail, except at the focus or at the origin.
1293
+ const safe = startSafe && !strict && (op === "count" || (BOOLEAN_LIST_OPS.has(op) && body.v.kind === "boolean"));
1294
+ return { s, v: { code: r.result, kind: listKind(op, body.v.kind), safe, deps } };
1295
+ }
1296
+
1297
+ /**
1298
+ * This method gives the parts of a list op that reduces the values of its items. The parts are the variable `v` of
1299
+ * the value of an item, the first statement, the step and the result. A value of the wrong kind is an error of the op.
1300
+ */
1301
+ #reduction(op: string, kind: Kind | undefined): { readonly v: string; readonly init: string; readonly step: string; readonly result: string } {
1302
+ const a = this.fresh("a");
1303
+ const n = this.fresh("n");
1304
+ const v = this.fresh("x");
1305
+ const num = kind === "number" ? v : `${this.use("U")}(${v})`;
1306
+ const bool = kind === "boolean" ? v : `${this.use("B")}(${v})`;
1307
+ const inits: Readonly<Record<string, string>> = {
1308
+ count: `let ${n} = 0;`,
1309
+ sum: `let ${a} = 0;`,
1310
+ mean: `let ${a} = 0, ${n} = 0;`,
1311
+ any: `let ${a} = false;`,
1312
+ none: `let ${a} = false;`,
1313
+ all: `let ${a} = true;`,
1314
+ };
1315
+ const steps: Readonly<Record<string, string>> = {
1316
+ count: `${n}++;`,
1317
+ sum: `${a} += ${num};`,
1318
+ mean: `${a} += ${num}; ${n}++;`,
1319
+ min: `${a} = ${n}++ === 0 ? ${num} : Math.min(${a}, ${num});`,
1320
+ max: `${a} = ${n}++ === 0 ? ${num} : Math.max(${a}, ${num});`,
1321
+ any: `if (${bool}) ${a} = true;`,
1322
+ none: `if (${bool}) ${a} = true;`,
1323
+ all: `if (!${bool}) ${a} = false;`,
1324
+ first: `if (${n}++ === 0) ${a} = ${v};`,
1325
+ };
1326
+ const F = this.use("F");
1327
+ const results: Readonly<Record<string, string>> = {
1328
+ count: n,
1329
+ sum: this.#checked("number", a),
1330
+ mean: `(${n} === 0 ? ${F}() : ${this.#checked("number", `${a} / ${n}`)})`,
1331
+ any: a,
1332
+ all: a,
1333
+ none: `!${a}`,
1334
+ };
1335
+ return { v, init: inits[op] ?? `let ${a}, ${n} = 0;`, step: steps[op] as string, result: results[op] ?? `(${n} === 0 ? ${F}() : ${a})` };
1336
+ }
1337
+
1338
+ /**
1339
+ * This method prints a list as an array (LIST.VALUE): a pair of the key and the value of each item. A test that
1340
+ * fails, a body that fails and an error item of the axis list give the error sentinel as the value.
1341
+ */
1342
+ #eachList(e: ExprOf<"each">, ctx: Ctx): Code {
1343
+ const at = e.at ?? [];
1344
+ const { s, j, head, key, check, skip, start, startSafe, tests, inner } = this.#targetLoop(e.axis, at, ctx);
1345
+ const testCodes = tests.map((t) => this.#hoist(this.expr(t, inner), hasLoop(t)));
1346
+ const body = this.#hoist(this.expr(e.body, inner), hasLoop(e.body));
1347
+ const deps = new Set([...start, ...[body, ...testCodes].flatMap((x) => [...x.v.deps])].filter((d) => d !== inner.level));
1348
+ const list = this.fresh("L");
1349
+ const v = this.fresh("x");
1350
+ const item = [...check, ...testCodes.flatMap((t) => [...t.s, `if (!${this.#boolean(t.v)}) continue;`]), ...body.s];
1351
+ const safeItem = check.length === 0 && body.v.safe && testCodes.every((t) => this.#safeBoolean(t.v));
1352
+ const loop = [
1353
+ ...key,
1354
+ ...(skip === undefined ? [] : [`if (${j} === ${skip}) continue;`]),
1355
+ ...(safeItem ? [...item, `${list}.push([${j}, ${body.v.code}]);`] : [`let ${v};`, "try {", ...ind(item), ` ${v} = ${body.v.code};`, "} catch {", ` ${v} = E;`, "}", `${list}.push([${j}, ${v}]);`]),
1356
+ ];
1357
+ return { s: [...s, `const ${list} = [];`, head, ...ind(loop), "}"], v: { code: list, kind: undefined, safe: startSafe, deps, list: { item: body.v.kind } } };
1358
+ }
1359
+
1360
+ /**
1361
+ * This method prints sortBy and take (LIST.SORT, LIST.TAKE): a new array from the array of a list. An error item is
1362
+ * not in the new list, and with strict it is the error of the op.
1363
+ */
1364
+ #order(op: "sortBy" | "take", head: Expr, rest: readonly Expr[], ctx: Ctx): Code {
1365
+ const list = this.#listOf(head, ctx);
1366
+ // A missing count is the literal null, which is not a whole number, so take gives its error.
1367
+ const exprs = [head, ...(op === "take" ? [rest[0] ?? lit(null)] : [])];
1368
+ const strict = this.#strict(op, rest.slice(exprs.length - 1));
1369
+ const raw = [list, ...exprs.slice(1).map((x) => this.expr(x, ctx))];
1370
+ const deps = depsOf(...raw);
1371
+ const parts = this.#settle(raw, deps, exprs);
1372
+ const item = (list.v.list as ListInfo).item;
1373
+ return { s: stmtsOf(...parts), v: { code: `${this.use(op === "sortBy" ? "SB" : "TK")}(${[...parts.map((x) => x.v.code), String(strict)].join(", ")})`, kind: undefined, safe: false, deps, list: { item } } };
1374
+ }
1375
+
1376
+ /** This method prints a list op over a list that is not an each: a loop over its array, and nth (LIST.NTH). */
1377
+ #overList(op: string, head: Expr, rest: readonly Expr[], ctx: Ctx): Code {
1378
+ const list = this.#listOf(head, ctx);
1379
+ // A missing position is the literal null, which is not a whole number, so nth gives its error.
1380
+ const exprs = [head, ...(op === "nth" ? [rest[0] ?? lit(null)] : [])];
1381
+ const strict = this.#strict(op, rest.slice(exprs.length - 1));
1382
+ const raw = [list, ...exprs.slice(1).map((x) => this.expr(x, ctx))];
1383
+ const deps = depsOf(...raw);
1384
+ const parts = this.#settle(raw, deps, exprs);
1385
+ const [l] = parts as [Code];
1386
+ const item = (list.v.list as ListInfo).item;
1387
+ if (op === "nth") return { s: stmtsOf(...parts), v: { code: `${this.use("NT")}(${[...parts.map((x) => x.v.code), String(strict)].join(", ")})`, kind: item, safe: false, deps } };
1388
+ const r = this.#reduction(op, item);
1389
+ const { v } = r;
1390
+ const s = [...l.s, r.init, `for (const [, ${v}] of ${l.v.code}) {`, ` if (${v} === E) ${strict ? `${this.use("F")}();` : "continue;"}`, ` ${r.step}`, "}"];
1391
+ return { s, v: { code: r.result, kind: listKind(op, item), safe: false, deps } };
1392
+ }
1393
+
1394
+ /**
1395
+ * This method gives the names of a loop (LOOP.NAMES): a variable for each name of `init`, with its first value at the
1396
+ * node. Inside the loop, each name has the level `loop`. Thus a part that reads a name stays in the loop. A loop that
1397
+ * reads no key of the run is a constant of the run.
1398
+ */
1399
+ #loopNames(init: Names, ctx: Ctx, loop: number): { readonly s: string[]; readonly env: Map<string, Name>; readonly vars: ReadonlyMap<string, Name>; readonly deps: Set<number> } {
1400
+ const s: string[] = [];
1401
+ const env = new Map(ctx.env);
1402
+ const vars = new Map<string, Name>();
1403
+ const deps = new Set<number>();
1404
+ for (const [name, x] of Object.entries(init)) {
1405
+ const c = this.expr(x, ctx);
1406
+ if (c.v.kind === undefined) throw new NotStandalone(`the first value of the name "${name}" of a loop has no kind`);
1407
+ const v = this.fresh("l");
1408
+ s.push(...c.s, `let ${v} = ${c.v.code};`);
1409
+ const read: Name = { code: v, kind: c.v.kind, lazy: false, deps: new Set([loop]) };
1410
+ env.set(name, read);
1411
+ vars.set(name, read);
1412
+ for (const d of c.v.deps) deps.add(d);
1413
+ }
1414
+ return { s, env, vars, deps };
1415
+ }
1416
+
1417
+ /** This method gives the statements of one step of a loop: each new value first, and then each name gets its value. */
1418
+ #loopStep(step: Names, inner: Ctx, vars: ReadonlyMap<string, Name>): { readonly s: string[]; readonly deps: ReadonlySet<number> } {
1419
+ const s: string[] = [];
1420
+ const sets: string[] = [];
1421
+ const deps = new Set<number>();
1422
+ for (const [name, x] of Object.entries(step)) {
1423
+ const c = this.#hoist(this.expr(x, inner), hasLoop(x));
1424
+ const v = vars.get(name) as Name;
1425
+ if (c.v.kind !== v.kind) throw new NotStandalone(`a step of a loop changes the kind of the name "${name}"`);
1426
+ const t = this.fresh("t");
1427
+ s.push(...c.s, `const ${t} = ${c.v.code};`);
1428
+ sets.push(`${v.code} = ${t};`);
1429
+ for (const d of c.v.deps) deps.add(d);
1430
+ }
1431
+ return { s: [...s, ...sets], deps };
1432
+ }
1433
+
1434
+ /**
1435
+ * An iteration (ITERATE.LIMIT, ITERATE.UNTIL): a `for` loop with a variable for each name. An error of a value, of the
1436
+ * test or of the result throws, so it is the value of the iteration.
1437
+ */
1438
+ #iterate(e: ExprOf<"iterate">, ctx: Ctx): Code {
1439
+ // Stryker disable next-line UpdateOperator: a level of a loop is a name, so a count down gives other names, and the same code
1440
+ const loop = this.#loops++;
1441
+ const names = this.#loopNames(e.init, ctx, loop);
1442
+ const inner: Ctx = { ...ctx, env: names.env };
1443
+ const until = e.until === undefined ? undefined : this.expr(e.until, inner);
1444
+ const step = this.#loopStep(e.step, inner, names.vars);
1445
+ const result = this.expr(e.result, inner);
1446
+ const k = this.fresh("k");
1447
+ const body = [
1448
+ ...(until === undefined ? [] : [...until.s, `if (${this.#boolean(until.v)}) break;`]),
1449
+ `if (${k} === ${String(e.limit)}) ${until === undefined ? "break;" : `${this.use("F")}();`}`,
1450
+ ...step.s,
1451
+ ];
1452
+ const inside = [...(until?.v.deps ?? []), ...step.deps, ...result.v.deps].filter((d) => d !== loop);
1453
+ const deps = new Set([...names.deps, ...inside]);
1454
+ return { s: [...names.s, `for (let ${k} = 0; ; ${k}++) {`, ...ind(body), "}", ...result.s], v: { code: result.v.code, kind: result.v.kind, safe: false, deps } };
1455
+ }
1456
+
1457
+ /**
1458
+ * A fold (FOLD.ORDER, FOLD.ERROR): the loop over the targets of an axis, with a variable for each name. The tests read
1459
+ * only the names outside the fold. An error throws, so it is the value of the fold.
1460
+ */
1461
+ #fold(e: ExprOf<"fold">, ctx: Ctx): Code {
1462
+ // Stryker disable next-line UpdateOperator: a level of a loop is a name, so a count down gives other names, and the same code
1463
+ const loop = this.#loops++;
1464
+ const names = this.#loopNames(e.init, ctx, loop);
1465
+ const t = this.#targetLoop(e.axis, e.at ?? [], ctx);
1466
+ const tests = t.tests.map((x) => this.#hoist(this.expr(x, t.inner), hasLoop(x)));
1467
+ const step = this.#loopStep(e.step, { ...t.inner, env: names.env }, names.vars);
1468
+ const result = this.expr(e.result, { ...ctx, env: names.env });
1469
+ const body = [
1470
+ ...t.key,
1471
+ ...(t.skip === undefined ? [] : [`if (${t.j} === ${t.skip}) continue;`]),
1472
+ ...t.check,
1473
+ ...tests.flatMap((c) => [...c.s, `if (!${this.#boolean(c.v)}) continue;`]),
1474
+ ...step.s,
1475
+ ];
1476
+ const inside = [...tests.flatMap((c) => [...c.v.deps]), ...step.deps].filter((d) => d !== loop && d !== t.inner.level);
1477
+ const deps = new Set([...names.deps, ...t.start, ...inside, ...[...result.v.deps].filter((d) => d !== loop)]);
1478
+ return { s: [...names.s, ...t.s, t.head, ...ind(body), "}", ...result.s], v: { code: result.v.code, kind: result.v.kind, safe: false, deps } };
1479
+ }
1480
+
1481
+ /**
1482
+ * A node of the memo: one function of its keys for each structure, with an entry for each value of the keys. A key
1483
+ * that is a constant of the run is the variable of that constant, not a key of the function. A node with no other key
1484
+ * is a constant of the run itself.
1485
+ */
1486
+ #memoized(e: Expr, keys: readonly Expr[], ctx: Ctx): Code {
1487
+ const values = keys.map((k) => this.#hoist(this.expr(k, ctx)));
1488
+ const varying = keys.filter((_k, i) => (values[i] as Code).v.deps.size > 0);
1489
+ const params = varying.map(() => this.fresh("q"));
1490
+ const names = new Map(
1491
+ keys.map((k, i): [Expr, Name] => {
1492
+ const x = (values[i] as Code).v;
1493
+ const p = varying.indexOf(k);
1494
+ return [k, p < 0 ? this.#nameOf(x) : { code: params[p] as string, kind: x.kind, lazy: true, deps: new Set([1]) }];
1495
+ }),
1496
+ );
1497
+ const outer = this.#inside;
1498
+ this.#inside = e;
1499
+ const bodyCtx: Ctx = { origin: undefined, focus: undefined, level: 1, originLevel: 1, env: new Map(), fns: new Map(), keys: names };
1500
+ if (varying.length === 0) {
1501
+ const body = this.#hoist(this.expr(e, bodyCtx));
1502
+ this.#inside = outer;
1503
+ return body;
1504
+ }
1505
+ // The kinds of the keys decide the ops in the node, so they are a part of the structure. Each key of the function
1506
+ // can hold the error sentinel, so the nodes with a safe key and the nodes without one share it.
1507
+ const tokens = new Map(keys.map((k, i): [Expr, object] => [k, varying.includes(k) ? { "#": varying.indexOf(k), kind: (values[i] as Code).v.kind } : { "@": (names.get(k) as Name).code }]));
1508
+ const structure = canonical(e, (x) => tokens.get(x as Expr));
1509
+ let fn = this.#structures.get(structure);
1510
+ if (fn === undefined) {
1511
+ fn = this.fresh("m");
1512
+ this.#structures.set(structure, fn);
1513
+ this.memos = true;
1514
+ const cached = varying.length === 1 ? this.#cached(e, varying[0] as Expr, bodyCtx, fn) : undefined;
1515
+ if (cached !== undefined) {
1516
+ this.#kinds.set(fn, cached.kind);
1517
+ this.run.push(...cached.lines);
1518
+ } else {
1519
+ // The loop of the node gives statements.
1520
+ const body = this.expr(e, bodyCtx);
1521
+ this.#kinds.set(fn, body.v.kind);
1522
+ this.#lists.set(fn, body.v.list);
1523
+ this.run.push(`const ${fn} = ${this.use(params.length === 1 ? "M1" : "M")}((${params.join(", ")}) => {`, ...ind(body.s), ` return ${body.v.code};`, "});");
1524
+ }
1525
+ }
1526
+ this.#inside = outer;
1527
+ // Each key of the function gets its value, or the error sentinel.
1528
+ const s: string[] = [];
1529
+ const args = varying.map((k) => {
1530
+ const c = values[keys.indexOf(k)] as Code;
1531
+ if (c.v.safe && c.s.length === 0) return c.v.code;
1532
+ if (c.s.length === 0 && c.v.held !== undefined) return c.v.held;
1533
+ const t = this.fresh("k");
1534
+ s.push(...this.#store(t, c));
1535
+ return t;
1536
+ });
1537
+ return { s, v: { code: `${fn}(${args.join(", ")})`, kind: this.#kinds.get(fn), safe: false, deps: depsOf(...values), list: this.#lists.get(fn) } };
1538
+ }
1539
+
1540
+ /**
1541
+ * This method gives the code of a node of the memo whose key is only in one test of a list op: `test(T, key)`. Such a
1542
+ * node keeps its items in the helper `S`. One pass gives the tests before the test of the key and the value `T` of each
1543
+ * item. The rest of an item evaluates once, at the first key whose test is true.
1544
+ *
1545
+ * With the test `===`, each value `T` has a group of items. With `<` or `<=` and values `T` that do not decrease, the
1546
+ * items whose test is true are a prefix. Each prefix keeps its running value. The values add in the order of the items, so the result has the bits of the interpreter. An error before the test
1547
+ * of the key is an error of the item at each key. An error after it is an error at the keys whose test is true.
1548
+ */
1549
+ #cached(e: Expr, key: Expr, bodyCtx: Ctx, fn: string): { readonly lines: readonly string[]; readonly kind: Kind | undefined } | undefined {
1550
+ // Only an app has an op, and a node of the memo has a loop, so a list op has its target.
1551
+ const { op, args } = e as ExprOf<"app">;
1552
+ if (!LIST_OPS.has(op)) return undefined;
1553
+ const [target, ...rest] = args as [Expr, ...Expr[]];
1554
+ if (target.tag !== "each" || (target.at ?? []).length > 0) return undefined;
1555
+ const strict = this.#strict(op, rest);
1556
+ const kind = (bodyCtx.keys.get(key) as Name).kind;
1557
+ const { base, tests: raw } = testsOf(target.axis);
1558
+ const tests = raw.flatMap(partsOf);
1559
+ const at = tests.findIndex((t) => contains(t, key));
1560
+ const test = tests[at];
1561
+ if (base.t !== "all" || test?.tag !== "app" || test.args.length !== 2 || contains(target.body, key) || tests.some((t, i) => i !== at && contains(t, key))) return undefined;
1562
+ const [l, r] = test.args as [Expr, Expr];
1563
+ const keyFirst = l === key;
1564
+ const other = keyFirst ? r : l;
1565
+ if ((!keyFirst && r !== key) || contains(other, key)) return undefined;
1566
+ const j = this.fresh("j");
1567
+ const loop: Ctx = { ...bodyCtx, focus: j, level: 2 };
1568
+ const t = this.#hoist(this.expr(other, loop));
1569
+ // The test of the key is an op whose inline form cannot fail: then the loop over the items needs no try.
1570
+ const site = this.#facts.staticSite(test.op, keyFirst ? [kind, t.v.kind] : [t.v.kind, kind]);
1571
+ if (site?.t !== "fn" || site.bad || site.returns !== "boolean" || this.check("boolean") !== undefined) return undefined;
1572
+ // A static site of a domain has the function of the op of that domain.
1573
+ const form = inlineForm(Function.prototype.toString.call(((this.#domains[site.domain] as AnyDomain).ops[test.op] as { fn: (...a: never[]) => unknown }).fn));
1574
+ if (form?.params.length !== 2) return undefined;
1575
+ const before = tests.slice(0, at).map((x) => this.#hoist(this.expr(x, loop)));
1576
+ const after = tests.slice(at + 1).map((x) => this.#hoist(this.expr(x, loop)));
1577
+ const body = this.#hoist(this.expr(target.body, loop));
1578
+ const B = (v: Value): string => this.#boolean(v);
1579
+ // The kind of the test of the key: `===` gives the groups of equal values, and `<` or `<=` from T to the key gives
1580
+ // the prefixes of the items when T does not decrease. NaN satisfies neither test, so its item is in no group.
1581
+ const pattern = patternOf(form, (p) => (keyFirst ? 1 - p : p));
1582
+ const mode = pattern === "#0===#1" || pattern === "#1===#0" ? 1 : ["#0<#1", "#0<=#1", "#1>#0", "#1>=#0"].includes(pattern) ? 2 : 0;
1583
+ const testArgs = keyFirst ? ["q", "t"] : ["t", "q"];
1584
+ const keyTest = form.parts.map((p) => (typeof p === "number" ? `(${testArgs[p] as string})` : p)).join("");
1585
+ if (mode === 1) this.features.add("group");
1586
+ if (mode === 2) this.features.add("prefix");
1587
+ if (strict) this.features.add("strict");
1588
+ const F = this.use("F");
1589
+ // A function of the index of an item, from its statements and its value.
1590
+ const arrow = (lines: readonly string[], code: string): readonly string[] => (lines.length === 0 ? [`(${j}) => ${code}`] : [`(${j}) => {`, ...ind(lines), ` return ${code};`, "}"]);
1591
+ const pre = before.length === 0 ? undefined : before.every((x) => x.s.length === 0) ? arrow([], before.map((x) => B(x.v)).join(" && ")) : arrow(before.flatMap((x, i) => [...x.s, ...(i < before.length - 1 ? [`if (!${B(x.v)}) return false;`] : [])]), B((before.at(-1) as Code).v));
1592
+ // The value of an item: the tests after the test of the key, and the body. N is an item that a later test excludes,
1593
+ // and E is an error.
1594
+ const value =
1595
+ after.length === 0 && body.v.safe && body.s.length === 0
1596
+ ? arrow([], body.v.code)
1597
+ : [`(${j}) => {`, " try {", ...ind(ind([...after.flatMap((x) => [...x.s, `if (!${B(x.v)}) return N;`]), ...body.s])), ` return ${body.v.code};`, " } catch {", " return E;", " }", "}"];
1598
+ const [stepName, stepCode] = STEPS[op] as readonly [string, string];
1599
+ this.top.set(stepName, `const ${stepName} = ${stepCode};`);
1600
+ // A sum has the check of a number, and only a sum or a mean needs that check.
1601
+ const results: Readonly<Record<string, () => readonly [string, string]>> = {
1602
+ count: () => ["r_count", "(a, c) => c"],
1603
+ sum: () => [this.check("number") ?? "r_id", "(a) => a"],
1604
+ mean: () => ["r_mean", `(a, c) => (c === 0 ? ${F}() : ${this.#checked("number", "a / c")})`],
1605
+ any: () => ["r_id", "(a) => a"],
1606
+ all: () => ["r_id", "(a) => a"],
1607
+ none: () => ["r_not", "(a) => !a"],
1608
+ };
1609
+ const [resultName, resultCode] = results[op]?.() ?? ["r_one", `(a, c) => (c === 0 ? ${F}() : a)`];
1610
+ if (!this.top.has(resultName)) this.top.set(resultName, `const ${resultName} = ${resultCode};`);
1611
+ const a0 = op === "sum" || op === "mean" ? "0" : op === "all" ? "true" : BOOLEAN_LIST_OPS.has(op) ? "false" : "undefined";
1612
+ // The values of an op of numbers or of booleans have that kind, or the result is an error. Count takes each kind.
1613
+ const needs = op === "count" ? undefined : listKind(op, undefined);
1614
+ const ok = needs === undefined || body.v.kind === needs ? [] : [`(x) => typeof x === "${needs}"`];
1615
+ if (ok.length > 0) this.features.add("ok");
1616
+ if (pre !== undefined) this.features.add("pre");
1617
+ const fns = [arrow(t.s, t.v.code), value, [`(t, q) => ${keyTest}`], ...(pre === undefined && ok.length === 0 ? [] : [pre ?? ["undefined"]]), ...(ok.length === 0 ? [] : [ok])];
1618
+ const lines = fns.flatMap((x, i) => [...x.slice(0, -1), `${x.at(-1) ?? ""}${i < fns.length - 1 ? "," : ""}`]);
1619
+ return { lines: [`const ${fn} = ${this.use("S")}(n, ${mode}, ${String(strict)}, ${a0}, ${stepName}, ${resultName},`, ...ind(lines), ");"], kind: listKind(op, body.v.kind) };
1620
+ }
1621
+
1622
+ /** This method gives the code of the program at the key of the run. A constant of the run evaluates once. */
1623
+ root(expr: Expr): Code {
1624
+ const c = this.#hoist(this.expr(expr, { origin: "o", focus: "o", level: 1, originLevel: 1, env: new Map(), fns: new Map(), keys: new Map() }));
1625
+ // A function of an op with an inline form at each of its sites needs no declaration.
1626
+ for (const [name, form] of this.#forms) if (form !== undefined && !this.#called.has(name)) this.top.delete(name);
1627
+ return c;
1628
+ }
1629
+
1630
+ /**
1631
+ * This method gives a text that is the same for two expressions with the same structure and the same reads. A name
1632
+ * that the expression does not bind gives its variable in the code, and a key of the memo gives its variable too.
1633
+ */
1634
+ #constKey(e: Expr, ctx: Ctx): string {
1635
+ // A name gives its variable for each read, also for a read of a name that the expression binds. The variable depends
1636
+ // only on the name, so two expressions with the same text have the same value.
1637
+ return canonical(e, (x) => {
1638
+ const key = ctx.keys.get(x as Expr);
1639
+ if (key !== undefined) return { "@": key.code };
1640
+ const node = x as Expr | undefined;
1641
+ if (node?.tag === "var") return { $: ctx.env.get(node.name)?.code ?? node.name };
1642
+ // A call gives the number of the binding of its function, so two functions with one name give two keys.
1643
+ return node?.tag === "call" ? { "()": node.fn, of: ctx.fns.get(node.fn)?.id ?? null, args: node.args } : undefined;
1644
+ });
1645
+ }
1646
+ }
1647
+
1648
+ /**
1649
+ * This function prints a program as a standalone ES module. The module exports `VexContractError`, `VEX_ERROR` and a
1650
+ * function that takes the records and the variables and gives the value at each key. It is pure, so a build can use it.
1651
+ */
1652
+ export function emitModule(expr: Expr, options: ModuleOptions): Emitted {
1653
+ const name = options.name ?? "run";
1654
+ if (!/^[A-Za-z_$][\w$]*$/.test(name)) return { ok: false, reason: `the name "${name}" is not a JavaScript name` };
1655
+ // EVAL.SHAPE: a module of an expression that is not valid has no use, so the printer gives the reason.
1656
+ const shape = shapeError(expr);
1657
+ if (shape !== undefined) return { ok: false, reason: shape };
1658
+ const p = new Printer(expr, options);
1659
+ let value: Code;
1660
+ try {
1661
+ value = p.root(expr);
1662
+ } catch (thrown) {
1663
+ // Each error of the printer is a NotStandalone. Another exception is a defect, so it goes to the caller.
1664
+ if (!(thrown instanceof NotStandalone)) throw thrown;
1665
+ return { ok: false, reason: thrown.message };
1666
+ }
1667
+ p.use("C");
1668
+ const helpers = new Set<Helper>();
1669
+ // A helper comes after the helpers that it needs. A set keeps the first place of each helper.
1670
+ const add = (h: Helper): void => {
1671
+ for (const x of NEEDS[h]) add(x);
1672
+ helpers.add(h);
1673
+ };
1674
+ const fields = Object.entries(options.schema.fields ?? {});
1675
+ const vars = Object.entries(options.schema.vars ?? {});
1676
+ let fieldChecks: string;
1677
+ let varChecks: string;
1678
+ try {
1679
+ fieldChecks = fields.map(([f, k]) => ` || ${p.against(k, `r[${JSON.stringify(f)}]`)}`).join("");
1680
+ varChecks = vars.map(([v, k]) => ` || ${p.against(k, `vars[${JSON.stringify(v)}]`)}`).join("");
1681
+ } catch (thrown) {
1682
+ if (!(thrown instanceof NotStandalone)) throw thrown;
1683
+ return { ok: false, reason: thrown.message };
1684
+ }
1685
+ [...p.helpers].toSorted().forEach(add);
1686
+ const lines = [
1687
+ "// Generated by @mark1russell7/vex-compiler from a Vex program. Do not edit.",
1688
+ "/** The error of a run whose input does not keep the schema of the program. */",
1689
+ "export class VexContractError extends Error {}",
1690
+ "/** The value of a key where the program gives an error of Vex. */",
1691
+ "export const VEX_ERROR = Object.freeze({ vexError: true });",
1692
+ "const E = {};",
1693
+ ...(p.memos ? ["const Z = {};"] : []),
1694
+ // The values of an item of a node that keeps its items: excluded by a later test, and of the wrong kind.
1695
+ ...(helpers.has("S") ? ["const N = {}, W = {};"] : []),
1696
+ ...[...helpers].map((h) => (h === "S" ? helperS(p.features) : HELPERS[h])),
1697
+ ...p.top.values(),
1698
+ `export function ${name}(records, vars) {`,
1699
+ ' if (!Array.isArray(records)) C("the records are not an array");',
1700
+ " const R = records;",
1701
+ " const n = R.length;",
1702
+ " for (let i = 0; i < n; i++) {",
1703
+ " const r = R[i];",
1704
+ ` if (typeof r !== "object" || r === null${fieldChecks}) C(\`the record \${i} does not keep the schema\`);`,
1705
+ " }",
1706
+ ` if (typeof vars !== "object" || vars === null${varChecks}) C("the variables do not keep the schema");`,
1707
+ ...[...p.vars].map(([v, code]) => ` const ${code} = vars[${JSON.stringify(v)}];`),
1708
+ ...ind(p.run),
1709
+ " const out = [];",
1710
+ " for (let o = 0; o < n; o++) {",
1711
+ " try {",
1712
+ ...ind(ind(ind(value.s))),
1713
+ ` out.push(${value.v.code});`,
1714
+ " } catch {",
1715
+ " out.push(VEX_ERROR);",
1716
+ " }",
1717
+ " }",
1718
+ " return out;",
1719
+ "}",
1720
+ "",
1721
+ ];
1722
+ return { ok: true, source: lines.join("\n") };
1723
+ }