@mark1russell7/vex-compiler 0.17.2 → 0.18.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 CHANGED
@@ -31,10 +31,16 @@
31
31
  * starts the search of `SheetRun`. Thus each cell on a cycle gives the error of Vex. A cell can hold a list, and a
32
32
  * formula reads it with the list ops (COMPILE.MODULE.SHEET.LIST).
33
33
  */
34
- import { addrExprs, app, CELL_KIND, children, fromDocument, isDocument, isFieldName, isListOp, isVexList, lit, moveExpr, nestingOf, rec, shapeError, vexList, type AnyDomain, type Axis, type CellFormulas, type Envelope, type Expr, type ExprOf, type ItemNames, type Move, type Names, type PrimitiveKind, type VexList } from "@mark1russell7/vex";
34
+ import { addrExprs, type AnyDomain, app, type Axis, axisExprs, CELL_KIND, type CellFormulas, children, columnOrder, type Envelope, evaluate, type Expr, type ExprOf, fromDocument, isCellRef, isDocument, isFieldName, isListOp, isVexList, type ItemNames, joinKind, limitAxis, listOf, lit, MAX_ITERATIONS, monotoneError, type Move, moveExpr, type Names, nestingError, nestingOf, type PrimitiveKind, readsOf, rec, shapeError, sizeError, space as spaces, splitLimit, stepError, vexList, type VexList, type VexStep } from "@mark1russell7/vex";
35
35
  import { factsOf, kindOfDomain, primitiveOf, type Facts, type Kind, type ListKind, type Schema } from "./facts.ts";
36
+ import { functionText } from "./fn-text.ts";
36
37
  import { memoNodes } from "./memo.ts";
37
- import { columnOrder, isCellRef, keyOrderOf, readsFinished, readsOf } from "./sheet-order.ts";
38
+ import { deadConstants, keepFaults, namesOfCode, tidy, type Tidied, wordsOf } from "./module-tidy.ts";
39
+ import { canonical, type KeyScope, KeyTable, keyText, NotStandalone } from "./scope-key.ts";
40
+ import { keyOrderOf, readsFinished } from "./sheet-order.ts";
41
+ import { originalOf, placesRead, unsharedAll } from "./unshared.ts";
42
+ // This import is the last one. Before the import of `@mark1russell7/vex`, it cost 2 to 6 % on two rows of the module bench (V-093).
43
+ import { sameValue } from "@mark1russell7/coeval";
38
44
 
39
45
  /** The options of a standalone module. */
40
46
  export interface ModuleOptions {
@@ -42,17 +48,47 @@ export interface ModuleOptions {
42
48
  /** The kinds of the fields of the records and of the variables. A module reads only the names of its schema. */
43
49
  readonly schema: Schema;
44
50
  /**
45
- * The name of the function that the module exports. The default is `run`. A reserved word, a name that the module
46
- * declares and a global that a module reads (`MODULE_GLOBALS`) are not names of the run (V-060).
51
+ * The name of the function that the module exports. The default is `run`. A reserved word, `VEX_ERROR` and
52
+ * `VexContractError` are not names of the run (V-060). Each other name hides nothing from the code (COMPILE.MODULE.NAME).
47
53
  */
48
54
  readonly name?: string;
49
55
  /**
50
- * The space of the records. In each space, the key of a record is the text of its position. The default `array`
56
+ * The space of the records. In each space, the key of a record is the text of its position, unless the option
57
+ * `keys` is true. The default `array`
51
58
  * has no parents. A `tree` takes the parents as the third argument of the run (COMPILE.MODULE.TREE). Each entry
52
59
  * is the position of the parent of its record, or -1 for a root. A `graph` takes the edges as the third argument
53
60
  * (COMPILE.MODULE.GRAPH). Each entry is an array of the positions of the ends of the edges from its record, in order.
54
61
  */
55
62
  readonly space?: "array" | "tree" | "graph";
63
+ /**
64
+ * The highest step of the language that the host accepts (STEP.MAX). The default is B. A program that needs a higher
65
+ * step gives a reason that names its step.
66
+ */
67
+ readonly maxStep?: VexStep;
68
+ /**
69
+ * True to fuse the chains of list ops into loops (`COMPILER.md` §7.6), and false for the code without fusion
70
+ * (COMPILE.MODULE.FUSE.OFF). The default is true. In this version, the two values print the same code.
71
+ */
72
+ readonly fuse?: boolean;
73
+ /**
74
+ * The form of the lists of the input and of the result (COMPILE.MODULE.LIST.PLAIN). The default `envelope` gives each
75
+ * list as a `vex.list`. With `plain`, a list is an array of the values of its items, and an error item is `VEX_ERROR`.
76
+ * The key of an item of the input is the text of its position, and the result has no keys. A list in a record or in
77
+ * an argument of an op stays a `vex.list`.
78
+ */
79
+ readonly lists?: "envelope" | "plain";
80
+ /**
81
+ * True when the run takes the keys of the records as its last argument (COMPILE.MODULE.KEYS). The argument is an array
82
+ * with one text for each record, and each text is different. A program that reads no key ignores it and prints the
83
+ * same text as without the option. The default is false.
84
+ */
85
+ readonly keys?: boolean;
86
+ /**
87
+ * What a catch of the module does with an exception that no function of a domain gives (COMPILE.MODULE.FAULT). The
88
+ * default `value` gives the error of Vex for each exception. With `throw`, the exception leaves the run, so a fault
89
+ * of the printed code does not become a value. An exception of a function of a domain stays an error of Vex.
90
+ */
91
+ readonly faults?: "value" | "throw";
56
92
  }
57
93
 
58
94
  /** The options of a module of a sheet (COMPILE.MODULE.SHEET): the options of a module, and the parts of a sheet. */
@@ -74,8 +110,45 @@ export type { ListKind } from "./facts.ts";
74
110
  /** The source of a standalone module, or the reason that the program cannot be one. */
75
111
  export type Emitted = { readonly ok: true; readonly source: string } | { readonly ok: false; readonly reason: string };
76
112
 
77
- /** The error of a construct that a standalone module does not have. */
78
- class NotStandalone extends Error {}
113
+
114
+ /**
115
+ * The error that stops the second print of a fast sum (`#packed`) or of the steps of a fold (`#packedSteps`). Then the
116
+ * loop keeps the code of its first print.
117
+ */
118
+ class NoPack extends Error {}
119
+
120
+ /**
121
+ * The state of the second print of a fast sum (`#packed`) or of the steps of a fold (`#packedSteps`). It has the foci
122
+ * of the loops whose reads of a column read its pack. It also has the local name of the pack of each column.
123
+ */
124
+ interface Pack {
125
+ readonly foci: Set<string>;
126
+ /** True when a column of the function that the printer prints has a pack too, with a variable in that function. */
127
+ readonly calls: boolean;
128
+ readonly cols: Map<string, string>;
129
+ /** The value locals that the second print makes. Each one is a local of its loop until a line of the run declares it. */
130
+ readonly locals: Set<string>;
131
+ /** The count of the calls that the second print puts at their place. A count over `INLINES` stops the print. */
132
+ inlines: number;
133
+ }
134
+
135
+ /**
136
+ * The state of the keys of one print (COMPILE.MODULE.KEYS). With `keyed`, the code uses the keys of the argument of the
137
+ * run. The printer sets `read` when the program can show a key of a record to a part of the code or to the host.
138
+ */
139
+ interface KeyPrint {
140
+ readonly keyed: boolean;
141
+ read: boolean;
142
+ }
143
+
144
+ /** The helpers that show the key of an item: a compare of keys, and a `vex.list` of a result, an argument or a field. */
145
+ const KEY_READS: ReadonlySet<string> = new Set(["GT", "WO", "WOC", "LO", "LS", "LOC", "LSC", "LV", "LVC", "LC"]);
146
+
147
+ /** The most calls that the second print of a fast sum puts at their place. Thus a chain of calls stays linear. */
148
+ const INLINES = 64;
149
+
150
+ /** The list ops that a fast sum can be: each one adds or compares numbers, and its step cannot throw (`#packed`). */
151
+ const PACK_OPS: ReadonlySet<string> = new Set(["sum", "mean", "min", "max"]);
79
152
 
80
153
  /**
81
154
  * A value of the printer: its code, its kind if the printer knows it, and true when its code cannot throw. A literal,
@@ -110,6 +183,45 @@ interface ListInfo {
110
183
  readonly texts?: boolean;
111
184
  /** True for a list without items: the empty literal, and a list from it. Such a list fits each list. */
112
185
  readonly empty?: boolean;
186
+ /** True when no item of the list holds the error sentinel (COMPILE.MODULE.FUSE.FACTS). Fusion uses this fact. */
187
+ readonly clean?: boolean;
188
+ /** True when no other part of the code holds the array of the list, so an op can take the array as its own. */
189
+ readonly fresh?: boolean;
190
+ }
191
+
192
+ /** This function gives the facts of a list without the facts of fusion. A signature and a key of the memo use them. */
193
+ /** The facts of the prints of one program about the names of loops that start with the empty list (COMPILE.MODULE.LOOP.EMPTY). */
194
+ interface EmptyStarts {
195
+ /** The kinds of the items that the steps give, by the expression of the step of each name. */
196
+ readonly found: Map<Expr, Pick<ListInfo, "item" | "inner">>;
197
+ /** The expressions of a program with one object at each place. The prints use one set of copies, so `found` holds for each print. */
198
+ readonly copies: Map<object, readonly Expr[]>;
199
+ /** True for a print that only looks for these kinds. There, each name without a kind counts as an empty list. */
200
+ readonly seek: boolean;
201
+ }
202
+
203
+ function plainList(l: ListInfo | undefined): ListInfo | undefined {
204
+ if (l === undefined) return undefined;
205
+ const { clean: _clean, fresh: _fresh, ...rest } = l;
206
+ return { ...rest, inner: plainList(l.inner) };
207
+ }
208
+
209
+ /** This function gives the facts of a list that another part of the code can hold: the list is not fresh. */
210
+ function heldList(l: ListInfo | undefined): ListInfo | undefined {
211
+ return l?.fresh === true ? { ...l, fresh: false } : l;
212
+ }
213
+
214
+ /**
215
+ * The facts of fusion of a list node of a program (COMPILE.MODULE.FUSE.FACTS). They are `clean` for the list and for
216
+ * each level of its items, `fresh` and the count of the reads of its value. A count of `Infinity` tells that a loop, a
217
+ * memo node or the loop over the keys reads the value again. The tests of the analysis read these facts.
218
+ */
219
+ export interface ListFacts {
220
+ readonly clean: boolean;
221
+ /** The fact `clean` of each level of a list of lists, from the outside in. */
222
+ readonly inner: readonly boolean[];
223
+ readonly fresh: boolean;
224
+ readonly reads: number;
113
225
  }
114
226
 
115
227
  /** The op of each step of `reduce` (COMPILE.MODULE.REDUCE): the name of the op, and the value of the option `domain`. */
@@ -124,6 +236,68 @@ interface Code {
124
236
  readonly v: Value;
125
237
  }
126
238
 
239
+ /**
240
+ * The code of a list in a fused loop (COMPILE.MODULE.FUSE). It has the statements that push its items into the output
241
+ * of the loop, and their levels. It also has the fact that they cannot throw, and the facts of the list.
242
+ */
243
+ interface Pushed {
244
+ readonly s: readonly string[];
245
+ readonly deps: ReadonlySet<number>;
246
+ readonly safe: boolean;
247
+ readonly list: ListInfo | undefined;
248
+ }
249
+
250
+ /**
251
+ * The code of a list of `fill` that a loop or `count` reads only as a range (COMPILE.MODULE.FILL.RANGE). The module
252
+ * makes no array for it. The count checks the arguments, as `FI` does. Each item has the key of its position and the
253
+ * value `item`, a name or a literal. The statements come before the count, and `count.safe` covers them too.
254
+ */
255
+ interface Range {
256
+ readonly s: readonly string[];
257
+ readonly count: Value;
258
+ readonly item: string;
259
+ readonly info: ListInfo;
260
+ }
261
+
262
+ /**
263
+ * A part of a fused loop before the decision about the constants of the run (COMPILE.MODULE.FUSE). Its function `s`
264
+ * gives its statements. With `settle`, a part that is a constant of the run evaluates once, before the loop over the keys.
265
+ */
266
+ interface Part {
267
+ readonly s: (settle: boolean) => readonly string[];
268
+ readonly deps: ReadonlySet<number>;
269
+ readonly safe: boolean;
270
+ readonly list: ListInfo | undefined;
271
+ }
272
+
273
+ /** The tags of the nodes that can read at the focus. Only a node with one of them can be a column of the run. */
274
+ const FOCUS_TAGS: ReadonlySet<string> = new Set(["ref", "ext", "call", "each", "fold"]);
275
+
276
+ /** This function tells if an expression has a node that can read at the focus. */
277
+ const readsFocus = (e: Expr): boolean => FOCUS_TAGS.has(e.tag) || (e.tag === "iterate" && limitAxis(e) !== undefined) || children(e).some(readsFocus);
278
+
279
+ /**
280
+ * This function tells if an expression has a node that can read a cell: a read of a cell or a call. The interpreter
281
+ * evaluates each list of an append, also after an error. Thus a search of a sheet sees each read of a cell.
282
+ */
283
+ const readsCells = (e: Expr): boolean => e.tag === "ext" || e.tag === "call" || children(e).some(readsCells);
284
+
285
+ /** This function tells if an expression is the literal 1. */
286
+ // Stryker disable next-line OptionalChaining: each caller gives an argument.
287
+ const isOne = (e: Expr | undefined): boolean => e?.tag === "lit" && e.value === 1;
288
+
289
+ /** This function gives the value of a literal. For each other expression, it gives undefined, also for a node with an extra field `value`. */
290
+ const literalOf = (e: Expr): unknown => (e.tag === "lit" ? e.value : undefined);
291
+
292
+ /** The kinds of a literal whose code is its value. A read of such code at each item costs nothing (COMPILE.MODULE.FILL.RANGE). */
293
+ const PLAIN_LITERALS: ReadonlySet<string> = new Set(["number", "string", "boolean"]);
294
+
295
+ /** This function tells if an expression reads nothing of a run: it has only literals and ops. */
296
+ const isClosed = (e: Expr): boolean => e.tag === "lit" || (e.tag === "app" && e.args.every((x) => isClosed(x)));
297
+
298
+ /** The space of the evaluation of an expression that reads nothing of a run. */
299
+ const ONE_RECORD = spaces.array([{}]);
300
+
127
301
  /** A name of the program in the code: its variable, its kind, true when it can hold the error sentinel, and its levels. */
128
302
  interface Name {
129
303
  readonly code: string;
@@ -156,6 +330,12 @@ const withNames = (env: ReadonlyMap<string, Name>, items: ReadonlyMap<string, Na
156
330
  */
157
331
  const CELLS = -1;
158
332
 
333
+ /**
334
+ * The level of a read of a column in its step (COMPILE.FIX.MODULE). A row changes in each round. Thus a value that reads
335
+ * a row is not a constant or a column of the run. The `fix` node removes this level.
336
+ */
337
+ const ROUNDS = -2;
338
+
159
339
  /** The name of the function of a run of a sheet that reads a cell: its column and its position. */
160
340
  const READ_CELL = "RC";
161
341
 
@@ -198,16 +378,65 @@ interface Ctx {
198
378
  readonly keys: ReadonlyMap<Expr, Name>;
199
379
  /** The bound functions (FN.BIND), with the context of their binding. */
200
380
  readonly fns: ReadonlyMap<string, BoundFn>;
381
+ /** The columns of the steps around the node (COMPILE.FIX.MODULE): the name of the array of the last round, and its kind. */
382
+ readonly columns: ReadonlyMap<string, FixColumn>;
383
+ }
384
+
385
+ /** A column in the step of its `fix`: the name of the array with the value of each row, and the kind of the values. */
386
+ interface FixColumn {
387
+ readonly code: string;
388
+ readonly kind: Kind;
389
+ }
390
+
391
+ /** The code of the step of one name of a loop: the statements of its new value and the statement that sets it. */
392
+ interface StepPart {
393
+ readonly name: string;
394
+ readonly s: readonly string[];
395
+ readonly set: string;
396
+ /** True when the value of the step cannot throw. */
397
+ readonly safe: boolean;
398
+ }
399
+
400
+ /** The printed step of a loop: its statements, their levels, the names that append to their own lists, and the code of each name. */
401
+ interface LoopStep {
402
+ readonly s: readonly string[];
403
+ readonly deps: ReadonlySet<number>;
404
+ readonly owners: readonly Owner[];
405
+ readonly parts: readonly StepPart[];
406
+ }
407
+
408
+ /** The parts of a printed fold that its scan reads (COMPILE.MODULE.SCAN): its names, its targets, its test, its steps and its result. */
409
+ interface ScanParts {
410
+ readonly loop: number;
411
+ readonly names: { readonly s: readonly string[]; readonly vars: ReadonlyMap<string, Name>; readonly deps: ReadonlySet<number> };
412
+ readonly t: { readonly s: readonly string[]; readonly j: string; readonly key: readonly string[]; readonly check: readonly string[]; readonly skip: string | undefined; readonly inner: Ctx; readonly tests: readonly Expr[] };
413
+ readonly test: Code | undefined;
414
+ readonly step: LoopStep;
415
+ readonly result: Code;
201
416
  }
202
417
 
203
418
  /**
204
419
  * A name of a loop whose step appends to its own list (COMPILE.MODULE.APPEND.OWN). It has the name, its read in the
205
420
  * loop and the variable of the array of its last append. The printer makes the variable at the first append that uses it.
421
+ * With `adopt`, the variable starts with the first list of the name, so the first append makes no copy
422
+ * (COMPILE.MODULE.FUSE.ADOPT). With `sure`, each append of the name gets the array of the variable as its list. Then
423
+ * an append of one item pushes the item with no check.
206
424
  */
207
425
  interface Owner {
208
426
  readonly name: string;
209
427
  readonly read: Name;
210
428
  w: string | undefined;
429
+ readonly adopt: boolean;
430
+ readonly sure: boolean;
431
+ }
432
+
433
+ /**
434
+ * A `let` in the result of a loop that binds the list of an owner to the name `bind` (COMPILE.MODULE.FUSE.ADOPT). The
435
+ * append nodes in `nodes` append to the list of `bind` in the body of the let. They get the owner when the let prints.
436
+ */
437
+ interface Relay {
438
+ readonly bind: string;
439
+ readonly nodes: readonly Expr[];
211
440
  }
212
441
 
213
442
  /**
@@ -265,10 +494,16 @@ interface Spec {
265
494
  }
266
495
 
267
496
  /** The name of a helper of the generated code. */
268
- type Helper = "F" | "C" | "T" | "L" | "Q" | "G" | "B" | "U" | "X" | "I" | "K" | "M" | "M1" | "S" | "V" | "SB" | "SK" | "TK" | "VW" | "NT" | "CT" | "FS" | "FI" | "LI" | BuildHelper | TreeHelper | GraphHelper | SheetHelper;
497
+ type Helper = "F" | "C" | "T" | "L" | "Q" | "G" | "B" | "U" | "X" | "I" | "K" | "M" | "M1" | "S" | "V" | "SB" | "SK" | "TK" | "VW" | "NT" | "CT" | "FS" | "FI" | "FN" | "TN" | "LI" | "LA" | "LP" | "LS" | "KC" | "KP" | BuildHelper | TreeHelper | GraphHelper | SheetHelper | CleanHelper | "SBI" | "SKI" | "PF" | "QA" | "AI" | "AW" | "KS";
498
+
499
+ /**
500
+ * The helpers of the clean form (COMPILE.MODULE.FUSE.CLEAN). Each one is the helper without the last letter `C`, for
501
+ * lists that the facts prove clean. Thus it has no scan of `V`, no `VW` and no test of the sentinel.
502
+ */
503
+ type CleanHelper = "SBC" | "SKC" | "TKC" | "DRC" | "AOC" | "AIC" | "AWC" | "WOC" | "FLC" | "IXC" | "NTC" | "SNC" | "FSC" | "LOC" | "LSC" | "LVC" | "LPC";
269
504
 
270
505
  /** The helpers of the list ops that build a list (LIST.BUILD), of `get` (LIST.GET) and of `indexOf` (LIST.INDEXOF). */
271
- type BuildHelper = "DR" | "AP" | "AO" | "WO" | "FL" | "GT" | "IX";
506
+ type BuildHelper = "DR" | "AP" | "AO" | "WO" | "FL" | "GT" | "IX" | "SN";
272
507
 
273
508
  /** The helpers of a tree space (COMPILE.MODULE.TREE). */
274
509
  type TreeHelper = "PT" | "CH" | "SG" | "PR" | "UP" | "SO" | "AN" | "BF";
@@ -277,7 +512,7 @@ type TreeHelper = "PT" | "CH" | "SG" | "PR" | "UP" | "SO" | "AN" | "BF";
277
512
  type GraphHelper = "GR" | "GI" | "RB";
278
513
 
279
514
  /** The helpers of a sheet (COMPILE.MODULE.SHEET): the state of a run of a sheet, and the order of the keys of a tree. */
280
- type SheetHelper = "SH" | "KO" | "DO" | "LO" | "LC" | "LV";
515
+ type SheetHelper = "SH" | "KO" | "DO" | "LO" | "LC" | "LV" | "LCP";
281
516
 
282
517
  /** The helpers of the generated code. A module has only the helpers that it uses. */
283
518
  const HELPERS: Readonly<Record<Exclude<Helper, "S">, string>> = {
@@ -291,6 +526,48 @@ const HELPERS: Readonly<Record<Exclude<Helper, "S">, string>> = {
291
526
  // A column of the run: the value of an expression at each record, on its first read.
292
527
  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; }; }",
293
528
  G: "function G(x) { return x === E ? F() : x; }",
529
+ // The pack of a column of the run: an array with the value of the column at each record (`#packed`).
530
+ QA: "function QA(n, f) { const a = []; for (let j = 0; j < n; j++) a.push(f(j)); return a; }",
531
+ // A fold over the targets before the origin, as a scan (COMPILE.MODULE.SCAN). The first call evaluates the first
532
+ // state and the value of each target. When these values do not decrease, the targets of each origin are a prefix,
533
+ // and each prefix keeps its state. NaN satisfies no test, so its target is in no prefix.
534
+ PF: [
535
+ "function PF(n, init, key, test, step, result) {",
536
+ " let ts, js, a0, bad, mono, pa;",
537
+ " return (q) => {",
538
+ " if (ts === undefined) {",
539
+ " ts = [];",
540
+ " js = [];",
541
+ " bad = false;",
542
+ " try { a0 = init(); } catch { a0 = E; }",
543
+ " for (let j = 0; j < n; j++) {",
544
+ " let t;",
545
+ " try { t = key(j); } catch { bad = true; break; }",
546
+ " if (t !== t) continue;",
547
+ " ts.push(t);",
548
+ " js.push(j);",
549
+ " }",
550
+ " mono = true;",
551
+ " for (let i = 1; i < ts.length; i++) if (!(ts[i - 1] <= ts[i])) mono = false;",
552
+ " pa = [a0];",
553
+ " }",
554
+ " if (a0 === E || bad || q === E) F();",
555
+ " if (!mono) {",
556
+ " let a = a0;",
557
+ " for (let i = 0; i < ts.length; i++) if (test(ts[i], q)) a = step(a, js[i]);",
558
+ " return result(a);",
559
+ " }",
560
+ " let lo = 0, hi = ts.length;",
561
+ " while (lo < hi) {",
562
+ " const h = (lo + hi) >> 1;",
563
+ " if (test(ts[h], q)) lo = h + 1;",
564
+ " else hi = h;",
565
+ " }",
566
+ " for (let i = pa.length - 1; i < lo; i++) pa.push(step(pa[i], js[i]));",
567
+ " return result(pa[lo]);",
568
+ " };",
569
+ "}",
570
+ ].join("\n"),
294
571
  B: 'function B(x) { return typeof x === "boolean" ? x : F(); }',
295
572
  U: 'function U(x) { return typeof x === "number" ? x : F(); }',
296
573
  X: "function X(t, n) { return t >= 0 && t < n ? t : F(); }",
@@ -345,6 +622,17 @@ const HELPERS: Readonly<Record<Exclude<Helper, "S">, string>> = {
345
622
  FS: "function FS(l, s) { const o = VW(l); return (s && o.length < l.length) || o.length === 0 ? F() : o[0][1]; }",
346
623
  // fill (LIST.FILL, COMPILE.MODULE.FILL): n items with the value v, and the keys 0 to n - 1. A count that is not a whole
347
624
  // number from 0 to 100000, or a missing value, is the error of the interpreter. Each item can share the array of a list.
625
+ // setNth (LIST.SETNTH, COMPILE.MODULE.SETNTH): a new array with a new pair at the position i. The item keeps its key.
626
+ // V removes the error items, so the position counts the items with values. The old array and its pairs do not change.
627
+ SN: [
628
+ "function SN(l, i, v, s) {",
629
+ " const x = V(l, s);",
630
+ " if (!(Number.isSafeInteger(i) && i >= 0 && i < x.length && v !== undefined)) F();",
631
+ " const o = x.slice();",
632
+ " o[i] = [x[i][0], v];",
633
+ " return o;",
634
+ "}",
635
+ ].join("\n"),
348
636
  FI: [
349
637
  "function FI(n, v) {",
350
638
  " if (!(Number.isSafeInteger(n) && n >= 0 && n <= 100000 && v !== undefined)) F();",
@@ -353,6 +641,10 @@ const HELPERS: Readonly<Record<Exclude<Helper, "S">, string>> = {
353
641
  " return o;",
354
642
  "}",
355
643
  ].join("\n"),
644
+ // A range of fill (COMPILE.MODULE.FILL.RANGE). FN gives the count of the items of `fill(n, v)` with the check of FI.
645
+ // TN gives the count of `take` of a range with the check of TK. A sum with 0 changes -0 to 0, as the length does.
646
+ FN: "function FN(n, v) { return Number.isSafeInteger(n) && n >= 0 && n <= 100000 && v !== undefined ? n + 0 : F(); }",
647
+ TN: "function TN(n, k) { return Number.isSafeInteger(k) && k >= 0 ? Math.min(n, k + 0) : F(); }",
356
648
  // A list of a field of the input (COMPILE.MODULE.LIST.INPUT): the array of a `vex.list` whose items have lists to the
357
649
  // depth `h`, and values that pass the test `t`. The shape is the shape of `isVexList`. An error item holds the sentinel.
358
650
  // An input that is not such a list, or an error item of `#DEPTH!`, gives undefined, so the check of the run fails.
@@ -377,16 +669,43 @@ const HELPERS: Readonly<Record<Exclude<Helper, "S">, string>> = {
377
669
  " return o;",
378
670
  "}",
379
671
  ].join("\n"),
672
+ // A plain list of a field of the input (COMPILE.MODULE.LIST.PLAIN): an array of the values of the items, with arrays to
673
+ // the depth `h`. The key of an item is its position. The value VEX_ERROR is an error item, also if `t` accepts it.
674
+ // Another value gives undefined, so the check of the run fails.
675
+ LA: [
676
+ "function LA(x, h, t) {",
677
+ " if (!Array.isArray(x)) return undefined;",
678
+ " const o = [];",
679
+ " for (let i = 0; i < x.length; i++) {",
680
+ " const y = x[i];",
681
+ " if (y === VEX_ERROR) {",
682
+ " o.push([i, E]);",
683
+ " continue;",
684
+ " }",
685
+ " const v = h > 0 ? LA(y, h - 1, t) : y !== undefined && t(y) ? y : undefined;",
686
+ " if (v === undefined) return undefined;",
687
+ " o.push([i, v]);",
688
+ " }",
689
+ " return o;",
690
+ "}",
691
+ ].join("\n"),
380
692
  // The ops that build a list (LIST.BUILD) keep the key and the value of each item. A key is a position or a text, so
381
693
  // `without` and `get` compare the text of each key. A list is an array that does not change after the op that makes it.
382
- // The one exception is the array of AO during its loop, which no other part reads (COMPILE.MODULE.APPEND.OWN).
694
+ // The one exception is the array of AO of a loop, which no other part reads (COMPILE.MODULE.APPEND.OWN).
383
695
  DR: "function DR(l, n, s) { const o = V(l, s); return Number.isSafeInteger(n) && n >= 0 ? o.slice(n) : F(); }",
384
696
  AP: "function AP(l, o, s) { return V(l, s).concat(V(o, s)); }",
385
697
  // append into the list of a name of a loop (COMPILE.MODULE.APPEND.OWN). w is the array of the last append of the name
386
698
  // in this run of the loop, and no other part reads it. Such an array has no error items, so VW of it is the array.
699
+ // With fuse, w can start with a first list that is clean and fresh (COMPILE.MODULE.FUSE.ADOPT). An append in the result
700
+ // of the loop can use w too, when no part reads the list after it.
387
701
  // Each other list gets the copy of AP. V(o, s) throws before the first push, so an error does not change l. The loop
388
702
  // reads n items, so it ends also if a is l.
389
703
  AO: "function AO(l, o, s, w) { if (l !== w) return AP(l, o, s); const a = V(o, s), n = a.length; for (let i = 0; i < n; i++) l.push(a[i]); return l; }",
704
+ // The target of an append of an owner that pushes the items of its second list (COMPILE.MODULE.APPEND.PUSH). The
705
+ // array w is the target. Each other list gets a copy without its error items, and with s an error item is an error.
706
+ // AI pushes the one item x of fill(1, x) into the target. The code of x evaluates before the call, as in the interpreter.
707
+ AW: "function AW(l, s, w) { if (l === w) return l; const a = V(l, s), o = []; for (let i = 0; i < a.length; i++) o.push(a[i]); return o; }",
708
+ AI: "function AI(l, x, s, w) { const o = AW(l, s, w); o.push(x); return o; }",
390
709
  WO: [
391
710
  "function WO(l, o, s) {",
392
711
  " const a = V(l, s), g = new Map();",
@@ -403,17 +722,23 @@ const HELPERS: Readonly<Record<Exclude<Helper, "S">, string>> = {
403
722
  ].join("\n"),
404
723
  // The index of the keys of a list (LIST.GET): the value of the first item of each key. The array keeps its index, so a
405
724
  // step that reads each key of a list of n items costs O(n). The key E marks an error item, for strict.
725
+ // The array of a loop gets a push after a read (COMPILE.MODULE.APPEND.LET), so `n` counts the items in the index.
726
+ // A push only adds items at the end, so the index adds only the new items. No other change of an array has a read before it.
406
727
  GT: [
407
728
  "function GT(l, k, s) {",
408
729
  " let x = l.ix;",
409
730
  " if (x === undefined) {",
410
731
  " x = new Map();",
411
- " for (const [q, v] of l) {",
412
- " const t = `${q}`;",
732
+ " x.n = 0;",
733
+ " l.ix = x;",
734
+ " }",
735
+ " if (x.n !== l.length) {",
736
+ " for (let i = x.n; i < l.length; i++) {",
737
+ " const [q, v] = l[i], t = `${q}`;",
413
738
  " if (v === E) x.set(E, E);",
414
739
  " else if (!x.has(t)) x.set(t, v);",
415
740
  " }",
416
- " l.ix = x;",
741
+ " x.n = l.length;",
417
742
  " }",
418
743
  ' return (s && x.has(E)) || typeof k !== "string" || !x.has(k) ? F() : x.get(k);',
419
744
  "}",
@@ -427,6 +752,22 @@ const HELPERS: Readonly<Record<Exclude<Helper, "S">, string>> = {
427
752
  " return F();",
428
753
  "}",
429
754
  ].join("\n"),
755
+ // The keys of a run (COMPILE.MODULE.KEYS): a map of each key to its position. A key that is not a text, or a second
756
+ // use of a key, is against the contract, because a space has no such keys.
757
+ KC: [
758
+ "function KC(a, n) {",
759
+ ' if (!Array.isArray(a) || a.length !== n) C("the keys are not an array with one key for each record");',
760
+ " const m = new Map();",
761
+ " for (let i = 0; i < n; i++) {",
762
+ " const k = a[i];",
763
+ ' if (typeof k !== "string" || m.has(k)) C(`the key ${i} is not a text of its own`);',
764
+ " m.set(k, i);",
765
+ " }",
766
+ " return m;",
767
+ "}",
768
+ ].join("\n"),
769
+ // The position of a key of a move. A value that is not a key of the space is an error of the move (NAV.KEY).
770
+ KP: "function KP(m, k) { const i = m.get(k); return i === undefined ? F() : i; }",
430
771
  // The parents of a tree space: the position of the parent of each record, or -1 for a root. A walk up from each record
431
772
  // marks its keys, so a walk that meets a key of the same walk finds a cycle. Each key is in one walk, so the check is linear.
432
773
  PT: [
@@ -471,19 +812,33 @@ const HELPERS: Readonly<Record<Exclude<Helper, "S">, string>> = {
471
812
  // The keys depth first, with each parent before its children, and the position and the size of the subtree of each
472
813
  // record. Thus the descendants of a record are the keys after it, as many as its subtree has under it.
473
814
  PR: [
474
- "function PR(h, r, n) {",
475
- " const o = [], at = new Int32Array(n), z = new Int32Array(n), st = [];",
476
- " for (let q = r.length - 1; q >= 0; q--) st.push(r[q]);",
477
- " while (st.length > 0) {",
478
- " const k = st.pop();",
479
- " at[k] = o.length;",
480
- " o.push(k);",
481
- " for (let q = h[k].length - 1; q >= 0; q--) st.push(h[k][q]);",
815
+ "function PR(P, n) {",
816
+ " const f = new Int32Array(n).fill(-1), x = new Int32Array(n), o = new Int32Array(n), at = new Int32Array(n), z = new Int32Array(n);",
817
+ " let r = -1;",
818
+ " for (let i = n - 1; i >= 0; i--) {",
819
+ " const p = P[i];",
820
+ " if (p < 0) {",
821
+ " x[i] = r;",
822
+ " r = i;",
823
+ " } else {",
824
+ " x[i] = f[p];",
825
+ " f[p] = i;",
826
+ " }",
827
+ " }",
828
+ " let m = 0;",
829
+ " for (let k = r; k >= 0; ) {",
830
+ " at[k] = m;",
831
+ " o[m++] = k;",
832
+ " if (f[k] >= 0) k = f[k];",
833
+ " else {",
834
+ " while (k >= 0 && x[k] < 0) k = P[k];",
835
+ " if (k >= 0) k = x[k];",
836
+ " }",
482
837
  " }",
483
838
  " for (let q = n - 1; q >= 0; q--) {",
484
- " const k = o[q];",
485
- " z[k] = 1;",
486
- " for (const c of h[k]) z[k] += z[c];",
839
+ " const k = o[q], p = P[k];",
840
+ " z[k]++;",
841
+ " if (p >= 0) z[p] += z[k];",
487
842
  " }",
488
843
  " return [o, at, z];",
489
844
  "}",
@@ -525,22 +880,140 @@ const HELPERS: Readonly<Record<Exclude<Helper, "S">, string>> = {
525
880
  // A column of a direct fill (COMPILE.MODULE.SHEET.DIRECT): the error sentinel of a cell changes to VEX_ERROR.
526
881
  DO: "function DO(d) { for (let k = 0; k < d.length; k++) if (d[k] === E) d[k] = VEX_ERROR; return d; }",
527
882
  // A list of a result (COMPILE.MODULE.LIST.RESULT): a `vex.list` with a text key for each item. An error item has the
528
- // error VEX_ERROR. The depth `h` is the number of the levels of lists in the items.
883
+ // error VEX_ERROR. The depth `h` is the number of the levels of lists in the items. One key gets the list, so it is not frozen.
529
884
  LO: 'function LO(l, h) { return { kind: "vex.list", items: l.map(([k, v]) => ({ key: `${k}`, result: v === E ? { ok: false, error: VEX_ERROR } : { ok: true, value: h > 0 ? LO(v, h - 1) : v } })) }; }',
885
+ // The list of a run that each key gets (COMPILE.MODULE.FUSE.OUT): LO, but frozen, because the keys share the object. LS
886
+ // keeps no object on the array, because a property on each new list made the list ops slower (ireko, vex-compiler 0.17.1).
887
+ LS: 'function LS(l, h) { return Object.freeze({ kind: "vex.list", items: Object.freeze(l.map(([k, v]) => ({ key: `${k}`, result: v === E ? { ok: false, error: VEX_ERROR } : { ok: true, value: h > 0 ? LS(v, h - 1) : v } }))) }); }',
888
+ // A plain list of a result (COMPILE.MODULE.LIST.PLAIN): an array of the values of the items, with no keys. An error
889
+ // item is VEX_ERROR. The depth `h` is the number of the levels of lists in the items.
890
+ LP: "function LP(l, h) { return l.map((x) => (x[1] === E ? VEX_ERROR : h > 0 ? LP(x[1], h - 1) : x[1])); }",
530
891
  // A list in an argument of an op or in a field of a record (COMPILE.MODULE.LIST.ARG, COMPILE.MODULE.LIST.FIELD): a frozen
531
892
  // `vex.list`, as the interpreter gives. The array keeps it, so each later read of the list gives the same object.
893
+ // The array of a loop gets a push after a read (COMPILE.MODULE.APPEND.LET). A push only adds items, so an object with
894
+ // another count of items is old, and LV makes a new object.
532
895
  LV: [
533
896
  "function LV(l, h) {",
534
897
  " let o = l.vl;",
535
- " if (o === undefined) {",
898
+ " if (o === undefined || o.items.length !== l.length) {",
536
899
  ' o = Object.freeze({ kind: "vex.list", items: Object.freeze(l.map(([k, v]) => ({ key: `${k}`, result: v === E ? { ok: false, error: VEX_ERROR } : { ok: true, value: h > 0 ? LV(v, h - 1) : v } }))) });',
537
900
  " l.vl = o;",
538
901
  " }",
539
902
  " return o;",
540
903
  "}",
541
904
  ].join("\n"),
542
- // A column of lists (COMPILE.MODULE.SHEET.LIST): each cell with a list gives a `vex.list`.
905
+ // The clean form (COMPILE.MODULE.FUSE.CLEAN): the facts prove that no item of a list holds the sentinel. Thus V gives
906
+ // the list itself, VW gives the list, and strict cannot fail. Each helper below is the helper without its last letter,
907
+ // with no scan, no test of the sentinel and no option strict. The other checks stay, so each error stays an error.
908
+ SBC: [
909
+ "function SBC(l) {",
910
+ " const t = l.length > 0 ? typeof l[0][1] : \"number\";",
911
+ " for (const [, v] of l) if (typeof v !== t || (t !== \"number\" && t !== \"string\") || v !== v) F();",
912
+ " return l.slice().sort((a, b) => (a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0));",
913
+ "}",
914
+ ].join("\n"),
915
+ SKC: [
916
+ "function SKC(l, f) {",
917
+ " const o = l.map((x) => [x, f(x[1])]);",
918
+ " const t = o.length > 0 ? typeof o[0][1] : \"number\";",
919
+ " for (const [, v] of o) if (typeof v !== t || (t !== \"number\" && t !== \"string\") || v !== v) F();",
920
+ " return o.sort((a, b) => (a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0)).map((x) => x[0]);",
921
+ "}",
922
+ ].join("\n"),
923
+ // The sort in place (COMPILE.MODULE.FUSE): a clean list that is fresh is its own sort buffer, so the sort makes no
924
+ // copy. No other part holds the array, so a failure leaves no changed list that a part reads. The sort is stable.
925
+ // A list of 64 items or fewer gets an insertion sort (COMPILE.MODULE.FUSE.SORT), which calls no comparator function.
926
+ // Its test ">" moves an item only past a larger value, so equal values keep their order. A longer list gets the
927
+ // stable sort of the engine. The kinds of the sort values go through the same check before each of the two sorts.
928
+ SBI: [
929
+ "function SBI(l) {",
930
+ " const n = l.length, t = n > 0 ? typeof l[0][1] : \"number\";",
931
+ " for (let i = 0; i < n; i++) { const v = l[i][1]; if (typeof v !== t || (t !== \"number\" && t !== \"string\") || v !== v) F(); }",
932
+ " if (n > 64) l.sort((a, b) => (a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0));",
933
+ " else for (let i = 1; i < n; i++) {",
934
+ " const x = l[i], v = x[1];",
935
+ " let j = i - 1;",
936
+ " for (; j >= 0 && l[j][1] > v; j--) l[j + 1] = l[j];",
937
+ " l[j + 1] = x;",
938
+ " }",
939
+ " return l;",
940
+ "}",
941
+ ].join("\n"),
942
+ // The option by: the array k holds the sort value of each item, so the sort makes no pair for an item. f runs once
943
+ // for each item, in order, and the array l does not change before the check of the sort values. A long list sorts an
944
+ // array of indices by k, and then reads the items from a copy of l.
945
+ SKI: [
946
+ "function SKI(l, f) {",
947
+ " const n = l.length, k = new Array(n);",
948
+ " for (let i = 0; i < n; i++) k[i] = f(l[i][1]);",
949
+ " const t = n > 0 ? typeof k[0] : \"number\";",
950
+ " for (const v of k) if (typeof v !== t || (t !== \"number\" && t !== \"string\") || v !== v) F();",
951
+ " if (n > 64) {",
952
+ " const o = new Array(n), c = l.slice();",
953
+ " for (let i = 0; i < n; i++) o[i] = i;",
954
+ " o.sort((a, b) => (k[a] < k[b] ? -1 : k[a] > k[b] ? 1 : 0));",
955
+ " for (let i = 0; i < n; i++) l[i] = c[o[i]];",
956
+ " } else for (let i = 1; i < n; i++) {",
957
+ " const v = k[i], x = l[i];",
958
+ " let j = i - 1;",
959
+ " for (; j >= 0 && k[j] > v; j--) { k[j + 1] = k[j]; l[j + 1] = l[j]; }",
960
+ " k[j + 1] = v; l[j + 1] = x;",
961
+ " }",
962
+ " return l;",
963
+ "}",
964
+ ].join("\n"),
965
+ TKC: "function TKC(l, n) { return Number.isSafeInteger(n) && n >= 0 ? l.slice(0, n) : F(); }",
966
+ DRC: "function DRC(l, n) { return Number.isSafeInteger(n) && n >= 0 ? l.slice(n) : F(); }",
967
+ // The loop reads n items, so it ends also if o is l.
968
+ AWC: "function AWC(l, w) { if (l === w) return l; const o = []; for (let i = 0; i < l.length; i++) o.push(l[i]); return o; }",
969
+ AIC: "function AIC(l, x, w) { if (l !== w) { const o = []; for (let i = 0; i < l.length; i++) o.push(l[i]); l = o; } l.push(x); return l; }",
970
+ // The end of a filter of the array of a loop in place (COMPILE.MODULE.APPEND.KEEP): the array keeps its first n items.
971
+ // GT and LV count only the pushes of their array, so the filter removes their caches. VW of the array is the array.
972
+ KS: "function KS(l, n) { l.length = n; if (l.ix !== undefined) l.ix = undefined; if (l.vl !== undefined) l.vl = undefined; }",
973
+ AOC: "function AOC(l, o, w) { if (l !== w) return l.concat(o); const n = o.length; for (let i = 0; i < n; i++) l.push(o[i]); return l; }",
974
+ WOC: [
975
+ "function WOC(l, o) {",
976
+ " const g = new Map();",
977
+ " for (const [k] of o) g.set(`${k}`, 1);",
978
+ " return l.filter((x) => !g.has(`${x[0]}`));",
979
+ "}",
980
+ ].join("\n"),
981
+ FLC: "function FLC(l) { const o = []; for (const [, v] of l) for (const x of v) o.push(x); return o; }",
982
+ IXC: [
983
+ "function IXC(l, x) {",
984
+ ' if (typeof x !== "number" && typeof x !== "string" && typeof x !== "boolean") F();',
985
+ " for (let i = 0; i < l.length; i++) if (l[i][1] === x) return i;",
986
+ " return F();",
987
+ "}",
988
+ ].join("\n"),
989
+ NTC: "function NTC(l, i) { return Number.isSafeInteger(i) && i >= 0 && i < l.length ? l[i][1] : F(); }",
990
+ SNC: [
991
+ "function SNC(l, i, v) {",
992
+ " if (!(Number.isSafeInteger(i) && i >= 0 && i < l.length && v !== undefined)) F();",
993
+ " const o = l.slice();",
994
+ " o[i] = [l[i][0], v];",
995
+ " return o;",
996
+ "}",
997
+ ].join("\n"),
998
+ FSC: "function FSC(l) { return l.length === 0 ? F() : l[0][1]; }",
999
+ LOC: 'function LOC(l, h) { return { kind: "vex.list", items: l.map(([k, v]) => ({ key: `${k}`, result: { ok: true, value: h > 0 ? LOC(v, h - 1) : v } })) }; }',
1000
+ LSC: 'function LSC(l, h) { return Object.freeze({ kind: "vex.list", items: Object.freeze(l.map(([k, v]) => ({ key: `${k}`, result: { ok: true, value: h > 0 ? LSC(v, h - 1) : v } }))) }); }',
1001
+ LPC: "function LPC(l, h) { return l.map(h > 0 ? (x) => LPC(x[1], h - 1) : (x) => x[1]); }",
1002
+ // LV and LVC keep one object on the array. A clean list gives the same object from both.
1003
+ LVC: [
1004
+ "function LVC(l, h) {",
1005
+ " let o = l.vl;",
1006
+ " if (o === undefined || o.items.length !== l.length) {",
1007
+ ' o = Object.freeze({ kind: "vex.list", items: Object.freeze(l.map(([k, v]) => ({ key: `${k}`, result: { ok: true, value: h > 0 ? LVC(v, h - 1) : v } }))) });',
1008
+ " l.vl = o;",
1009
+ " }",
1010
+ " return o;",
1011
+ "}",
1012
+ ].join("\n"),
1013
+ // A column of lists (COMPILE.MODULE.SHEET.LIST): each cell with a list gives a `vex.list`. No two cells share it, so LC uses LO.
543
1014
  LC: "function LC(d, h) { for (let k = 0; k < d.length; k++) if (d[k] !== VEX_ERROR) d[k] = LO(d[k], h); return d; }",
1015
+ // A plain column of lists (COMPILE.MODULE.LIST.PLAIN): each cell with a list gives an array.
1016
+ LCP: "function LCP(d, h) { for (let k = 0; k < d.length; k++) if (d[k] !== VEX_ERROR) d[k] = LP(d[k], h); return d; }",
544
1017
  SH: [
545
1018
  "function SH(n, cols, own, budget) {",
546
1019
  " const pg = (c, k) => {",
@@ -636,8 +1109,8 @@ const HELPERS: Readonly<Record<Exclude<Helper, "S">, string>> = {
636
1109
  " else D[c][k] = x;",
637
1110
  " };",
638
1111
  " const o = (c) => {",
639
- " const d = D[c], out = [];",
640
- " for (let k = 0; k < n; k++) out.push(d[k] === E ? VEX_ERROR : d[k]);",
1112
+ " const d = D[c], out = new Array(n);",
1113
+ " for (let k = 0; k < n; k++) out[k] = d[k] === E ? VEX_ERROR : d[k];",
641
1114
  " return out;",
642
1115
  " };",
643
1116
  " return { r, f, o };",
@@ -824,20 +1297,34 @@ const STEPS: Readonly<Record<string, readonly [string, string]>> = {
824
1297
 
825
1298
  /** The helpers that each helper uses. */
826
1299
  const NEEDS: Readonly<Record<Helper, readonly Helper[]>> = {
827
- F: [], C: [], T: [], L: [], Q: [], G: ["F"], B: ["F"], U: ["F"], X: ["F"], I: ["F"], K: ["F"], M: ["G"], M1: ["G"], S: ["M1", "F"],
1300
+ F: [], C: [], T: [], L: [], Q: [], G: ["F"], PF: ["F"], B: ["F"], U: ["F"], X: ["F"], I: ["F"], K: ["F"], M: ["G"], M1: ["G"], S: ["M1", "F"],
828
1301
  // Only the helpers of the list ops use V, and each of them needs F too, so the need of V only completes the list.
829
1302
  // Stryker disable next-line ArrayDeclaration: see the comment above
830
1303
  V: ["F"],
831
- SB: ["V", "F"], SK: ["V", "F"], TK: ["V", "F"], VW: [], NT: ["VW", "F"], CT: ["VW", "F"], FS: ["VW", "F"], FI: ["F"], LI: [],
832
- DR: ["V", "F"], AP: ["V"], AO: ["AP", "V"], WO: ["V"], FL: ["V"], GT: ["F"], IX: ["V", "F"],
1304
+ SB: ["V", "F"], SK: ["V", "F"], TK: ["V", "F"], VW: [], NT: ["VW", "F"], CT: ["VW", "F"], FS: ["VW", "F"], FI: ["F"], FN: ["F"], TN: ["F"], LI: [], LA: [], LP: [],
1305
+ DR: ["V", "F"], AP: ["V"], AO: ["AP", "V"], WO: ["V"], FL: ["V"], GT: ["F"], IX: ["V", "F"], SN: ["V", "F"],
833
1306
  // Each module has C, and each move uses F (#move), so these needs only complete the list.
834
1307
  // Stryker disable next-line ArrayDeclaration: see the comment above
835
1308
  PT: ["C"], GR: ["C"], UP: ["F"], SO: ["F"],
836
1309
  CH: [], SG: [], PR: [], AN: [], BF: [],
837
1310
  GI: [], RB: [],
838
- SH: [], KO: [], DO: [], LO: [], LC: ["LO"], LV: [],
1311
+ KC: ["C"], KP: ["F"], SH: [], KO: [], DO: [], LO: [], LS: [], LC: ["LO"], LV: [], LCP: ["LP"],
1312
+ SBC: ["F"], SKC: ["F"], TKC: ["F"], DRC: ["F"], AOC: [], WOC: [], FLC: [], IXC: ["F"], NTC: ["F"], SNC: ["F"], FSC: ["F"], LOC: [], LSC: [], LVC: [], LPC: [],
1313
+ SBI: ["F"], SKI: ["F"], QA: [], AW: ["V"], AI: ["AW"], AWC: [], AIC: [], KS: [],
839
1314
  };
840
1315
 
1316
+ /**
1317
+ * The forms of the helpers of the list fields, for a module where each list field has the depth 0. The test of the
1318
+ * value takes the place of the recursion, and the helper has no argument `h` (COMPILE.MODULE.SIZE.FLAT).
1319
+ */
1320
+ const FLAT_LIST_HELPERS: Readonly<Record<"LI" | "LA", string>> = {
1321
+ LI: HELPERS.LI.replace("LI(x, h, t)", "LI(x, t)").replace("h > 0 ? LI(r.value, h - 1, t) : ", ""),
1322
+ LA: HELPERS.LA.replace("LA(x, h, t)", "LA(x, t)").replace("h > 0 ? LA(y, h - 1, t) : ", ""),
1323
+ };
1324
+
1325
+ /** The clean form of each helper that gives a list of the code to the outside (COMPILE.MODULE.FUSE.CLEAN). */
1326
+ const CLEAN_FORMS = { LO: "LOC", LS: "LSC", LV: "LVC", LP: "LPC" } as const;
1327
+
841
1328
  /** The parts of a tree that a run computes before the loop over its keys, if the program needs them. */
842
1329
  type TreePart = "children" | "siblings" | "order";
843
1330
 
@@ -845,7 +1332,7 @@ type TreePart = "children" | "siblings" | "order";
845
1332
  const TREE_PARTS: Readonly<Record<TreePart, readonly [TreeHelper, string]>> = {
846
1333
  children: ["CH", "const [H, RT] = CH(P, n);"],
847
1334
  siblings: ["SG", "const [GP, SI] = SG(P, H, RT, n);"],
848
- order: ["PR", "const [PO, PI, SZ] = PR(H, RT, n);"],
1335
+ order: ["PR", "const [PO, PI, SZ] = PR(P, n);"],
849
1336
  };
850
1337
 
851
1338
  /** An axis whose targets in a tree space are a range of an array of positions: an axis of a tree, or a window. */
@@ -888,17 +1375,23 @@ const BUILD_HELPERS: Readonly<Record<string, BuildHelper>> = { append: "AP", wit
888
1375
  * The ops whose value is a list: the list ops of LIST.SORT, LIST.TAKE and LIST.BUILD, and `fill` (LIST.FILL). A domain
889
1376
  * can have the op `fill`. Then the op of the domain gives no list, and the place of a list gives a reason.
890
1377
  */
891
- const LIST_RESULTS: ReadonlySet<string> = new Set(["sortBy", "take", "drop", "append", "without", "flat", "fill"]);
1378
+ const LIST_RESULTS: ReadonlySet<string> = new Set(["sortBy", "take", "setNth", "drop", "append", "without", "flat", "fill"]);
1379
+
1380
+ /** The list ops that give the value of an item (LIST.NTH, LIST.GET) and `first`. An item of a list of lists is a list. */
1381
+ const ITEM_OPS: ReadonlySet<string> = new Set(["nth", "first", "get"]);
892
1382
 
893
1383
  /**
894
- * The scope of `listy`. `name` tells if a name holds a list, and `fn` gives the bound function of a name. `cell` tells
895
- * if a read of a cell gives a list, and `field` tells if a read of a field gives a list (COMPILE.MODULE.LIST.INPUT).
1384
+ * The scope of `listy`. `key` gives the name of a key of a node of the memo. `name`, `cell` and `field` tell if a name, a
1385
+ * cell or a field gives a list with `levels` levels (COMPILE.MODULE.LIST.INPUT). `op` tells if a domain declares a list as
1386
+ * the result of an op (COMPILE.MODULE.LIST.OP). `fn` gives the bound function of a name.
896
1387
  */
897
1388
  interface ListScope {
898
- readonly name: (name: string) => boolean;
1389
+ readonly key: (e: Expr) => Name | undefined;
1390
+ readonly op: (name: string) => boolean;
1391
+ readonly name: (name: string, levels: number) => boolean;
899
1392
  readonly fn: (name: string) => ListFn | undefined;
900
- readonly cell: (e: ExprOf<"ext">) => boolean;
901
- readonly field: (e: ExprOf<"ref">) => boolean;
1393
+ readonly cell: (e: ExprOf<"ext">, levels: number) => boolean;
1394
+ readonly field: (e: ExprOf<"ref">, levels: number) => boolean;
902
1395
  }
903
1396
 
904
1397
  /** A bound function for `listy`: its node, and the scope of its binding (FN.BIND). */
@@ -907,36 +1400,48 @@ interface ListFn {
907
1400
  readonly scope: ListScope;
908
1401
  }
909
1402
 
1403
+ /** This function tells if a list has `levels` levels of lists: 1 for each list, and 2 for a list of lists. */
1404
+ function hasLevels(l: ListInfo | undefined, levels: number): boolean {
1405
+ return l !== undefined && (levels === 1 || hasLevels(l.inner, levels - 1));
1406
+ }
1407
+
910
1408
  /**
911
- * This function tells if an expression gives a list. An each, a list literal and a list op of `LIST_RESULTS` give a
912
- * list. A name of a list, and a let or a loop whose result is a list, give a list too. A call gives a list when the
913
- * body of its function gives one (COMPILE.MODULE.LIST.CALL). The scope tells the names and the functions outside the expression.
1409
+ * This function tells if an expression gives a list with `levels` levels of lists (COMPILE.MODULE.LIST.NESTED). An each,
1410
+ * a list literal and a list op of `LIST_RESULTS` give a list. A name of a list, and a let or a loop whose result is a
1411
+ * list, give a list too. A call gives a list when the body of its function gives one (COMPILE.MODULE.LIST.CALL). An op of
1412
+ * `ITEM_OPS` gives one level less than its list. The scope tells the names and the functions outside the expression.
914
1413
  */
915
- function listy(e: Expr, scope: ListScope): boolean {
1414
+ function listy(e: Expr, scope: ListScope, levels = 1): boolean {
1415
+ const key = scope.key(e);
1416
+ if (key !== undefined) return hasLevels(key.list, levels);
916
1417
  switch (e.tag) {
917
1418
  case "each":
918
- return true;
1419
+ return levels === 1 || listy(e.body, itemsIn(e, scope), levels - 1);
919
1420
  case "lit":
920
- return isVexList(e.value);
1421
+ // A module has no list literal with lists as items, so a literal has one level.
1422
+ return levels === 1 && isVexList(e.value);
921
1423
  case "app":
922
- // A branch of if and ifError can be a list (COMPILE.MODULE.LIST.RESULT).
923
- return LIST_RESULTS.has(e.op) || ((e.op === "if" || e.op === "ifError") && e.args.slice(e.op === "if" ? 1 : 0).some((x) => listy(x, scope)));
1424
+ return listyApp(e, scope, levels);
924
1425
  case "var":
925
- return scope.name(e.name);
1426
+ return scope.name(e.name, levels);
926
1427
  case "let":
927
- return listy(e.body, scopeIn(e.bind, scope));
1428
+ return listy(e.body, scopeIn(e.bind, scope), levels);
928
1429
  case "fold":
929
1430
  case "iterate":
930
- return listy(e.result, scopeIn(e.init, scope));
1431
+ return listy(e.result, scopeIn(e.init, scope), levels);
1432
+ // A column gives a boolean or a number (FIX.KIND).
1433
+ case "fix":
1434
+ case "last":
1435
+ return false;
931
1436
  case "ext":
932
- return scope.cell(e);
1437
+ return scope.cell(e, levels);
933
1438
  case "ref":
934
- return scope.field(e);
1439
+ return scope.field(e, levels);
935
1440
  case "call": {
936
1441
  // A call of no function gives a reason in the printer. A value or a parameter with the name of a function makes
937
1442
  // the printer give that reason too, so the scope does not hide the function.
938
1443
  const f = scope.fn(e.fn);
939
- return f !== undefined && listy(f.fn.body, paramsIn(f, e.args, scope));
1444
+ return f !== undefined && listy(f.fn.body, paramsIn(f, e.args, scope), levels);
940
1445
  }
941
1446
  case "fn":
942
1447
  case "rec":
@@ -944,35 +1449,67 @@ function listy(e: Expr, scope: ListScope): boolean {
944
1449
  }
945
1450
  }
946
1451
 
1452
+ /** This function tells if an op gives a list with `levels` levels of lists (`listy`). */
1453
+ function listyApp(e: ExprOf<"app">, scope: ListScope, levels: number): boolean {
1454
+ const { op, args } = e;
1455
+ const argument = (i: number, change: number): boolean => args.slice(i, i + 1).some((x) => listy(x, scope, levels + change));
1456
+ // A branch of if and ifError can be a list (COMPILE.MODULE.LIST.RESULT).
1457
+ if (op === "if" || op === "ifError") return args.slice(op === "if" ? 1 : 0).some((x) => listy(x, scope, levels));
1458
+ // An op of a domain gives a list of values (COMPILE.MODULE.LIST.OP).
1459
+ if (levels === 1 && scope.op(op)) return true;
1460
+ if (ITEM_OPS.has(op)) return argument(0, 1);
1461
+ if (!LIST_RESULTS.has(op)) return false;
1462
+ if (levels === 1) return true;
1463
+ if (op === "fill") return argument(1, -1);
1464
+ if (op === "flat") return argument(0, 1);
1465
+ // An empty list literal takes the levels of the other list of append.
1466
+ return argument(0, 0) || (op === "append" && argument(1, 0));
1467
+ }
1468
+
1469
+ /**
1470
+ * This function gives the scope of the body of an each. The first name `as` holds an item of the list of the axis, so it
1471
+ * has one level less than the list. The second name holds a position (COMPILE.MODULE.LIST.ITEM).
1472
+ */
1473
+ function itemsIn(e: ExprOf<"each">, scope: ListScope): ListScope {
1474
+ if (e.as === undefined) return scope;
1475
+ const [item, index] = e.as;
1476
+ // The kernel refuses names `as` over an axis without a list.
1477
+ const list = listOf(e.axis) as Expr;
1478
+ return { ...scope, name: (name, levels) => (name === item ? listy(list, scope, levels + 1) : name !== index && scope.name(name, levels)) };
1479
+ }
1480
+
947
1481
  /**
948
1482
  * This function gives the scope of some bindings. A value hides a name outside, and a function is not a list. A
949
1483
  * function sees the scope outside the bindings, so it cannot call itself.
950
1484
  */
951
1485
  function scopeIn(bind: Readonly<Record<string, Expr>>, scope: ListScope): ListScope {
952
- const lists = new Map<string, boolean>();
953
1486
  const fns = new Map<string, ListFn>();
954
- for (const [name, x] of Object.entries(bind)) {
955
- if (x.tag === "fn") fns.set(name, { fn: x, scope });
956
- lists.set(name, listy(x, scope));
957
- }
958
- return { ...scope, name: (name) => lists.get(name) ?? scope.name(name), fn: (name) => fns.get(name) ?? scope.fn(name) };
1487
+ for (const [name, x] of Object.entries(bind)) if (x.tag === "fn") fns.set(name, { fn: x, scope });
1488
+ return { ...scope, name: (name, levels) => (Object.hasOwn(bind, name) ? listy(bind[name] as Expr, scope, levels) : scope.name(name, levels)), fn: (name) => fns.get(name) ?? scope.fn(name) };
959
1489
  }
960
1490
 
961
1491
  /**
962
1492
  * This function gives the scope of the body of a function at a call. The body sees the scope of the binding of the
963
- * function, and each parameter holds a list when its argument does.
1493
+ * function, and each parameter has the levels of its argument.
964
1494
  */
965
1495
  function paramsIn(f: ListFn, args: readonly Expr[], scope: ListScope): ListScope {
966
- const lists = new Map(args.map((x, i) => [f.fn.params[i], listy(x, scope)]));
967
- return { ...f.scope, name: (name) => lists.get(name) ?? f.scope.name(name) };
1496
+ const lists = new Map(args.map((x, i) => [f.fn.params[i], x]));
1497
+ return {
1498
+ ...f.scope,
1499
+ name: (name, levels) => {
1500
+ const arg = lists.get(name);
1501
+ return arg === undefined ? f.scope.name(name, levels) : listy(arg, scope, levels);
1502
+ },
1503
+ };
968
1504
  }
969
1505
 
970
1506
  /**
971
- * This function tells if an expression has a list literal with an item (LIST.LITERAL), or `fill` (LIST.FILL). Then a key
972
- * of a list of the expression can be a key that is not the position of a record.
1507
+ * This function tells if an expression has a list literal with an item (LIST.LITERAL), `fill` (LIST.FILL) or an op for
1508
+ * which `gives` is true (COMPILE.MODULE.LIST.OP). Then a key of a list of the expression can be a key that is not the
1509
+ * position of a record.
973
1510
  */
974
- function hasTextKeys(e: Expr): boolean {
975
- return (e.tag === "lit" && isVexList(e.value) && e.value.items.length > 0) || (e.tag === "app" && e.op === "fill") || children(e).some(hasTextKeys);
1511
+ function hasTextKeys(e: Expr, gives: (name: string) => boolean): boolean {
1512
+ return (e.tag === "lit" && isVexList(e.value) && e.value.items.length > 0) || (e.tag === "app" && (e.op === "fill" || gives(e.op))) || children(e).some((x) => hasTextKeys(x, gives));
976
1513
  }
977
1514
 
978
1515
  /**
@@ -980,11 +1517,13 @@ function hasTextKeys(e: Expr): boolean {
980
1517
  * `if` from its two branches. An empty list fits each list. The op `op` names the op in the reason.
981
1518
  */
982
1519
  function joinLists(a: ListInfo, b: ListInfo, op: string): ListInfo {
983
- if (a.empty === true) return b;
984
- if (b.empty === true) return a;
1520
+ // The value can be the array of the empty list, so it is fresh only when both lists are fresh.
1521
+ if (a.empty === true) return { ...b, clean: a.clean === true && b.clean === true, fresh: false };
1522
+ if (b.empty === true) return { ...a, clean: a.clean === true && b.clean === true, fresh: false };
985
1523
  if ((a.inner === undefined) !== (b.inner === undefined)) throw new NotStandalone(`"${op}" of a list of lists and a list of values`);
986
1524
  const texts = a.texts === true || b.texts === true;
987
- return { item: join(a.item, b.item), inner: a.inner === undefined ? undefined : joinLists(a.inner, b.inner as ListInfo, op), texts };
1525
+ const inner = a.inner === undefined ? undefined : joinLists(a.inner, b.inner as ListInfo, op);
1526
+ return { item: join(a.item, b.item), inner, texts, clean: a.clean === true && b.clean === true, fresh: a.fresh === true && b.fresh === true };
988
1527
  }
989
1528
 
990
1529
  /** This function gives the facts of the list of `if` or `ifError` from its two branches. Two values that are not lists give undefined. */
@@ -1005,6 +1544,190 @@ function fits(name: ListInfo, step: ListInfo): boolean {
1005
1544
  return name.inner === undefined ? step.inner === undefined : step.inner !== undefined && fits(name.inner, step.inner);
1006
1545
  }
1007
1546
 
1547
+ /**
1548
+ * This function gives the names of a loop with a clean list (COMPILE.MODULE.FUSE.FACTS). A name is clean when its first
1549
+ * list is clean and each step gives a clean list. The function first assumes the fact for each name with a clean first
1550
+ * list. Then it removes each name whose step does not prove the fact, until no name changes. A name of an item in
1551
+ * `items` hides each other name. `outer` gives the fact of a name outside the loop.
1552
+ */
1553
+ function cleanNames(firsts: ReadonlyMap<string, boolean>, step: Names, items: readonly string[], outer: (name: string) => boolean): ReadonlySet<string> {
1554
+ const clean = new Set([...firsts].flatMap(([name, c]) => (c ? [name] : [])));
1555
+ const fact = (name: string): boolean => !items.includes(name) && (firsts.has(name) ? clean.has(name) : outer(name));
1556
+ for (let changed = true; changed; ) {
1557
+ changed = false;
1558
+ for (const name of clean) {
1559
+ const x = step[name];
1560
+ if (x !== undefined && !cleanForm(x, fact)) {
1561
+ clean.delete(name);
1562
+ changed = true;
1563
+ }
1564
+ }
1565
+ }
1566
+ return clean;
1567
+ }
1568
+
1569
+ /** The list ops whose value is clean, because `V` removes each error item or `FI` checks each value. */
1570
+ const CLEAN_OPS: ReadonlySet<string> = new Set(["append", "flat", "drop", "take", "setNth", "without", "sortBy", "fill"]);
1571
+
1572
+ /**
1573
+ * This function tells if the form of an expression proves that its list is clean, with the facts `fact` of the names.
1574
+ * It does not print the expression, so it knows only the clean ops, the literals, `if`, `ifError`, `let` and names.
1575
+ */
1576
+ function cleanForm(e: Expr, fact: (name: string) => boolean): boolean {
1577
+ switch (e.tag) {
1578
+ case "app":
1579
+ if (CLEAN_OPS.has(e.op)) return true;
1580
+ return (e.op === "if" || e.op === "ifError") && e.args.slice(e.op === "if" ? 1 : 0).every((x) => cleanForm(x, fact));
1581
+ case "lit":
1582
+ return isVexList(e.value) && e.value.items.every((it) => it.result.ok);
1583
+ case "var":
1584
+ return fact(e.name);
1585
+ case "let":
1586
+ // A binding sees the context of the let, so its form has the facts of the names outside.
1587
+ return cleanForm(e.body, (name) => (name in e.bind ? cleanForm(e.bind[name] as Expr, fact) : fact(name)));
1588
+ case "fold":
1589
+ case "iterate": {
1590
+ // The result of a loop sees the names of the loop, with the facts of their own fixpoint, and the names outside.
1591
+ const firsts = new Map(Object.entries(e.init).map(([name, x]): [string, boolean] => [name, cleanForm(x, fact)]));
1592
+ const clean = cleanNames(firsts, e.step, e.tag === "fold" ? (e.as ?? []) : [], fact);
1593
+ return cleanForm(e.result, (name) => (name in e.init ? clean.has(name) : fact(name)));
1594
+ }
1595
+ // Stryker disable StringLiteral,ConditionalExpression: without its case, the switch gives undefined, and each caller reads undefined as false.
1596
+ case "call":
1597
+ case "each":
1598
+ case "ext":
1599
+ case "fix":
1600
+ case "fn":
1601
+ case "last":
1602
+ case "rec":
1603
+ case "ref":
1604
+ // Stryker restore StringLiteral,ConditionalExpression
1605
+ return false;
1606
+ }
1607
+ }
1608
+
1609
+ /** This function gives the count of the reads of a part that a loop or a function can evaluate again. */
1610
+ const again = (n: number): number => (n > 0 ? Infinity : 0);
1611
+
1612
+ /** This function adds the counts of the reads of the parts `xs`. */
1613
+ const refsIn = (xs: readonly Expr[], name: string): number => xs.reduce((n, x) => n + refsOf(x, name), 0);
1614
+
1615
+ /**
1616
+ * This function counts the reads of the name `name` in an expression. A read in the body of an `each`, of a step of
1617
+ * a loop or of a function counts `Infinity`. Such a part can evaluate many times. A name of the expression
1618
+ * hides the name.
1619
+ */
1620
+ function refsOf(e: Expr, name: string): number {
1621
+ switch (e.tag) {
1622
+ case "var":
1623
+ return e.name === name ? 1 : 0;
1624
+ case "let":
1625
+ return refsIn(Object.values(e.bind), name) + (name in e.bind ? 0 : refsOf(e.body, name));
1626
+ case "fn":
1627
+ return e.params.includes(name) ? 0 : again(refsOf(e.body, name));
1628
+ // The first values and the step evaluate at each row (FIX.ROUNDS).
1629
+ case "fix":
1630
+ return again(refsOf(e.init, name) + refsOf(e.step, name));
1631
+ case "last":
1632
+ return 0;
1633
+ case "each": {
1634
+ // Only the body sees the names of the items (AXIS.LIST.SCOPE). The tests of the axis evaluate for each item.
1635
+ const list = listOf(e.axis);
1636
+ const tests = axisExprs(e.axis).filter((x) => x !== list);
1637
+ const own = list === undefined ? [] : [list];
1638
+ return refsIn([...own, ...addrExprs(e.at)], name) + again(refsIn(tests, name)) + (e.as?.includes(name) === true ? 0 : again(refsOf(e.body, name)));
1639
+ }
1640
+ case "fold":
1641
+ case "iterate": {
1642
+ // The steps and the result see the names of the loop. The tests of a fold or of a data limit read only the names outside the loop.
1643
+ const hidden = name in e.init;
1644
+ const steps = [...Object.values(e.step), ...(e.tag === "iterate" && e.until !== undefined ? [e.until] : [])];
1645
+ const axis = e.tag === "fold" ? e.axis : limitAxis(e);
1646
+ const list = axis === undefined ? undefined : listOf(axis);
1647
+ const once = [...(list === undefined ? [] : [list]), ...(e.tag === "fold" ? addrExprs(e.at) : [])];
1648
+ // Stryker disable next-line ArrayDeclaration: refsOf of a string gives NaN, and again(NaN) gives 0.
1649
+ const tests = axis === undefined ? [] : axisExprs(axis).filter((x) => x !== list);
1650
+ const item = e.tag === "fold" && e.as?.includes(name) === true;
1651
+ return refsIn([...Object.values(e.init), ...once], name) + again(refsIn(tests, name)) + (hidden || item ? 0 : again(refsIn(steps, name))) + (hidden ? 0 : refsOf(e.result, name));
1652
+ }
1653
+ case "app":
1654
+ case "call":
1655
+ case "ext":
1656
+ case "lit":
1657
+ case "rec":
1658
+ case "ref":
1659
+ return refsIn(children(e), name);
1660
+ }
1661
+ }
1662
+
1663
+ /**
1664
+ * This function counts the reads of the value of each node of a program, from its form (COMPILE.MODULE.FUSE.FACTS).
1665
+ * The parent of a node reads its value once. A branch of `if` and of `ifError`, the body of a `let` and the result of
1666
+ * a loop give their value to their parent. Thus they get the count of the parent. A loop reads its first values and its
1667
+ * steps at each step, so they get `Infinity`. A binding gets the count of the reads of its name. An argument of a call
1668
+ * gets the count of the reads of its parameter. The printer adds the parts that the code reads again (`#shared`).
1669
+ */
1670
+ function readCounts(root: Expr): ReadonlyMap<Expr, number> {
1671
+ const out = new Map<Expr, number>();
1672
+ const visit = (e: Expr, reads: number, fns: ReadonlyMap<string, ExprOf<"fn">>): void => {
1673
+ // A node at two places of the program evaluates at each place, so each place reads its own value.
1674
+ out.set(e, Math.max(out.get(e) ?? 0, reads));
1675
+ const all = (xs: readonly Expr[], n: number): void => {
1676
+ for (const x of xs) visit(x, n, fns);
1677
+ };
1678
+ switch (e.tag) {
1679
+ case "app": {
1680
+ // The branches of if and of ifError give their value to the parent.
1681
+ const first = e.op === "if" ? 1 : e.op === "ifError" ? 0 : e.args.length;
1682
+ e.args.forEach((x, i) => visit(x, i < first ? 1 : reads, fns));
1683
+ return;
1684
+ }
1685
+ case "let": {
1686
+ // A binding sees the context of the let, so a function cannot call itself. A value hides a function of its name.
1687
+ const inner = new Map(fns);
1688
+ for (const [name, x] of Object.entries(e.bind)) {
1689
+ if (x.tag === "fn") inner.set(name, x);
1690
+ else inner.delete(name);
1691
+ visit(x, x.tag === "fn" ? 1 : refsOf(e.body, name), fns);
1692
+ }
1693
+ visit(e.body, reads, inner);
1694
+ return;
1695
+ }
1696
+ case "call": {
1697
+ const fn = fns.get(e.fn);
1698
+ e.args.forEach((x, i) => {
1699
+ const param = fn?.params[i];
1700
+ visit(x, param === undefined ? Infinity : refsOf((fn as ExprOf<"fn">).body, param), fns);
1701
+ });
1702
+ return;
1703
+ }
1704
+ case "fix":
1705
+ all(children(e), Infinity);
1706
+ return;
1707
+ case "fold":
1708
+ case "iterate": {
1709
+ const names = new Set([...Object.values(e.init), ...Object.values(e.step)]);
1710
+ for (const x of children(e)) visit(x, x === e.result ? reads : names.has(x) ? Infinity : 1, fns);
1711
+ return;
1712
+ }
1713
+ case "each":
1714
+ // Stryker disable next-line StringLiteral: an extension has no children.
1715
+ case "ext":
1716
+ case "last":
1717
+ case "fn":
1718
+ // Stryker disable next-line StringLiteral: a literal has no children.
1719
+ case "lit":
1720
+ case "rec":
1721
+ case "ref":
1722
+ // Stryker disable next-line StringLiteral: a variable has no children.
1723
+ case "var":
1724
+ all(children(e), 1);
1725
+ }
1726
+ };
1727
+ visit(root, 1, new Map());
1728
+ return out;
1729
+ }
1730
+
1008
1731
  /** This function tells if the step of a list op throws for a value of the kind `kind`, which is the wrong kind. */
1009
1732
  const stepThrows = (op: string, kind: Kind | undefined): boolean => op === "reduce" || (NUMBER_STEPS.has(op) && kind !== "number") || (BOOLEAN_LIST_OPS.has(op) && kind !== "boolean");
1010
1733
 
@@ -1021,47 +1744,203 @@ const LOOPS = new WeakMap<Expr, boolean>();
1021
1744
  * It puts the append nodes of the form into `out`. The form is a read of the name,
1022
1745
  * `append(form, X)`, `if(c, form, form)` or a let with the form as its body. No other part of the form reads the name:
1023
1746
  * not `X`, not `c` and not a binding of a let.
1747
+ *
1748
+ * A let can also bind a form to a new name (COMPILE.MODULE.APPEND.LET). Then no other binding reads the name, and the
1749
+ * body does not read the old list. The body can read the new name in each way. Such a let goes into `lets`, because the
1750
+ * value of the step can then be another list.
1751
+ *
1752
+ * With `wide`, one branch of an `if` can be another list (COMPILE.MODULE.APPEND.OTHER). The body of such a let can
1753
+ * then be a form of the new name.
1024
1754
  */
1025
- function ownForm(e: Expr, name: string, out: Expr[]): boolean {
1755
+ function ownForm(e: Expr, name: string, out: Expr[], lets: Expr[], wide = false): boolean {
1026
1756
  const free = (x: Expr): boolean => !namesOf(x).has(name);
1027
1757
  if (e.tag === "var") return e.name === name;
1028
- if (e.tag === "let") return Object.values(e.bind).every(free) && ownForm(e.body, name, out);
1758
+ if (e.tag === "let") {
1759
+ const held = Object.entries(e.bind).filter(([, x]) => !free(x));
1760
+ if (held.length === 0) return ownForm(e.body, name, out, lets, wide);
1761
+ const [bind, x] = held[0] as [string, Expr];
1762
+ // A binding of the name itself hides the old list in the body, so the body can read the name.
1763
+ if (held.length > 1 || (bind !== name && !free(e.body)) || !ownForm(x, name, out, lets, wide)) return false;
1764
+ lets.push(e);
1765
+ // The body can append to the new name (COMPILE.MODULE.APPEND.OTHER). Then these appends push into the array too.
1766
+ if (wide && bind !== name) {
1767
+ const relay: Expr[] = [];
1768
+ if (ownForm(e.body, bind, relay, lets, wide)) out.push(...relay);
1769
+ }
1770
+ return true;
1771
+ }
1029
1772
  if (e.tag !== "app" || e.args.length === 0) return false;
1030
1773
  const [head, ...rest] = e.args as [Expr, ...Expr[]];
1031
1774
  // An if without three arguments gives a reason (#if), so the form does not check the count.
1032
- if (e.op === "if") return free(head) && rest.every((x) => ownForm(x, name, out));
1033
- if (e.op !== "append" || !rest.every(free) || !ownForm(head, name, out)) return false;
1775
+ if (e.op === "if") {
1776
+ if (!free(head)) return false;
1777
+ const forms = rest.map((x) => ownForm(x, name, out, lets, wide));
1778
+ // One branch must be a form, so the step reads the name. The other branch can be another list.
1779
+ return forms.every(Boolean) || (forms.some(Boolean) && otherList(e, lets, wide));
1780
+ }
1781
+ if (e.op !== "append" || !rest.every(free) || !ownForm(head, name, out, lets, wide)) return false;
1034
1782
  out.push(e);
1035
1783
  return true;
1036
1784
  }
1037
1785
 
1038
- /** This function gives the names that an expression reads, also the names that it binds itself. */
1039
- function namesOf(e: Expr, out = new Set<string>()): Set<string> {
1040
- if (e.tag === "var") out.add(e.name);
1041
- for (const x of children(e)) namesOf(x, out);
1042
- return out;
1786
+ /**
1787
+ * This function tells if the branch `x` of the `if` node `e` of a form is another list (COMPILE.MODULE.APPEND.OTHER).
1788
+ * Such a branch evaluates before each push of the step, so it can read the name in each way. Its value can be another
1789
+ * list, so the `if` goes into `lets`. The printer gives each place of the program an object of its own (`unsharedAll`).
1790
+ * Thus an append of the form is not also an append in such a branch.
1791
+ */
1792
+ function otherList(e: Expr, lets: Expr[], wide: boolean): boolean {
1793
+ if (wide) lets.push(e);
1794
+ return wide;
1043
1795
  }
1044
1796
 
1045
1797
  /**
1046
- * 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
1047
- * constant of the run count as one node each. A part with less work costs less than the read of its column.
1798
+ * This function gives the filters of the list of the name `name` in the branches of the `if` nodes in `lets`
1799
+ * (COMPILE.MODULE.APPEND.KEEP). These nodes are the branches of other lists of COMPILE.MODULE.APPEND.OTHER. A filter is
1800
+ * `flat` over an each over the axis `list` of the name. The body of the each does not read the name, so it does
1801
+ * not see the array while the filter changes it. The other nodes in `lets` are `let` nodes, and the test of an `if`
1802
+ * does not read the name.
1048
1803
  */
1049
- const COLUMN_WORK = 10;
1050
-
1051
- /** 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. */
1052
- 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}++) {`);
1053
-
1054
- /** This function tells if an expression has a loop in a loop: an axis, a fold or an iteration in another one. */
1055
- function nestsLoops(e: Expr, inLoop = false): boolean {
1056
- const loop = e.tag === "each" || e.tag === "fold" || e.tag === "iterate";
1057
- return (loop && inLoop) || children(e).some((x) => nestsLoops(x, inLoop || loop));
1804
+ function keepsOf(lets: readonly Expr[], name: string): readonly Expr[] {
1805
+ const keeps = (e: Expr): boolean => {
1806
+ const [each] = e.tag === "app" && e.op === "flat" ? e.args : [];
1807
+ return each?.tag === "each" && each.axis.t === "list" && each.axis.list.tag === "var" && each.axis.list.name === name && !namesOf(each.body).has(name);
1808
+ };
1809
+ return lets.flatMap((e) => (e.tag === "app" ? e.args.filter(keeps) : []));
1810
+ }
1811
+
1812
+ /**
1813
+ * This function tells if each value of the list `e` has at most one item (COMPILE.MODULE.APPEND.KEEP). Such a list is
1814
+ * `fill(0, x)`, `fill(1, x)`, a literal of at most one item or an `if` of such lists. `fill` must be the op of the
1815
+ * language (`own`). A filter in place then puts at most one item for each item of its list, as the last statement of
1816
+ * the item. Thus a put does not come before the read of the item at its position.
1817
+ */
1818
+ function atMostOne(e: Expr, own: boolean): boolean {
1819
+ if (e.tag === "lit") return isVexList(e.value) && e.value.items.length <= 1;
1820
+ if (e.tag !== "app") return false;
1821
+ // An if without three arguments gives a reason (#if), so the function does not check the count.
1822
+ if (e.op === "if") return e.args.slice(1).every((x) => atMostOne(x, own));
1823
+ const [count] = e.args.map(literalOf);
1824
+ return own && e.op === "fill" && (count === 0 || count === 1);
1825
+ }
1826
+
1827
+ /** The list ops whose value is a number or an item of the list, so the value cannot hold the array of the list. */
1828
+ const READ_OPS: ReadonlySet<string> = new Set(["count", "nth", "first"]);
1829
+
1830
+ /**
1831
+ * This function tells if each read of the name `name` in `e` only reads its list (COMPILE.MODULE.APPEND.READ). Such a
1832
+ * read is the list of `count`, `nth` or `first`, or the list of the axis `list` of a fold. These values are numbers,
1833
+ * items or the names of the fold, so they cannot hold the array of the list. A function that reads the name does not
1834
+ * read it.
1835
+ */
1836
+ function readsOnly(e: Expr, name: string): boolean {
1837
+ const reads = (x: Expr | undefined): boolean => x?.tag === "var" && x.name === name;
1838
+ if (reads(e) || (e.tag === "fn" && namesOf(e).has(name))) return false;
1839
+ if (e.tag === "app" && READ_OPS.has(e.op) && reads(e.args[0])) return e.args.slice(1).every((x) => readsOnly(x, name));
1840
+ const list = e.tag === "fold" && e.axis.t === "list" && reads(e.axis.list) ? e.axis.list : undefined;
1841
+ return children(e).every((x) => x === list || readsOnly(x, name));
1842
+ }
1843
+
1844
+ /**
1845
+ * This function tells if the result of a loop appends to the list of the name `name` as its last reader
1846
+ * (COMPILE.MODULE.FUSE.ADOPT). It puts the append nodes of the form into `out`. The form is the form of `ownForm`. A
1847
+ * `let` can also bind the form to a new name. Then no other binding and not the body reads `name`, and the body is a
1848
+ * form of the new name. Such a let goes into `relays`. No other part of the form reads the name, so no part reads the
1849
+ * old list after an append.
1850
+ */
1851
+ function lastForm(e: Expr, name: string, out: Expr[], relays: Map<Expr, Relay>): boolean {
1852
+ const free = (x: Expr): boolean => !namesOf(x).has(name);
1853
+ if (e.tag === "var") return e.name === name;
1854
+ if (e.tag === "let") {
1855
+ const held = Object.entries(e.bind).filter(([, x]) => !free(x));
1856
+ // A binding of the name hides the name of the loop in the body.
1857
+ if (held.length === 0) return !Object.hasOwn(e.bind, name) && lastForm(e.body, name, out, relays);
1858
+ const [bind, x] = held[0] as [string, Expr];
1859
+ const nodes: Expr[] = [];
1860
+ if (held.length > 1 || (bind !== name && !free(e.body)) || !lastForm(x, name, out, relays) || !lastForm(e.body, bind, nodes, relays)) return false;
1861
+ relays.set(e, { bind, nodes });
1862
+ return true;
1863
+ }
1864
+ if (e.tag !== "app" || e.args.length === 0) return false;
1865
+ const [head, ...rest] = e.args as [Expr, ...Expr[]];
1866
+ if (e.op === "if") return free(head) && rest.every((x) => lastForm(x, name, out, relays));
1867
+ if (e.op !== "append" || !rest.every(free) || !lastForm(head, name, out, relays)) return false;
1868
+ out.push(e);
1869
+ return true;
1870
+ }
1871
+
1872
+ /**
1873
+ * This function tells if a `let` of the form of `ownForm` binds the name `name` again. The appends under such a let
1874
+ * append to another list. Then the value of the step can be a list that is not the array of the name
1875
+ * (COMPILE.MODULE.FUSE.ADOPT).
1876
+ */
1877
+ function shadows(e: Expr, name: string): boolean {
1878
+ if (e.tag === "let") return Object.hasOwn(e.bind, name) || shadows(e.body, name);
1879
+ if (e.tag !== "app") return false;
1880
+ const [head, ...rest] = e.args as [Expr, ...Expr[]];
1881
+ return e.op === "if" ? rest.some((x) => shadows(x, name)) : shadows(head, name);
1882
+ }
1883
+
1884
+ /**
1885
+ * This function tells if an append into the list of a name of a loop can take the first list as its own array
1886
+ * (COMPILE.MODULE.FUSE.ADOPT). No other part of the code holds a fresh array. AO does not scan the array that it
1887
+ * takes, so the list must also be clean.
1888
+ */
1889
+ function adoptable(l: ListInfo | undefined): boolean {
1890
+ if (l?.fresh !== true) return false;
1891
+ // Stryker disable next-line ConditionalExpression: each fresh list of the printer is clean, but the test keeps AO correct for a new fresh list
1892
+ return l.clean === true;
1893
+ }
1894
+
1895
+ /** This function gives the names that an expression reads, also the names that it binds itself. */
1896
+ function namesOf(e: Expr, out = new Set<string>()): Set<string> {
1897
+ if (e.tag === "var") out.add(e.name);
1898
+ for (const x of children(e)) namesOf(x, out);
1899
+ return out;
1900
+ }
1901
+
1902
+ /**
1903
+ * 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
1904
+ * constant of the run count as one node each. A part with less work costs less than the read of its column.
1905
+ */
1906
+ const COLUMN_WORK = 10;
1907
+
1908
+ /** The parts of the head of a loop over targets: the first value, the condition and the step. */
1909
+ interface ForParts {
1910
+ readonly init: string;
1911
+ readonly cond: string;
1912
+ readonly next: string;
1913
+ }
1914
+
1915
+ /** This function gives the parts of a loop over targets: from `lo` up to `hi`, or from `hi` down to `lo` in the reverse order. */
1916
+ const forParts = (j: string, lo: string, hi: string, reverse: boolean): ForParts =>
1917
+ reverse ? { init: `${hi} - 1`, cond: `${j} >= ${lo}`, next: `${j}--` } : { init: lo, cond: `${j} < ${hi}`, next: `${j}++` };
1918
+
1919
+ /** This function gives the head of a loop over targets from its parts. */
1920
+ const forHead = (j: string, p: ForParts): string => `for (let ${j} = ${p.init}; ${p.cond}; ${p.next}) {`;
1921
+
1922
+ /**
1923
+ * This function gives the value that stops the step `x` of the name `name` of a fold (COMPILE.MODULE.EXIT), or
1924
+ * undefined. The step `and(name, ...)` stops at false, and the step `or(name, ...)` stops at true. A name of `as` is
1925
+ * not a name of `init`, so the first argument reads the name of the fold.
1926
+ */
1927
+ const stopOf = (x: Expr, name: string): boolean | undefined => {
1928
+ if (x.tag !== "app" || (x.op !== "and" && x.op !== "or")) return undefined;
1929
+ const [head] = x.args;
1930
+ return head?.tag === "var" && head.name === name ? x.op === "or" : undefined;
1931
+ };
1932
+
1933
+ /** This function tells if an expression has a loop in a loop: an axis, a fold or an iteration in another one. */
1934
+ function nestsLoops(e: Expr, inLoop = false): boolean {
1935
+ const loop = e.tag === "each" || e.tag === "fold" || e.tag === "iterate";
1936
+ return (loop && inLoop) || children(e).some((x) => nestsLoops(x, inLoop || loop));
1058
1937
  }
1059
1938
 
1060
1939
  /** This function tells if an expression has a loop of names: a fold or an iteration. */
1061
1940
  function hasLoop(e: Expr): boolean {
1062
1941
  let found = LOOPS.get(e);
1063
1942
  if (found === undefined) {
1064
- found = e.tag === "fold" || e.tag === "iterate" || children(e).some(hasLoop);
1943
+ found = e.tag === "fold" || e.tag === "iterate" || e.tag === "fix" || children(e).some(hasLoop);
1065
1944
  LOOPS.set(e, found);
1066
1945
  }
1067
1946
  return found;
@@ -1082,6 +1961,9 @@ function memoOf(expr: Expr): ReadonlyMap<Expr, readonly Expr[]> {
1082
1961
  return new Map([...all].filter(([e, keys]) => ownLoop(e, e, all, new Set(keys))));
1083
1962
  }
1084
1963
 
1964
+ /** This function tells if each level of `deps` is one of `levels`. */
1965
+ const within = (deps: ReadonlySet<number>, levels: readonly number[]): boolean => [...deps].every((d) => levels.includes(d));
1966
+
1085
1967
  /** This function tells if an expression contains the expression `x`, the same object. */
1086
1968
  function contains(e: Expr, x: Expr): boolean {
1087
1969
  return e === x || children(e).some((c) => contains(c, x));
@@ -1115,6 +1997,16 @@ const plainValue = (code: string, kind: Kind | undefined): Value => ({ code, kin
1115
1997
  /** This function gives the code of a value with no statements. */
1116
1998
  const bare = (v: Value): Code => ({ s: [], v });
1117
1999
 
2000
+ /**
2001
+ * This function gives a domain in the form of a module (COMPILE.MODULE.FORM). Each part of the form replaces the part of
2002
+ * the domain, so the printer reads one domain of plain data. A domain without a form stays the same object.
2003
+ */
2004
+ function formOf(d: AnyDomain): AnyDomain {
2005
+ const form = d.moduleForm;
2006
+ if (form === undefined) return d;
2007
+ return { ...d, ...form, ops: Object.fromEntries(Object.entries(d.ops).map(([name, spec]) => [name, { ...spec, ...form.ops?.[name] }])) } as AnyDomain;
2008
+ }
2009
+
1118
2010
  /** 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. */
1119
2011
  function literal(value: unknown): Value {
1120
2012
  if (typeof value === "number") {
@@ -1127,15 +2019,6 @@ function literal(value: unknown): Value {
1127
2019
  throw new NotStandalone("a literal is not a number, a text, a boolean or null");
1128
2020
  }
1129
2021
 
1130
- /**
1131
- * This function gives a text that is the same for two expressions with the same structure. -0 is not 0. A part with a
1132
- * 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
1133
- * not, so a token is not the text of a literal.
1134
- */
1135
- function canonical(e: Expr, token: (x: unknown) => object | undefined): string {
1136
- return JSON.stringify(e, (_name, x: unknown) => token(x) ?? (Object.is(x, -0) ? { "-0": 0 } : x));
1137
- }
1138
-
1139
2022
  /** The values of each kind that `copied` gives to a function and to its copy. */
1140
2023
  const SAMPLES: Readonly<Record<PrimitiveKind, readonly unknown[]>> = {
1141
2024
  number: [0, 1, -1, 2.5, -0, 1e300, -7],
@@ -1148,14 +2031,33 @@ function samples(each: readonly (readonly unknown[])[]): readonly (readonly unkn
1148
2031
  return each.reduce<readonly (readonly unknown[])[]>((acc, values) => acc.flatMap((xs) => values.map((x) => [...xs, x])), [[]]);
1149
2032
  }
1150
2033
 
1151
- /** This function gives the text of plain data, with -0 apart from 0. */
1152
- const dataText = (x: unknown): string => canonical(x as Expr, () => undefined);
2034
+ /** This function tells if a value is an object. A function is not one here. */
2035
+ const isObject = (x: unknown): x is object => typeof x === "object" && x !== null;
2036
+
2037
+ /** This function gives the parts of a value of a class: the items of a `Map` or of a `Set`, or else the own fields. */
2038
+ const partsOfInstance = (x: object): unknown => (x instanceof Map || x instanceof Set ? [...x] : { ...x });
2039
+
2040
+ /**
2041
+ * This function is the rule of `same` for two objects. Two objects with different prototypes differ. Two values of a
2042
+ * class compare by their parts. The rules of `sameValue` compare each list and each plain record.
2043
+ */
2044
+ function sameObjects(a: unknown, b: unknown): boolean | undefined {
2045
+ if (!isObject(a) || !isObject(b)) return undefined;
2046
+ const proto: unknown = Object.getPrototypeOf(a);
2047
+ if (proto !== Object.getPrototypeOf(b)) return false;
2048
+ if (proto === null || proto === Object.prototype || Array.isArray(a)) return undefined;
2049
+ return sameValue(partsOfInstance(a), partsOfInstance(b), sameObjects);
2050
+ }
1153
2051
 
1154
- /** This function tells if two values are the same: the same primitive, or plain data with the same structure. */
2052
+ /**
2053
+ * This function tells if two values are the same. The walk of `sameValue` sees each leaf with `Object.is`, so
2054
+ * `Infinity`, `NaN` and `undefined` differ from `null`, and `-0` differs from `0` (V-093). The JSON text sees the order of
2055
+ * the fields and the result of a `toJSON` function. A value that has no JSON text compares by the walk only.
2056
+ */
1155
2057
  function same(a: unknown, b: unknown): boolean {
1156
2058
  if (Object.is(a, b)) return true;
1157
- if (typeof a !== "object" || a === null || typeof b !== "object" || b === null || Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) return false;
1158
- return dataText(a) === dataText(b);
2059
+ if (!isObject(a) || !isObject(b)) return false;
2060
+ return call(() => JSON.stringify(a)).value === call(() => JSON.stringify(b)).value && sameValue(a, b, sameObjects);
1159
2061
  }
1160
2062
 
1161
2063
  /** This function gives the value of a call, or that it threw. */
@@ -1181,7 +2083,7 @@ function sameCall(a: () => unknown, b: () => unknown): boolean {
1181
2083
  * the same for the samples of their kinds.
1182
2084
  */
1183
2085
  function copied(f: (...a: never[]) => unknown, each: readonly (readonly unknown[])[], what: string): string {
1184
- const src = Function.prototype.toString.call(f);
2086
+ const src = functionText(f);
1185
2087
  let copy: (...a: unknown[]) => unknown;
1186
2088
  try {
1187
2089
  // oxlint-disable-next-line typescript/no-implied-eval -- the source is the source of a function of a domain.
@@ -1246,13 +2148,16 @@ function isTokens(t: string): boolean {
1246
2148
  return true;
1247
2149
  }
1248
2150
 
2151
+ /** The source of an arrow function with plain parameters: its parameters and its body. */
2152
+ const ARROW = /^\(?\s*((?:[A-Za-z_$][\w$]*\s*,\s*)*[A-Za-z_$][\w$]*)\s*\)?\s*=>\s*([\s\S]*)/;
2153
+
1249
2154
  /**
1250
2155
  * This function gives the inline form of the source of an arrow function. The body of the function must be an
1251
2156
  * expression of operators, numbers, its parameters and the functions of `CALLS`. Such a body cannot throw for primitive
1252
2157
  * values (§7.1). The inline form is the text of the function itself, so it has its bits.
1253
2158
  */
1254
2159
  function inlineForm(src: string): InlineForm | undefined {
1255
- const m = /^\(?\s*((?:[A-Za-z_$][\w$]*\s*,\s*)*[A-Za-z_$][\w$]*)\s*\)?\s*=>\s*([\s\S]*)/.exec(src);
2160
+ const m = ARROW.exec(src);
1256
2161
  if (m === null) return undefined;
1257
2162
  const params = (m[1] as string).split(",").map((x) => x.trim());
1258
2163
  const parts: (string | number)[] = [];
@@ -1281,20 +2186,80 @@ function inlineForm(src: string): InlineForm | undefined {
1281
2186
  /** This function gives the text of an inline form without spaces, with `#i` for the parameter `at(i)`. */
1282
2187
  const patternOf = (form: InlineForm, at: (p: number) => number): string => form.parts.map((p) => (typeof p === "number" ? `#${at(p)}` : p.replaceAll(/\s/g, ""))).join("");
1283
2188
 
2189
+ /** The results of an op that are not values (CALL.RESULT). */
2190
+ const NOT_VALUES: readonly unknown[] = [undefined, null, Number.NaN, Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY];
2191
+
2192
+ /** This function gives a text without the content of its parentheses, brackets and braces. */
2193
+ function outlineOf(t: string): string {
2194
+ let depth = 0;
2195
+ let out = "";
2196
+ for (const c of t) {
2197
+ if (")]}".includes(c)) depth--;
2198
+ if (depth === 0) out += c;
2199
+ if ("([{".includes(c)) depth++;
2200
+ }
2201
+ return out;
2202
+ }
2203
+
2204
+ /** This function tells if each operator of a part of an expression is a comparison, so the part gives a boolean. */
2205
+ function isComparison(part: string): boolean {
2206
+ const operators = part.match(/>>>?=?|<<=?|[=!]==?|[<>]=?|[&|^?,=]+/g);
2207
+ return operators !== null && operators.every((x) => /^([=!]==?|[<>]=?)$/.test(x));
2208
+ }
2209
+
2210
+ /** This function tells if an expression gives a boolean or an object. An object needs parentheses in an arrow body. */
2211
+ function isValueText(t: string, inParentheses: boolean): boolean {
2212
+ const outline = outlineOf(t);
2213
+ if (outline === "{}") return inParentheses;
2214
+ if (outline === "()") return isValueText(t.slice(1, -1).trim(), true);
2215
+ return outline.split(/&&|\|\|/).every((part) => isComparison(part) || /^\s*!+[\w$.()\s]*$/.test(part));
2216
+ }
2217
+
2218
+ /**
2219
+ * This function tells if the text of an op proves that its result is a value (COMPILE.MODULE.RESULT). The proofs are a
2220
+ * comparison, a negation, an `&&` or an `||` of these, and an object literal. A proof reads only the expression body of
2221
+ * an arrow function. A quote, a regular expression and a comment can hide a bracket, so they stop the proof.
2222
+ */
2223
+ function givesValue(src: string): boolean {
2224
+ const body = ARROW.exec(src)?.[2];
2225
+ return body !== undefined && !/["'`/]/.test(body) && isValueText(body.trim(), false);
2226
+ }
2227
+
2228
+ /** This function tells if a check `valid` refuses a value: it gives false, or it throws. */
2229
+ function refuses(valid: (x: never) => boolean, value: unknown): boolean {
2230
+ try {
2231
+ return !valid(value as never);
2232
+ } catch {
2233
+ return true;
2234
+ }
2235
+ }
2236
+
1284
2237
  /** The reserved words of the strict code of a module, and the two names that strict code does not bind. */
1285
2238
  const RESERVED: ReadonlySet<string> = new Set(
1286
2239
  "await break case catch class const continue debugger default delete do else enum export extends false finally for function if implements import in instanceof interface let new null package private protected public return static super switch this throw true try typeof var void while with yield arguments eval".split(" "),
1287
2240
  );
1288
2241
 
2242
+ /** The names that each module exports. A run with such a name is a second export, and the module does not parse. */
2243
+ const MODULE_EXPORTS: ReadonlySet<string> = new Set(["VEX_ERROR", "VexContractError"]);
2244
+
2245
+ /** The comment of the class of a contract error in each module. */
2246
+ const ERROR_NOTE = "/** The error of a run whose input does not keep the schema of the program. */";
2247
+
2248
+ /** This function gives the reason that a name cannot be the name of the run, or `undefined` for a good name (V-060). */
2249
+ function nameReason(name: string): string | undefined {
2250
+ if (RESERVED.has(name)) return `the name "${name}" is a reserved word of JavaScript`;
2251
+ return MODULE_EXPORTS.has(name) ? `the name "${name}" is a name of the module` : undefined;
2252
+ }
2253
+
1289
2254
  /**
1290
- * This function gives the reason that a name cannot be the name of the run, or `undefined` for a good name (V-060). A
1291
- * reserved word does not parse, and a second declaration of a name of the module does not parse. The function of the
1292
- * run with the name of a global of `MODULE_GLOBALS` hides that global from the code of the module.
2255
+ * This function gives the name of the function of the run (COMPILE.MODULE.NAME). A function with a name of the code hides
2256
+ * that name from the code. Thus the run of such a module has an internal name that the code does not have.
1293
2257
  */
1294
- function nameReason(name: string, declared: ReadonlySet<string>): string | undefined {
1295
- if (RESERVED.has(name)) return `the name "${name}" is a reserved word of JavaScript`;
1296
- if (MODULE_GLOBALS.has(name)) return `the name "${name}" is a global that a module reads`;
1297
- return declared.has(name) ? `the name "${name}" is a name of the module` : undefined;
2258
+ function innerName(name: string, code: ReadonlySet<string>): string {
2259
+ if (!code.has(name)) return name;
2260
+ let at = 0;
2261
+ while (code.has(`run$${String(at)}`)) at += 1;
2262
+ return `run$${String(at)}`;
1298
2263
  }
1299
2264
 
1300
2265
  class Printer {
@@ -1305,6 +2270,10 @@ class Printer {
1305
2270
  readonly helpers = new Set<Helper>();
1306
2271
  /** The declarations at the top of the module: the functions of the domains and the checks of the results. */
1307
2272
  readonly top = new Map<string, string>();
2273
+ /** The names of `top` that hold a copy of a function of a domain (COMPILE.MODULE.FAULT). */
2274
+ readonly copies = new Set<string>();
2275
+ /** This value is true when the code reads the list of an op of a domain. That read gives the depth (COMPILE.MODULE.LIST.OP). */
2276
+ opList = false;
1308
2277
  /** The array of the lists of each field of the input that the program reads (COMPILE.MODULE.LIST.INPUT). */
1309
2278
  readonly inputs = new Map<string, string>();
1310
2279
  /** The statements at the start of a run: the constants of the run and the functions of the memo. */
@@ -1320,9 +2289,13 @@ class Printer {
1320
2289
  readonly treeParts = new Set<TreePart>();
1321
2290
  /** True for a graph space, and true when the program reads the predecessors of a graph (COMPILE.MODULE.GRAPH). */
1322
2291
  readonly #graph: boolean;
2292
+ readonly #keys: KeyPrint;
1323
2293
  into = false;
2294
+ /** True when the code reads the keys of the run (COMPILE.MODULE.KEYS). */
2295
+ runKeys = false;
1324
2296
  /** The columns of a sheet, for a module of a sheet (COMPILE.MODULE.SHEET). */
1325
2297
  readonly #sheet: SheetInfo | undefined;
2298
+ readonly #starts: EmptyStarts;
1326
2299
  #names = 0;
1327
2300
  /** The number of the next bound function, and of the next printed function. */
1328
2301
  #fnIds = 0;
@@ -1333,20 +2306,52 @@ class Printer {
1333
2306
  #inside: Expr | undefined;
1334
2307
  /** The owner of each append node of the step of a loop that the printer prints (COMPILE.MODULE.APPEND.OWN). */
1335
2308
  readonly #own = new Map<Expr, Owner>();
2309
+ /** The owner of each relay `let` of the result of a loop that the printer prints (COMPILE.MODULE.FUSE.ADOPT). */
2310
+ readonly #relays = new Map<Expr, Relay & { readonly owner: Owner }>();
2311
+ /**
2312
+ * The second lists of the appends of an owner that the printer prints (COMPILE.MODULE.FUSE.ADOPT). A list of
2313
+ * `fill(1, x)` gets the value of its print and the code of its one item. Such a print does not use `FI`, so a push of
2314
+ * the item needs no `FI`.
2315
+ */
2316
+ readonly #ones = new Map<Expr | undefined, { readonly v: Value; readonly item: string } | undefined>();
2317
+ /**
2318
+ * The owner of each filter of its list in a branch of another list (COMPILE.MODULE.APPEND.KEEP). The step of the owner
2319
+ * that the printer prints has these filters.
2320
+ */
2321
+ readonly #keeps = new Map<Expr, Owner>();
2322
+ /**
2323
+ * The outputs of the filters in place that the printer prints (COMPILE.MODULE.APPEND.KEEP). An item goes to the
2324
+ * position `n` of its output, and `n` then increases. `pair` is the pair of the item of the list, and `item` is the
2325
+ * code of its value. A pair with the key 0 is its own copy.
2326
+ */
2327
+ readonly #sinks = new Map<string, { readonly n: string; readonly pair: string; readonly item: string | undefined }>();
1336
2328
  readonly #structures = new Map<string, string>();
1337
2329
  readonly #kinds = new Map<string, Kind | undefined>();
1338
2330
  readonly #ops = new Map<string, number>();
1339
2331
  /** The inline form of each function of an op, or undefined for a function that the module calls. */
1340
2332
  readonly #forms = new Map<string, InlineForm | undefined>();
2333
+ /** The ops whose text does not prove that the result is a value, so their results get the check of a value. */
2334
+ readonly #unproved = new Set<string>();
1341
2335
  /** The functions of ops that the module calls, not in an inline form. */
1342
2336
  readonly #called = new Set<string>();
1343
2337
  /** The key of the expression of each code that is a constant of the run, and the read of each hoisted constant by key. */
1344
2338
  readonly #keyOf = new WeakMap<Code, string>();
2339
+ readonly #keyTable = new KeyTable();
1345
2340
  readonly #constants = new Map<string, Code>();
1346
2341
  /** The columns of the run, by the structure of their expression. */
1347
2342
  readonly #columns = new Map<string, string>();
1348
2343
  /** The expressions whose code is the read of a column of the run. */
1349
2344
  readonly #columned = new WeakSet<Expr>();
2345
+ /** The kind of each column at the start of a run that holds no list. A column of a call is not in this map. */
2346
+ readonly #runColumns = new Map<string, Kind | undefined>();
2347
+ /** The function and the kind of each column of a call that holds no list. Only a read in that function reads its pack. */
2348
+ readonly #callColumns = new Map<string, { readonly scope: CallScope; readonly kind: Kind | undefined; readonly deps: ReadonlySet<number> }>();
2349
+ /** The code of each printed function, by its name. A fast sum looks in it for the columns that a call reads. */
2350
+ readonly #specCode = new Map<string, string>();
2351
+ /** The module variable of the pack of each column of the run, by the name of the column. */
2352
+ readonly #packs = new Map<string, string>();
2353
+ /** The state of the second print of a fast sum, or undefined outside it. */
2354
+ #pack: Pack | undefined;
1350
2355
  /** The lazy constants of the run, and the printed functions that have a loop: code that reads one waits for its read. */
1351
2356
  readonly #deferred = new Set<string>();
1352
2357
  /** The functions that the printer prints at this time, the innermost last. */
@@ -1354,28 +2359,108 @@ class Printer {
1354
2359
  readonly #scopes: CallScope[] = [];
1355
2360
  /** The work of the body of each bound function, by the number of its binding. */
1356
2361
  readonly #fnWork = new Map<number, number>();
1357
- /** The expressions whose code is a constant of the run. */
2362
+ /** The expressions whose code is a constant of the run. Each entry is the original of a copy, so a second place of a shared list has the fact too. */
1358
2363
  readonly #constant = new WeakSet<Expr>();
1359
2364
  /** The expressions at a place that takes a list: a binding, the head of a list op and the list of an axis. */
1360
2365
  readonly #wantList = new WeakSet<Expr>();
1361
2366
  /** The facts of the list of each function of the memo whose value is a list. */
1362
2367
  readonly #lists = new Map<string, ListInfo | undefined>();
2368
+ /** True when a test of the analysis reads the facts of fusion (`listFactsOf`), and the facts of each list node. */
2369
+ readonly #noting: boolean;
2370
+ readonly #noted = new Map<Expr, Omit<ListFacts, "reads">>();
2371
+ /** The count of the reads of the value of each node, from the form of the program (`readCounts`). */
2372
+ readonly #reads: ReadonlyMap<Expr, number>;
2373
+ /** The nodes whose value the code reads again: a constant of the run, a column and a node of the memo. */
2374
+ readonly #shared = new Set<Expr>();
2375
+ /** The node of each code that `expr` gives, while the printer notes the facts of fusion. */
2376
+ readonly #nodeOf = new WeakMap<Code, Expr>();
2377
+ /** True when the printer prints the forms of fusion (COMPILE.MODULE.FUSE.OFF). `runOf` checks the option first. */
2378
+ readonly #fuse: boolean;
2379
+ /**
2380
+ * The code of each fused loop, with the index of the statement that declares its output (COMPILE.MODULE.FUSE). A chain
2381
+ * that reads the loop changes that statement, and then the loop pushes into the output of the chain.
2382
+ */
2383
+ readonly #outputs = new WeakMap<Code, number>();
1363
2384
 
1364
- constructor(expr: Expr, options: ModuleOptions, sheet?: SheetInfo) {
1365
- this.#domains = options.domains ?? [];
2385
+ constructor(expr: Expr, options: ModuleOptions, keys: KeyPrint, starts: EmptyStarts, sheet?: SheetInfo) {
2386
+ this.#keys = keys;
2387
+ this.#fuse = options.fuse !== false;
2388
+ this.#starts = starts;
2389
+ this.#domains = (options.domains ?? []).map(formOf);
1366
2390
  this.#facts = factsOf({ domains: this.#domains });
1367
2391
  this.#schema = options.schema;
1368
2392
  this.#memo = memoOf(expr);
1369
2393
  this.#tree = options.space === "tree";
1370
2394
  this.#graph = options.space === "graph";
1371
2395
  this.#sheet = sheet;
2396
+ this.#noting = recorder !== undefined;
2397
+ this.#reads = this.#noting ? readCounts(expr) : new Map();
2398
+ recorder?.push(this);
2399
+ }
2400
+
2401
+ /** This method gives the facts of fusion of each list node that the printer printed (COMPILE.MODULE.FUSE.FACTS). */
2402
+ listFacts(): ReadonlyMap<Expr, ListFacts> {
2403
+ const out = new Map<Expr, ListFacts>();
2404
+ // A part that the code reads again holds the array of the node, so the node is not fresh. Each node of a list is a
2405
+ // node of the program, but a node without a count gets the safe count. The copies of a shared object give one fact.
2406
+ for (const [e, f] of this.#noted) {
2407
+ const fact = this.#shared.has(e) ? { ...f, fresh: false, reads: Infinity } : { ...f, reads: this.#reads.get(e) ?? Infinity };
2408
+ const old = out.get(originalOf(e));
2409
+ out.set(originalOf(e), old === undefined ? fact : bothPlaces(old, fact));
2410
+ }
2411
+ return out;
2412
+ }
2413
+
2414
+ /** This method notes the facts of fusion of the list of a node. A node that prints at two places gets the facts of both. */
2415
+ #note(e: Expr, c: Code, memo: boolean): void {
2416
+ const list = c.v.list;
2417
+ if (!this.#noting || list === undefined) return;
2418
+ this.#nodeOf.set(c, e);
2419
+ if (memo) this.#shared.add(e);
2420
+ const inner: boolean[] = [];
2421
+ for (let l = list.inner; l !== undefined; l = l.inner) inner.push(l.clean === true);
2422
+ const old = this.#noted.get(e);
2423
+ const clean = list.clean === true && (old?.clean ?? true);
2424
+ const fresh = list.fresh === true && (old?.fresh ?? true);
2425
+ this.#noted.set(e, { clean, inner: old === undefined ? inner : inner.map((x, i) => x && old.inner[i] === true), fresh });
1372
2426
  }
1373
2427
 
1374
2428
  use(name: Helper): string {
2429
+ if (KEY_READS.has(name)) this.#keys.read = true;
1375
2430
  this.helpers.add(name);
1376
2431
  return name;
1377
2432
  }
1378
2433
 
2434
+ /**
2435
+ * This method tells if the printer prints the clean form of a list (COMPILE.MODULE.FUSE.CLEAN). The option `fuse` must
2436
+ * be true, and the facts must prove the list clean. With `levels`, each level of a list of lists must be clean too.
2437
+ */
2438
+ #clean(l: ListInfo | undefined, levels = false): boolean {
2439
+ if (!this.#fuse) return false;
2440
+ for (let x = l; x !== undefined; x = levels ? x.inner : undefined) if (x.clean !== true) return false;
2441
+ return l !== undefined;
2442
+ }
2443
+
2444
+ /**
2445
+ * This method gives the code of a list in the form of the helper `form`: a `vex.list`, or a plain array for `LP`
2446
+ * (COMPILE.MODULE.LIST.PLAIN). A list that the facts prove clean uses the clean form of the helper (COMPILE.MODULE.FUSE.CLEAN).
2447
+ */
2448
+ envelope(v: Value, form: keyof typeof CLEAN_FORMS): string {
2449
+ const list = v.list as ListInfo;
2450
+ const helper = this.#clean(list, true) ? CLEAN_FORMS[form] : form;
2451
+ return `${this.use(helper)}(${v.code}, ${String(depthOf(list))})`;
2452
+ }
2453
+
2454
+ /**
2455
+ * This method gives the code of a list that is the value of the run at a key. With `fuse`, a `vex.list` that reads no
2456
+ * key evaluates once, on its first read, so each key gets one object (COMPILE.MODULE.FUSE.OUT). The keys share that
2457
+ * object, so only that object is frozen. A plain array stays one array for each key, because a host can change an array.
2458
+ */
2459
+ runList(v: Value, plain: boolean): string {
2460
+ if (plain || !this.#fuse || v.deps.size > 0) return this.envelope(v, plain ? "LP" : "LO");
2461
+ return this.#hoist(bare({ ...v, code: this.envelope(v, "LS"), plain: false }), true).v.code;
2462
+ }
2463
+
1379
2464
  /** This method gives the name of a part of the tree, for example `H` for the children, and marks the part as read. */
1380
2465
  #part(part: TreePart, name: string): string {
1381
2466
  this.treeParts.add(part);
@@ -1385,7 +2470,8 @@ class Printer {
1385
2470
  /**
1386
2471
  * This method gives the check of a result of a kind, or undefined for a result that needs no check. A number must be
1387
2472
  * finite, and the domain of the kind can check the value with valid. The law checker of the test kit checks the
1388
- * declaration `returns` of each op (KIND.RETURNS), so the module trusts the kind itself.
2473
+ * declaration `returns` of each op (KIND.RETURNS), so the module trusts the kind of each value. A result that is not a
2474
+ * value does not break the declaration, and `#value` gives its check (COMPILE.MODULE.RESULT).
1389
2475
  */
1390
2476
  check(kind: Kind): string | undefined {
1391
2477
  const d = this.#facts.checkOf(kind);
@@ -1412,16 +2498,42 @@ class Printer {
1412
2498
  return k === undefined ? code : `${k}(${code})`;
1413
2499
  }
1414
2500
 
2501
+ /**
2502
+ * This method tells if the check of a kind can miss a result that is not a value. The check of a number finds each
2503
+ * such result, and a check `valid` finds them when it refuses each one.
2504
+ */
2505
+ #missesNoValue(kind: Kind): boolean {
2506
+ if (kind === "number") return false;
2507
+ const valid = this.#domains[this.#facts.checkOf(kind) as number]?.valid;
2508
+ return valid === undefined || !NOT_VALUES.every((x) => refuses(valid, x));
2509
+ }
2510
+
2511
+ /**
2512
+ * This method gives the code of the result of the op `name` with the check of a value, if the op needs it. The
2513
+ * interpreter gives an error for `undefined`, `null` and a number that is not finite (CALL.RESULT).
2514
+ */
2515
+ #value(name: string, code: string): string {
2516
+ if (!this.#unproved.has(name)) return code;
2517
+ this.top.set("k_value", `const k_value = (x) => (x === undefined || x === null || (typeof x === "number" && !Number.isFinite(x)) ? ${this.use("F")}() : x);`);
2518
+ return `k_value(${code})`;
2519
+ }
2520
+
1415
2521
  #valid(d: number, domain: string, kind: Kind, valid: (x: never) => boolean): string | undefined {
1416
2522
  const name = `v_${d}`;
1417
2523
  const src = copied(valid, [this.#samples(kind)], `the check "valid" of the domain ${domain}`);
1418
2524
  // A check that is Number.isFinite of a number adds nothing to the check of the result.
1419
2525
  const form = inlineForm(src);
1420
2526
  if (kind === "number" && form !== undefined && patternOf(form, (p) => p) === "Number.isFinite(#0)") return undefined;
1421
- this.top.set(name, `const ${name} = ${src};`);
2527
+ this.#copy(name, src);
1422
2528
  return name;
1423
2529
  }
1424
2530
 
2531
+ /** This method keeps the copy of a function of a domain as a declaration of the module. */
2532
+ #copy(name: string, src: string): void {
2533
+ this.top.set(name, `const ${name} = ${src};`);
2534
+ this.copies.add(name);
2535
+ }
2536
+
1425
2537
  /** This method gives the samples of a kind: the samples of a primitive type, or the samples of a domain (KIND.DOMAIN). */
1426
2538
  #samples(kind: Kind): readonly unknown[] {
1427
2539
  const primitive = primitiveOf(kind);
@@ -1460,14 +2572,16 @@ class Printer {
1460
2572
  const name = `is_${String(d)}`;
1461
2573
  if (!this.top.has(name)) {
1462
2574
  const src = copied(domain.is, [[...SAMPLES.number, ...SAMPLES.string, ...SAMPLES.boolean, null, {}, [], ...this.#samples(kind)]], `the test "is" of the domain ${domain.name}`);
1463
- this.top.set(name, `const ${name} = ${src};`);
2575
+ this.#copy(name, src);
1464
2576
  }
1465
2577
  return name;
1466
2578
  }
1467
2579
 
1468
2580
  /** This method gives a new name for the code. */
1469
2581
  fresh(prefix: string): string {
1470
- return `${prefix}${this.#names++}`;
2582
+ const name = `${prefix}${this.#names++}`;
2583
+ if (prefix === "b") this.#pack?.locals.add(name);
2584
+ return name;
1471
2585
  }
1472
2586
 
1473
2587
  /** This method tells if code reads a lazy constant of the run, or calls a printed function that has a loop. */
@@ -1477,7 +2591,8 @@ class Printer {
1477
2591
 
1478
2592
  /** This method gives the code of a name: a read that throws the error of its value, if it can hold an error. */
1479
2593
  #read(name: Name): Value {
1480
- const base = { kind: name.kind, deps: name.deps, plain: true, list: name.list };
2594
+ // A name holds its list, so a read of the name is not fresh.
2595
+ const base = { kind: name.kind, deps: name.deps, plain: true, list: heldList(name.list) };
1481
2596
  return name.lazy ? { ...base, code: `${this.use("G")}(${name.code})`, safe: false, held: name.code } : { ...base, code: name.code, safe: true };
1482
2597
  }
1483
2598
 
@@ -1504,9 +2619,14 @@ class Printer {
1504
2619
  */
1505
2620
  #hoist(c: Code, lazy = false): Code {
1506
2621
  if (c.v.deps.size > 0 || (c.v.plain === true && c.s.length === 0)) return c;
2622
+ // The loop over the keys reads each constant of the run again.
2623
+ const node = this.#nodeOf.get(c);
2624
+ if (node !== undefined) this.#shared.add(node);
1507
2625
  const key = this.#keyOf.get(c);
1508
2626
  const hit = key === undefined ? undefined : this.#constants.get(key);
1509
2627
  if (hit !== undefined) return hit;
2628
+ // A pack is a local of the loop of a second print, so a constant of the run cannot read it (V-077).
2629
+ this.#leavePack([c.v.code, ...c.s]);
1510
2630
  const name = this.fresh("c");
1511
2631
  const deferred = lazy || this.#defers(c);
1512
2632
  if (deferred) {
@@ -1528,19 +2648,36 @@ class Printer {
1528
2648
  }
1529
2649
 
1530
2650
  expr(e: Expr, ctx: Ctx): Code {
2651
+ if (!this.#starts.seek) return this.#exprCode(e, ctx);
2652
+ // A part of a step can read the items of its own name, so a search cannot print it yet. The rest of the step can
2653
+ // decide the kind, and the last print proves it (COMPILE.MODULE.LOOP.EMPTY). The search keeps no text, and the last
2654
+ // print gives each error again.
2655
+ try {
2656
+ return this.#exprCode(e, ctx);
2657
+ } catch {
2658
+ return bare({ code: "E", kind: undefined, safe: true, deps: NO_DEPS, list: { item: undefined, empty: true } });
2659
+ }
2660
+ }
2661
+
2662
+ #exprCode(e: Expr, ctx: Ctx): Code {
1531
2663
  const key = ctx.keys.get(e);
1532
2664
  if (key !== undefined) return bare(this.#read(key));
1533
2665
  const keys = this.#memo.get(e);
1534
- const c = keys !== undefined && this.#inside !== e ? this.#memoized(e, keys, ctx) : this.#node(e, ctx);
2666
+ // In the second print of a fast sum, a column of the run at the item is the read of its pack, with no print of its parts.
2667
+ const packed = this.#packAt(ctx) && this.#columned.has(e) ? this.#packRead(this.#columns.get(this.#constKey(e, ctx)), ctx) : undefined;
2668
+ if (packed !== undefined) return packed;
2669
+ const c = keys !== undefined && this.#inside !== e ? this.#unpacked(() => this.#memoized(e, keys, ctx)) : this.#node(e, ctx);
1535
2670
  if (c.v.deps.size === 0) {
1536
2671
  // A constant of the run with the structure of an earlier one is that constant.
1537
2672
  this.#keyOf.set(c, this.#constKey(e, ctx));
1538
- this.#constant.add(e);
2673
+ this.#constant.add(originalOf(e));
1539
2674
  }
1540
2675
  // A list is a value only at a place that takes a list: a result, a binding, an argument, a field and the body of a
1541
2676
  // function take one. A condition, an argument of and or of or, and a key of get take no list.
1542
2677
  if (c.v.list !== undefined && !this.#wantList.has(e)) throw new NotStandalone("a list is a value of the program");
1543
- return this.#columnar(e, c, ctx) ? this.#column(e, c, ctx) : c;
2678
+ const out = this.#columnar(e, c, ctx) ? this.#column(e, c, ctx) : c;
2679
+ this.#note(e, out, keys !== undefined);
2680
+ return out;
1544
2681
  }
1545
2682
 
1546
2683
  /** This method gives the code of a list at a place that takes a list (LIST.VALUE): an each, a name, sortBy or take. */
@@ -1553,9 +2690,6 @@ class Printer {
1553
2690
 
1554
2691
  /** This method tells if an expression gives a list at a place that takes one (`listy`). */
1555
2692
  #isList(e: Expr, ctx: Ctx): boolean {
1556
- // A key of a node of the memo is a name of its function, and the name keeps the facts of a list.
1557
- const key = ctx.keys.get(e);
1558
- if (key !== undefined) return key.list !== undefined;
1559
2693
  return listy(e, this.#scopeOf(ctx));
1560
2694
  }
1561
2695
 
@@ -1565,23 +2699,33 @@ class Printer {
1565
2699
  * array of the each, and that array gives the value of the interpreter too (COMPILE.MODULE.LIST.ITEM).
1566
2700
  */
1567
2701
  #bodyList(e: ExprOf<"each">, ctx: Ctx): boolean {
1568
- if (e.as === undefined) return this.#isList(e.body, ctx);
1569
- // A list of the axis list is not in the memo, so the body is not a key of a node of the memo.
1570
2702
  const scope = this.#scopeOf(ctx);
2703
+ if (e.as === undefined) return listy(e.body, scope);
1571
2704
  const names: readonly string[] = e.as;
1572
- return listy(e.body, { ...scope, name: (name) => names.includes(name) || scope.name(name) });
2705
+ return listy(e.body, { ...scope, name: (name, levels) => names.includes(name) || scope.name(name, levels) });
1573
2706
  }
1574
2707
 
1575
- /** This method gives the scope of `listy` at a node: the names and the bound functions of its context. */
2708
+ /** This method gives the scope of `listy` at a node: the keys of its node of the memo, its names and its bound functions. */
1576
2709
  #scopeOf(ctx: Ctx): ListScope {
1577
2710
  return {
1578
- name: (name) => ctx.env.get(name)?.list !== undefined,
2711
+ // A key of a node of the memo is a name of its function, and the name keeps the facts of a list.
2712
+ key: (e) => ctx.keys.get(e),
2713
+ op: (name) => this.#facts.givesList(name),
2714
+ name: (name, levels) => {
2715
+ const bound = ctx.env.get(name);
2716
+ if (bound !== undefined) return hasLevels(bound.list, levels);
2717
+ const kind = this.#schema.vars?.[name];
2718
+ return typeof kind === "object" && hasLevels(listOfKind(kind), levels);
2719
+ },
1579
2720
  fn: (name) => {
1580
2721
  const bound = ctx.fns.get(name);
1581
2722
  return bound === undefined ? undefined : { fn: bound.fn, scope: this.#scopeOf(bound.ctx) };
1582
2723
  },
1583
- cell: (x) => this.#cellList(x) !== undefined,
1584
- field: (x) => typeof this.#schema.fields?.[x.path.join(".")] === "object",
2724
+ cell: (x, levels) => hasLevels(this.#cellList(x), levels),
2725
+ field: (x, levels) => {
2726
+ const kind = this.#schema.fields?.[x.path.join(".")];
2727
+ return typeof kind === "object" && hasLevels(listOfKind(kind), levels);
2728
+ },
1585
2729
  };
1586
2730
  }
1587
2731
 
@@ -1590,13 +2734,27 @@ class Printer {
1590
2734
  return e.kind === CELL_KIND && isCellRef(e.data) ? this.#sheet?.lists.get(e.data.column) : undefined;
1591
2735
  }
1592
2736
 
2737
+ /**
2738
+ * This method gives the code of a literal. A value of a domain with a module form is an object of plain data, with the
2739
+ * kind of its domain (COMPILE.MODULE.FORM). Such a value is a constant of the run, so it gets a variable.
2740
+ */
2741
+ #literal(value: unknown): Value {
2742
+ for (const d of this.#domains) {
2743
+ const data = d.moduleForm?.literal?.(value);
2744
+ if (data !== undefined) return { code: `({ ${Object.entries(data).map(([k, x]) => `${k}: ${literal(x).code}`).join(", ")} })`, kind: kindOfDomain(d), safe: true, deps: NO_DEPS };
2745
+ }
2746
+ return literal(value);
2747
+ }
2748
+
1593
2749
  /** This method prints a list literal (LIST.LITERAL) as an array of pairs of a key and a value. An error item holds the sentinel. */
1594
2750
  #listLiteral(l: VexList): Code {
1595
- const values = l.items.map((it) => (it.result.ok ? literal(it.result.value) : undefined));
2751
+ const values = l.items.map((it) => (it.result.ok ? this.#literal(it.result.value) : undefined));
1596
2752
  const kinds = values.flatMap((x) => (x === undefined ? [] : [x.kind]));
1597
2753
  const code = `[${l.items.map((it, i) => `[${JSON.stringify(it.key)}, ${values[i]?.code ?? "E"}]`).join(", ")}]`;
1598
2754
  const has = l.items.length > 0;
1599
- return bare({ code, kind: undefined, safe: true, deps: NO_DEPS, list: { item: kinds.reduce(join, kinds[0]), texts: has, empty: !has } });
2755
+ // An error item of the literal holds the sentinel, so only a literal without error items is clean.
2756
+ const clean = values.every((x) => x !== undefined);
2757
+ return bare({ code, kind: undefined, safe: true, deps: NO_DEPS, list: { item: kinds.reduce(join, kinds[0]), texts: has, empty: !has, clean } });
1600
2758
  }
1601
2759
 
1602
2760
  /**
@@ -1606,8 +2764,8 @@ class Printer {
1606
2764
  */
1607
2765
  #columnar(e: Expr, c: Code, ctx: Ctx): boolean {
1608
2766
  // A node of the memo has the level 1, so a column has a focus. The results of the cells change in a run, so a part
1609
- // that reads a cell is not a column.
1610
- if (ctx.level < 2 || c.v.deps.has(CELLS) || !c.v.deps.has(ctx.level) || this.#work(e, ctx.fns) < COLUMN_WORK) return false;
2767
+ // that reads a cell is not a column. The rows of a column change in each round, so a part that reads one is not either.
2768
+ if (ctx.level < 2 || c.v.deps.has(CELLS) || c.v.deps.has(ROUNDS) || !c.v.deps.has(ctx.level) || this.#work(e, ctx.fns) < COLUMN_WORK) return false;
1611
2769
  const scope = this.#callScope(c, ctx);
1612
2770
  if (c.v.deps.size !== 1 && scope === undefined) return false;
1613
2771
  // A node of the memo with keys keeps its costly part for each value of its keys already.
@@ -1650,7 +2808,7 @@ class Printer {
1650
2808
  * adds the work of the body of its function, because the body evaluates at each call.
1651
2809
  */
1652
2810
  #work(e: Expr, fns: ReadonlyMap<string, BoundFn>): number {
1653
- if (this.#memo.has(e) || this.#constant.has(e)) return 1;
2811
+ if (this.#memo.has(e) || this.#constant.has(originalOf(e))) return 1;
1654
2812
  // Stryker disable next-line ConditionalExpression: a node that is not a call has no field fn, so the map gives undefined
1655
2813
  const body = e.tag === "call" ? this.#bodyWork(fns.get(e.fn)) : 0;
1656
2814
  return children(e).reduce((sum, x) => sum + this.#work(x, fns), 1 + body);
@@ -1671,25 +2829,85 @@ class Printer {
1671
2829
  return work;
1672
2830
  }
1673
2831
 
2832
+ /**
2833
+ * This method stops the second print when some lines for the run read a local of its loop (V-077, V-094). That
2834
+ * local is a pack, or a value local that the lines do not declare. Else the declared locals go to the run too.
2835
+ */
2836
+ #leavePack(lines: readonly string[]): void {
2837
+ const pack = this.#pack;
2838
+ if (pack === undefined) return;
2839
+ const text = lines.join("\n");
2840
+ if ([...pack.cols.values()].some((local) => text.includes(`${local}[`))) throw new NoPack();
2841
+ // Stryker disable next-line ConditionalExpression: with no locals the scan below finds no read, so this return only saves the scan
2842
+ if (pack.locals.size === 0) return;
2843
+ const declared = new Set([...text.matchAll(/\b(?:const|let) (b\d+)\b/gu)].map((m) => m[1]));
2844
+ // A call at its place keeps an argument in a local, and a read of that argument has no levels (V-094).
2845
+ if ([...text.matchAll(/\bb\d+\b/gu)].some(([name]) => pack.locals.has(name) && !declared.has(name))) throw new NoPack();
2846
+ for (const name of declared) pack.locals.delete(name as string);
2847
+ }
2848
+
2849
+ /**
2850
+ * This method adds some lines to the run. A pack is a local of the loop of a second print, so a line of the run
2851
+ * cannot read it (V-077, V-084). Then the second print stops, and the loop keeps its first print.
2852
+ */
2853
+ #intoRun(lines: readonly string[]): void {
2854
+ this.#leavePack(lines);
2855
+ this.run.push(...lines);
2856
+ }
2857
+
2858
+ /** This method tells if a second print (`#packed`, `#packedSteps`) reads the packs of the columns at the focus of `ctx`. */
2859
+ #packAt(ctx: Ctx): boolean {
2860
+ return this.#pack !== undefined && ctx.focus !== undefined && this.#pack.foci.has(ctx.focus);
2861
+ }
2862
+
2863
+ /**
2864
+ * This method gives the read of the pack of a column in a second print (`#packed`, `#packedSteps`), or undefined. The
2865
+ * column must be a column of the run, or a column of the function that the printer prints. The read must be at a
2866
+ * focus of the print. The read holds the value of the column or the sentinel, as a read of the column does.
2867
+ */
2868
+ #packRead(name: string | undefined, ctx: Ctx): Code | undefined {
2869
+ const pack = this.#pack;
2870
+ if (pack === undefined || name === undefined || !this.#packAt(ctx)) return undefined;
2871
+ const own = this.#callColumns.get(name);
2872
+ if (!this.#runColumns.has(name) && (!pack.calls || own?.scope !== this.#scopes.at(-1))) return undefined;
2873
+ let local = pack.cols.get(name);
2874
+ if (local === undefined) {
2875
+ local = this.fresh("pk");
2876
+ pack.cols.set(name, local);
2877
+ }
2878
+ const held = `${local}[${ctx.focus as string}]`;
2879
+ // A column of a call can read a parameter, the focus and the origin of the function, so its read keeps these markers (V-081).
2880
+ const deps = new Set([ctx.level, ...(own?.deps ?? [])]);
2881
+ return bare({ code: `${this.use("G")}(${held})`, kind: own === undefined ? this.#runColumns.get(name) : own.kind, safe: false, held, deps });
2882
+ }
2883
+
1674
2884
  /** This method gives the read of a column of the run. Two parts with the same structure share one column. */
1675
2885
  #column(e: Expr, c: Code, ctx: Ctx): Code {
1676
2886
  const key = this.#constKey(e, ctx);
1677
2887
  let name = this.#columns.get(key);
1678
2888
  if (name === undefined) {
2889
+ // The first print of a fast sum makes each column of its term, so the second print makes none (`#packed`).
2890
+ if (this.#pack !== undefined) throw new NoPack();
1679
2891
  name = this.fresh("col");
1680
2892
  // A column of a call is at the start of the body of its function, so each call has its own.
1681
2893
  const scope = this.#callScope(c, ctx);
1682
2894
  (scope?.decls ?? this.run).push(`const ${name} = ${this.use("Q")}((${ctx.focus as string}) => {`, ...ind(c.s), ` return ${c.v.code};`, "});");
2895
+ if (c.v.list === undefined) {
2896
+ if (scope === undefined) this.#runColumns.set(name, c.v.kind);
2897
+ else this.#callColumns.set(name, { scope, kind: c.v.kind, deps: new Set([...c.v.deps].filter((d) => d !== ctx.level)) });
2898
+ }
1683
2899
  this.#columns.set(key, name);
1684
2900
  }
1685
2901
  this.#columned.add(e);
1686
- 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 });
2902
+ // Each key of the column reads the array of the column again.
2903
+ this.#shared.add(e);
2904
+ return this.#packRead(name, ctx) ?? bare({ code: `${this.use("G")}(${name}(${ctx.focus as string}))`, kind: c.v.kind, safe: false, deps: c.v.deps, list: heldList(c.v.list) });
1687
2905
  }
1688
2906
 
1689
2907
  #node(e: Expr, ctx: Ctx): Code {
1690
2908
  switch (e.tag) {
1691
2909
  case "lit":
1692
- return isVexList(e.value) ? this.#listLiteral(e.value) : bare(literal(e.value));
2910
+ return isVexList(e.value) ? this.#listLiteral(e.value) : bare(this.#literal(e.value));
1693
2911
  case "ref":
1694
2912
  return this.#ref(e, ctx);
1695
2913
  case "var":
@@ -1723,6 +2941,13 @@ class Printer {
1723
2941
  return this.#fold(e, ctx);
1724
2942
  case "iterate":
1725
2943
  return this.#iterate(e, ctx);
2944
+ case "fix":
2945
+ return this.#fix(e, ctx);
2946
+ case "last": {
2947
+ // The check of the program comes before the printer, so each read has its column (FIX.MONOTONE).
2948
+ const { code, kind } = ctx.columns.get(e.name) as FixColumn;
2949
+ return bare({ code: `${code}[${ctx.focus as string}]`, kind, safe: true, deps: new Set([ctx.level, ROUNDS]) });
2950
+ }
1726
2951
  case "ext":
1727
2952
  return this.#cell(e, ctx);
1728
2953
  }
@@ -1763,9 +2988,9 @@ class Printer {
1763
2988
  *
1764
2989
  * The statements of the parts come before the code of their values. The last part that reads a cell keeps its place
1765
2990
  * only if no statement after it can throw. Also, with `all`, a value before it must not throw, or the code of its value
1766
- * must read no cell.
2991
+ * must read no cell. With `held`, code before the parts can throw, so the last part also goes into a variable.
1767
2992
  */
1768
- #inOrder(parts: readonly Code[], all: boolean): readonly Code[] {
2993
+ #inOrder(parts: readonly Code[], all: boolean, held = false): readonly Code[] {
1769
2994
  // A read of a finished cell starts no search, so the order of the reads does not change a result.
1770
2995
  if (this.#sheet?.direct === true) return parts;
1771
2996
  const last = parts.findLastIndex((x) => x.v.deps.has(CELLS));
@@ -1773,13 +2998,22 @@ class Printer {
1773
2998
  const before = !all || parts.slice(0, Math.max(last, 0)).every((x) => x.v.safe) || !READS_IN_CODE.test((parts[last] as Code).v.code);
1774
2999
  return parts.map((x, i) => {
1775
3000
  // A part after the last read of a cell cannot stop a read. A part that cannot throw and reads no cell cannot either.
1776
- if (i > last || (x.v.safe && !x.v.deps.has(CELLS)) || (i === last && after && before)) return x;
3001
+ if (i > last || (x.v.safe && !x.v.deps.has(CELLS)) || (i === last && after && before && !held)) return x;
1777
3002
  const b = this.fresh("b");
1778
3003
  if (all && !x.v.safe) return { s: this.#store(b, x), v: { ...x.v, code: `${this.use("G")}(${b})`, held: b, plain: false } };
1779
3004
  return { s: [...x.s, `const ${b} = ${x.v.code};`], v: { kind: x.v.kind, deps: x.v.deps, list: x.v.list, code: b, safe: true, plain: true } };
1780
3005
  });
1781
3006
  }
1782
3007
 
3008
+ /**
3009
+ * This method gives the parts of the expressions of an address. The interpreter evaluates each expression before the
3010
+ * first move, but the code of an address has each expression after the moves before it. A move can fail, so it must
3011
+ * not stop a read of a cell in a later expression (COMPILE.MODULE.SHEET).
3012
+ */
3013
+ #addressParts(at: readonly Move[], values: readonly Code[], deps: ReadonlySet<number>): readonly Code[] {
3014
+ return this.#inOrder(this.#settle(values, deps), false, at.findLastIndex((m) => moveExpr(m) !== undefined) > 0);
3015
+ }
3016
+
1783
3017
  /**
1784
3018
  * This method gives the code of the index of an address from the focus. `values` has the code of the value of each
1785
3019
  * computed move, in order (NAV.COMPUTED).
@@ -1806,7 +3040,30 @@ class Printer {
1806
3040
 
1807
3041
  /** This method gives the code of the index of a computed move, from the code of its value. */
1808
3042
  #computed(m: Move, value: Code): string {
1809
- return `${this.use(m.t === "key" ? "K" : "I")}(${value.v.code}, n)`;
3043
+ return (m.t === "key" ? this.#keyMove(value.v.code) : undefined) ?? `${this.use(m.t === "key" ? "K" : "I")}(${value.v.code}, n)`;
3044
+ }
3045
+
3046
+ /** This method gives the code of the position of a key of a move in a keyed print, and undefined in each other print. */
3047
+ #keyMove(key: string): string | undefined {
3048
+ this.#keys.read = true;
3049
+ if (!this.#keys.keyed) return undefined;
3050
+ this.runKeys = true;
3051
+ return `${this.use("KP")}(KM, ${key})`;
3052
+ }
3053
+
3054
+ /** This method gives a reason for an offset of an array space with keys. The keys of a record space have no order (NAV.OFFSET). */
3055
+ #noOffset(): void {
3056
+ if (this.#keys.keyed) throw new NotStandalone('an offset or the axis "window" in an array space with the option "keys"');
3057
+ }
3058
+
3059
+ /**
3060
+ * This method gives the key of the pair of an item at the target `j`. A keyed print puts the key of the record in the
3061
+ * pair, because `GT`, `WO` and `LO` read the pair as text (COMPILE.MODULE.KEYS). A target with text keys is that key.
3062
+ */
3063
+ #pairKey(j: string, texts: boolean): string {
3064
+ if (!this.#keys.keyed || texts) return j;
3065
+ this.runKeys = true;
3066
+ return `keys[${j}]`;
1810
3067
  }
1811
3068
 
1812
3069
  #move(m: Move, focus: string | undefined, origin: string | undefined): string {
@@ -1818,8 +3075,8 @@ class Printer {
1818
3075
  if (origin === undefined) throw new NotStandalone("a node of the memo reads its origin");
1819
3076
  return origin;
1820
3077
  case "key":
1821
- // A key of an array space is the text of its index.
1822
- return typeof m.key === "string" && /^(0|[1-9]\d*)$/.test(m.key) ? `(${m.key} < n ? ${m.key} : ${F}())` : `${F}()`;
3078
+ // A key of an array space is the text of its index, unless the run has its own keys.
3079
+ return this.#keyMove(JSON.stringify(m.key)) ?? (typeof m.key === "string" && /^(0|[1-9]\d*)$/.test(m.key) ? `(${m.key} < n ? ${m.key} : ${F}())` : `${F}()`);
1823
3080
  case "index":
1824
3081
  return typeof m.i === "number" && Number.isInteger(m.i) && m.i >= 0 ? `(${m.i} < n ? ${m.i} : ${F}())` : `${F}()`;
1825
3082
  case "offset": {
@@ -1831,6 +3088,7 @@ class Printer {
1831
3088
  if (this.#graph || d === undefined || more.length > 0 || !Number.isInteger(d)) return `${F}()`;
1832
3089
  // In a tree space, an offset goes among the siblings (NAV.OFFSET.TREE).
1833
3090
  if (this.#tree) return `${this.use("SO")}(${this.#part("siblings", "GP")}, SI, ${focus}, ${d})`;
3091
+ this.#noOffset();
1834
3092
  return `${this.use("X")}(${focus} + ${d}, n)`;
1835
3093
  }
1836
3094
  case "other":
@@ -1860,7 +3118,7 @@ class Printer {
1860
3118
  const values = this.#addressValues(at, ctx);
1861
3119
  const deps = this.#addressDeps(at, ctx, values);
1862
3120
  // The interpreter evaluates the expressions of the address before its moves, and the first error stops them.
1863
- const parts = this.#inOrder(this.#settle(values, deps), false);
3121
+ const parts = this.#addressParts(at, values, deps);
1864
3122
  const address = this.#address(at, ctx, parts);
1865
3123
  if (typeof kind === "object") return { s: stmtsOf(...parts), v: { code: `${input as string}[${address}]`, kind: undefined, safe, deps, list: listOfKind(kind, true) } };
1866
3124
  return { s: stmtsOf(...parts), v: { code: `R[${address}][${JSON.stringify(field)}]`, kind, safe, deps } };
@@ -1914,7 +3172,8 @@ class Printer {
1914
3172
  code = `v${this.vars.size}`;
1915
3173
  this.vars.set(name, code);
1916
3174
  }
1917
- return plainValue(code, kind);
3175
+ // The check of the run keeps the array of a list of the variables (COMPILE.MODULE.LIST.VAR).
3176
+ return typeof kind === "object" ? { ...plainValue(code, undefined), list: listOfKind(kind, true) } : plainValue(code, kind);
1918
3177
  }
1919
3178
 
1920
3179
  /**
@@ -1956,6 +3215,13 @@ class Printer {
1956
3215
  // The statements of the binding read its keys, so the let is not a constant of the run.
1957
3216
  deps = new Set([...deps, ...c.v.deps]);
1958
3217
  }
3218
+ // The body of a relay appends to the list of the bound name, into the array of the owner (COMPILE.MODULE.FUSE.ADOPT).
3219
+ // The binding of the relay is not a function, so the let binds its name.
3220
+ const relay = this.#relays.get(e);
3221
+ if (relay !== undefined) {
3222
+ const owner: Owner = { name: relay.bind, read: env.get(relay.bind) as Name, w: relay.owner.w, adopt: relay.owner.adopt, sure: relay.owner.sure };
3223
+ for (const node of relay.nodes) this.#own.set(node, owner);
3224
+ }
1959
3225
  // A list op over a let is the list op over its body, in the scope of its bindings (`#app`).
1960
3226
  const inner = wrap === undefined ? e.body : wrap(e.body);
1961
3227
  // A let at a place that takes a list gives its body there (LIST.VALUE).
@@ -1974,6 +3240,8 @@ class Printer {
1974
3240
  const bound = ctx.env.has(e.fn) ? undefined : ctx.fns.get(e.fn);
1975
3241
  if (bound === undefined) throw new NotStandalone(`a call of "${e.fn}", which is not a function`);
1976
3242
  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)}`);
3243
+ // The second print of a fast sum puts the body of a function at the place of its call (`#inline`).
3244
+ if (this.#packAt(ctx)) return this.#inline(bound, e, ctx);
1977
3245
  const s: string[] = [];
1978
3246
  const args = e.args.map((x): Arg => {
1979
3247
  // An argument can be a list, as a binding of a let can (COMPILE.MODULE.LIST.ARG).
@@ -1992,15 +3260,60 @@ class Printer {
1992
3260
  return { code: b, kind, deps, list };
1993
3261
  });
1994
3262
  // Each parameter can hold the error of its argument, so one function serves the arguments of one kind. The facts of
1995
- // a list are a part of its kind.
1996
- const sig = JSON.stringify(args.map((a) => (a.list === undefined ? (a.kind ?? null) : { list: a.list })));
1997
- const spec = bound.specs.get(sig) ?? this.#printFn(bound, args, sig);
3263
+ // a list are a part of its kind. With fuse, the fact clean of each list is a part too (COMPILE.MODULE.FUSE.CLEAN).
3264
+ // The function of a list that is not clean also serves a clean list, so a call takes it if it exists.
3265
+ const sig = this.#signature(args, this.#fuse);
3266
+ const spec = bound.specs.get(sig) ?? bound.specs.get(this.#signature(args, false)) ?? this.#unpacked(() => this.#printFn(bound, args, sig));
1998
3267
  // Each marker becomes the levels at the call. The levels of the arguments count for each call, because their
1999
3268
  // statements read their keys, so the marker of the parameters gives no level.
2000
3269
  const levels = (d: number): readonly number[] => (d === spec.origin ? [ctx.originLevel] : d === spec.focus ? [ctx.level] : d === spec.param ? [] : [d]);
2001
3270
  const deps = new Set([...args.flatMap((a) => [...a.deps]), ...[...spec.deps].flatMap(levels)]);
2002
- const position = spec.deps.has(spec.origin) ? [ctx.focus, ctx.origin] : spec.deps.has(spec.focus) ? [ctx.focus] : [];
2003
- return { s, v: { code: `${spec.name}(${[...args.map((a) => a.code), ...position].join(", ")})`, kind: spec.kind, safe: spec.safe, deps, list: spec.list } };
3271
+ const position = [...(spec.deps.has(spec.focus) ? [ctx.focus] : []), ...(spec.deps.has(spec.origin) ? [ctx.origin] : [])];
3272
+ return { s, v: { code: `${spec.name}(${[...args.map((a) => a.code), ...position].join(", ")})`, kind: spec.kind, safe: spec.safe, deps, list: heldList(spec.list) } };
3273
+ }
3274
+
3275
+ /**
3276
+ * This method prints a call in the second print of a fast sum (`#packed`). The body of the function is at the place
3277
+ * of the call, as the body of a let. Each argument evaluates at the place of the call. The body sees the names of the
3278
+ * place of its binding (FN.CALL). Thus a read of a column in the body reads the pack of the column.
3279
+ */
3280
+ #inline(bound: BoundFn, e: ExprOf<"call">, ctx: Ctx): Code {
3281
+ // A function at the place of its binding reads names of that place, so its body stays in its function.
3282
+ if (bound.local || ++(this.#pack as Pack).inlines > INLINES) throw new NoPack();
3283
+ const s: string[] = [];
3284
+ const deps: number[] = [];
3285
+ const env = new Map(bound.ctx.env);
3286
+ bound.fn.params.forEach((p, i) => {
3287
+ const x = e.args[i] as Expr;
3288
+ this.#wantList.add(x);
3289
+ const c = this.#hoist(this.expr(x, ctx), hasLoop(x));
3290
+ if (c.v.list !== undefined) throw new NoPack();
3291
+ deps.push(...c.v.deps);
3292
+ // A short safe value is the read itself. A read of a name that can hold the error reads that name.
3293
+ let code = c.v.code;
3294
+ if (!c.v.safe && c.s.length === 0 && c.v.held !== undefined) code = c.v.held;
3295
+ else if (!c.v.safe || c.s.length > 0 || !/^[\w$.]+$/.test(code)) {
3296
+ code = this.fresh("b");
3297
+ s.push(...this.#store(code, c));
3298
+ }
3299
+ env.set(p, { code, kind: c.v.kind, lazy: !c.v.safe, deps: c.v.deps, list: undefined });
3300
+ });
3301
+ this.#wantList.add(bound.fn.body);
3302
+ const body = this.expr(bound.fn.body, { ...ctx, env, fns: bound.ctx.fns, keys: new Map() });
3303
+ if (body.v.list !== undefined) throw new NoPack();
3304
+ // The statements of an argument read their keys, also when the body does not read the parameter (V-081).
3305
+ return { s: [...s, ...body.s], v: { ...body.v, deps: new Set([...deps, ...body.v.deps]) } };
3306
+ }
3307
+
3308
+ /** This method runs `f` outside the second print of a fast sum: a function and a node of the memo print as before. */
3309
+ #unpacked<T>(f: () => T): T {
3310
+ const pack = this.#pack;
3311
+ this.#pack = undefined;
3312
+ try {
3313
+ return f();
3314
+ } finally {
3315
+ this.#pack = pack;
3316
+ }
2004
3317
  }
2005
3318
 
2006
3319
  /**
@@ -2020,30 +3333,47 @@ class Printer {
2020
3333
  const o = this.fresh("o");
2021
3334
  const env = new Map(bound.ctx.env);
2022
3335
  // A parameter hides a function of its name, because a read looks at the values first.
2023
- 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]), list: (args[i] as Arg).list }));
3336
+ 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]), list: this.#paramList((args[i] as Arg).list, this.#fuse) }));
2024
3337
  const scope: CallScope = { param, focus, repeats: nestsLoops(bound.fn.body), names: new Set(names), decls: [], root: bound.fn.body };
2025
3338
  this.#scopes.push(scope);
2026
3339
  // The value of a call can be a list, as the value of a let can (COMPILE.MODULE.LIST.CALL). The call is at a place
2027
3340
  // that takes a list, or it gives the reason.
2028
3341
  this.#wantList.add(bound.fn.body);
2029
- const body = this.expr(bound.fn.body, { origin: o, focus: k, level: focus, originLevel: origin, env, fns: bound.ctx.fns, keys: new Map() });
3342
+ const body = this.expr(bound.fn.body, { origin: o, focus: k, level: focus, originLevel: origin, env, fns: bound.ctx.fns, keys: new Map(), columns: new Map() });
2030
3343
  this.#scopes.pop();
2031
3344
  const markers = new Set([origin, focus, param]);
2032
3345
  const global = [...body.v.deps].every((d) => markers.has(d));
2033
3346
  const name = this.fresh("fn");
2034
3347
  if (hasLoop(bound.fn.body) || this.#defers(body)) this.#deferred.add(name);
2035
- const position = body.v.deps.has(origin) ? [k, o] : body.v.deps.has(focus) ? [k] : [];
3348
+ // A parameter is here only if the body reads it, so the text of a call reads only the levels of its deps (V-085).
3349
+ const position = [...(body.v.deps.has(focus) ? [k] : []), ...(body.v.deps.has(origin) ? [o] : [])];
2036
3350
  const head = `const ${name} = (${[...names, ...position].join(", ")}) =>`;
2037
3351
  // The columns of the call come first. Each one reads a binding of the root only after the binding has its value.
2038
3352
  const s = [...scope.decls, ...body.s];
2039
3353
  const decl = s.length === 0 ? [`${head} ${body.v.code};`] : [`${head} {`, ...ind(s), ` return ${body.v.code};`, "};"];
2040
3354
  (global ? this.run : bound.decls).push(...decl);
3355
+ this.#specCode.set(name, decl.join("\n"));
2041
3356
  if (!global) bound.local = true;
2042
3357
  const spec: Spec = { name, kind: body.v.kind, list: body.v.list, safe: body.v.safe, deps: body.v.deps, origin, focus, param, global };
2043
3358
  bound.specs.set(sig, spec);
2044
3359
  return spec;
2045
3360
  }
2046
3361
 
3362
+ /**
3363
+ * This method gives the facts of the list of a parameter. Only the fact clean of the list itself stays, and only with
3364
+ * `clean`. The fact clean of the items of a list of lists makes more functions, so it does not stay. `fresh` does not
3365
+ * hold for a parameter, because the caller holds its argument.
3366
+ */
3367
+ #paramList(l: ListInfo | undefined, clean: boolean): ListInfo | undefined {
3368
+ const plain = plainList(l);
3369
+ return plain !== undefined && clean && l?.clean === true ? { ...plain, clean: true } : plain;
3370
+ }
3371
+
3372
+ /** This method gives the signature of the arguments of a call: the kind of each one, with the facts of each list. */
3373
+ #signature(args: readonly Arg[], clean: boolean): string {
3374
+ return JSON.stringify(args.map((a) => (a.list === undefined ? (a.kind ?? null) : { list: this.#paramList(a.list, clean) })));
3375
+ }
3376
+
2047
3377
  #boolean(v: Value): string {
2048
3378
  return v.kind === "boolean" ? v.code : `${this.use("B")}(${v.code})`;
2049
3379
  }
@@ -2066,9 +3396,20 @@ class Printer {
2066
3396
  if (FOLD_OPS.has(op) && head?.tag === "each" && !this.#bodyList(head, ctx)) return this.#list(op, head, rest, ctx);
2067
3397
  // A list op over a let with only literal options is the list op over the body of the let, so an each in the body
2068
3398
  // is one loop with a running value, not an array. A builder sheet prints such a let, for example `sum(let($0 = 0, each(…)))`.
2069
- if (FOLD_OPS.has(op) && head?.tag === "let" && rest.every((x) => x.tag === "lit")) return this.#let(head, ctx, (body) => app(op, body, ...rest));
3399
+ if (FOLD_OPS.has(op) && head?.tag === "let" && rest.every((x) => x.tag === "lit")) {
3400
+ // The list op over the body is a new node, and an item of a list can be a list. `expr` still examines the place of this op.
3401
+ this.#wantList.add(head);
3402
+ return this.#let(head, ctx, (body) => app(op, body, ...rest));
3403
+ }
2070
3404
  // sortBy and take are list ops for each receiver. Each other list op needs a list, and a domain can have its name.
2071
3405
  if (head !== undefined && (op === "sortBy" || op === "take" || (op === "drop" && this.#isList(head, ctx)))) return this.#order(op, head, rest, ctx);
3406
+ if (head !== undefined && op === "setNth" && this.#isList(head, ctx)) return this.#setNth(head, rest, ctx);
3407
+ // With fuse, flat over an each is one loop with one output (COMPILE.MODULE.FUSE).
3408
+ const strict = op === "flat" && head?.tag === "each" ? this.#fusedStrict(head, rest, ctx) : undefined;
3409
+ if (strict !== undefined) return this.#flatEach(head as ExprOf<"each">, strict, ctx, this.#keepOwner(e));
3410
+ // With fuse, a chain of append with a part that pushes its items is one output (COMPILE.MODULE.FUSE).
3411
+ const joined = op === "append" ? this.#appendStrict(e, ctx) : undefined;
3412
+ if (joined !== undefined && args.slice(0, 2).some((x) => this.#pushes(x, ctx))) return this.#appendChain(e, joined, ctx);
2072
3413
  if (head !== undefined && BUILD_OPS.has(op) && this.#isList(head, ctx)) return this.#build(op, head, rest, ctx, this.#own.get(e));
2073
3414
  if (head !== undefined && (FOLD_OPS.has(op) || op === "nth") && this.#isList(head, ctx)) return this.#overList(op, head, rest, ctx);
2074
3415
  // An argument can be a list (COMPILE.MODULE.LIST.ARG).
@@ -2077,7 +3418,7 @@ class Printer {
2077
3418
  const deps = depsOf(...raw);
2078
3419
  // The interpreter evaluates each argument, also after an error.
2079
3420
  const values = this.#inOrder(this.#settle(raw, deps, args), true);
2080
- if (op === "fill" && this.#facts.own(op)) return this.#fill(values, deps);
3421
+ if (op === "fill" && this.#facts.own(op)) return this.#fill(e, values, deps);
2081
3422
  return this.#opCall(op, values, deps);
2082
3423
  }
2083
3424
 
@@ -2086,10 +3427,77 @@ class Printer {
2086
3427
  * gets each value, so an error of an argument after the value is the error of the op. The keys are not the positions
2087
3428
  * of records, so the axis `list` over the list cannot read a record at its keys.
2088
3429
  */
2089
- #fill(values: readonly Code[], deps: ReadonlySet<number>): Code {
3430
+ #fill(e: ExprOf<"app">, values: readonly Code[], deps: ReadonlySet<number>): Code {
2090
3431
  const value = values[1]?.v;
2091
- const list: ListInfo = { item: value?.kind, inner: value?.list, texts: true };
2092
- return { s: stmtsOf(...values), v: { code: `${this.use("FI")}(${values.map((x) => x.v.code).join(", ")})`, kind: undefined, safe: false, deps, list } };
3432
+ // FI gives a new array of checked values, so the list is clean and fresh.
3433
+ const list: ListInfo = { item: value?.kind, inner: heldList(value?.list), texts: true, clean: true, fresh: true };
3434
+ if (this.#fillsNothing(e, values[1])) {
3435
+ // The helper stays in the names of the module, so the option `name` has the same refusal. The last pass removes it.
3436
+ this.use("FI");
3437
+ return { s: [], v: { code: "[]", kind: undefined, safe: true, deps, list } };
3438
+ }
3439
+ // The one item of an append of an owner has the key 0, as FI gives it (COMPILE.MODULE.FUSE.ADOPT). The append uses FI
3440
+ // only when it does not push the item.
3441
+ const one = this.#ones.has(e) && values.length === 2 && isOne(e.args[0]);
3442
+ const v: Value = { code: `${one ? "FI" : this.use("FI")}(${values.map((x) => x.v.code).join(", ")})`, kind: undefined, safe: false, deps, list };
3443
+ if (one) this.#ones.set(e, { v, item: `[0, ${(value as Value).code}]` });
3444
+ return { s: stmtsOf(...values), v };
3445
+ }
3446
+
3447
+ /**
3448
+ * This method tells if `fill` gives no items and cannot fail, so `[]` is its code (COMPILE.MODULE.SIZE.FILL). The count
3449
+ * must be the literal 0. The code of the value cannot throw, or the value reads nothing of a run and the interpreter
3450
+ * gives the empty list. A value that fails keeps FI, so the list keeps its error. The option `fuse` must be true.
3451
+ */
3452
+ #fillsNothing(e: ExprOf<"app">, value: Code | undefined): boolean {
3453
+ const [count, x] = e.args;
3454
+ if (!this.#fuse || value === undefined || x === undefined || e.args.length !== 2 || count?.tag !== "lit" || count.value !== 0) return false;
3455
+ if (value.s.length === 0 && value.v.safe) return true;
3456
+ if (!isClosed(x)) return false;
3457
+ const r = evaluate(e, { space: ONE_RECORD, origin: "0", domains: this.#domains });
3458
+ return r.ok && isVexList(r.value) && r.value.items.length === 0;
3459
+ }
3460
+
3461
+ /**
3462
+ * This method gives the range of a list that a loop or `count` reads, or undefined (COMPILE.MODULE.FILL.RANGE). The
3463
+ * list is `fill(n, v)` or `take(range, k)`, with no other argument. The option `fuse` must be true, and no domain can
3464
+ * have the op `fill`. Each other list keeps its array. So does a key of a node of the memo, which has a name.
3465
+ */
3466
+ #range(e: Expr, ctx: Ctx): Range | undefined {
3467
+ if (!this.#fuse || e.tag !== "app" || e.args.length !== 2 || !this.#facts.own("fill") || ctx.keys.has(e)) return undefined;
3468
+ const [head, second] = e.args as readonly [Expr, Expr];
3469
+ if (e.op === "take") {
3470
+ const range = this.#range(head, ctx);
3471
+ if (range === undefined) return undefined;
3472
+ // TK checks its count after its list, so an error of the range comes first. A count that is a constant of the run
3473
+ // evaluates once, as in TK.
3474
+ const [n, k] = this.#inOrder([{ s: [], v: range.count }, this.#hoist(this.expr(second, ctx), hasLoop(second))], true) as readonly [Code, Code];
3475
+ const count: Value = { code: `${this.use("TN")}(${n.v.code}, ${k.v.code})`, kind: "number", safe: false, deps: depsOf(n, k) };
3476
+ return { s: [...range.s, ...stmtsOf(n, k)], count, item: range.item, info: range.info };
3477
+ }
3478
+ const size = literalOf(head);
3479
+ // The empty fill has its own code (COMPILE.MODULE.SIZE.FILL).
3480
+ if (e.op !== "fill" || size === 0) return undefined;
3481
+ for (const x of e.args) this.#wantList.add(x);
3482
+ // The interpreter evaluates each argument, also after an error, as for FI. A loop at each key reads the range again,
3483
+ // so each argument that is a constant of the run evaluates once, before the loop over the keys.
3484
+ const raw = e.args.map((x) => this.#hoist(this.expr(x, ctx), hasLoop(x)));
3485
+ const deps = depsOf(...raw);
3486
+ const [n, v] = this.#inOrder(raw, true) as readonly [Code, Code];
3487
+ const s = stmtsOf(n, v);
3488
+ const info: ListInfo = { item: v.v.kind, inner: heldList(v.v.list), texts: true, clean: true, fresh: false };
3489
+ // Each item reads the value. Thus a value that is not a literal evaluates once, before the loop.
3490
+ const plain = PLAIN_LITERALS.has(typeof literalOf(second));
3491
+ const item = plain ? v.v.code : this.fresh("b");
3492
+ // A literal count that FI takes needs no check, when the value cannot fail.
3493
+ if (Number.isSafeInteger(size) && (size as number) >= 1 && (size as number) <= 100000 && v.v.safe) {
3494
+ if (!plain) s.push(`const ${item} = ${v.v.code};`);
3495
+ return { s, count: { code: String(size), kind: "number", safe: true, deps, plain: true }, item, info };
3496
+ }
3497
+ // The count evaluates before the value, as in FI.
3498
+ const number = plain ? n.v.code : this.fresh("b");
3499
+ if (!plain) s.push(`const ${number} = ${n.v.code};`, `const ${item} = ${v.v.code};`);
3500
+ return { s, count: { code: `${this.use("FN")}(${number}, ${item})`, kind: "number", safe: false, deps }, item, info };
2093
3501
  }
2094
3502
 
2095
3503
  /**
@@ -2097,7 +3505,7 @@ class Printer {
2097
3505
  * (COMPILE.MODULE.LIST.ARG, COMPILE.MODULE.LIST.FIELD). An error item has the error `VEX_ERROR`.
2098
3506
  */
2099
3507
  #plain(v: Value): string {
2100
- return v.list === undefined ? v.code : `${this.use("LV")}(${v.code}, ${String(depthOf(v.list))})`;
3508
+ return v.list === undefined ? v.code : this.envelope(v, "LV");
2101
3509
  }
2102
3510
 
2103
3511
  /** This method gives the samples of a list of the facts `l`: no items, items with values, and an error item. */
@@ -2108,16 +3516,30 @@ class Printer {
2108
3516
  return [vexList([]), vexList(items), vexList([{ key: "0", result: { ok: false, error: { vexError: true } as never } }])];
2109
3517
  }
2110
3518
 
3519
+ /**
3520
+ * This method gives the code of a number that an op lifts: the call of a copy of `fromScalar` of the domain (KIND.LIFT).
3521
+ * The op checks its result, as in the interpreter, so a lift that gives a value that is not valid needs no check here.
3522
+ */
3523
+ #lifted(x: Code, domain: number, d: AnyDomain): Code {
3524
+ const name = `lift_${domain}`;
3525
+ this.#copy(name, copied(d.fromScalar as (...a: never[]) => unknown, [SAMPLES.number], `the lift of the domain ${d.name}`));
3526
+ return { s: x.s, v: { ...x.v, code: `${name}(${x.v.code})`, kind: kindOfDomain(d), safe: false, plain: false } };
3527
+ }
3528
+
2111
3529
  /** This method prints the call of the op of a domain on some values, from the static site of their kinds. */
2112
- #opCall(op: string, values: readonly Code[], deps: ReadonlySet<number>): Code {
2113
- const lists = new Set(values.flatMap((x, i) => (x.v.list === undefined ? [] : [i])));
3530
+ #opCall(op: string, given: readonly Code[], deps: ReadonlySet<number>): Code {
3531
+ const lists = new Set(given.flatMap((x, i) => (x.v.list === undefined ? [] : [i])));
2114
3532
  // A list op of the interpreter that a module does not have, and an op of a domain, cannot take a list as the receiver.
2115
3533
  if (lists.has(0)) throw new NotStandalone(isListOp(op) ? `the list op "${op}"` : `a list as the receiver of the op "${op}"`);
2116
- const site = this.#facts.staticSite(op, values.map((x) => x.v.kind), lists);
3534
+ const site = this.#facts.staticSite(op, given.map((x) => x.v.kind), lists, true);
2117
3535
  if (site?.t !== "fn") throw new NotStandalone(`the kinds of the values of "${op}" do not decide its op`);
2118
- if (site.bad) return { s: stmtsOf(...values), v: { code: `${this.use("F")}()`, kind: site.returns, safe: false, deps } };
2119
- if (site.returns === undefined) throw new NotStandalone(`the op "${op}" does not declare the kind of its result`);
3536
+ // LI gives a new array, and its keys are texts (COMPILE.MODULE.LIST.OP).
3537
+ const list: ListInfo | undefined = site.item === undefined ? undefined : { item: site.item, texts: true, fresh: true };
3538
+ if (site.bad) return { s: stmtsOf(...given), v: { code: `${this.use("F")}()`, kind: site.returns, safe: false, deps, list } };
3539
+ if (site.returns === undefined && list === undefined) throw new NotStandalone(`the op "${op}" does not declare the kind of its result`);
2120
3540
  const d = this.#domains[site.domain] as AnyDomain;
3541
+ const lifted = site.lifted ?? [];
3542
+ const values = given.map((x, i) => (lifted.includes(i - 1) ? this.#lifted(x, site.domain, d) : x));
2121
3543
  const name = `op_${site.domain}_${this.#opIndex(op)}`;
2122
3544
  // Stryker disable next-line ConditionalExpression: the form of an op is always the same, so the map only saves time
2123
3545
  if (!this.#forms.has(name)) {
@@ -2128,20 +3550,30 @@ class Printer {
2128
3550
  const src = copied(fn, each, `the op "${op}" of the domain ${d.name}`);
2129
3551
  // An inline form cannot throw for primitive values only.
2130
3552
  this.#forms.set(name, lists.size === 0 && kinds.every((k) => primitiveOf(k) !== undefined) ? inlineForm(src) : undefined);
2131
- this.top.set(name, `const ${name} = ${src};`);
3553
+ if (site.returns !== undefined && !givesValue(src) && this.#missesNoValue(site.returns)) this.#unproved.add(name);
3554
+ this.#copy(name, src);
3555
+ }
3556
+ // The result is a `vex.list`. Its array of pairs comes from the helper of a list of the input, so a result that is not
3557
+ // a list of the declared kind is an error (COMPILE.MODULE.LIST.OP).
3558
+ if (list !== undefined) {
3559
+ this.#called.add(name);
3560
+ this.opList = true;
3561
+ const read = `${this.use("LI")}(${name}(${values.map((x) => this.#plain(x.v)).join(", ")}), 0, ${this.test(list.item as Kind)})`;
3562
+ return { s: stmtsOf(...values), v: { code: `(${read} ?? ${this.use("F")}())`, kind: undefined, safe: false, deps, list } };
2132
3563
  }
2133
3564
  const form = this.#forms.get(name);
2134
3565
  // An inline form takes each argument once, or a plain argument more often, so each argument evaluates once.
2135
3566
  const inline = form !== undefined && lists.size === 0 && 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));
2136
3567
  if (inline) {
2137
3568
  const text = form.parts.map((x) => (typeof x === "number" ? `(${(values[x] as Code).v.code})` : x)).join("");
2138
- const checked = this.check(site.returns);
2139
- const code = checked === undefined ? `(${text})` : `${checked}(${text})`;
2140
- return { s: stmtsOf(...values), v: { code, kind: site.returns, safe: checked === undefined && values.every((x) => x.v.safe), deps } };
3569
+ const checked = this.check(site.returns as Kind);
3570
+ const value = this.#value(name, text);
3571
+ const code = checked === undefined ? `(${value})` : `${checked}(${value})`;
3572
+ return { s: stmtsOf(...values), v: { code, kind: site.returns, safe: checked === undefined && value === text && values.every((x) => x.v.safe), deps } };
2141
3573
  }
2142
3574
  this.#called.add(name);
2143
3575
  // An exception of the op is an error of Vex: the boundary around the op catches it.
2144
- const code = this.#checked(site.returns, `${name}(${values.map((x) => this.#plain(x.v)).join(", ")})`);
3576
+ const code = this.#checked(site.returns as Kind, this.#value(name, `${name}(${values.map((x) => this.#plain(x.v)).join(", ")})`));
2145
3577
  return { s: stmtsOf(...values), v: { code, kind: site.returns, safe: false, deps } };
2146
3578
  }
2147
3579
 
@@ -2226,6 +3658,62 @@ class Printer {
2226
3658
  * A list op over an axis: one `for` loop with a running value. An item with an error is skipped, and with `strict` it
2227
3659
  * is an error of the list op. A value of the wrong kind is an error of the list op, as in the interpreter.
2228
3660
  */
3661
+ /**
3662
+ * This method prints a fixed point (COMPILE.FIX.MODULE). The column is an array with the value of each position. The
3663
+ * rows of `init` give its first values, and each round makes the array of the next values. A round without a change
3664
+ * ends the loop with the old array (FIX.ROUNDS). The last round that still changes a row throws (FIX.LIMIT). Each
3665
+ * error of a module is one sentinel, so the first row that fails can stop the column. A column that reads no key is
3666
+ * a constant of the run. It evaluates on its first read, as a branch of the interpreter does.
3667
+ */
3668
+ #fix(e: ExprOf<"fix">, ctx: Ctx): Code {
3669
+ const kind = joinKind(e.join);
3670
+ const old = this.fresh("fx");
3671
+ const next = this.fresh("fx");
3672
+ const changed = this.fresh("ch");
3673
+ const round = this.fresh("k");
3674
+ const first = this.#rows(e, e.init, ctx, (x, j) => [`${old}[${j}] = ${x};`]);
3675
+ const step = this.#rows(e, e.step, { ...ctx, columns: new Map([...ctx.columns, [e.name, { code: old, kind }]]) }, (x, j) => {
3676
+ const y = this.fresh("y");
3677
+ const read = `${old}[${j}]`;
3678
+ const joined = e.join === "or" ? `${read} || ${x}` : e.join === "and" ? `${read} && ${x}` : `Math.${e.join}(${read}, ${x})`;
3679
+ return [`const ${y} = ${joined};`, `if (${y} !== ${read}) ${changed} = true;`, `${next}[${j}] = ${y};`];
3680
+ });
3681
+ const s = [
3682
+ `let ${old} = [];`,
3683
+ ...first.s,
3684
+ `for (let ${round} = 0; ; ${round}++) {`,
3685
+ ` if (${round} === Math.min(n + 1, ${MAX_ITERATIONS})) ${this.use("F")}();`,
3686
+ ` const ${next} = [];`,
3687
+ ` let ${changed} = false;`,
3688
+ ...ind(step.s),
3689
+ ` if (!${changed}) break;`,
3690
+ ` ${old} = ${next};`,
3691
+ "}",
3692
+ ];
3693
+ const held = this.#hoist({ s, v: { code: old, kind: undefined, safe: false, deps: new Set([...first.deps, ...step.deps]) } }, true);
3694
+ return { s: held.s, v: { code: `${held.v.code}[${ctx.focus as string}]`, kind, safe: false, deps: new Set([...held.v.deps, ctx.level]) } };
3695
+ }
3696
+
3697
+ /**
3698
+ * This method prints the loop over the rows of a column: the evaluation of `x` and the check of its kind (FIX.KIND).
3699
+ * `store` gives the statements of a good value. A search of a sheet must see each read of a cell, so a row that reads
3700
+ * a cell does not stop the loop (FIX.ERROR). A flag holds the failure until the end of the loop.
3701
+ */
3702
+ #rows(e: ExprOf<"fix">, x: Expr, ctx: Ctx, store: (value: string, row: string) => readonly string[]): { readonly s: readonly string[]; readonly deps: ReadonlySet<number> } {
3703
+ const { j, head, inner } = this.#targetLoop({ t: "all" }, [], ctx);
3704
+ // A list has the wrong kind for a column, and the check of the row gives the failure (FIX.KIND).
3705
+ this.#wantList.add(x);
3706
+ const c = this.#hoist(this.expr(x, inner), hasLoop(x));
3707
+ const v = this.fresh("x");
3708
+ const F = this.use("F");
3709
+ const boolean = joinKind(e.join) === "boolean";
3710
+ const row = [...c.s, `const ${v} = ${boolean ? this.#boolean(c.v) : c.v.code};`, ...(boolean ? [] : [`if (!Number.isFinite(${v})) ${F}();`]), ...store(v, j)];
3711
+ const deps = new Set([...c.v.deps].filter((d) => d !== inner.level && d !== ROUNDS));
3712
+ if (!c.v.deps.has(CELLS)) return { s: [head, ...ind(row), "}"], deps };
3713
+ const failed = this.fresh("f");
3714
+ return { s: [`let ${failed} = false;`, head, ...ind(["try {", ...ind(row), "} catch {", ` ${failed} = true;`, "}"]), "}", `if (${failed}) ${F}();`], deps };
3715
+ }
3716
+
2229
3717
  /**
2230
3718
  * This method gives the loop over the targets of an axis: the statements before it, its bounds and the key that it
2231
3719
  * skips. `start` has the levels of the address, and `inner` is the position at a target. The axes all, others,
@@ -2237,6 +3725,8 @@ class Printer {
2237
3725
  readonly j: string;
2238
3726
  /** The head of the loop, and the statements at the start of each item before the try and inside it. */
2239
3727
  readonly head: string;
3728
+ /** The parts of the head. An early exit (COMPILE.MODULE.EXIT) goes on from the next target with them. */
3729
+ readonly parts: ForParts;
2240
3730
  readonly key: readonly string[];
2241
3731
  readonly check: readonly string[];
2242
3732
  readonly skip: string | undefined;
@@ -2244,6 +3734,8 @@ class Printer {
2244
3734
  readonly start: ReadonlySet<number>;
2245
3735
  /** True when the statements before the loop cannot throw. */
2246
3736
  readonly startSafe: boolean;
3737
+ /** True when the statements of `check` cannot throw: no item is an error item (COMPILE.MODULE.FUSE.CLEAN). */
3738
+ readonly checkSafe: boolean;
2247
3739
  readonly tests: readonly Expr[];
2248
3740
  readonly inner: Ctx;
2249
3741
  /** True when a target can be a key that is not the position of a record: a key of a literal or of `fill`. */
@@ -2251,6 +3743,8 @@ class Printer {
2251
3743
  /** The names `as` of the items, and their level. Only the body of an each and the steps of a fold read them. */
2252
3744
  readonly items: ReadonlyMap<string, Name>;
2253
3745
  readonly item: number | undefined;
3746
+ /** The array of a loop over the array of a list, and the pair of the item in it (COMPILE.MODULE.APPEND.KEEP). */
3747
+ readonly array?: { readonly a: string; readonly pair: string };
2254
3748
  } {
2255
3749
  const { base: outer, tests } = testsOf(axis);
2256
3750
  // The reverse order of an axis is a loop from its end (AXIS.REVERSE). The validation keeps a base axis inside.
@@ -2262,22 +3756,42 @@ class Printer {
2262
3756
  // error item is an item that fails.
2263
3757
  if (base.t === "list") {
2264
3758
  if (at.length > 0) throw new NotStandalone('the axis "list" with an address');
3759
+ // A range of fill is a loop over its count, with no array (COMPILE.MODULE.FILL.RANGE). The key is the position.
3760
+ const range = this.#range(base.list, ctx);
3761
+ if (range !== undefined) {
3762
+ const a = this.fresh("A");
3763
+ const q = this.fresh("q");
3764
+ const parts = forParts(q, "0", a, reverse);
3765
+ const s = [...range.s, `const ${a} = ${range.count.code};`];
3766
+ const named = as === undefined ? undefined : this.#itemNames(as, range.info, range.item, () => a, reverse);
3767
+ if (named !== undefined) s.push(...named.s);
3768
+ return { s, j, head: forHead(q, parts), parts, key: [`const ${j} = ${q};`], check: [...(named?.check ?? [])], checkSafe: true, skip: undefined, fixed: false, start: range.count.deps, startSafe: range.count.safe, tests, inner, texts: true, items: named?.items ?? NO_NAMES, item: named?.level };
3769
+ }
2265
3770
  const list = this.#hoist(this.#listOf(base.list, ctx), hasLoop(base.list));
2266
3771
  // A key of a literal or of fill is not the position of a record. Such a focus is a key of a list of the code only.
2267
3772
  const texts = (list.v.list as ListInfo).texts === true;
2268
3773
  const a = this.fresh("A");
2269
3774
  const q = this.fresh("q");
2270
- const head = reverse ? `for (let ${q} = ${a}.length - 1; ${q} >= 0; ${q}--) {` : `for (let ${q} = 0; ${q} < ${a}.length; ${q}++) {`;
2271
- const key = [`const ${j} = ${a}[${q}][0];`];
2272
- const check = [`if (${a}[${q}][1] === E) ${this.use("F")}();`];
3775
+ const parts = forParts(q, "0", `${a}.length`, reverse);
3776
+ const head = forHead(q, parts);
3777
+ // The pair of a keyed print holds the key of its record, and the loop reads the position of that record.
3778
+ const read = `${a}[${q}][0]`;
3779
+ const key = [`const ${j} = ${this.#pairKey(j, texts) === j ? read : `KM.get(${read})`};`];
3780
+ // The loop over a clean list has no test of the sentinel (COMPILE.MODULE.FUSE.CLEAN).
3781
+ const clean = this.#clean(list.v.list);
3782
+ const check = clean ? [] : [`if (${a}[${q}][1] === E) ${this.use("F")}();`];
2273
3783
  const s = [...list.s, `const ${a} = ${list.v.code};`];
2274
- const named = as === undefined ? undefined : this.#itemNames(as, list.v.list as ListInfo, `${a}[${q}][1]`, a, reverse);
3784
+ // The count of a clean list is its length (COMPILE.MODULE.FUSE.CLEAN).
3785
+ const count = (): string => (clean ? `${a}.length` : `${this.use("CT")}(${a}, false)`);
3786
+ const named = as === undefined ? undefined : this.#itemNames(as, list.v.list as ListInfo, `${a}[${q}][1]`, count, reverse);
2275
3787
  if (named !== undefined) {
2276
3788
  s.push(...named.s);
2277
3789
  check.push(...named.check);
2278
3790
  }
2279
- return { s, j, head, key, check, skip: undefined, fixed: false, start: list.v.deps, startSafe: list.v.safe, tests, inner, texts, items: named?.items ?? NO_NAMES, item: named?.level };
3791
+ return { s, j, head, parts, key, check, checkSafe: clean, skip: undefined, fixed: false, start: list.v.deps, startSafe: list.v.safe, tests, inner, texts, items: named?.items ?? NO_NAMES, item: named?.level, array: { a, pair: `${a}[${q}]` } };
2280
3792
  }
3793
+ // The focus of each other axis is the position of a record, so a loop in a second print reads the packs there too.
3794
+ this.#pack?.foci.add(j);
2281
3795
  const s: string[] = [];
2282
3796
  let lo = "0";
2283
3797
  let hi = "n";
@@ -2289,32 +3803,38 @@ class Printer {
2289
3803
  if (f !== undefined) {
2290
3804
  const values = this.#addressValues(at, ctx);
2291
3805
  start = this.#addressDeps(at, ctx, values);
2292
- const parts = this.#inOrder(this.#settle(values, start), false);
3806
+ const parts = this.#addressParts(at, values, start);
2293
3807
  s.push(...stmtsOf(...parts), `const ${f} = ${this.#address(at, ctx, parts)};`);
2294
3808
  }
2295
3809
  const startSafe = at.every((m) => m.t === "origin");
2296
3810
  if (base.t === "window" && (!Number.isInteger(base.from) || !Number.isInteger(base.to))) throw new NotStandalone('the axis "window" with a bound that is not an integer');
3811
+ // The ancestors are a walk up the parents, with no array (COMPILE.MODULE.TREE.ALLOC). The reverse order needs the array.
3812
+ if (this.#tree && base.t === "ancestors" && !reverse) {
3813
+ const parts = { init: `P[${f as string}]`, cond: `${j} >= 0`, next: `${j} = P[${j}]` };
3814
+ return { s, j, head: forHead(j, parts), parts, key: [], check: [], checkSafe: true, skip: undefined, fixed: false, start, startSafe, tests, inner, texts: false, items: NO_NAMES, item: undefined };
3815
+ }
2297
3816
  // In a tree space, the targets of a tree axis and of a window are a range of an array of positions.
2298
3817
  if (this.#tree && isTreeAxis(base)) {
2299
3818
  const range = this.#treeRange(base, f as string);
2300
3819
  const q = this.fresh("q");
2301
- return { s: [...s, ...range.s], j, head: forHead(q, range.lo, range.hi, reverse), key: [`const ${j} = ${range.a}[${q}];`], check: [], skip: range.skip, fixed: false, start, startSafe, tests, inner, texts: false, items: NO_NAMES, item: undefined };
3820
+ return { s: [...s, ...range.s], j, head: forHead(q, forParts(q, range.lo, range.hi, reverse)), parts: forParts(q, range.lo, range.hi, reverse), key: [`const ${j} = ${range.a}[${q}];`], check: [], checkSafe: true, skip: range.skip, fixed: false, start, startSafe, tests, inner, texts: false, items: NO_NAMES, item: undefined };
2302
3821
  }
2303
3822
  // In a graph space, the targets of an axis of a graph are an array of positions. A graph has no offsets and no tree.
2304
3823
  if (this.#graph && GRAPH_AXES.has(base.t)) {
2305
3824
  const range = this.#graphRange(base.t, f as string);
2306
3825
  const q = this.fresh("q");
2307
- return { s: [...s, ...range.s], j, head: forHead(q, range.lo, range.hi, reverse), key: [`const ${j} = ${range.a}[${q}];`], check: [], skip: undefined, fixed: false, start, startSafe, tests, inner, texts: false, items: NO_NAMES, item: undefined };
3826
+ return { s: [...s, ...range.s], j, head: forHead(q, forParts(q, range.lo, range.hi, reverse)), parts: forParts(q, range.lo, range.hi, reverse), key: [`const ${j} = ${range.a}[${q}];`], check: [], checkSafe: true, skip: undefined, fixed: false, start, startSafe, tests, inner, texts: false, items: NO_NAMES, item: undefined };
2308
3827
  }
2309
3828
  if (this.#graph && base.t === "window") throw new NotStandalone('the axis "window" in a graph space');
2310
3829
  if (base.t === "others") skip = f;
2311
3830
  else if (base.t === "window") {
3831
+ this.#noOffset();
2312
3832
  const h = this.fresh("h");
2313
3833
  lo = `Math.max(0, ${f as string} + Math.max(${base.from}, -n))`;
2314
3834
  s.push(`const ${h} = Math.min(n, ${f as string} + Math.min(${base.to}, n) + 1);`);
2315
3835
  hi = h;
2316
3836
  } else if (base.t !== "all") throw new NotStandalone(`the axis "${base.t}"`);
2317
- return { s, j, head: forHead(j, lo, hi, reverse), key: [], check: [], skip, fixed: f === undefined, start, startSafe, tests, inner, texts: false, items: NO_NAMES, item: undefined };
3837
+ return { s, j, head: forHead(j, forParts(j, lo, hi, reverse)), parts: forParts(j, lo, hi, reverse), key: [], check: [], checkSafe: true, skip, fixed: f === undefined, start, startSafe, tests, inner, texts: false, items: NO_NAMES, item: undefined };
2318
3838
  }
2319
3839
 
2320
3840
  /**
@@ -2324,7 +3844,9 @@ class Printer {
2324
3844
  * `nth` does (AXIS.LIST.INDEX). In the reverse order, it counts down from the number of these items. The names have a
2325
3845
  * level of their own. Thus a part that reads them stays in the loop, and a key of a literal can still be a target.
2326
3846
  */
2327
- #itemNames(as: ItemNames, info: ListInfo, value: string, a: string, reverse: boolean): { readonly s: readonly string[]; readonly check: readonly string[]; readonly items: ReadonlyMap<string, Name>; readonly level: number } {
3847
+ #itemNames(as: ItemNames, info: ListInfo, value: string, count: () => string, reverse: boolean): { readonly s: readonly string[]; readonly check: readonly string[]; readonly items: ReadonlyMap<string, Name>; readonly level: number } {
3848
+ // A search cannot know the items of a name that starts empty. The part gives an empty list (COMPILE.MODULE.LOOP.EMPTY).
3849
+ if (this.#starts.seek && info.empty === true) throw new NotStandalone("a search reads the items of an empty list");
2328
3850
  // Stryker disable next-line UpdateOperator: a level of a loop is a name, so a count down gives other names, and the same code
2329
3851
  const level = this.#loops++;
2330
3852
  const deps = new Set([level]);
@@ -2337,7 +3859,8 @@ class Printer {
2337
3859
  const i = this.fresh("i");
2338
3860
  const z = this.fresh("z");
2339
3861
  // The check before the index throws for an error item, so the count skips it.
2340
- s.push(`let ${z} = ${reverse ? `${this.use("CT")}(${a}, false)` : "0"};`);
3862
+ const total = count();
3863
+ s.push(`let ${z} = ${reverse ? total : "0"};`);
2341
3864
  check.push(`const ${i} = ${reverse ? `--${z}` : `${z}++`};`);
2342
3865
  items.set(index, { code: i, kind: "number", lazy: false, deps });
2343
3866
  }
@@ -2407,7 +3930,7 @@ class Printer {
2407
3930
  #list(op: string, target: ExprOf<"each">, rest: readonly Expr[], ctx: Ctx): Code {
2408
3931
  const { strict, step } = this.#foldOptions(op, rest);
2409
3932
  const at = target.at ?? [];
2410
- const { s, j, head, key, check, skip, fixed, start, startSafe, tests, inner, texts, items, item: own } = this.#targetLoop(target.axis, at, ctx, target.as);
3933
+ const { s, j, head, key, check, checkSafe, skip, fixed, start, startSafe, tests, inner, texts, items, item: own } = this.#targetLoop(target.axis, at, ctx, target.as);
2411
3934
  const { level } = inner;
2412
3935
  // Inside the loop, a constant of the run evaluates once, before the loop over the keys of the run. The tests do not
2413
3936
  // see the names of the items, and the body sees them (AXIS.LIST.SCOPE).
@@ -2424,7 +3947,7 @@ class Printer {
2424
3947
  s.push(r.init);
2425
3948
  const item = [...check, ...testCodes.flatMap((t) => [...t.s, `if (!${this.#boolean(t.v)}) continue;`]), ...body.s];
2426
3949
  // An item whose tests and body cannot fail needs no try.
2427
- const safeItem = check.length === 0 && body.v.safe && testCodes.every((t) => this.#safeBoolean(t.v));
3950
+ const safeItem = checkSafe && body.v.safe && testCodes.every((t) => this.#safeBoolean(t.v));
2428
3951
  // The interpreter evaluates each item before the list op (COMPILE.MODULE.SHEET). When an item reads a cell, an error
2429
3952
  // of an item or of a step must not stop the reads of the next items. So the items go into an array first.
2430
3953
  if ([body, ...testCodes].some((x) => x.v.deps.has(CELLS)) && (strict || stepThrows(op, body.v.kind))) {
@@ -2434,6 +3957,9 @@ class Printer {
2434
3957
  const reduce = [`for (const ${v} of ${list}) {`, ` if (${v} === E) ${strict ? `${this.use("F")}();` : "continue;"}`, ` ${r.step}`, "}"];
2435
3958
  return { s: [...s, `const ${list} = [];`, head, ...ind(all), "}", ...reduce], v: { code: r.result, kind: r.kind, safe: false, deps } };
2436
3959
  }
3960
+ // A sum over all the records whose term reads columns of the run can read their packs (`#packed`).
3961
+ const packed = fixed && tests.length === 0 && testsOf(target.axis).base.t === "all" ? this.#packed(op, step, strict, target, inner, body, r) : undefined;
3962
+ if (packed !== undefined) return { s: [...s, ...packed], v: { code: r.result, kind: r.kind, safe: false, deps } };
2437
3963
  const loop = [
2438
3964
  ...key,
2439
3965
  ...(skip === undefined ? [] : [`if (${j} === ${skip}) continue;`]),
@@ -2449,6 +3975,102 @@ class Printer {
2449
3975
  return { s, v: { code: r.result, kind: r.kind, safe, deps } };
2450
3976
  }
2451
3977
 
3978
+ /**
3979
+ * This method gives the fast loop of a sum, a mean, a min or a max over all the records, or undefined. The term must
3980
+ * be a number that reads values of the record only through columns of the run. It must have no loop, no cell and no
3981
+ * function of its own. Then the term prints again, with the body of each call at the place of the call (`#inline`).
3982
+ * Each read of a column at the item reads the pack of the column: an array of its values. The first sum of a run
3983
+ * makes it. The pack holds the sentinel for an error value, as the column does. Thus each read gives the value of the
3984
+ * column. One try covers all the items. An item that throws stops the inner loop, and the outer loop continues after
3985
+ * that item. The step comes after the value of the item, and it cannot throw.
3986
+ */
3987
+ #packed(op: string, step: Step | undefined, strict: boolean, target: ExprOf<"each">, inner: Ctx, body: Code, r: { readonly v: string; readonly step: string }): string[] | undefined {
3988
+ if (this.#pack !== undefined || !PACK_OPS.has(op) || step !== undefined || body.v.kind !== "number") return undefined;
3989
+ if (!this.#packable(target.body, inner.fns, new Set()) || !this.#reaches(body)) return undefined;
3990
+ const j = inner.focus as string;
3991
+ const pack: Pack = { foci: new Set([j]), calls: false, cols: new Map(), locals: new Set(), inlines: 0 };
3992
+ const scopes = this.#scopes.length;
3993
+ const outer = this.#inside;
3994
+ this.#pack = pack;
3995
+ let second: Code;
3996
+ try {
3997
+ second = this.expr(target.body, inner);
3998
+ } catch (err) {
3999
+ if (!(err instanceof NoPack || err instanceof NotStandalone)) throw err;
4000
+ this.#scopes.length = scopes;
4001
+ this.#inside = outer;
4002
+ return undefined;
4003
+ } finally {
4004
+ this.#pack = undefined;
4005
+ }
4006
+ // A part of the term that is a column reads its pack, so the packs that the code of that part read are not in the term.
4007
+ const text = [second.v.code, ...second.s].join("\n");
4008
+ const used = [...pack.cols].filter(([, local]) => text.includes(`${local}[`));
4009
+ if (used.length === 0) return undefined;
4010
+ // Each other read of the item is a value that no column holds, so the term keeps its first code.
4011
+ const rest = text.replaceAll(new RegExp(String.raw`\b(?:${used.map(([, local]) => local).join("|")})\[${j}\]`, "g"), "");
4012
+ if (new RegExp(String.raw`\b${j}\b`).test(rest)) return undefined;
4013
+ const lets = this.#packLets(used);
4014
+ const items = [...second.s, `const ${r.v} = ${second.v.code};`, r.step];
4015
+ const head = `for (let ${j} = 0; ${j} < n; ${j}++) {`;
4016
+ if (strict) return [...lets, "try {", ...ind([head, ...ind(items), "}"]), "} catch {", ` ${this.use("F")}();`, "}"];
4017
+ return [...lets, head, ...ind(["try {", ...ind([`for (; ${j} < n; ${j}++) {`, ...ind(items), "}"]), "} catch {}"]), "}"];
4018
+ }
4019
+
4020
+ /**
4021
+ * This method gives the statements that read the packs of some columns before a loop. Each pair has a column and its
4022
+ * local name. The first loop that reads a pack makes it. The variable of the pack of a column of the run is in the
4023
+ * run. The variable of the pack of a column of a call is in the function of the call.
4024
+ */
4025
+ #packLets(used: readonly (readonly [string, string])[]): string[] {
4026
+ return used.map(([col, local]) => {
4027
+ let name = this.#packs.get(col);
4028
+ if (name === undefined) {
4029
+ name = this.fresh("PK");
4030
+ this.#packs.set(col, name);
4031
+ (this.#callColumns.get(col)?.scope.decls ?? this.run).push(`let ${name};`);
4032
+ }
4033
+ return `const ${local} = ${name} || (${name} = ${this.use("QA")}(n, ${col}));`;
4034
+ });
4035
+ }
4036
+
4037
+ /**
4038
+ * This method tells if the term of a fast sum can print at the place of its loop (`#packed`). It has no loop, no cell,
4039
+ * no node of the memo and no function of its own. Each function that it calls is at the start of a run, and its body
4040
+ * is such a term too. A part that is a column is one read, so the parts in it do not count.
4041
+ */
4042
+ #packable(e: Expr, fns: ReadonlyMap<string, BoundFn>, seen: Set<number>): boolean {
4043
+ if (this.#columned.has(e)) return true;
4044
+ if (e.tag === "each" || e.tag === "fold" || e.tag === "iterate" || e.tag === "fix" || e.tag === "ext" || this.#memo.has(e)) return false;
4045
+ if (e.tag === "let" && Object.values(e.bind).some((x) => x.tag === "fn")) return false;
4046
+ if (e.tag === "call") {
4047
+ const bound = fns.get(e.fn);
4048
+ if (bound === undefined || bound.local) return false;
4049
+ if (!seen.has(bound.id)) {
4050
+ seen.add(bound.id);
4051
+ if (!this.#packable(bound.fn.body, bound.ctx.fns, seen)) return false;
4052
+ }
4053
+ }
4054
+ return children(e).every((x) => this.#packable(x, fns, seen));
4055
+ }
4056
+
4057
+ /** This method tells if code reads a column of the run, itself or in a printed function that it calls. */
4058
+ #reaches(c: Code): boolean {
4059
+ const seen = new Set<string>();
4060
+ const todo = [[c.v.code, ...c.s].join("\n")];
4061
+ for (let text = todo.pop(); text !== undefined; text = todo.pop()) {
4062
+ for (const [name] of text.matchAll(/\b(?:col|fn)\d+\b/g)) {
4063
+ if (this.#runColumns.has(name)) return true;
4064
+ const code = this.#specCode.get(name);
4065
+ if (code !== undefined && !seen.has(name)) {
4066
+ seen.add(name);
4067
+ todo.push(code);
4068
+ }
4069
+ }
4070
+ }
4071
+ return false;
4072
+ }
4073
+
2452
4074
  /**
2453
4075
  * This method gives the parts of a list op that reduces the values of its items. The parts are the variable `v` of
2454
4076
  * 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.
@@ -2520,7 +4142,7 @@ class Printer {
2520
4142
  const [i, d] = only;
2521
4143
  const name = `id_${String(i)}_${String(this.#opIndex(op))}`;
2522
4144
  // Stryker disable next-line ConditionalExpression: the copy of an identity is always the same, so the test only saves time
2523
- if (!this.top.has(name)) this.top.set(name, `const ${name} = ${copied((d.ops[op] as { readonly identity: () => unknown }).identity, [], `the identity of the op "${op}" of the domain ${d.name}`)};`);
4145
+ if (!this.top.has(name)) this.#copy(name, copied((d.ops[op] as { readonly identity: () => unknown }).identity, [], `the identity of the op "${op}" of the domain ${d.name}`));
2524
4146
  return { code: `${name}()`, kind: kindOfDomain(d) };
2525
4147
  }
2526
4148
 
@@ -2529,8 +4151,10 @@ class Printer {
2529
4151
  * fails, a body that fails and an error item of the axis list give the error sentinel as the value.
2530
4152
  */
2531
4153
  #eachList(e: ExprOf<"each">, ctx: Ctx): Code {
4154
+ const alias = this.#sameList(e, ctx);
4155
+ if (alias !== undefined) return alias;
2532
4156
  const at = e.at ?? [];
2533
- const { s, j, head, key, check, skip, start, startSafe, tests, inner, texts, items, item: own } = this.#targetLoop(e.axis, at, ctx, e.as);
4157
+ const { s, j, head, key, check, checkSafe, skip, start, startSafe, tests, inner, texts, items, item: own } = this.#targetLoop(e.axis, at, ctx, e.as);
2534
4158
  const testCodes = tests.map((t) => this.#hoist(this.expr(t, inner), hasLoop(t)));
2535
4159
  // The value of an item can be a list, for flat (LIST.FLAT). The facts of the list tell it.
2536
4160
  if (this.#wantList.has(e)) this.#wantList.add(e.body);
@@ -2540,14 +4164,304 @@ class Printer {
2540
4164
  const deps = new Set([...start, ...[body, ...testCodes].flatMap((x) => [...x.v.deps])].filter((d) => d !== inner.level && d !== own));
2541
4165
  const list = this.fresh("L");
2542
4166
  const v = this.fresh("x");
4167
+ const pair = this.#pairKey(j, texts);
2543
4168
  const item = [...check, ...testCodes.flatMap((t) => [...t.s, `if (!${this.#boolean(t.v)}) continue;`]), ...body.s];
2544
- const safeItem = check.length === 0 && body.v.safe && testCodes.every((t) => this.#safeBoolean(t.v));
4169
+ const safeItem = checkSafe && body.v.safe && testCodes.every((t) => this.#safeBoolean(t.v));
2545
4170
  const loop = [
2546
4171
  ...key,
2547
4172
  ...(skip === undefined ? [] : [`if (${j} === ${skip}) continue;`]),
2548
- ...(safeItem ? [...item, `${list}.push([${j}, ${body.v.code}]);`] : [`let ${v};`, "try {", ...ind(item), ` ${v} = ${body.v.code};`, "} catch {", ` ${v} = E;`, "}", `${list}.push([${j}, ${v}]);`]),
4173
+ ...(safeItem ? [...item, `${list}.push([${pair}, ${body.v.code}]);`] : [`let ${v};`, "try {", ...ind(item), ` ${v} = ${body.v.code};`, "} catch {", ` ${v} = E;`, "}", `${list}.push([${pair}, ${v}]);`]),
2549
4174
  ];
2550
- return { s: [...s, `const ${list} = [];`, head, ...ind(loop), "}"], v: { code: list, kind: undefined, safe: startSafe, deps, list: { item: body.v.kind, inner: body.v.list, texts } } };
4175
+ // Only the catch of an item puts the sentinel into the list, so a safe item gives a clean list.
4176
+ const facts: ListInfo = { item: body.v.kind, inner: heldList(body.v.list), texts, clean: safeItem };
4177
+ return { s: [...s, `const ${list} = [];`, head, ...ind(loop), "}"], v: { code: list, kind: undefined, safe: startSafe, deps, list: facts } };
4178
+ }
4179
+
4180
+ /**
4181
+ * This method gives the code of an each that gives its list again (COMPILE.MODULE.EACH.SAME), and undefined for each
4182
+ * other each. The axis is `list`, with no `where`, no `reverse` and no address. The body is a read of the name of the
4183
+ * item. Such an each gives the key and the value of each item, and an error item stays an error item. Thus its value
4184
+ * is the array of its list, with no copy. The option `fuse` must be true.
4185
+ *
4186
+ * The value is not fresh, because the list holds the same array. Thus no op changes the array in place: an append
4187
+ * copies it, and `sortBy` sorts a copy.
4188
+ */
4189
+ #sameList(e: ExprOf<"each">, ctx: Ctx): Code | undefined {
4190
+ // The check of the document refuses two names `as` that are the same name, so the body reads the value of the item.
4191
+ if (!this.#fuse || e.axis.t !== "list" || (e.at ?? []).length > 0 || e.body.tag !== "var" || e.body.name !== e.as?.[0]) return undefined;
4192
+ const list = this.#hoist(this.#listOf(e.axis.list, ctx), hasLoop(e.axis.list));
4193
+ const info = list.v.list as ListInfo;
4194
+ // A search cannot know the items of a name that starts empty, as for each other read of the items (#itemNames).
4195
+ if (this.#starts.seek && info.empty === true) throw new NotStandalone("a search reads the items of an empty list");
4196
+ // The facts are the facts of the each of the loop: its items keep the facts of the items of the list. A list of
4197
+ // lists holds each list of its items, so the facts of an item are not fresh.
4198
+ const facts: ListInfo = { item: info.item, inner: info.inner, texts: info.texts === true, clean: this.#clean(info) };
4199
+ return { s: list.s, v: { ...list.v, list: facts } };
4200
+ }
4201
+
4202
+ /**
4203
+ * This method gives the option strict of `flat` over the each `e` when the two ops fuse (COMPILE.MODULE.FUSE), and
4204
+ * undefined when they do not fuse. The option `fuse` must be true, and the body of the each must give a list. The
4205
+ * code reads a node of the memo again. It also reads a constant of the run that the module printed before. Thus these
4206
+ * nodes do not fuse. Options that are not a literal give the reason of `flat`, so they do not fuse either.
4207
+ */
4208
+ #fusedStrict(e: ExprOf<"each">, rest: readonly Expr[], ctx: Ctx): boolean | undefined {
4209
+ if (!this.#fuse || this.#memo.has(e) || ctx.keys.has(e) || this.#constant.has(originalOf(e)) || !this.#bodyList(e, ctx)) return undefined;
4210
+ try {
4211
+ return this.#strict("flat", rest);
4212
+ } catch {
4213
+ return undefined;
4214
+ }
4215
+ }
4216
+
4217
+ /**
4218
+ * This method prints `flat` over an each as one loop with one output array (COMPILE.MODULE.FUSE). The body pushes the
4219
+ * items of its list into the output. Thus the each has no array of its own, and `FL` and `V` do not scan a list.
4220
+ *
4221
+ * - The loop keeps the length of the output before each item. An item that fails sets the length back, so it adds no
4222
+ * item (COMPILE.MODULE.FUSE.ITEM). With `strict`, the failure is the error of `flat`.
4223
+ * - An error item of the source fails at the check of the item, as in the each without fusion.
4224
+ * - When an item reads a cell, a strict failure does not stop the loop. The search of the run must see each read, as
4225
+ * in the loop of an aggregate. Thus a flag holds the failure until the end of the loop.
4226
+ *
4227
+ * The output has only items with values, and no other part holds its array, so it is clean and fresh.
4228
+ *
4229
+ * With `owner`, the each is a filter of the list of the owner (COMPILE.MODULE.APPEND.KEEP). When the list is the array
4230
+ * `w` of the owner, that array is the output. The loop then moves each kept item down in place, and `KS` sets the
4231
+ * length. Each other list gets a new output. This output is not fresh, because the loop can hold it.
4232
+ */
4233
+ #flatEach(e: ExprOf<"each">, strict: boolean, ctx: Ctx, owner?: Owner): Code {
4234
+ const { s, j, head, key, check, checkSafe, skip, start, startSafe, tests, inner, texts, items, item: own, array } = this.#targetLoop(e.axis, e.at ?? [], ctx, e.as);
4235
+ const testCodes = tests.map((t) => this.#hoist(this.expr(t, inner), hasLoop(t)));
4236
+ const o = this.fresh("o");
4237
+ // The axis of a filter is the axis list of the name of the owner, so the loop goes over an array.
4238
+ const place = owner !== undefined && array !== undefined ? { w: (owner.w ??= this.fresh("w")), n: this.fresh("n"), a: array.a } : undefined;
4239
+ if (place !== undefined) this.#sinks.set(o, { n: place.n, pair: (array as { readonly pair: string }).pair, item: e.as === undefined ? undefined : items.get(e.as[0])?.code });
4240
+ // Only the body sees the names of the items (AXIS.LIST.SCOPE).
4241
+ let body: Pushed;
4242
+ try {
4243
+ body = this.#push(e.body, { ...inner, env: withNames(inner.env, items) }, o, strict);
4244
+ } finally {
4245
+ this.#sinks.delete(o);
4246
+ }
4247
+ const parts = [body.deps, ...testCodes.map((x) => x.v.deps)];
4248
+ this.#readsNoTarget(texts, inner.level, parts);
4249
+ const deps = new Set([...start, ...parts.flatMap((d) => [...d])].filter((d) => d !== inner.level && d !== own));
4250
+ const item = [...testCodes.flatMap((t) => [...t.s, `if (!${this.#boolean(t.v)}) continue;`]), ...body.s];
4251
+ const safeItem = checkSafe && body.safe && testCodes.every((t) => this.#safeBoolean(t.v));
4252
+ // The output keeps the key of each item of the body. Thus the loop needs the key of its target only for a read at
4253
+ // the target, or for the target that the axis skips.
4254
+ const at = new RegExp(String.raw`\b${j}\b`);
4255
+ const skips = skip === undefined ? [] : [`if (${j} === ${skip}) continue;`];
4256
+ const lead = [...([...skips, ...item].some((x) => at.test(x)) ? key : []), ...skips];
4257
+ const flag = strict && !safeItem && parts.some((d) => d.has(CELLS)) ? this.fresh("f") : undefined;
4258
+ let loop: string[];
4259
+ if (safeItem) loop = [...lead, ...check, ...item];
4260
+ else {
4261
+ // An item of a filter in place puts at most one item, at its end. Thus an item that fails puts no item.
4262
+ const m = strict || place !== undefined ? undefined : this.fresh("m");
4263
+ const caught = flag !== undefined ? [`${flag} = true;`] : strict ? [`${this.use("F")}();`] : m === undefined ? [] : [`${o}.length = ${m};`];
4264
+ // A check that cannot throw comes before the try.
4265
+ const [before, inside] = checkSafe ? [check, item] : [[], [...check, ...item]];
4266
+ loop = [...lead, ...before, ...(m === undefined ? [] : [`const ${m} = ${o}.length;`]), "try {", ...ind(inside), "} catch {", ...ind(caught), "}"];
4267
+ }
4268
+ // The output of a filter in place is the array of the list only when that array is w (COMPILE.MODULE.APPEND.KEEP).
4269
+ const first = place === undefined ? [`const ${o} = [];`] : [`const ${o} = ${place.a} === ${place.w} ? ${place.a} : [];`, `let ${place.n} = 0;`];
4270
+ const last = place === undefined ? [] : [`${this.use("KS")}(${o}, ${place.n});`];
4271
+ const out = [...s, ...first, ...(flag === undefined ? [] : [`let ${flag} = false;`]), head, ...ind(loop), "}", ...last, ...(flag === undefined ? [] : [`if (${flag}) ${this.use("F")}();`])];
4272
+ const facts: ListInfo = { ...(body.list as ListInfo), clean: true, fresh: place === undefined };
4273
+ const c: Code = { s: out, v: { code: o, kind: undefined, safe: startSafe && (safeItem || !strict), deps, list: facts } };
4274
+ // A fused loop around a filter in place cannot push into its output, because the output can be the array w.
4275
+ // Stryker disable next-line ConditionalExpression: a filter in place is a branch of a step, and no fused loop pushes it
4276
+ if (place === undefined) this.#outputs.set(c, s.length);
4277
+ return c;
4278
+ }
4279
+
4280
+ /**
4281
+ * This method gives the owner of the filter `e` when the filter compacts the array of the owner in place
4282
+ * (COMPILE.MODULE.APPEND.KEEP). For each other node, it gives undefined. `#loopStep` finds the filter in a branch of
4283
+ * another list. Each place of the program has an object of its own (`unsharedAll`), so the node is at that branch
4284
+ * only. Each item of the body gives at most one item.
4285
+ */
4286
+ #keepOwner(e: ExprOf<"app">): Owner | undefined {
4287
+ const owner = this.#keeps.get(e);
4288
+ return owner !== undefined && atMostOne((e.args[0] as ExprOf<"each">).body, this.#facts.own("fill")) ? owner : undefined;
4289
+ }
4290
+
4291
+ /**
4292
+ * This method gives the option strict of the append `e` for a fused chain (COMPILE.MODULE.FUSE). This method gives
4293
+ * undefined when the append cannot be a part of a chain. The option `fuse` must be true, both arguments must be lists, and the options must be
4294
+ * a literal. An append into the list of its name keeps `AO` (COMPILE.MODULE.APPEND.OWN). In a sheet with a search, an
4295
+ * append that can read a cell does not fuse, because the fused chain stops at the first failure.
4296
+ */
4297
+ #appendStrict(e: ExprOf<"app">, ctx: Ctx): boolean | undefined {
4298
+ const [a, b] = e.args;
4299
+ if (!this.#fuse || a === undefined || b === undefined || this.#own.has(e) || !this.#isList(a, ctx) || !this.#isList(b, ctx)) return undefined;
4300
+ if (this.#sheet !== undefined && !this.#sheet.direct && readsCells(e)) return undefined;
4301
+ try {
4302
+ return this.#strict("append", e.args.slice(2));
4303
+ } catch {
4304
+ return undefined;
4305
+ }
4306
+ }
4307
+
4308
+ /** This method gives the node `e` when a fused loop can print it as a stage, and undefined when the loop reads its array. */
4309
+ #stageOf(e: Expr, ctx: Ctx): ExprOf<"app"> | undefined {
4310
+ return e.tag === "app" && !this.#memo.has(e) && !ctx.keys.has(e) && !this.#constant.has(originalOf(e)) && (this.#work(e, ctx.fns) < COLUMN_WORK || !readsFocus(e)) ? e : undefined;
4311
+ }
4312
+
4313
+ /**
4314
+ * This method gives the option strict of the append `e` when it is a link of a fused chain, and undefined when it is
4315
+ * not. A node of the memo, a key of a column and a constant of the run keep their arrays, because other parts read them.
4316
+ */
4317
+ #link(e: Expr, ctx: Ctx): boolean | undefined {
4318
+ if (e.tag !== "app" || e.op !== "append" || this.#memo.has(e) || ctx.keys.has(e) || this.#constant.has(originalOf(e))) return undefined;
4319
+ return this.#appendStrict(e, ctx);
4320
+ }
4321
+
4322
+ /**
4323
+ * This method tells if a part of an append pushes its items with no array of its own (COMPILE.MODULE.FUSE). These
4324
+ * parts are `fill(1, v)`, `flat` over an each that fuses, and an append or an `if` with such a part. An append of two
4325
+ * arrays keeps `concat`, because a loop that copies the items costs more. A `flat` and an append print their own
4326
+ * loops, so they need no test of a stage.
4327
+ */
4328
+ #pushes(e: Expr, ctx: Ctx): boolean {
4329
+ if (e.tag !== "app" || this.#memo.has(e) || ctx.keys.has(e) || this.#constant.has(originalOf(e))) return false;
4330
+ const [head, ...rest] = e.args;
4331
+ if (e.op === "flat") return head?.tag === "each" && this.#fusedStrict(head, rest, ctx) !== undefined;
4332
+ if (e.op === "append") return this.#link(e, ctx) !== undefined && e.args.slice(0, 2).some((x) => this.#pushes(x, ctx));
4333
+ if (this.#stageOf(e, ctx) === undefined) return false;
4334
+ if (e.op === "fill") return rest.length === 1 && isOne(head) && this.#facts.own("fill");
4335
+ return e.op === "if" && rest.length === 2 && rest.every((x) => this.#isList(x, ctx)) && rest.some((x) => this.#pushes(x, ctx));
4336
+ }
4337
+
4338
+ /**
4339
+ * This method prints a chain of append as one output array (COMPILE.MODULE.FUSE). Each part pushes its items into the
4340
+ * output, in order. A part that fails is the error of the chain, as the error of a list is the error of append. The
4341
+ * output has only items with values, and no other part holds its array, so it is clean and fresh.
4342
+ */
4343
+ #appendChain(e: ExprOf<"app">, strict: boolean, ctx: Ctx): Code {
4344
+ const o = this.fresh("o");
4345
+ const parts = this.#pushAppend(e, strict, ctx, o);
4346
+ const c: Code = { s: [`const ${o} = [];`, ...parts.s], v: { code: o, kind: undefined, safe: parts.safe, deps: parts.deps, list: { ...(parts.list as ListInfo), clean: true, fresh: true } } };
4347
+ this.#outputs.set(c, 0);
4348
+ return c;
4349
+ }
4350
+
4351
+ /**
4352
+ * This method prints the statements that push the items of the lists of an append into the output `o`, in order. An
4353
+ * append that is a stage gives the parts of its lists. The option `strict` of each append applies to the error items of
4354
+ * its lists (LIST.BUILD).
4355
+ *
4356
+ * Each part prints before the decision about the constants of the run. A chain that is a constant of the run keeps its
4357
+ * parts in its own code, because the module evaluates the chain once. In each other chain, and with `settle`, a part
4358
+ * that is a constant of the run evaluates once, before the loop over the keys.
4359
+ */
4360
+ #pushAppend(e: ExprOf<"app">, strict: boolean, ctx: Ctx, o: string, settle?: boolean): Pushed {
4361
+ const lists: { readonly e: Expr; readonly strict: boolean }[] = [];
4362
+ const walk = (x: Expr, s: boolean): void => {
4363
+ const joined = this.#link(x, ctx);
4364
+ if (joined === undefined) lists.push({ e: x, strict: s });
4365
+ else for (const y of (x as ExprOf<"app">).args.slice(0, 2)) walk(y, joined);
4366
+ };
4367
+ for (const x of e.args.slice(0, 2)) walk(x, strict);
4368
+ const parts = lists.map((x) => this.#pushPart(x.e, ctx, o, x.strict));
4369
+ const deps = new Set(parts.flatMap((x) => [...x.deps]));
4370
+ const now = settle ?? deps.size > 0;
4371
+ const list = parts.map((x) => x.list as ListInfo).reduce((a, b) => joinLists(a, b, "append"));
4372
+ return { s: parts.flatMap((x) => x.s(now)), deps, safe: parts.every((x) => x.safe), list };
4373
+ }
4374
+
4375
+ /**
4376
+ * This method prints the statements that push the items of the list of `e` into the output `o` of a fused loop
4377
+ * (COMPILE.MODULE.FUSE). The forms of a stage are these:
4378
+ *
4379
+ * - `if` with two lists pushes the items of the branch that its condition selects.
4380
+ * - `fill(1, x)` pushes one item with the key 0, as `FI` gives it.
4381
+ * - The empty literal pushes no item.
4382
+ * - `append` pushes the items of its first list, then the items of its second list.
4383
+ *
4384
+ * Each other list prints its array, and a loop pushes its items (`#pushPart`).
4385
+ */
4386
+ #push(e: Expr, ctx: Ctx, o: string, strict: boolean): Pushed {
4387
+ const joined = this.#link(e, ctx);
4388
+ if (joined !== undefined) return this.#pushAppend(e as ExprOf<"app">, joined, ctx, o, true);
4389
+ const stage = this.#stageOf(e, ctx);
4390
+ if (stage?.op === "if" && stage.args.length === 3 && stage.args.slice(1).every((x) => this.#isList(x, ctx))) {
4391
+ const [c, a, b] = stage.args as [Expr, Expr, Expr];
4392
+ // The condition evaluates once for each run when it is a constant of the run.
4393
+ const cond = this.#hoist(this.expr(c, ctx), hasLoop(c));
4394
+ const yes = this.#push(a, ctx, o, strict);
4395
+ const no = this.#push(b, ctx, o, strict);
4396
+ // A branch that pushes nothing prints no block.
4397
+ const s = [...cond.s, `if (${this.#boolean(cond.v)}) {`, ...ind(yes.s), ...(no.s.length === 0 ? [] : ["} else {", ...ind(no.s)]), "}"];
4398
+ return { s, deps: new Set([...cond.v.deps, ...yes.deps, ...no.deps]), safe: this.#safeBoolean(cond.v) && yes.safe && no.safe, list: branchLists("if", yes.list, no.list) };
4399
+ }
4400
+ const part = this.#pushPart(e, ctx, o, strict);
4401
+ return { ...part, s: part.s(true) };
4402
+ }
4403
+
4404
+ /**
4405
+ * This method prints a part of a fused loop that is not `if` or `append`: `fill(1, x)`, the empty literal or a list.
4406
+ * The code of the part comes from `s`. With `settle`, a part that is a constant of the run evaluates once.
4407
+ *
4408
+ * A list prints its array, and a loop pushes its items. A list that is not clean can hold error items. The loop skips
4409
+ * them, and with `strict` such an item is an error.
4410
+ *
4411
+ * A node of the memo also prints its array. So does a constant of the
4412
+ * run that the module printed before, and a node that can be a column of the run. Thus the module keeps these values
4413
+ * for each read. A fused loop that the module does not keep pushes into `o` itself.
4414
+ */
4415
+ #pushPart(e: Expr, ctx: Ctx, o: string, strict: boolean): Part {
4416
+ const stage = this.#stageOf(e, ctx);
4417
+ if (stage?.op === "fill" && stage.args.length === 2 && isOne(stage.args[0]) && this.#facts.own("fill")) {
4418
+ const x = stage.args[1] as Expr;
4419
+ // The value can be a list, so fill gives a list of lists (COMPILE.MODULE.FILL).
4420
+ this.#wantList.add(x);
4421
+ const raw = this.expr(x, ctx);
4422
+ const list: ListInfo = { item: raw.v.kind, inner: heldList(raw.v.list), texts: true };
4423
+ const s = (settle: boolean): readonly string[] => {
4424
+ const value = settle ? this.#hoist(raw, hasLoop(x)) : raw;
4425
+ return [...value.s, this.#put(o, `[0, ${value.v.code}]`, value.v)];
4426
+ };
4427
+ return { s, deps: raw.v.deps, safe: raw.v.safe, list };
4428
+ }
4429
+ if (e.tag === "lit" && isVexList(e.value) && e.value.items.length === 0) {
4430
+ const empty = this.#listLiteral(e.value);
4431
+ // A literal is a constant of the module, as at each other place, so its facts tell that each run reads it.
4432
+ this.#note(e, empty, true);
4433
+ return { s: () => [], deps: NO_DEPS, safe: true, list: empty.v.list };
4434
+ }
4435
+ const raw = this.#listOf(e, ctx);
4436
+ // A `fill` that gives no items pushes nothing (COMPILE.MODULE.SIZE.FILL).
4437
+ if (raw.v.code === "[]") return { s: () => [], deps: raw.v.deps, safe: true, list: raw.v.list };
4438
+ const clean = this.#clean(raw.v.list);
4439
+ const s = (settle: boolean): readonly string[] => {
4440
+ const c = settle ? this.#hoist(raw, hasLoop(e)) : raw;
4441
+ // The output of a fused loop has only items with values, so the loop can push into `o` in place of its own output.
4442
+ // A filter in place puts each item at its position, so it keeps the output of the part (COMPILE.MODULE.APPEND.KEEP).
4443
+ const at = this.#outputs.get(c);
4444
+ // Stryker disable next-line ConditionalExpression: atMostOne gives no fused loop in the body of a filter in place
4445
+ if (at !== undefined && !this.#sinks.has(o)) return c.s.map((x, i) => (i === at ? `const ${c.v.code} = ${o};` : x));
4446
+ const z = this.fresh("z");
4447
+ const put = this.#put(o, `${z}[i]`);
4448
+ const each = clean ? put : strict ? `{ if (${z}[i][1] === E) ${this.use("F")}(); ${put} }` : `if (${z}[i][1] !== E) ${put}`;
4449
+ return [...c.s, `const ${z} = ${c.v.code};`, `for (let i = 0; i < ${z}.length; i++) ${each}`];
4450
+ };
4451
+ return { s, deps: raw.v.deps, safe: raw.v.safe && (clean || !strict), list: raw.v.list };
4452
+ }
4453
+
4454
+ /**
4455
+ * This method gives the statement that puts the pair `pair` into the output `o` of a fused loop. `value` is the value
4456
+ * of a pair of `fill`. A filter in place puts the pair at the next position of its output (COMPILE.MODULE.APPEND.KEEP).
4457
+ * There the item of the list keeps its pair when its key is 0, the key of `fill`. Each other output gets a push.
4458
+ */
4459
+ #put(o: string, pair: string, value?: { readonly code: string; readonly safe: boolean }): string {
4460
+ const sink = this.#sinks.get(o);
4461
+ if (sink === undefined) return `${o}.push(${pair});`;
4462
+ if (value !== undefined && value.code === sink.item) return `${o}[${sink.n}++] = ${sink.pair}[0] === 0 ? ${sink.pair} : ${pair};`;
4463
+ // JavaScript increments n before it gets the value of the pair. Thus a value that can fail increments n after the put.
4464
+ return value === undefined || value.safe ? `${o}[${sink.n}++] = ${pair};` : `${o}[${sink.n}] = ${pair}; ${sink.n}++;`;
2551
4465
  }
2552
4466
 
2553
4467
  /**
@@ -2564,10 +4478,40 @@ class Printer {
2564
4478
  const raw = [list, ...exprs.slice(1).map((x) => this.expr(x, ctx))];
2565
4479
  const deps = depsOf(...raw);
2566
4480
  const parts = this.#inOrder(this.#settle(raw, deps, exprs), true);
2567
- const helper = by !== undefined ? "SK" : op === "sortBy" ? "SB" : op === "take" ? "TK" : "DR";
2568
- const args = [...parts.map((x) => x.v.code), String(strict), ...(by === undefined ? [] : [by])];
2569
- // The new list has some items of the list, so it keeps the facts of the list.
2570
- return { s: stmtsOf(...parts), v: { code: `${this.use(helper)}(${args.join(", ")})`, kind: undefined, safe: false, deps, list: list.v.list } };
4481
+ const plain = by !== undefined ? "SK" : op === "sortBy" ? "SB" : op === "take" ? "TK" : "DR";
4482
+ // The clean form has no scan of V and no option strict (COMPILE.MODULE.FUSE.CLEAN).
4483
+ const clean = this.#clean(list.v.list);
4484
+ // sortBy is the sink of a chain: a clean list that is fresh is its own sort buffer (COMPILE.MODULE.FUSE).
4485
+ const inPlace = op === "sortBy" && clean && list.v.list?.fresh === true;
4486
+ const helper = inPlace ? (by === undefined ? "SBI" : "SKI") : clean ? (`${plain}C` as const) : plain;
4487
+ const args = [...parts.map((x) => x.v.code), ...(clean ? [] : [String(strict)]), ...(by === undefined ? [] : [by])];
4488
+ // The new list has some items of the list, so it keeps the facts of the list. V removes each error item. A sort in
4489
+ // place gives the array of its list, which no other part holds.
4490
+ const facts: ListInfo = { ...(list.v.list as ListInfo), clean: true, fresh: inPlace };
4491
+ return { s: stmtsOf(...parts), v: { code: `${this.use(helper)}(${args.join(", ")})`, kind: undefined, safe: false, deps, list: facts } };
4492
+ }
4493
+
4494
+ /**
4495
+ * This method prints `setNth` (LIST.SETNTH, COMPILE.MODULE.SETNTH): a new array with a new value at a position. An
4496
+ * error item is not in the new list, and with strict it is the error of the op. The value can be a list, as for `fill`.
4497
+ */
4498
+ #setNth(head: Expr, rest: readonly Expr[], ctx: Ctx): Code {
4499
+ const [position, value, ...options] = rest;
4500
+ // Without a position or a value the op gives an error at each run, so a module refuses the program.
4501
+ if (position === undefined || value === undefined) throw new NotStandalone('"setNth" without a position and a value');
4502
+ const strict = this.#strict("setNth", options);
4503
+ const list = this.#listOf(head, ctx);
4504
+ this.#wantList.add(value);
4505
+ const raw = [list, this.expr(position, ctx), this.expr(value, ctx)];
4506
+ const deps = depsOf(...raw);
4507
+ const [from, at, put] = this.#inOrder(this.#settle(raw, deps, [head, position, value]), true) as [Code, Code, Code];
4508
+ const info = list.v.list as ListInfo;
4509
+ // The clean form has no scan of V and no option strict (COMPILE.MODULE.FUSE.CLEAN).
4510
+ const clean = this.#clean(info);
4511
+ const args = [from.v.code, at.v.code, put.v.code, ...(clean ? [] : [String(strict)])];
4512
+ // The items have the facts of the list and of the value. V removes each error item, and the value is not the sentinel.
4513
+ const facts: ListInfo = { ...joinLists(info, { item: put.v.kind, inner: heldList(put.v.list) }, "setNth"), clean: true, fresh: false };
4514
+ return { s: stmtsOf(from, at, put), v: { code: `${this.use(clean ? "SNC" : "SN")}(${args.join(", ")})`, kind: undefined, safe: false, deps, list: facts } };
2571
4515
  }
2572
4516
 
2573
4517
  /**
@@ -2598,27 +4542,96 @@ class Printer {
2598
4542
  // gives its error. A missing second list of append and without is not a list, so it gives a reason.
2599
4543
  const exprs = [head, ...(op === "flat" ? [] : [rest[0] ?? lit(null)])];
2600
4544
  const strict = this.#strict(op, rest.slice(exprs.length - 1));
4545
+ // A function of the program can share a node with the step, but its body has its own names (FN.BIND).
4546
+ const owned = owner !== undefined && ctx.env.get(owner.name) === owner.read;
4547
+ // With fuse, an append of an owner pushes the items of a list that a fused loop pushes, with no array of that list
4548
+ // (COMPILE.MODULE.APPEND.PUSH). The one item of `fill(1, x)` goes through `#ones` below.
4549
+ const pushed = op === "append" && owned && this.#fuse ? this.#ownPush(list, exprs[1] as Expr, strict, ctx, owner) : undefined;
4550
+ if (pushed !== undefined) return pushed;
4551
+ // With fuse, an append of an owner can push the one item of `fill(1, x)` (COMPILE.MODULE.FUSE.ADOPT). Only `#fill`
4552
+ // reads the mark of the node. An error of a print stops the module, so the mark needs no `finally`.
4553
+ const right = owned && this.#fuse ? exprs[1] : undefined;
4554
+ this.#ones.set(right, undefined);
2601
4555
  const raw = [list, ...exprs.slice(1).map((x) => (two ? this.#listOf(x, ctx) : this.expr(x, ctx)))];
4556
+ const one = this.#ones.get(right);
4557
+ this.#ones.delete(right);
2602
4558
  const deps = depsOf(...raw);
2603
4559
  const parts = this.#inOrder(this.#settle(raw, deps, exprs), true);
2604
- const helper = BUILD_HELPERS[op] as BuildHelper;
2605
- const args = [...parts.map((x) => x.v.code), String(strict)];
2606
- // A function of the program can share a node with the step, but its body has its own names (FN.BIND).
2607
- const w = owner !== undefined && ctx.env.get(owner.name) === owner.read ? (owner.w ??= this.fresh("w")) : undefined;
2608
- const code = w === undefined ? `${this.use(helper)}(${args.join(", ")})` : `(${w} = ${this.use("AO")}(${[...args, w].join(", ")}))`;
4560
+ const w = owned ? (owner.w ??= this.fresh("w")) : undefined;
4561
+ // The item is the item of the list of the append only if no other part holds the value of fill. The list of a sure
4562
+ // owner is the array of w. Each other list can be another array, so AI or AIC selects the push or a copy with the push.
4563
+ const item = one !== undefined && (parts[1] as Code).v === one.v ? one.item : undefined;
4564
+ if (one !== undefined && item === undefined) this.use("FI");
4565
+ const code = this.#buildCode(op, parts, strict, w, item === undefined ? undefined : { item, sure: (owner as Owner).sure });
2609
4566
  const value = (kind: Kind | undefined, facts: ListInfo | undefined): Code => ({ s: stmtsOf(...parts), v: { code, kind, safe: false, deps, list: facts } });
2610
4567
  if (op === "get") return value(info.item, info.inner);
2611
4568
  if (op === "indexOf") return value("number", undefined);
2612
- if (op === "without") return value(undefined, info);
2613
- if (op === "append") return value(undefined, joinLists(info, (parts[1] as Code).v.list as ListInfo, op));
4569
+ // V removes each error item, so the value of without, append and flat is clean.
4570
+ const built = (facts: ListInfo): Code => value(undefined, { ...facts, clean: true, fresh: false });
4571
+ if (op === "without") return built(info);
4572
+ if (op === "append") return built(joinLists(info, (parts[1] as Code).v.list as ListInfo, op));
2614
4573
  // flat: the value of each item must be a list, so a list of values gives a reason. An empty list gives an empty list.
2615
- if (info.empty === true) return value(undefined, info);
4574
+ if (info.empty === true) return built(info);
2616
4575
  if (info.inner === undefined) throw new NotStandalone('"flat" over a list whose items are not lists');
2617
- return value(undefined, info.inner);
4576
+ return built(info.inner);
4577
+ }
4578
+
4579
+ /**
4580
+ * This method prints an append of an owner whose second list a fused loop pushes (COMPILE.MODULE.APPEND.PUSH). Such a
4581
+ * list is an append chain, an `if` or a fused `flat` over an each (`#pushes`). The items go into the target, with no array
4582
+ * of that list. The target is the array `w` when the first list is `w`. Each other first list gets one copy, as the
4583
+ * fused chain of the version before COMPILE.MODULE.APPEND.OTHER does. `fill(1, x)` keeps the expression of AIC, and
4584
+ * this method gives undefined for it.
4585
+ *
4586
+ * The second list does not read the name (`ownForm`), so no part of it reads the target. A push of a part that
4587
+ * fails stops the step, and an error of a step is the error of the loop. Thus no part reads such a target after it.
4588
+ * The target goes into `w` after the last push, so an error before it does not change `w`.
4589
+ */
4590
+ #ownPush(list: Code, right: Expr, strict: boolean, ctx: Ctx, owner: Owner): Code | undefined {
4591
+ if ((right.tag === "app" && right.op === "fill") || !this.#pushes(right, ctx)) return undefined;
4592
+ // In a sheet with a search, a part that reads a cell does not fuse, as in `#appendStrict`.
4593
+ if (this.#sheet !== undefined && !this.#sheet.direct && readsCells(right)) return undefined;
4594
+ const w = (owner.w ??= this.fresh("w"));
4595
+ const o = this.fresh("o");
4596
+ const info = list.v.list as ListInfo;
4597
+ const target = owner.sure ? list.v.code : this.#clean(info) ? `${this.use("AWC")}(${list.v.code}, ${w})` : `${this.use("AW")}(${list.v.code}, ${String(strict)}, ${w})`;
4598
+ const items = this.#push(right, ctx, o, strict);
4599
+ const s = [...list.s, `const ${o} = ${target};`, ...items.s, ...(owner.sure ? [] : [`${w} = ${o};`])];
4600
+ // The target has only items with values, and the loop holds it, so it is clean and not fresh.
4601
+ const facts: ListInfo = { ...joinLists(info, items.list as ListInfo, "append"), clean: true, fresh: false };
4602
+ return { s, v: { code: o, kind: undefined, safe: false, deps: new Set([...list.v.deps, ...items.deps]), list: facts } };
4603
+ }
4604
+
4605
+ /**
4606
+ * This method gives the code of a list op of `#build`, with the variable `w` of an append into its own list. The clean
4607
+ * form applies when the facts prove each list that the helper scans clean (COMPILE.MODULE.FUSE.CLEAN). Then the
4608
+ * helper has no scan of V and no option strict. The append of two clean lists is `concat`. `get` scans no list, so
4609
+ * it has no clean form.
4610
+ */
4611
+ #buildCode(op: string, parts: readonly Code[], strict: boolean, w: string | undefined, push?: { readonly item: string; readonly sure: boolean }): string {
4612
+ const [l, o] = parts as [Code, Code | undefined];
4613
+ const codes = parts.map((x) => x.v.code);
4614
+ const info = l.v.list as ListInfo;
4615
+ // flat scans the list and each list of its items. An empty list has no items.
4616
+ const clean = op === "flat" ? this.#clean(info) && (info.inner === undefined || this.#clean(info.inner)) : op !== "get" && this.#clean(info) && (o?.v.list === undefined || this.#clean(o.v.list));
4617
+ if (w !== undefined) {
4618
+ // A list that is the array of w gets the one item with a push (COMPILE.MODULE.FUSE.ADOPT). With `sure`, the list is
4619
+ // that array. Else AI or AIC pushes the item into w, or into a copy of another list, with no list of fill
4620
+ // (COMPILE.MODULE.APPEND.PUSH).
4621
+ if (push?.sure === true) return `(${l.v.code}.push(${push.item}), ${w})`;
4622
+ if (push !== undefined) return clean ? `(${w} = ${this.use("AIC")}(${l.v.code}, ${push.item}, ${w}))` : `(${w} = ${this.use("AI")}(${l.v.code}, ${push.item}, ${String(strict)}, ${w}))`;
4623
+ return clean ? `(${w} = ${this.use("AOC")}(${[...codes, w].join(", ")}))` : `(${w} = ${this.use("AO")}(${[...codes, String(strict), w].join(", ")}))`;
4624
+ }
4625
+ if (!clean) return `${this.use(BUILD_HELPERS[op] as BuildHelper)}(${[...codes, String(strict)].join(", ")})`;
4626
+ if (op === "append") return `${l.v.code}.concat(${(o as Code).v.code})`;
4627
+ return `${this.use(`${BUILD_HELPERS[op] as "WO" | "FL" | "IX"}C`)}(${codes.join(", ")})`;
2618
4628
  }
2619
4629
 
2620
4630
  /** This method prints a list op over a list that is not an each: a loop over its array, and nth (LIST.NTH). */
2621
4631
  #overList(op: string, head: Expr, rest: readonly Expr[], ctx: Ctx): Code {
4632
+ // The count of a range of fill is the checked count, with no array (COMPILE.MODULE.FILL.RANGE).
4633
+ const range = op === "count" && rest.length === 0 ? this.#range(head, ctx) : undefined;
4634
+ if (range !== undefined) return { s: range.s, v: { ...range.count, list: undefined } };
2622
4635
  const list = this.#listOf(head, ctx);
2623
4636
  // A missing position is the literal null, which is not a whole number, so nth gives its error.
2624
4637
  const exprs = [head, ...(op === "nth" ? [rest[0] ?? lit(null)] : [])];
@@ -2628,15 +4641,19 @@ class Printer {
2628
4641
  const parts = this.#inOrder(this.#settle(raw, deps, exprs), true);
2629
4642
  const [l] = parts as [Code];
2630
4643
  const { item, inner } = list.v.list as ListInfo;
4644
+ // A clean list is its own array of items with values, so the clean form reads it with no VW and no test of the
4645
+ // sentinel (COMPILE.MODULE.FUSE.CLEAN). strict cannot fail.
4646
+ const clean = this.#clean(list.v.list);
2631
4647
  // The value of an item of a list of lists is a list, so nth and first give a list (LIST.FLAT).
2632
- 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, list: inner } };
4648
+ if (op === "nth") return { s: stmtsOf(...parts), v: { code: clean ? `${this.use("NTC")}(${parts.map((x) => x.v.code).join(", ")})` : `${this.use("NT")}(${[...parts.map((x) => x.v.code), String(strict)].join(", ")})`, kind: item, safe: false, deps, list: inner } };
2633
4649
  // count and first read the items with values on the array of the list, as nth does (COMPILE.MODULE.NTH.INDEX). Thus
2634
- // a step of a loop that counts a list of n items costs O(1) after the first count.
2635
- if (op === "count") return { s: l.s, v: { code: `${this.use("CT")}(${l.v.code}, ${String(strict)})`, kind: "number", safe: false, deps, list: undefined } };
2636
- if (op === "first") return { s: l.s, v: { code: `${this.use("FS")}(${l.v.code}, ${String(strict)})`, kind: item, safe: false, deps, list: inner } };
4650
+ // a step of a loop that counts a list of n items costs O(1) after the first count. The length of an array cannot throw.
4651
+ if (op === "count") return { s: l.s, v: clean ? { code: `${l.v.code}.length`, kind: "number", safe: l.v.safe, deps, list: undefined } : { code: `${this.use("CT")}(${l.v.code}, ${String(strict)})`, kind: "number", safe: false, deps, list: undefined } };
4652
+ if (op === "first") return { s: l.s, v: { code: clean ? `${this.use("FSC")}(${l.v.code})` : `${this.use("FS")}(${l.v.code}, ${String(strict)})`, kind: item, safe: false, deps, list: inner } };
2637
4653
  const r = this.#reduction(op, item, step);
2638
4654
  const { v } = r;
2639
- const s = [...l.s, r.init, `for (const [, ${v}] of ${l.v.code}) {`, ` if (${v} === E) ${strict ? `${this.use("F")}();` : "continue;"}`, ` ${r.step}`, "}"];
4655
+ const test = clean ? [] : [` if (${v} === E) ${strict ? `${this.use("F")}();` : "continue;"}`];
4656
+ const s = [...l.s, r.init, `for (const [, ${v}] of ${l.v.code}) {`, ...test, ` ${r.step}`, "}"];
2640
4657
  return { s, v: { code: r.result, kind: r.kind, safe: false, deps, list: op === "first" ? inner : undefined } };
2641
4658
  }
2642
4659
 
@@ -2645,74 +4662,192 @@ class Printer {
2645
4662
  * node. Inside the loop, each name has the level `loop`. Thus a part that reads a name stays in the loop. A loop that
2646
4663
  * reads no key of the run is a constant of the run.
2647
4664
  */
2648
- #loopNames(init: Names, step: Names, ctx: Ctx, loop: number): { readonly s: string[]; readonly env: Map<string, Name>; readonly vars: ReadonlyMap<string, Name>; readonly deps: Set<number> } {
4665
+ #loopNames(init: Names, step: Names, ctx: Ctx, loop: number, items: readonly string[] = []): { readonly s: string[]; readonly env: Map<string, Name>; readonly vars: ReadonlyMap<string, Name>; readonly deps: Set<number>; readonly adopt: ReadonlySet<string> } {
2649
4666
  const s: string[] = [];
2650
4667
  const env = new Map(ctx.env);
2651
4668
  const vars = new Map<string, Name>();
2652
4669
  const deps = new Set<number>();
2653
- // A step with a list literal or fill can give a name the keys of the literal or of fill (LOOP.LIST).
2654
- const keyed = Object.values(step).some(hasTextKeys);
2655
- for (const [name, x] of Object.entries(init)) {
4670
+ // A step with a list literal, fill or an op with a list result can give a name keys that are not positions (LOOP.LIST).
4671
+ const keyed = Object.values(step).some((x) => hasTextKeys(x, (name) => this.#facts.givesList(name)));
4672
+ const firsts = Object.entries(init).map(([name, x]): [string, Code, string] => {
2656
4673
  // A name of a loop can hold a list (LOOP.LIST). Its first list fixes the kind of the items, if it has one.
2657
4674
  this.#wantList.add(x);
2658
4675
  const c = this.expr(x, ctx);
2659
- const facts = c.v.list;
2660
- if (c.v.kind === undefined && facts === undefined) throw new NotStandalone(`the first value of the name "${name}" of a loop has no kind`);
4676
+ if (c.v.kind === undefined && c.v.list === undefined) throw new NotStandalone(`the first value of the name "${name}" of a loop has no kind`);
2661
4677
  const v = this.fresh("l");
2662
4678
  s.push(...c.s, `let ${v} = ${c.v.code};`);
2663
- const list = facts === undefined ? undefined : { item: facts.item, inner: facts.inner, texts: facts.texts === true || keyed };
4679
+ for (const d of c.v.deps) deps.add(d);
4680
+ return [name, c, v];
4681
+ });
4682
+ const clean = cleanNames(new Map(firsts.map(([name, c]) => [name, c.v.list?.clean === true])), step, items, (name) => ctx.env.get(name)?.list?.clean === true);
4683
+ for (const [name, c, v] of firsts) {
4684
+ const facts = c.v.list;
4685
+ // A step can give the items of a list a new value, so the facts of fusion of the items do not stay.
4686
+ const list = facts === undefined ? undefined : { ...this.#startItems(facts, step[name] as Expr), texts: facts.texts === true || keyed, clean: clean.has(name) };
2664
4687
  const read: Name = { code: v, kind: c.v.kind, lazy: false, deps: new Set([loop]), list };
2665
4688
  env.set(name, read);
2666
4689
  vars.set(name, read);
2667
- for (const d of c.v.deps) deps.add(d);
2668
4690
  }
2669
- return { s, env, vars, deps };
4691
+ // With fuse, an append into the list of a name can take a first list that is clean and fresh as its own array
4692
+ // (COMPILE.MODULE.FUSE.ADOPT).
4693
+ const adopt = new Set(this.#fuse ? firsts.flatMap(([name, c]) => (adoptable(c.v.list) ? [name] : [])) : []);
4694
+ return { s, env, vars, deps, adopt };
4695
+ }
4696
+
4697
+ /**
4698
+ * This method gives the facts of the items of a name of a loop with the first list `facts` and the step `x`. The step
4699
+ * can decide the items of an empty first list (COMPILE.MODULE.LOOP.EMPTY).
4700
+ */
4701
+ #startItems(facts: ListInfo, x: Expr): Pick<ListInfo, "item" | "inner" | "empty"> {
4702
+ const start = facts.empty === true;
4703
+ const { item, inner } = (start ? this.#starts.found.get(x) : undefined) ?? facts;
4704
+ return { item, inner: plainList(inner), empty: start && this.#starts.seek };
2670
4705
  }
2671
4706
 
2672
4707
  /**
2673
4708
  * This method gives the statements of one step of a loop: each new value first, and then each name gets its value.
2674
- * `init` has the statements before the loop: the variable of each name that appends to its own list
2675
- * (COMPILE.MODULE.APPEND.OWN). Each such name has the form of `ownForm`, and no step of another name and no `until`
2676
- * reads it. The tests of a fold read only the names outside the fold, so they cannot read it.
4709
+ * `owners` has each name that appends to its own list (COMPILE.MODULE.APPEND.OWN). Each such name has the form of
4710
+ * `ownForm`, and no `until` reads it. The tests of a fold read only the names outside the fold, so they cannot read it.
4711
+ * A name in `adopt` has a first list that its appends can take (COMPILE.MODULE.FUSE.ADOPT).
4712
+ *
4713
+ * A step of another name can read it only before the step of the name, and only by `readsOnly`
4714
+ * (COMPILE.MODULE.APPEND.READ). The steps print in their order, so such a read ends before the first push.
4715
+ *
4716
+ * A step that is not such a form can be a wide form of `ownForm` with an append (COMPILE.MODULE.APPEND.OTHER). Each
4717
+ * step of another name that reads it must read it by `readsOnly`. A step of the name that such a read follows prints
4718
+ * after the other steps (COMPILE.MODULE.APPEND.LATE). The order must keep each read of each owner before its step.
4719
+ * These wide forms apply only with fuse.
2677
4720
  */
2678
- #loopStep(step: Names, inner: Ctx, vars: ReadonlyMap<string, Name>, until?: Expr): { readonly s: string[]; readonly deps: ReadonlySet<number>; readonly init: readonly string[] } {
4721
+ #loopStep(step: Names, inner: Ctx, vars: ReadonlyMap<string, Name>, adopt: ReadonlySet<string>, until?: Expr): LoopStep {
2679
4722
  const owners: Owner[] = [];
2680
4723
  const nodes: Expr[] = [];
2681
4724
  const steps = Object.entries(step);
4725
+ const keys = steps.map(([k]) => k);
4726
+ const found = new Map<string, { readonly own: readonly Expr[]; readonly lets: readonly Expr[] }>();
4727
+ const wide: { readonly name: string; readonly own: readonly Expr[]; readonly lets: readonly Expr[]; readonly late: boolean }[] = [];
4728
+ for (const [i, [name, x]] of steps.entries()) {
4729
+ const own: Expr[] = [];
4730
+ const lets: Expr[] = [];
4731
+ const read = (y: Expr): boolean => namesOf(y).has(name);
4732
+ if (until !== undefined && read(until)) continue;
4733
+ const others = steps.filter(([k, y], j) => k !== name && read(y) && !(j < i && readsOnly(y, name)));
4734
+ if (ownForm(x, name, own, lets) && others.length === 0) {
4735
+ found.set(name, { own, lets });
4736
+ continue;
4737
+ }
4738
+ // The wide forms need fuse, so fuse false prints the module of the version before fusion (COMPILE.MODULE.FUSE.OFF).
4739
+ if (!this.#fuse || !steps.every(([k, y]) => k === name || !read(y) || readsOnly(y, name))) continue;
4740
+ const more: Expr[] = [];
4741
+ const moreLets: Expr[] = [];
4742
+ if (!ownForm(x, name, more, moreLets, true) || more.length === 0) continue;
4743
+ wide.push({ name, own: more, lets: moreLets, late: steps.some(([k, y], j) => j > i && k !== name && read(y)) });
4744
+ }
4745
+ // The steps of the late names print last, in their order. Each read of an owner must come before its step.
4746
+ const orderOf = (late: readonly string[]): readonly string[] => [...keys.filter((k) => !late.includes(k)), ...late];
4747
+ const keepsReads = (names: readonly string[], order: readonly string[]): boolean =>
4748
+ names.every((n) => steps.every(([k, y]) => k === n || !namesOf(y).has(n) || order.indexOf(k) < order.indexOf(n)));
4749
+ let late: readonly string[] = [];
4750
+ for (const w of wide) {
4751
+ const next = w.late ? [...late, w.name] : late;
4752
+ if (!keepsReads([...found.keys(), w.name], orderOf(next))) continue;
4753
+ found.set(w.name, w);
4754
+ late = next;
4755
+ }
2682
4756
  for (const [name, x] of steps) {
4757
+ const f = found.get(name);
4758
+ if (f === undefined) continue;
4759
+ // The variable starts with the first list, and each value of the step is that list or the value of an append that
4760
+ // pushes into it. Thus each append of the name gets the array of the variable (COMPILE.MODULE.FUSE.ADOPT). The body
4761
+ // of a let of COMPILE.MODULE.APPEND.LET can give another list.
4762
+ const owner: Owner = { name, read: vars.get(name) as Name, w: undefined, adopt: adopt.has(name), sure: adopt.has(name) && f.lets.length === 0 && !shadows(x, name) };
4763
+ for (const node of f.own) this.#own.set(node, owner);
4764
+ owners.push(owner);
4765
+ nodes.push(...f.own);
4766
+ // A branch of another list can be a filter of the list of the name (COMPILE.MODULE.APPEND.KEEP).
4767
+ for (const node of keepsOf(f.lets, name)) {
4768
+ this.#keeps.set(node, owner);
4769
+ nodes.push(node);
4770
+ }
4771
+ }
4772
+ try {
4773
+ return { ...this.#steps(step, inner, vars, orderOf(late)), owners };
4774
+ } finally {
4775
+ for (const node of nodes) {
4776
+ this.#own.delete(node);
4777
+ this.#keeps.delete(node);
4778
+ }
4779
+ }
4780
+ }
4781
+
4782
+ /**
4783
+ * This method prints the result of a loop. With fuse, an append of the result to the list of an owner appends into
4784
+ * the array of the loop (COMPILE.MODULE.FUSE.ADOPT). The form of the result is the form of `lastForm`, so no part
4785
+ * reads the old list after the append. Only an owner whose step made its variable can do so, because the variable
4786
+ * holds only arrays that no other part holds. Each part of the result outside the form does not read the name. Thus
4787
+ * an inner loop there has no node and no relay of the form.
4788
+ */
4789
+ #loopResult(result: Expr, ctx: Ctx, owners: readonly Owner[]): Code {
4790
+ const nodes: Expr[] = [];
4791
+ const lets: Expr[] = [];
4792
+ for (const owner of this.#fuse ? owners : []) {
2683
4793
  const own: Expr[] = [];
2684
- const others = [...steps.filter(([k]) => k !== name).map(([, y]) => y), ...(until === undefined ? [] : [until])];
2685
- if (!ownForm(x, name, own) || others.some((y) => namesOf(y).has(name))) continue;
2686
- const owner: Owner = { name, read: vars.get(name) as Name, w: undefined };
4794
+ const relays = new Map<Expr, Relay>();
4795
+ if (owner.w === undefined || !lastForm(result, owner.name, own, relays)) continue;
2687
4796
  for (const node of own) this.#own.set(node, owner);
2688
- owners.push(owner);
4797
+ for (const [l, r] of relays) this.#relays.set(l, { ...r, owner });
2689
4798
  nodes.push(...own);
4799
+ lets.push(...relays.keys());
2690
4800
  }
2691
4801
  try {
2692
- const { s, deps } = this.#steps(step, inner, vars);
2693
- return { s, deps, init: owners.flatMap((o) => (o.w === undefined ? [] : [`let ${o.w} = null;`])) };
4802
+ return this.expr(result, ctx);
2694
4803
  } finally {
2695
4804
  for (const node of nodes) this.#own.delete(node);
4805
+ for (const l of lets) {
4806
+ for (const node of (this.#relays.get(l) as Relay).nodes) this.#own.delete(node);
4807
+ this.#relays.delete(l);
4808
+ }
2696
4809
  }
2697
4810
  }
2698
4811
 
2699
- /** This method gives the statements of one step of a loop, without the variables of COMPILE.MODULE.APPEND.OWN. */
2700
- #steps(step: Names, inner: Ctx, vars: ReadonlyMap<string, Name>): { readonly s: string[]; readonly deps: ReadonlySet<number> } {
4812
+ /**
4813
+ * This method gives the statements before a loop: the variable of each owner that its appends use. The variable of an
4814
+ * owner with `adopt` starts with the array of the first list (COMPILE.MODULE.FUSE.ADOPT), and each other one with null.
4815
+ */
4816
+ #ownVars(owners: readonly Owner[]): readonly string[] {
4817
+ return owners.flatMap((o) => (o.w === undefined ? [] : [`let ${o.w} = ${o.adopt ? o.read.code : "null"};`]));
4818
+ }
4819
+
4820
+ /**
4821
+ * This method gives the statements of one step of a loop, without the variables of COMPILE.MODULE.APPEND.OWN. It also
4822
+ * gives the statements of each name alone, for the rest of a fold after its exit (`#foldExit`). The steps print in the
4823
+ * order of `order` (COMPILE.MODULE.APPEND.LATE).
4824
+ */
4825
+ #steps(step: Names, inner: Ctx, vars: ReadonlyMap<string, Name>, order: readonly string[]): { readonly s: string[]; readonly deps: ReadonlySet<number>; readonly parts: readonly StepPart[] } {
2701
4826
  const s: string[] = [];
2702
4827
  const sets: string[] = [];
4828
+ const parts: StepPart[] = [];
2703
4829
  const deps = new Set<number>();
2704
- for (const [name, x] of Object.entries(step)) {
4830
+ for (const name of order) {
4831
+ const x = step[name] as Expr;
2705
4832
  this.#wantList.add(x);
2706
4833
  const c = this.#hoist(this.expr(x, inner), hasLoop(x));
2707
4834
  const v = vars.get(name) as Name;
2708
4835
  if (c.v.kind !== v.kind || (c.v.list === undefined) !== (v.list === undefined)) throw new NotStandalone(`a step of a loop changes the kind of the name "${name}"`);
4836
+ if (v.list?.empty === true) this.#noteStart(x, c.v.list as ListInfo);
2709
4837
  if (v.list !== undefined && !fits(v.list, c.v.list as ListInfo)) throw new NotStandalone(`a step of a loop gives the name "${name}" a list that does not fit its first list`);
2710
4838
  const t = this.fresh("t");
2711
- s.push(...c.s, `const ${t} = ${c.v.code};`);
4839
+ const value = [...c.s, `const ${t} = ${c.v.code};`];
4840
+ s.push(...value);
2712
4841
  sets.push(`${v.code} = ${t};`);
4842
+ parts.push({ name, s: value, set: `${v.code} = ${t};`, safe: c.v.safe });
2713
4843
  for (const d of c.v.deps) deps.add(d);
2714
4844
  }
2715
- return { s: [...s, ...sets], deps };
4845
+ return { s: [...s, ...sets], deps, parts };
4846
+ }
4847
+
4848
+ /** This method keeps the items of the list that the step `x` gives to a name that starts empty (COMPILE.MODULE.LOOP.EMPTY). */
4849
+ #noteStart(x: Expr, list: ListInfo): void {
4850
+ if (list.item !== undefined || list.inner !== undefined) this.#starts.found.set(x, { item: list.item, inner: list.inner });
2716
4851
  }
2717
4852
 
2718
4853
  /**
@@ -2724,20 +4859,38 @@ class Printer {
2724
4859
  const loop = this.#loops++;
2725
4860
  const names = this.#loopNames(e.init, e.step, ctx, loop);
2726
4861
  const inner: Ctx = { ...ctx, env: names.env };
4862
+ // The data limit reads the names outside the loop, after the first values (ITERATE.LIMIT.DATA).
4863
+ const limit = this.#limit(e, ctx);
2727
4864
  // A loop at a place that takes a list gives its result there (LOOP.LIST).
2728
4865
  if (this.#wantList.has(e)) this.#wantList.add(e.result);
2729
4866
  const until = e.until === undefined ? undefined : this.expr(e.until, inner);
2730
- const step = this.#loopStep(e.step, inner, names.vars, e.until);
2731
- const result = this.expr(e.result, inner);
4867
+ const step = this.#loopStep(e.step, inner, names.vars, names.adopt, e.until);
4868
+ const result = this.#loopResult(e.result, inner, step.owners);
2732
4869
  const k = this.fresh("k");
2733
4870
  const body = [
2734
4871
  ...(until === undefined ? [] : [...until.s, `if (${this.#boolean(until.v)}) break;`]),
2735
- `if (${k} === ${String(e.limit)}) ${until === undefined ? "break;" : `${this.use("F")}();`}`,
4872
+ `if (${k} === ${limit.code}) ${until === undefined ? "break;" : `${this.use("F")}();`}`,
2736
4873
  ...step.s,
2737
4874
  ];
2738
4875
  const inside = [...(until?.v.deps ?? []), ...step.deps, ...result.v.deps].filter((d) => d !== loop);
2739
- const deps = new Set([...names.deps, ...inside]);
2740
- return { s: [...names.s, ...step.init, `for (let ${k} = 0; ; ${k}++) {`, ...ind(body), "}", ...result.s], v: { code: result.v.code, kind: result.v.kind, safe: false, deps, list: result.v.list } };
4876
+ const deps = new Set([...names.deps, ...limit.deps, ...inside]);
4877
+ return { s: [...names.s, ...limit.s, ...this.#ownVars(step.owners), `for (let ${k} = 0; ; ${k}++) {`, ...ind(body), "}", ...result.s], v: { code: result.v.code, kind: result.v.kind, safe: false, deps, list: result.v.list } };
4878
+ }
4879
+
4880
+ /**
4881
+ * The number of steps of an iteration. A data limit is the strict count of the targets of its axis. An error of the
4882
+ * axis, of a test or of an item throws. A count above the cap throws too (ITERATE.LIMIT.ERROR). A count that reads no
4883
+ * key is a constant of the run, so each key reads one value and not the targets (COMPILE.MODULE.LIMIT.ONCE).
4884
+ */
4885
+ #limit(e: ExprOf<"iterate">, ctx: Ctx): { readonly s: readonly string[]; readonly code: string; readonly deps: ReadonlySet<number> } {
4886
+ const [targets] = splitLimit(e) ?? [];
4887
+ if (targets === undefined) {
4888
+ const limit = e.limit as number;
4889
+ return { s: [], code: String(limit), deps: new Set() };
4890
+ }
4891
+ const count = this.#hoist(this.expr(app("count", targets, lit({ strict: true })), ctx), true);
4892
+ const n = this.fresh("n");
4893
+ return { s: [...count.s, `const ${n} = ${count.v.code};`, `if (${n} > ${String(MAX_ITERATIONS)}) ${this.use("F")}();`], code: n, deps: count.v.deps };
2741
4894
  }
2742
4895
 
2743
4896
  /**
@@ -2747,7 +4900,8 @@ class Printer {
2747
4900
  #fold(e: ExprOf<"fold">, ctx: Ctx): Code {
2748
4901
  // Stryker disable next-line UpdateOperator: a level of a loop is a name, so a count down gives other names, and the same code
2749
4902
  const loop = this.#loops++;
2750
- const names = this.#loopNames(e.init, e.step, ctx, loop);
4903
+ // The names of the items hide the names outside the fold in the steps (AXIS.LIST.SCOPE).
4904
+ const names = this.#loopNames(e.init, e.step, ctx, loop, e.as);
2751
4905
  if (this.#wantList.has(e)) this.#wantList.add(e.result);
2752
4906
  const t = this.#targetLoop(e.axis, e.at ?? [], ctx, e.as);
2753
4907
  const tests = t.tests.map((x) => this.#hoist(this.expr(x, t.inner), hasLoop(x)));
@@ -2755,19 +4909,141 @@ class Printer {
2755
4909
  if (tests.some((x) => x.v.deps.has(CELLS))) throw new NotStandalone("a test of the axis of a fold reads a cell");
2756
4910
  // Only the steps see the names of the items (AXIS.LIST.SCOPE). A name of `as` is not a name of `init`, so the read of
2757
4911
  // each name of the fold stays its read, and an append into its own list keeps its owner (COMPILE.MODULE.APPEND.OWN).
2758
- const step = this.#loopStep(e.step, { ...t.inner, env: withNames(names.env, t.items) }, names.vars);
2759
- this.#readsNoTarget(t.texts, t.inner.level, [...tests.map((x) => x.v.deps), step.deps]);
2760
- const result = this.expr(e.result, { ...ctx, env: names.env });
2761
- const body = [
4912
+ const stepCtx: Ctx = { ...t.inner, env: withNames(names.env, t.items) };
4913
+ const first = this.#loopStep(e.step, stepCtx, names.vars, names.adopt);
4914
+ this.#readsNoTarget(t.texts, t.inner.level, [...tests.map((x) => x.v.deps), first.deps]);
4915
+ const result = this.#loopResult(e.result, { ...ctx, env: names.env }, first.owners);
4916
+ const scan = this.#scan(e, { loop, names, t, test: tests[0], step: first, result });
4917
+ if (scan !== undefined) return scan;
4918
+ // A fold over all the records can read the packs of its columns (COMPILE.MODULE.PAIRS).
4919
+ const packed = this.#packedSteps(e, t, stepCtx, names, first);
4920
+ const step = packed?.step ?? first;
4921
+ const item = [
2762
4922
  ...t.key,
2763
4923
  ...(t.skip === undefined ? [] : [`if (${t.j} === ${t.skip}) continue;`]),
2764
4924
  ...t.check,
2765
4925
  ...tests.flatMap((c) => [...c.s, `if (!${this.#boolean(c.v)}) continue;`]),
2766
- ...step.s,
2767
4926
  ];
4927
+ const body = [...item, ...step.s, ...this.#foldExit(e, t, item, tests, step, names.vars, result)];
2768
4928
  const inside = [...tests.flatMap((c) => [...c.v.deps]), ...step.deps].filter((d) => d !== loop && d !== t.inner.level && d !== t.item);
2769
4929
  const deps = new Set([...names.deps, ...t.start, ...inside, ...[...result.v.deps].filter((d) => d !== loop)]);
2770
- return { s: [...names.s, ...step.init, ...t.s, t.head, ...ind(body), "}", ...result.s], v: { code: result.v.code, kind: result.v.kind, safe: false, deps, list: result.v.list } };
4930
+ return { s: [...names.s, ...this.#ownVars(step.owners), ...t.s, ...(packed?.lets ?? []), t.head, ...ind(body), "}", ...result.s], v: { code: result.v.code, kind: result.v.kind, safe: false, deps, list: result.v.list } };
4931
+ }
4932
+
4933
+ /**
4934
+ * This method gives the second print of the steps of a fold over all the records (COMPILE.MODULE.PAIRS), or
4935
+ * undefined. The axis has no test, no address and no reverse order, and no name holds a list. The second print reads
4936
+ * the pack of a column at the focus of the fold and of each loop in its steps. A column of the function that the
4937
+ * printer prints has a pack too, which each call makes again.
4938
+ *
4939
+ * Each call at such a focus is the body of its function at the place of the call (`#inline`). A pack holds the value
4940
+ * or the sentinel of the column at each record. Thus each read gives the value of a read of the column. Where the
4941
+ * second print fails, the fold keeps its first print.
4942
+ */
4943
+ #packedSteps(e: ExprOf<"fold">, t: { readonly j: string; readonly fixed: boolean; readonly tests: readonly Expr[] }, inner: Ctx, names: { readonly vars: ReadonlyMap<string, Name>; readonly adopt: ReadonlySet<string> }, first: LoopStep): { readonly step: LoopStep; readonly lets: readonly string[] } | undefined {
4944
+ if (this.#pack !== undefined || testsOf(e.axis).base.t !== "all" || !t.fixed || t.tests.length > 0 || first.owners.length > 0) return undefined;
4945
+ if ([...names.vars.values()].some((x) => x.list !== undefined)) return undefined;
4946
+ // The first print must read a column that can have a pack: a column of the run, or a column of this function.
4947
+ const scope = this.#scopes.at(-1);
4948
+ const read = first.s.join("\n");
4949
+ const columns = [...this.#runColumns.keys(), ...[...this.#callColumns].flatMap(([name, c]) => (c.scope === scope ? [name] : []))];
4950
+ if (!columns.some((name) => read.includes(`${name}(`))) return undefined;
4951
+ const pack: Pack = { foci: new Set([t.j]), calls: true, cols: new Map(), locals: new Set(), inlines: 0 };
4952
+ const scopes = this.#scopes.length;
4953
+ const outer = this.#inside;
4954
+ this.#pack = pack;
4955
+ let step: LoopStep;
4956
+ try {
4957
+ step = this.#loopStep(e.step, inner, names.vars, names.adopt);
4958
+ } catch (err) {
4959
+ if (!(err instanceof NoPack || err instanceof NotStandalone)) throw err;
4960
+ this.#scopes.length = scopes;
4961
+ this.#inside = outer;
4962
+ return undefined;
4963
+ } finally {
4964
+ this.#pack = undefined;
4965
+ }
4966
+ const text = step.s.join("\n");
4967
+ return { step, lets: this.#packLets([...pack.cols].filter(([, local]) => text.includes(`${local}[`))) };
4968
+ }
4969
+
4970
+ /**
4971
+ * This method gives the exit of a fold (COMPILE.MODULE.EXIT): the statements after each step, or none. A name whose
4972
+ * step is `and(name, ...)` stops at false, and a name whose step is `or(name, ...)` stops at true. Then each later
4973
+ * step of the name gives the same value and evaluates no other argument. When each such name stops, the loop leaves.
4974
+ * The rest of the targets runs only the steps of the other names, with the checks and the tests of each target. Thus
4975
+ * an error of a later target is still the error of the fold. When these steps cannot throw and the result does not
4976
+ * read their names, the loop leaves at once.
4977
+ */
4978
+ #foldExit(e: ExprOf<"fold">, t: { readonly parts: ForParts; readonly checkSafe: boolean }, item: readonly string[], tests: readonly Code[], step: LoopStep, vars: ReadonlyMap<string, Name>, result: Code): string[] {
4979
+ if (step.owners.length > 0) return [];
4980
+ const stops: string[] = [];
4981
+ const rest: StepPart[] = [];
4982
+ for (const p of step.parts) {
4983
+ const stop = stopOf(e.step[p.name] as Expr, p.name);
4984
+ if (stop === undefined) rest.push(p);
4985
+ else stops.push(`${stop ? "" : "!"}${(vars.get(p.name) as Name).code}`);
4986
+ }
4987
+ if (stops.length === 0) return [];
4988
+ const test = stops.join(" && ");
4989
+ const reads = [result.v.code, ...result.s].join("\n");
4990
+ // A part with statements of its own can have a loop or a try block, so only a part with one statement is quiet.
4991
+ const quiet =
4992
+ t.checkSafe &&
4993
+ tests.every((c) => c.s.length === 0 && this.#safeBoolean(c.v)) &&
4994
+ rest.every((p) => p.safe && p.s.length === 1 && !new RegExp(String.raw`\b${(vars.get(p.name) as Name).code}\b`).test(reads));
4995
+ if (quiet) return [`if (${test}) break;`];
4996
+ // The rest goes on from the next target, in the order of the loop, with the parts of the head of the loop.
4997
+ const { cond, next } = t.parts;
4998
+ const residual = [...item, ...rest.flatMap((p) => p.s), ...rest.map((p) => p.set)];
4999
+ return [`if (${test}) {`, ...ind([`for (${next}; ${cond}; ${next}) {`, ...ind(residual), "}", "break;"]), "}"];
5000
+ }
5001
+
5002
+ /**
5003
+ * This method gives the code of a fold over the targets before the origin as a scan (COMPILE.MODULE.SCAN), or
5004
+ * undefined. The axis is `where(all, test)`, and the test compares a value `T` of the target with a key of the origin
5005
+ * by `<` or `<=`. The first values, the steps and the result read no key of the run. A run evaluates `T` once at
5006
+ * each record, and each step once at each record. When the values `T` do not decrease, the targets of each origin are
5007
+ * a prefix. A binary search finds it, and each prefix keeps its state. The steps run in the order of the fold, so the
5008
+ * result has the bits of the loop.
5009
+ */
5010
+ #scan(e: ExprOf<"fold">, p: ScanParts): Code | undefined {
5011
+ const { loop, names, t, test, step, result } = p;
5012
+ const level = t.inner.level;
5013
+ const [x] = t.tests;
5014
+ const { base } = testsOf(e.axis);
5015
+ if (base.t !== "all" || (e.at ?? []).length > 0 || e.as !== undefined || t.tests.length !== 1 || x?.tag !== "app" || x.args.length !== 2 || test === undefined) return undefined;
5016
+ // Stryker disable next-line all: for the axis all with no address, #targetLoop gives no statements, key, check or skip, so this test is always false
5017
+ if (t.s.length > 0 || t.key.length > 0 || t.check.length > 0 || t.skip !== undefined) return undefined;
5018
+ // The test reads the target and a key of the origin. The rest reads only the target, the names of the fold and the
5019
+ // constants of the run, so it can evaluate once for each run.
5020
+ if (!test.v.deps.has(level) || within(test.v.deps, [level]) || names.deps.size > 0 || step.owners.length > 0 || !within(step.deps, [loop, level]) || !within(result.v.deps, [loop])) return undefined;
5021
+ if ([...names.vars.values()].some((v) => v.list !== undefined) || result.v.list !== undefined) return undefined;
5022
+ const sides = x.args.map((a) => this.#hoist(this.expr(a, t.inner), hasLoop(a)));
5023
+ const at = sides.findIndex((c) => c.v.deps.size > 0 && !c.v.deps.has(level));
5024
+ const key = sides[at];
5025
+ const value = sides[1 - at];
5026
+ // The search needs an order of the values: `<=` of two numbers or of two texts.
5027
+ if (key === undefined || value === undefined || !within(value.v.deps, [level]) || (value.v.kind !== "number" && value.v.kind !== "string")) return undefined;
5028
+ // The test is an op whose inline form cannot fail, as for the prefixes of a node that keeps its items (`#cached`).
5029
+ const site = this.#facts.staticSite(x.op, sides.map((c) => c.v.kind));
5030
+ if (site?.t !== "fn" || site.bad || site.returns !== "boolean" || this.check("boolean") !== undefined) return undefined;
5031
+ const form = inlineForm(functionText(((this.#domains[site.domain] as AnyDomain).ops[x.op] as { fn: (...a: never[]) => unknown }).fn));
5032
+ if (form?.params.length !== 2) return undefined;
5033
+ // `#0` is the value of the target and `#1` is the key, in the order of the parameters of the op.
5034
+ const pattern = patternOf(form, (i) => (at === 0 ? 1 - i : i));
5035
+ if (!["#0<#1", "#0<=#1", "#1>#0", "#1>=#0"].includes(pattern)) return undefined;
5036
+ const keyTest = form.parts.map((part) => (typeof part === "number" ? `(${at === 0 ? ["q", "t"][part] : ["t", "q"][part]})` : part)).join("");
5037
+ const vars = [...names.vars.values()].map((v) => v.code);
5038
+ const s = this.fresh("s");
5039
+ const pack = vars.length === 1 ? (vars[0] as string) : `[${vars.join(", ")}]`;
5040
+ const unpack = vars.length === 1 ? [`let ${vars[0] as string} = ${s};`] : vars.map((v, i) => `let ${v} = ${s}[${String(i)}];`);
5041
+ const arrow = (params: string, lines: readonly string[], code: string): readonly string[] => (lines.length === 0 ? [`(${params}) => ${code}`] : [`(${params}) => {`, ...ind(lines), ` return ${code};`, "}"]);
5042
+ const fns = [arrow("", names.s, pack), arrow(t.j, value.s, value.v.code), [`(t, q) => ${keyTest}`], arrow(`${s}, ${t.j}`, [...unpack, ...step.s], pack), arrow(s, [...unpack, ...result.s], result.v.code)];
5043
+ const name = this.fresh("P");
5044
+ this.#intoRun([`const ${name} = ${this.use("PF")}(n,`, ...ind(fns.flatMap((f, i) => [...f.slice(0, -1), `${f.at(-1) as string}${i < fns.length - 1 ? "," : ""}`])), ");"]);
5045
+ const q = this.fresh("q");
5046
+ return { s: this.#store(q, key), v: { code: `${name}(${q})`, kind: result.v.kind, safe: false, deps: key.v.deps } };
2771
5047
  }
2772
5048
 
2773
5049
  /**
@@ -2785,12 +5061,12 @@ class Printer {
2785
5061
  keys.map((k, i): [Expr, Name] => {
2786
5062
  const x = (values[i] as Code).v;
2787
5063
  const p = varying.indexOf(k);
2788
- return [k, p < 0 ? this.#nameOf(x) : { code: params[p] as string, kind: x.kind, lazy: true, deps: new Set([1]), list: x.list }];
5064
+ return [k, p < 0 ? this.#nameOf(x) : { code: params[p] as string, kind: x.kind, lazy: true, deps: new Set([1]), list: plainList(x.list) }];
2789
5065
  }),
2790
5066
  );
2791
5067
  const outer = this.#inside;
2792
5068
  this.#inside = e;
2793
- const bodyCtx: Ctx = { origin: undefined, focus: undefined, level: 1, originLevel: 1, env: new Map(), fns: new Map(), keys: names };
5069
+ const bodyCtx: Ctx = { origin: undefined, focus: undefined, level: 1, originLevel: 1, env: new Map(), fns: new Map(), keys: names, columns: new Map() };
2794
5070
  if (varying.length === 0) {
2795
5071
  const body = this.#hoist(this.expr(e, bodyCtx));
2796
5072
  this.#inside = outer;
@@ -2798,24 +5074,24 @@ class Printer {
2798
5074
  }
2799
5075
  // The kinds of the keys decide the ops in the node, so they are a part of the structure. Each key of the function
2800
5076
  // can hold the error sentinel, so the nodes with a safe key and the nodes without one share it.
2801
- const tokens = new Map(keys.map((k, i): [Expr, object] => [k, varying.includes(k) ? { "#": varying.indexOf(k), kind: (values[i] as Code).v.kind, list: (values[i] as Code).v.list } : { "@": (names.get(k) as Name).code }]));
5077
+ const tokens = new Map(keys.map((k, i): [Expr, object] => [k, varying.includes(k) ? { "#": varying.indexOf(k), kind: (values[i] as Code).v.kind, list: plainList((values[i] as Code).v.list) } : { "@": (names.get(k) as Name).code }]));
2802
5078
  const structure = canonical(e, (x) => tokens.get(x as Expr));
2803
5079
  let fn = this.#structures.get(structure);
2804
5080
  if (fn === undefined) {
2805
5081
  fn = this.fresh("m");
2806
- this.#structures.set(structure, fn);
2807
5082
  this.memos = true;
2808
5083
  const cached = varying.length === 1 ? this.#cached(e, varying[0] as Expr, bodyCtx, fn) : undefined;
2809
5084
  if (cached !== undefined) {
2810
5085
  this.#kinds.set(fn, cached.kind);
2811
- this.run.push(...cached.lines);
5086
+ this.#intoRun(cached.lines);
2812
5087
  } else {
2813
5088
  // The loop of the node gives statements.
2814
5089
  const body = this.expr(e, bodyCtx);
2815
5090
  this.#kinds.set(fn, body.v.kind);
2816
- this.#lists.set(fn, body.v.list);
2817
- this.run.push(`const ${fn} = ${this.use(params.length === 1 ? "M1" : "M")}((${params.join(", ")}) => {`, ...ind(body.s), ` return ${body.v.code};`, "});");
5091
+ this.#lists.set(fn, heldList(body.v.list));
5092
+ this.#intoRun([`const ${fn} = ${this.use(params.length === 1 ? "M1" : "M")}((${params.join(", ")}) => {`, ...ind(body.s), ` return ${body.v.code};`, "});"]);
2818
5093
  }
5094
+ this.#structures.set(structure, fn);
2819
5095
  }
2820
5096
  this.#inside = outer;
2821
5097
  // Each key of the function gets its value, or the error sentinel.
@@ -2864,8 +5140,9 @@ class Printer {
2864
5140
  const site = this.#facts.staticSite(test.op, keyFirst ? [kind, t.v.kind] : [t.v.kind, kind]);
2865
5141
  if (site?.t !== "fn" || site.bad || site.returns !== "boolean" || this.check("boolean") !== undefined) return undefined;
2866
5142
  // A static site of a domain has the function of the op of that domain.
2867
- const form = inlineForm(Function.prototype.toString.call(((this.#domains[site.domain] as AnyDomain).ops[test.op] as { fn: (...a: never[]) => unknown }).fn));
2868
- if (form?.params.length !== 2) return undefined;
5143
+ const src = functionText(((this.#domains[site.domain] as AnyDomain).ops[test.op] as { fn: (...a: never[]) => unknown }).fn);
5144
+ const form = inlineForm(src);
5145
+ if (form?.params.length !== 2 || !givesValue(src)) return undefined;
2869
5146
  const before = tests.slice(0, at).map((x) => this.#hoist(this.expr(x, loop)));
2870
5147
  const after = tests.slice(at + 1).map((x) => this.#hoist(this.expr(x, loop)));
2871
5148
  const body = this.#hoist(this.expr(target.body, loop));
@@ -2918,7 +5195,7 @@ class Printer {
2918
5195
  root(expr: Expr): Code {
2919
5196
  // The value of a program and of a cell can be a list (COMPILE.MODULE.LIST.RESULT).
2920
5197
  this.#wantList.add(expr);
2921
- return this.#hoist(this.expr(expr, { origin: "o", focus: "o", level: 1, originLevel: 1, env: new Map(), fns: new Map(), keys: new Map() }));
5198
+ return this.#hoist(this.expr(expr, { origin: "o", focus: "o", level: 1, originLevel: 1, env: new Map(), fns: new Map(), keys: new Map(), columns: new Map() }));
2922
5199
  }
2923
5200
 
2924
5201
  /** This method removes the declarations that no code reads, after the last program. */
@@ -2927,21 +5204,49 @@ class Printer {
2927
5204
  for (const [name, form] of this.#forms) if (form !== undefined && !this.#called.has(name)) this.top.delete(name);
2928
5205
  }
2929
5206
 
2930
- /**
2931
- * This method gives a text that is the same for two expressions with the same structure and the same reads. A name
2932
- * that the expression does not bind gives its variable in the code, and a key of the memo gives its variable too.
2933
- */
5207
+ /** This method gives the key of an expression at the place of `ctx`. Two expressions with one key have one value. */
2934
5208
  #constKey(e: Expr, ctx: Ctx): string {
2935
- // A name gives its variable for each read, also for a read of a name that the expression binds. The variable depends
2936
- // only on the name, so two expressions with the same text have the same value.
2937
- return canonical(e, (x) => {
2938
- const key = ctx.keys.get(x as Expr);
2939
- if (key !== undefined) return { "@": key.code };
2940
- const node = x as Expr | undefined;
2941
- if (node?.tag === "var") return { $: ctx.env.get(node.name)?.code ?? node.name };
2942
- // A call gives the number of the binding of its function, so two functions with one name give two keys.
2943
- return node?.tag === "call" ? { "()": node.fn, of: ctx.fns.get(node.fn)?.id ?? null, args: node.args } : undefined;
2944
- });
5209
+ const key = keyText(e, ctx, this.#keyTable);
5210
+ keyProbe?.(e, ctx, key, this.#keyTable);
5211
+ return key;
5212
+ }
5213
+ }
5214
+
5215
+ /** The function that sees each key of a constant or a column. */
5216
+ export type KeyProbe = (e: Expr, scope: KeyScope, key: string, table: KeyTable) => void;
5217
+
5218
+ /** The function that a test of the keys gives, or undefined when no such test runs. */
5219
+ let keyProbe: KeyProbe | undefined;
5220
+
5221
+ /** This function gives the result of `emit`, and `probe` sees each key of its printers, after each outer probe. The tests of the keys use it. The probe does not change the printed code. */
5222
+ export function withKeyProbe<T>(probe: KeyProbe, emit: () => T): T {
5223
+ const outer = keyProbe;
5224
+ keyProbe = (e, scope, key, table): void => {
5225
+ outer?.(e, scope, key, table);
5226
+ probe(e, scope, key, table);
5227
+ };
5228
+ try {
5229
+ return emit();
5230
+ } finally {
5231
+ keyProbe = outer;
5232
+ }
5233
+ }
5234
+
5235
+ /** The printers that `listFactsOf` collects, or undefined when no test of the analysis runs. */
5236
+ let recorder: Printer[] | undefined;
5237
+
5238
+ /**
5239
+ * This function gives the facts of fusion of each list node of the modules that `emit` prints (COMPILE.MODULE.FUSE.FACTS),
5240
+ * and the result of `emit`. The tests of the analysis use it. The facts do not change the printed code.
5241
+ */
5242
+ export function listFactsOf(emit: () => Emitted): { readonly emitted: Emitted; readonly facts: ReadonlyMap<Expr, ListFacts> } {
5243
+ const printers: Printer[] = [];
5244
+ recorder = printers;
5245
+ try {
5246
+ const emitted = emit();
5247
+ return { emitted, facts: new Map(printers.flatMap((p) => [...p.listFacts()])) };
5248
+ } finally {
5249
+ recorder = undefined;
2945
5250
  }
2946
5251
  }
2947
5252
 
@@ -2951,14 +5256,22 @@ function runOf(options: ModuleOptions): Run | { readonly reason: string } {
2951
5256
  if (!/^[A-Za-z_$][\w$]*$/.test(name)) return { reason: `the name "${name}" is not a JavaScript name` };
2952
5257
  const space = options.space ?? "array";
2953
5258
  if (space !== "array" && space !== "tree" && space !== "graph") return { reason: `the space "${String(space)}" is not "array", "tree" or "graph"` };
2954
- return { name, tree: space === "tree", graph: space === "graph" };
5259
+ // The option fuse changes no code in this version, but a value that is not a boolean is an error of the caller.
5260
+ const fuse: unknown = options.fuse ?? true;
5261
+ if (typeof fuse !== "boolean") return { reason: `the option "fuse" is ${String(fuse)}, not true or false` };
5262
+ const lists: unknown = options.lists ?? "envelope";
5263
+ if (lists !== "envelope" && lists !== "plain") return { reason: `the option "lists" is ${String(lists)}, not "envelope" or "plain"` };
5264
+ const keys: unknown = options.keys ?? false;
5265
+ if (typeof keys !== "boolean") return { reason: `the option "keys" is ${String(keys)}, not true or false` };
5266
+ return { name, tree: space === "tree", graph: space === "graph", plain: lists === "plain" };
2955
5267
  }
2956
5268
 
2957
- /** The function of a module: its name, and its space. */
5269
+ /** The function of a module: its name, its space, and true for the plain form of the lists (COMPILE.MODULE.LIST.PLAIN). */
2958
5270
  interface Run {
2959
5271
  readonly name: string;
2960
5272
  readonly tree: boolean;
2961
5273
  readonly graph: boolean;
5274
+ readonly plain: boolean;
2962
5275
  }
2963
5276
 
2964
5277
  /** This function gives the reason of an error of the printer. Another exception is a defect, so it goes to the caller. */
@@ -2969,17 +5282,37 @@ function reasonOf(thrown: unknown): Emitted {
2969
5282
 
2970
5283
  /**
2971
5284
  * This function gives the code of the check of a field of a record `r` at the position `i`. The check of a list keeps
2972
- * the array of the list when the program reads the field (COMPILE.MODULE.LIST.INPUT). The code is true for a field
2973
- * against the schema.
5285
+ * the array of the list when the program reads the field (COMPILE.MODULE.LIST.INPUT). With `plain`, the field holds a
5286
+ * plain list (COMPILE.MODULE.LIST.PLAIN). With `flat`, the helper has no argument for the depth. The code is true for a
5287
+ * field against the schema.
2974
5288
  */
2975
- function fieldCheck(p: Printer, field: string, kind: Kind | ListKind): string {
5289
+ function fieldCheck(p: Printer, field: string, kind: Kind | ListKind, plain: boolean, flat: boolean): string {
2976
5290
  const input = `r[${JSON.stringify(field)}]`;
2977
5291
  if (typeof kind !== "object") return p.against(kind, input);
2978
- const read = `${p.use("LI")}(${input}, ${String(depthOf(listOfKind(kind)))}, ${p.test(leafOf(kind))})`;
5292
+ const read = listRead(p, input, kind, plain, flat);
2979
5293
  const keep = p.inputs.get(field);
2980
5294
  return `${keep === undefined ? read : `(${keep}[i] = ${read})`} === undefined`;
2981
5295
  }
2982
5296
 
5297
+ /** This function gives the code that reads a list of the input with the helper of its form. With `flat`, the helper has no argument for the depth. */
5298
+ function listRead(p: Printer, input: string, kind: ListKind, plain: boolean, flat: boolean): string {
5299
+ const depth = flat ? "" : `${String(depthOf(listOfKind(kind)))}, `;
5300
+ return `${p.use(plain ? "LA" : "LI")}(${input}, ${depth}${p.test(leafOf(kind))})`;
5301
+ }
5302
+
5303
+ /**
5304
+ * This function gives the code of the check of a variable of the run. The check of a list keeps the array of the list
5305
+ * in the variable of the code when the program reads the variable (COMPILE.MODULE.LIST.VAR). The code is true for a
5306
+ * variable against the schema.
5307
+ */
5308
+ function varCheck(p: Printer, name: string, kind: Kind | ListKind, plain: boolean, flat: boolean): string {
5309
+ const input = `vars[${JSON.stringify(name)}]`;
5310
+ if (typeof kind !== "object") return p.against(kind, input);
5311
+ const read = listRead(p, input, kind, plain, flat);
5312
+ const keep = p.vars.get(name);
5313
+ return `${keep === undefined ? read : `(${keep} = ${read})`} === undefined`;
5314
+ }
5315
+
2983
5316
  /**
2984
5317
  * This function gives the text of a module: the declarations, the helpers, and the function of the run. The run checks
2985
5318
  * its input, computes the parts of the tree and the constants of the run, and then gives the statements `body`.
@@ -2994,42 +5327,34 @@ function printModule(p: Printer, options: ModuleOptions, run: Run, body: readonl
2994
5327
  };
2995
5328
  const fields = Object.entries(options.schema.fields ?? {});
2996
5329
  const vars = Object.entries(options.schema.vars ?? {});
5330
+ // With no other depth, the list helpers have no argument for the depth (COMPILE.MODULE.SIZE.FLAT).
5331
+ const flat = options.fuse !== false && !p.opList && [...fields, ...vars].every(([, k]) => typeof k !== "object" || depthOf(listOfKind(k)) === 0);
2997
5332
  let fieldChecks: string;
2998
5333
  let varChecks: string;
2999
5334
  try {
3000
- fieldChecks = fields.map(([f, k]) => ` || ${fieldCheck(p, f, k)}`).join("");
3001
- varChecks = vars.map(([v, k]) => ` || ${p.against(k, `vars[${JSON.stringify(v)}]`)}`).join("");
5335
+ fieldChecks = fields.map(([f, k]) => ` || ${fieldCheck(p, f, k, run.plain, flat)}`).join("");
5336
+ varChecks = vars.map(([v, k]) => ` || ${varCheck(p, v, k, run.plain, flat)}`).join("");
3002
5337
  } catch (thrown) {
3003
5338
  return reasonOf(thrown);
3004
5339
  }
3005
5340
  const { name, tree, graph } = run;
3006
- // A tree checks its parents, and it computes the parts that the program reads. The siblings and the order need the
3007
- // children.
5341
+ const isListVar = (v: string): boolean => typeof options.schema.vars?.[v] === "object";
5342
+ // A tree checks its parents, and it computes the parts that the program reads. The siblings need the children. The
5343
+ // order reads only the parents (COMPILE.MODULE.TREE.ALLOC).
3008
5344
  if (tree) p.use("PT");
3009
- if (p.treeParts.size > 0) p.treeParts.add("children");
5345
+ if (p.treeParts.has("siblings")) p.treeParts.add("children");
3010
5346
  const parts = (["children", "siblings", "order"] as const).filter((x) => p.treeParts.has(x));
3011
5347
  for (const x of parts) p.use(TREE_PARTS[x][0]);
3012
5348
  // A graph checks its edges, and it computes the predecessors if the program reads them.
3013
5349
  if (graph) p.use("GR");
3014
5350
  if (p.into) p.use("GI");
5351
+ if (p.runKeys) p.use("KC");
3015
5352
  [...p.helpers].toSorted().forEach(add);
3016
- // The names that this module declares at its top: the constants, the helpers and the declarations of the printer.
3017
- const declared = new Set<string>(["VexContractError", "VEX_ERROR", "E", ...(p.memos ? ["Z"] : []), ...(helpers.has("S") ? ["N", "W"] : []), ...helpers, ...p.top.keys()]);
3018
- const bad = nameReason(name, declared);
5353
+ const bad = nameReason(name);
3019
5354
  if (bad !== undefined) return { ok: false, reason: bad };
3020
- const lines = [
3021
- "// Generated by @mark1russell7/vex-compiler from a Vex program. Do not edit.",
3022
- "/** The error of a run whose input does not keep the schema of the program. */",
3023
- "export class VexContractError extends Error {}",
3024
- "/** The value of a key where the program gives an error of Vex. */",
3025
- "export const VEX_ERROR = Object.freeze({ vexError: true });",
3026
- "const E = {};",
3027
- ...(p.memos ? ["const Z = {};"] : []),
3028
- // The values of an item of a node that keeps its items: excluded by a later test, and of the wrong kind.
3029
- ...(helpers.has("S") ? ["const N = {}, W = {};"] : []),
3030
- ...[...helpers].map((h) => (h === "S" ? helperS(p.features) : HELPERS[h])),
3031
- ...p.top.values(),
3032
- `export function ${name}(records, vars${tree ? ", parents" : graph ? ", edges" : ""}) {`,
5355
+ const textOf = (h: Helper): string => (h === "S" ? helperS(p.features) : flat && (h === "LI" || h === "LA") ? FLAT_LIST_HELPERS[h] : HELPERS[h]);
5356
+ const params = `(records, vars${tree ? ", parents" : graph ? ", edges" : ""}${p.runKeys ? ", keys" : ""}) {`;
5357
+ const start = [
3033
5358
  ' if (!Array.isArray(records)) C("the records are not an array");',
3034
5359
  " const R = records;",
3035
5360
  " const n = R.length;",
@@ -3038,16 +5363,78 @@ function printModule(p: Printer, options: ModuleOptions, run: Run, body: readonl
3038
5363
  " const r = R[i];",
3039
5364
  ` if (typeof r !== "object" || r === null${fieldChecks}) C(\`the record \${i} does not keep the schema\`);`,
3040
5365
  " }",
5366
+ ...[...p.vars].filter(([v]) => isListVar(v)).map(([, code]) => ` let ${code};`),
3041
5367
  ` if (typeof vars !== "object" || vars === null${varChecks}) C("the variables do not keep the schema");`,
3042
5368
  ...(tree ? [" const P = PT(parents, n);", ...parts.map((x) => ` ${TREE_PARTS[x][1]}`)] : []),
3043
5369
  ...(graph ? [" const GO = GR(edges, n);", ...(p.into ? [" const GN = GI(GO, n);"] : [])] : []),
3044
- ...[...p.vars].map(([v, code]) => ` const ${code} = vars[${JSON.stringify(v)}];`),
3045
- ...ind(p.run),
3046
- ...ind(body),
5370
+ ...(p.runKeys ? [" const KM = KC(keys, n);"] : []),
5371
+ ...[...p.vars].filter(([v]) => !isListVar(v)).map(([v, code]) => ` const ${code} = vars[${JSON.stringify(v)}];`),
5372
+ ];
5373
+ const all: Tidied = { decls: new Map<string, string>([...[...helpers].map((h) => [h as string, textOf(h)] as const), ...p.top]), lines: [...ind(p.run), ...ind(body)] };
5374
+ // The text with fuse false stays the form of the version before this pass (COMPILE.MODULE.FUSE.OFF). A dropped print still goes, because it can read a name with no declaration (V-086).
5375
+ const small = options.fuse === false ? { ...all, lines: deadConstants(all.lines) } : tidy({ ...all, kept: start.join("\n"), globals: MODULE_GLOBALS }, options.faults);
5376
+ const { decls, lines: statements } = options.faults === "throw" ? keepFaults(small, p.copies) : small;
5377
+ const textWith = (head: string, tail: readonly string[]): string => [
5378
+ "// Generated by @mark1russell7/vex-compiler from a Vex program. Do not edit.",
5379
+ ERROR_NOTE,
5380
+ "export class VexContractError extends Error {}",
5381
+ "/** The value of a key where the program gives an error of Vex. */",
5382
+ "export const VEX_ERROR = Object.freeze({ vexError: true });",
5383
+ "const E = {};",
5384
+ ...(p.memos ? ["const Z = {};"] : []),
5385
+ // The values of an item of a node that keeps its items: excluded by a later test, and of the wrong kind.
5386
+ ...(decls.has("S") ? ["const N = {}, W = {};"] : []),
5387
+ ...decls.values(),
5388
+ `${head}${params}`,
5389
+ ...start,
5390
+ ...statements,
3047
5391
  "}",
5392
+ ...tail,
3048
5393
  "",
3049
- ];
3050
- return { ok: true, source: lines.join("\n") };
5394
+ ].join("\n");
5395
+ // The check reads each line of the module, with the copies of the ops. The function of the run has no name in that text.
5396
+ const code = textWith("function", []);
5397
+ // The parse of the names takes time, so it starts only for a name that is a word of the code. The fixed note holds the word `run`.
5398
+ const inner = wordsOf(code.replace(ERROR_NOTE, "")).includes(name) ? innerName(name, namesOfCode(code)) : name;
5399
+ return { ok: true, source: inner === name ? textWith(`export function ${name}`, []) : textWith(`function ${inner}`, [`export { ${inner} as ${name} };`]) };
5400
+ }
5401
+
5402
+ /**
5403
+ * This function gives the module of a print (COMPILE.MODULE.LOOP.EMPTY). The first print keeps the text of each program
5404
+ * that it can print. After a reason, more prints look for the kinds that the steps give to the names that start empty.
5405
+ * Each print can find more kinds, because a step can read another such name. The last print uses the kinds, so its
5406
+ * checks of the steps prove them. A program without such a kind gets the reason of the first print.
5407
+ */
5408
+ function settledPrint(print: (starts: EmptyStarts) => Emitted): Emitted {
5409
+ const found: EmptyStarts["found"] = new Map();
5410
+ const copies: EmptyStarts["copies"] = new Map();
5411
+ const first = print({ found, copies, seek: false });
5412
+ if (first.ok) return first;
5413
+ for (let size = -1; size !== found.size; ) {
5414
+ size = found.size;
5415
+ print({ found, copies, seek: true });
5416
+ }
5417
+ return print({ found, copies, seek: false });
5418
+ }
5419
+
5420
+ /** This function gives the facts of a node from the facts of two of its places. */
5421
+ const bothPlaces = (a: ListFacts, b: ListFacts): ListFacts => ({ clean: a.clean && b.clean, fresh: a.fresh && b.fresh, inner: b.inner.map((x, i) => x && a.inner[i] === true), reads: Math.max(a.reads, b.reads) });
5422
+
5423
+ /** This function gives the expressions of a program with one object at each place, the same copies for each print of the program. */
5424
+ function copiesOf(program: object, exprs: readonly Expr[], starts: EmptyStarts, shares: boolean): readonly Expr[] {
5425
+ const copies = starts.copies.get(program) ?? unsharedAll(exprs, shares);
5426
+ starts.copies.set(program, copies);
5427
+ return copies;
5428
+ }
5429
+
5430
+ /**
5431
+ * This function prints a module. With the option `keys`, it prints again with the keys of the run when the first print
5432
+ * reads a key (COMPILE.MODULE.KEYS). Thus a program that reads no key keeps its text.
5433
+ */
5434
+ function keyedPrint(options: ModuleOptions, print: (keys: KeyPrint) => Emitted): Emitted {
5435
+ const keys = { keyed: false, read: false };
5436
+ const first = print(keys);
5437
+ return keys.read && options.keys === true ? print({ keyed: true, read: true }) : first;
3051
5438
  }
3052
5439
 
3053
5440
  /**
@@ -3055,28 +5442,45 @@ function printModule(p: Printer, options: ModuleOptions, run: Run, body: readonl
3055
5442
  * function that takes the records and the variables and gives the value at each key. A module of a tree space takes
3056
5443
  * the parents too. The function is pure, so a build can use it. The program can be an expression or a document
3057
5444
  * (DOC.ENTRY).
5445
+ *
5446
+ * This function is a tool of a build. A print of one module of ireko takes 16 to 172 ms on a CI runner, at 0.833 to
5447
+ * 1.149 times the fixed base of COMPILE.MODULE.COST. `docs/COMPILER.md` gives the ms and the ratio of each module. A
5448
+ * limit of that gate holds the cost of today. The target of 1.10 for each module is not proven. A caller on a request
5449
+ * path keeps the printed module, and it does not print for each request.
3058
5450
  */
3059
5451
  export function emitModule(source: Expr | Envelope, options: ModuleOptions): Emitted {
5452
+ return keyedPrint(options, (keys) => settledPrint((starts) => printProgram(source, options, keys, starts)));
5453
+ }
5454
+
5455
+ /** This function prints a program for one state of the keys, with the facts `starts`, for `emitModule`. */
5456
+ function printProgram(source: Expr | Envelope, options: ModuleOptions, keys: KeyPrint, starts: EmptyStarts): Emitted {
3060
5457
  const run = runOf(options);
3061
5458
  if ("reason" in run) return { ok: false, reason: run.reason };
3062
5459
  // DOC.ENTRY: a document gives its expression first, or the reason that it is not valid.
3063
5460
  const read = isDocument(source) ? fromDocument(source, options.domains) : { ok: true as const, value: source };
3064
5461
  if (!read.ok) return { ok: false, reason: read.error.message };
3065
5462
  const expr = read.value;
5463
+ // COMPILE.PLACES: the walks below take the time of the places, so the count comes first.
5464
+ const places = placesRead([expr]);
5465
+ if (places.error !== undefined) return { ok: false, reason: places.error };
3066
5466
  // EVAL.SHAPE: a module of an expression that is not valid has no use, so the printer gives the reason.
3067
5467
  const shape = shapeError(expr);
3068
5468
  if (shape !== undefined) return { ok: false, reason: shape };
3069
- const p = new Printer(expr, options);
5469
+ // COMPILE.MODULE.NESTING, LOOP.SIZE, STEP.MAX: a module refuses the programs that the interpreter refuses.
5470
+ const size = nestingError(expr) ?? sizeError(expr, options) ?? stepError(expr, options) ?? monotoneError(expr, options);
5471
+ if (size !== undefined) return { ok: false, reason: size };
5472
+ const plain = copiesOf(expr, [expr], starts, places.shares)[0] as Expr;
5473
+ const p = new Printer(plain, options, keys, starts);
3070
5474
  let value: Code;
3071
5475
  try {
3072
- value = p.root(expr);
5476
+ value = p.root(plain);
3073
5477
  p.finish();
3074
5478
  } catch (thrown) {
3075
5479
  return reasonOf(thrown);
3076
5480
  }
3077
- // A list gives a vex.list (COMPILE.MODULE.LIST.RESULT).
3078
- const result = value.v.list === undefined ? value.v.code : `${p.use("LO")}(${value.v.code}, ${String(depthOf(value.v.list))})`;
3079
- const body = ["const out = [];", "for (let o = 0; o < n; o++) {", " try {", ...ind(ind(value.s)), ` out.push(${result});`, " } catch {", " out.push(VEX_ERROR);", " }", "}", "return out;"];
5481
+ // A list gives a vex.list (COMPILE.MODULE.LIST.RESULT), or a plain array (COMPILE.MODULE.LIST.PLAIN).
5482
+ const result = value.v.list === undefined ? value.v.code : p.runList(value.v, run.plain);
5483
+ const body = ["const out = new Array(n);", "for (let o = 0; o < n; o++) {", " try {", ...ind(ind(value.s)), ` out[o] = ${result};`, " } catch {", " out[o] = VEX_ERROR;", " }", "}", "return out;"];
3080
5484
  return printModule(p, options, run, body);
3081
5485
  }
3082
5486
 
@@ -3124,11 +5528,21 @@ const columnList = (l: ListInfo): ListInfo => ({ item: l.item, inner: l.inner ==
3124
5528
  * cycle of reads gives `VEX_ERROR`.
3125
5529
  */
3126
5530
  export function emitSheetModule(columns: ReadonlyMap<string, Expr>, options: SheetModuleOptions): Emitted {
5531
+ return keyedPrint(options, (keys) => settledPrint((starts) => printSheet(columns, options, keys, starts)));
5532
+ }
5533
+
5534
+ /** This function prints the columns of a sheet for one state of the keys, with the facts `starts`, for `emitSheetModule`. */
5535
+ function printSheet(columns: ReadonlyMap<string, Expr>, options: SheetModuleOptions, keyPrint: KeyPrint, starts: EmptyStarts): Emitted {
3127
5536
  const run = runOf(options);
3128
5537
  if ("reason" in run) return { ok: false, reason: run.reason };
3129
5538
  const budget = options.budget ?? SHEET_BUDGET;
3130
5539
  if (!Number.isSafeInteger(budget) || budget < 0) return { ok: false, reason: `the budget ${String(budget)} is not a whole number of 0 or more` };
3131
5540
  const cells: CellFormulas = options.cells ?? new Map();
5541
+ // A formula of a cell has a position as its key at the time of the build, and the keys of a run come later.
5542
+ if (options.keys === true && cells.size > 0) return { ok: false, reason: 'the option "keys" with formulas of cells' };
5543
+ // COMPILE.PLACES: the walks below take the time of the places, so the count comes first.
5544
+ const places = placesRead([...columns.values(), ...[...cells.values()].flatMap((own) => [...own.values()])]);
5545
+ if (places.error !== undefined) return { ok: false, reason: places.error };
3132
5546
  const names = [...new Set([...columns.keys(), ...cells.keys()])];
3133
5547
  const order = columnOrder(columns, cells);
3134
5548
  // The formulas in the order of the columns. A key of a cell that is not the text of a position is not a key of the
@@ -3141,7 +5555,8 @@ export function emitSheetModule(columns: ReadonlyMap<string, Expr>, options: She
3141
5555
  for (const f of formulas) {
3142
5556
  // EVAL.SHAPE: the printer gives the reason for an expression that is not valid.
3143
5557
  const shape = shapeError(f.expr);
3144
- if (shape !== undefined) return { ok: false, reason: `${formulaText(f)}: ${shape}` };
5558
+ const reason = shape ?? nestingError(f.expr) ?? sizeError(f.expr, options) ?? stepError(f.expr, options) ?? monotoneError(f.expr, options);
5559
+ if (reason !== undefined) return { ok: false, reason: `${formulaText(f)}: ${reason}` };
3145
5560
  }
3146
5561
  const kinds = new Map<string, Kind | undefined>();
3147
5562
  const lists = new Map<string, ListInfo>();
@@ -3154,14 +5569,15 @@ export function emitSheetModule(columns: ReadonlyMap<string, Expr>, options: She
3154
5569
  // A sheet whose reads all read finished cells needs no search: each cell is the value of its formula
3155
5570
  // (COMPILE.MODULE.SHEET.DIRECT). A sheet with formulas of cells always has the search.
3156
5571
  const direct = formulas.every((f) => f.key === undefined) && order.every((c) => readsFinished(columns, order, c, run.tree));
3157
- const p = new Printer(rec(Object.fromEntries(formulas.map((f, i) => [`f${String(i)}`, f.expr]))), options, { columns: index, kinds, lists, direct });
5572
+ const plain = copiesOf(columns, formulas.map((f) => f.expr), starts, places.shares);
5573
+ const p = new Printer(rec(Object.fromEntries(plain.map((expr, i) => [`f${String(i)}`, expr]))), options, keyPrint, starts, { columns: index, kinds, lists, direct });
3158
5574
  const fns: string[] = [];
3159
5575
  const decls: string[] = [];
3160
5576
  // The statements that put the value of each formula into the array of its column at the key `o`, for a direct fill.
3161
5577
  const blocks = new Map<string, readonly string[]>();
3162
5578
  try {
3163
- for (const f of formulas) {
3164
- const code = p.root(f.expr);
5579
+ for (const [i, f] of formulas.entries()) {
5580
+ const code = p.root(plain[i] as Expr);
3165
5581
  const { kind, list } = code.v;
3166
5582
  // The first formula of a column without a kind of the options gives the kind of the column. Each other formula
3167
5583
  // must give a value of that kind, or a list that fits the lists of the column (COMPILE.MODULE.SHEET.LIST).
@@ -3230,10 +5646,11 @@ export function emitSheetModule(columns: ReadonlyMap<string, Expr>, options: She
3230
5646
  fill = order.map((c) => `${headOf(c)} SS.f(${String(index.get(c))}, o);`);
3231
5647
  }
3232
5648
  if (run.tree) p.treeParts.add("children");
3233
- // A column of lists gives a vex.list in each cell with a list (COMPILE.MODULE.LIST.RESULT).
5649
+ // A column of lists gives a vex.list in each cell with a list (COMPILE.MODULE.LIST.RESULT), or a plain array
5650
+ // (COMPILE.MODULE.LIST.PLAIN).
3234
5651
  const resultOf = (c: string, read: string): string => {
3235
5652
  const l = lists.get(c);
3236
- return l === undefined ? read : `${p.use("LC")}(${read}, ${String(depthOf(l))})`;
5653
+ return l === undefined ? read : `${p.use(run.plain ? "LCP" : "LC")}(${read}, ${String(depthOf(l))})`;
3237
5654
  };
3238
5655
  const body = [
3239
5656
  ...(direct ? [`const D = [${names.map(() => "new Array(n)").join(", ")}];`] : decls),