@mark1russell7/vex-compiler 0.13.1 → 0.13.2

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/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package",
3
3
  "name": "@mark1russell7/vex-compiler",
4
- "version": "0.13.1",
4
+ "version": "0.13.2",
5
5
  "description": "The Vex compiler: generated JavaScript for Vex programs, at run time and at build time, with the results of the interpreter.",
6
6
  "keywords": [
7
7
  "vex",
@@ -43,15 +43,15 @@
43
43
  },
44
44
  "devDependencies": {
45
45
  "@mark1russell7/cue": "github:mark1russell7/cue",
46
- "@mark1russell7/vex-domains": "0.13.1",
47
- "@mark1russell7/vex-testkit": "0.13.1",
46
+ "@mark1russell7/vex-domains": "0.13.2",
47
+ "@mark1russell7/vex-testkit": "0.13.2",
48
48
  "@types/node": "^26.6.4",
49
49
  "fast-check": "^4.10.2",
50
50
  "typescript": "^7.0.2",
51
51
  "vitest": "^5.0.3"
52
52
  },
53
53
  "dependencies": {
54
- "@mark1russell7/vex": "0.13.1"
54
+ "@mark1russell7/vex": "0.13.2"
55
55
  },
56
56
  "scripts": {
57
57
  "build": "tsdown",
package/src/module.ts CHANGED
@@ -15,11 +15,12 @@
15
15
  * before the loop over the keys. A node of the memo is one function of its other keys, with a map of its values. The
16
16
  * nodes with the same expression share the function.
17
17
  *
18
- * The printer takes a part of the language. It takes an array space or a tree space of records, and the fields and
19
- * the variables of the schema. It takes the axes `all`, `others` and `window`. A tree space also has the move `parent` and the
20
- * axes of a tree (COMPILE.MODULE.TREE). A list is an array of pairs of a key and a value. The list ops, list literals
21
- * and lists as names of loops are in a module (COMPILE.MODULE.LIST). The kinds of each op site must decide its op.
22
- * Another construct gives a reason, not code.
18
+ * The printer takes a part of the language. It takes an array space, a tree space or a graph space of records, and
19
+ * the fields and the variables of the schema. It takes the axes `all`, `others` and `window`. A tree space also has the
20
+ * move `parent` and the axes of a tree (COMPILE.MODULE.TREE). A graph space has the axes of a graph
21
+ * (COMPILE.MODULE.GRAPH). A list is an array of pairs of a key and a value. The list ops, `reduce`, list literals and
22
+ * lists as names of loops are in a module (COMPILE.MODULE.LIST, COMPILE.MODULE.REDUCE). The kinds of each op site must
23
+ * decide its op. Another construct gives a reason, not code.
23
24
  *
24
25
  * `emitSheetModule` prints the formula columns of a sheet as one module (COMPILE.MODULE.SHEET). Each column is an array
25
26
  * of results, and the run fills the arrays in the static order of `SheetRun.fill`. A read of a cell that is not finished
@@ -28,7 +29,7 @@
28
29
  import { addrExprs, app, CELL_KIND, children, fromDocument, isDocument, isFieldName, isVexList, lit, moveExpr, nestingOf, rec, shapeError, type AnyDomain, type Axis, type CellFormulas, type Envelope, type Expr, type ExprOf, type Move, type Names, type PrimitiveKind, type VexList } from "@mark1russell7/vex";
29
30
  import { factsOf, kindOfDomain, primitiveOf, type Facts, type Kind, type Schema } from "./facts.ts";
30
31
  import { memoNodes } from "./memo.ts";
31
- import { columnOrder, isCellRef, keyOrderOf, readsOf } from "./sheet-order.ts";
32
+ import { columnOrder, isCellRef, keyOrderOf, readsFinished, readsOf } from "./sheet-order.ts";
32
33
 
33
34
  /** The options of a standalone module. */
34
35
  export interface ModuleOptions {
@@ -41,11 +42,12 @@ export interface ModuleOptions {
41
42
  */
42
43
  readonly name?: string;
43
44
  /**
44
- * The space of the records. In both spaces, the key of a record is the text of its position. The default `array`
45
+ * The space of the records. In each space, the key of a record is the text of its position. The default `array`
45
46
  * has no parents. A `tree` takes the parents as the third argument of the run (COMPILE.MODULE.TREE). Each entry
46
- * is the position of the parent of its record, or -1 for a root.
47
+ * is the position of the parent of its record, or -1 for a root. A `graph` takes the edges as the third argument
48
+ * (COMPILE.MODULE.GRAPH). Each entry is an array of the positions of the ends of the edges from its record, in order.
47
49
  */
48
- readonly space?: "array" | "tree";
50
+ readonly space?: "array" | "tree" | "graph";
49
51
  }
50
52
 
51
53
  /** The options of a module of a sheet (COMPILE.MODULE.SHEET): the options of a module, and the parts of a sheet. */
@@ -102,6 +104,12 @@ interface ListInfo {
102
104
  readonly empty?: boolean;
103
105
  }
104
106
 
107
+ /** The op of each step of `reduce` (COMPILE.MODULE.REDUCE): the name of the op, and the value of the option `domain`. */
108
+ interface Step {
109
+ readonly op: string;
110
+ readonly domain: unknown;
111
+ }
112
+
105
113
  /** The code of a node: the statements before its value, and its value. `safe` covers the statements too. */
106
114
  interface Code {
107
115
  readonly s: readonly string[];
@@ -145,6 +153,8 @@ interface SheetInfo {
145
153
  readonly columns: ReadonlyMap<string, number>;
146
154
  /** The kind of each column that the printer knows: a kind of the options, or the kind of a printed formula. */
147
155
  readonly kinds: Map<string, Kind | undefined>;
156
+ /** True when each read of a cell reads a finished cell, so a read starts no search (COMPILE.MODULE.SHEET.DIRECT). */
157
+ readonly direct: boolean;
148
158
  }
149
159
 
150
160
  /** This function gives the levels of some codes together. */
@@ -226,7 +236,7 @@ interface Spec {
226
236
  }
227
237
 
228
238
  /** The name of a helper of the generated code. */
229
- type Helper = "F" | "C" | "T" | "L" | "Q" | "G" | "B" | "U" | "X" | "I" | "K" | "M" | "M1" | "S" | "V" | "SB" | "TK" | "NT" | BuildHelper | TreeHelper | SheetHelper;
239
+ type Helper = "F" | "C" | "T" | "L" | "Q" | "G" | "B" | "U" | "X" | "I" | "K" | "M" | "M1" | "S" | "V" | "SB" | "TK" | "NT" | BuildHelper | TreeHelper | GraphHelper | SheetHelper;
230
240
 
231
241
  /** The helpers of the list ops that build a list (LIST.BUILD), of `get` (LIST.GET) and of `indexOf` (LIST.INDEXOF). */
232
242
  type BuildHelper = "DR" | "AP" | "WO" | "FL" | "GT" | "IX";
@@ -234,8 +244,11 @@ type BuildHelper = "DR" | "AP" | "WO" | "FL" | "GT" | "IX";
234
244
  /** The helpers of a tree space (COMPILE.MODULE.TREE). */
235
245
  type TreeHelper = "PT" | "CH" | "SG" | "PR" | "UP" | "SO" | "AN" | "BF";
236
246
 
247
+ /** The helpers of a graph space (COMPILE.MODULE.GRAPH). */
248
+ type GraphHelper = "GR" | "GI" | "RB";
249
+
237
250
  /** 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. */
238
- type SheetHelper = "SH" | "KO";
251
+ type SheetHelper = "SH" | "KO" | "DO";
239
252
 
240
253
  /** The helpers of the generated code. A module has only the helpers that it uses. */
241
254
  const HELPERS: Readonly<Record<Exclude<Helper, "S">, string>> = {
@@ -378,9 +391,37 @@ const HELPERS: Readonly<Record<Exclude<Helper, "S">, string>> = {
378
391
  AN: "function AN(P, k) { const o = []; for (let p = P[k]; p >= 0; p = P[p]) o.push(p); return o; }",
379
392
  // The record and the keys under it, in the order of a breadth-first search. A tree has no cycle, so no key comes twice.
380
393
  BF: "function BF(h, k) { const o = [k]; for (let i = 0; i < o.length; i++) for (const c of h[o[i]]) o.push(c); return o; }",
394
+ // The edges of a graph space: the positions of the ends of the edges from each record, in order. A second edge to the
395
+ // same end is the same edge, as in the interpreter. The mark of an end is the number of its record plus 1.
396
+ GR: [
397
+ "function GR(e, n) {",
398
+ ' if (!Array.isArray(e) || e.length !== n) C("the edges are not an array with the ends of the edges of each record");',
399
+ " const O = [], s = new Int32Array(n);",
400
+ " for (let i = 0; i < n; i++) {",
401
+ " const x = e[i];",
402
+ " if (!Array.isArray(x)) C(`the edges of the record ${i} are not an array`);",
403
+ " const o = [];",
404
+ " for (const t of x) {",
405
+ " if (!(Number.isInteger(t) && t >= 0 && t < n)) C(`an edge of the record ${i} does not go to the position of a record`);",
406
+ " if (s[t] !== i + 1) {",
407
+ " s[t] = i + 1;",
408
+ " o.push(t);",
409
+ " }",
410
+ " }",
411
+ " O.push(o);",
412
+ " }",
413
+ " return O;",
414
+ "}",
415
+ ].join("\n"),
416
+ // The predecessors of each record of a graph, in key order: the records in key order, and the ends of the edges of each record.
417
+ GI: "function GI(O, n) { const I = []; for (let i = 0; i < n; i++) I.push([]); for (let i = 0; i < n; i++) for (const t of O[i]) I[t].push(i); return I; }",
418
+ // The record and the keys that a path of edges reaches from it, once, in the order of a breadth-first search.
419
+ RB: "function RB(O, k, n) { const s = new Uint8Array(n), o = [k]; s[k] = 1; for (let i = 0; i < o.length; i++) for (const c of O[o[i]]) if (s[c] === 0) { s[c] = 1; o.push(c); } return o; }",
381
420
  // The state of a run of a sheet (COMPILE.MODULE.SHEET), as in SheetRun: the result of each finished cell, the search
382
421
  // of Tarjan with its stack, and the budget of the stack. `r` reads a cell, `f` fills a cell, and `o` gives a column.
383
422
  // A cell without a formula has the error sentinel from the start, as the error of its read.
423
+ // A column of a direct fill (COMPILE.MODULE.SHEET.DIRECT): the error sentinel of a cell changes to VEX_ERROR.
424
+ DO: "function DO(d) { for (let k = 0; k < d.length; k++) if (d[k] === E) d[k] = VEX_ERROR; return d; }",
384
425
  SH: [
385
426
  "function SH(n, cols, own, budget) {",
386
427
  " const pg = (c, k) => {",
@@ -672,9 +713,10 @@ const NEEDS: Readonly<Record<Helper, readonly Helper[]>> = {
672
713
  DR: ["V", "F"], AP: ["V"], WO: ["V"], FL: ["V"], GT: ["F"], IX: ["V", "F"],
673
714
  // Each module has C, and each move uses F (#move), so these needs only complete the list.
674
715
  // Stryker disable next-line ArrayDeclaration: see the comment above
675
- PT: ["C"], UP: ["F"], SO: ["F"],
716
+ PT: ["C"], GR: ["C"], UP: ["F"], SO: ["F"],
676
717
  CH: [], SG: [], PR: [], AN: [], BF: [],
677
- SH: [], KO: [],
718
+ GI: [], RB: [],
719
+ SH: [], KO: [], DO: [],
678
720
  };
679
721
 
680
722
  /** The parts of a tree that a run computes before the loop over its keys, if the program needs them. */
@@ -696,6 +738,9 @@ const TREE_AXES: ReadonlySet<string> = new Set(["children", "ancestors", "descen
696
738
  /** This function tells if an axis has its targets in a range of an array of positions in a tree space. */
697
739
  const isTreeAxis = (a: Axis): a is TreeAxis => a.t === "window" || TREE_AXES.has(a.t);
698
740
 
741
+ /** The axes of a graph space in a module (COMPILE.MODULE.GRAPH), other than the axes of each space. */
742
+ const GRAPH_AXES: ReadonlySet<string> = new Set(["successors", "predecessors", "reachable"]);
743
+
699
744
  /**
700
745
  * The targets of an axis of a tree space: the statements before the loop, and the positions `a[q]` for `q` from `lo` up
701
746
  * to `hi`. The loop skips the key `skip`.
@@ -710,6 +755,8 @@ interface TreeRange {
710
755
 
711
756
  /** The list ops of a standalone module. */
712
757
  const LIST_OPS: ReadonlySet<string> = new Set(["count", "sum", "mean", "min", "max", "any", "all", "none", "first"]);
758
+ /** The list ops with a running value in a module: the list ops above, and `reduce` with the op of a domain (COMPILE.MODULE.REDUCE). */
759
+ const FOLD_OPS: ReadonlySet<string> = new Set([...LIST_OPS, "reduce"]);
713
760
  const NUMBER_LIST_OPS: ReadonlySet<string> = new Set(["count", "sum", "mean", "min", "max"]);
714
761
  const BOOLEAN_LIST_OPS: ReadonlySet<string> = new Set(["any", "all", "none"]);
715
762
  /** The list ops over lists of `#build`: append, without and flat (LIST.BUILD), get (LIST.GET) and indexOf (LIST.INDEXOF). */
@@ -781,7 +828,7 @@ function fits(name: ListInfo, step: ListInfo): boolean {
781
828
  }
782
829
 
783
830
  /** This function tells if the step of a list op throws for a value of the kind `kind`, which is the wrong kind. */
784
- const stepThrows = (op: string, kind: Kind | undefined): boolean => (NUMBER_STEPS.has(op) && kind !== "number") || (BOOLEAN_LIST_OPS.has(op) && kind !== "boolean");
831
+ const stepThrows = (op: string, kind: Kind | undefined): boolean => op === "reduce" || (NUMBER_STEPS.has(op) && kind !== "number") || (BOOLEAN_LIST_OPS.has(op) && kind !== "boolean");
785
832
 
786
833
  /** The list ops whose step takes a number. */
787
834
  const NUMBER_STEPS: ReadonlySet<string> = new Set(["sum", "mean", "min", "max"]);
@@ -1072,6 +1119,9 @@ class Printer {
1072
1119
  /** True for a tree space, and the parts of the tree that the program reads (COMPILE.MODULE.TREE). */
1073
1120
  readonly #tree: boolean;
1074
1121
  readonly treeParts = new Set<TreePart>();
1122
+ /** True for a graph space, and true when the program reads the predecessors of a graph (COMPILE.MODULE.GRAPH). */
1123
+ readonly #graph: boolean;
1124
+ into = false;
1075
1125
  /** The columns of a sheet, for a module of a sheet (COMPILE.MODULE.SHEET). */
1076
1126
  readonly #sheet: SheetInfo | undefined;
1077
1127
  #names = 0;
@@ -1116,6 +1166,7 @@ class Printer {
1116
1166
  this.#schema = options.schema;
1117
1167
  this.#memo = memoOf(expr);
1118
1168
  this.#tree = options.space === "tree";
1169
+ this.#graph = options.space === "graph";
1119
1170
  this.#sheet = sheet;
1120
1171
  }
1121
1172
 
@@ -1457,6 +1508,8 @@ class Printer {
1457
1508
  * must read no cell.
1458
1509
  */
1459
1510
  #inOrder(parts: readonly Code[], all: boolean): readonly Code[] {
1511
+ // A read of a finished cell starts no search, so the order of the reads does not change a result.
1512
+ if (this.#sheet?.direct === true) return parts;
1460
1513
  const last = parts.findLastIndex((x) => x.v.deps.has(CELLS));
1461
1514
  const after = parts.slice(last + 1).every((x) => x.s.length === 0 || x.v.safe);
1462
1515
  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);
@@ -1516,7 +1569,8 @@ class Printer {
1516
1569
  // Stryker disable next-line ConditionalExpression,StringLiteral: see #address
1517
1570
  /* v8 ignore next -- @preserve */
1518
1571
  if (focus === undefined) throw new NotStandalone("a node of the memo reads its focus");
1519
- if (d === undefined || more.length > 0 || !Number.isInteger(d)) return `${F}()`;
1572
+ // A graph space has no offsets (NAV.OFFSET), so an offset fails at each key.
1573
+ if (this.#graph || d === undefined || more.length > 0 || !Number.isInteger(d)) return `${F}()`;
1520
1574
  // In a tree space, an offset goes among the siblings (NAV.OFFSET.TREE).
1521
1575
  if (this.#tree) return `${this.use("SO")}(${this.#part("siblings", "GP")}, SI, ${focus}, ${d})`;
1522
1576
  return `${this.use("X")}(${focus} + ${d}, n)`;
@@ -1729,18 +1783,23 @@ class Printer {
1729
1783
  const [head] = args;
1730
1784
  const rest = args.slice(1);
1731
1785
  // An each whose body is a list gives a list of lists (LIST.FLAT), so a list op over it goes over its array.
1732
- if (LIST_OPS.has(op) && head?.tag === "each" && !this.#isList(head.body, ctx)) return this.#list(op, head, rest, ctx);
1786
+ if (FOLD_OPS.has(op) && head?.tag === "each" && !this.#isList(head.body, ctx)) return this.#list(op, head, rest, ctx);
1733
1787
  // 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
1734
1788
  // is one loop with a running value, not an array. A builder sheet prints such a let, for example `sum(let($0 = 0, each(…)))`.
1735
- if (LIST_OPS.has(op) && head?.tag === "let" && rest.every((x) => x.tag === "lit")) return this.#let(head, ctx, (body) => app(op, body, ...rest));
1789
+ if (FOLD_OPS.has(op) && head?.tag === "let" && rest.every((x) => x.tag === "lit")) return this.#let(head, ctx, (body) => app(op, body, ...rest));
1736
1790
  // sortBy and take are list ops for each receiver. Each other list op needs a list, and a domain can have its name.
1737
1791
  if (head !== undefined && (op === "sortBy" || op === "take" || (op === "drop" && this.#isList(head, ctx)))) return this.#order(op, head, rest, ctx);
1738
1792
  if (head !== undefined && BUILD_OPS.has(op) && this.#isList(head, ctx)) return this.#build(op, head, rest, ctx);
1739
- if (head !== undefined && (LIST_OPS.has(op) || op === "nth") && this.#isList(head, ctx)) return this.#overList(op, head, rest, ctx);
1793
+ if (head !== undefined && (FOLD_OPS.has(op) || op === "nth") && this.#isList(head, ctx)) return this.#overList(op, head, rest, ctx);
1740
1794
  const raw = args.map((x) => this.expr(x, ctx));
1741
1795
  const deps = depsOf(...raw);
1742
1796
  // The interpreter evaluates each argument, also after an error.
1743
1797
  const values = this.#inOrder(this.#settle(raw, deps, args), true);
1798
+ return this.#opCall(op, values, deps);
1799
+ }
1800
+
1801
+ /** This method prints the call of the op of a domain on some values, from the static site of their kinds. */
1802
+ #opCall(op: string, values: readonly Code[], deps: ReadonlySet<number>): Code {
1744
1803
  const site = this.#facts.staticSite(op, values.map((x) => x.v.kind));
1745
1804
  if (site?.t !== "fn") throw new NotStandalone(`the kinds of the values of "${op}" do not decide its op`);
1746
1805
  if (site.bad) return { s: stmtsOf(...values), v: { code: `${this.use("F")}()`, kind: site.returns, safe: false, deps } };
@@ -1827,15 +1886,28 @@ class Printer {
1827
1886
  * This method gives the option strict of a list op. The options must be one literal with only strict. Only a literal
1828
1887
  * has a value, so another expression gives the reason too.
1829
1888
  */
1830
- #strict(op: string, rest: readonly Expr[]): boolean {
1889
+ #strict(op: string, rest: readonly Expr[], names: readonly string[] = ["strict"]): boolean {
1831
1890
  const [options, ...more] = rest;
1832
1891
  if (more.length > 0) throw new NotStandalone(`"${op}" with more than one option`);
1833
1892
  if (options === undefined) return false;
1834
1893
  const opts = (options as { readonly value?: unknown }).value;
1835
- if (typeof opts !== "object" || opts === null || Object.keys(opts).some((k) => k !== "strict")) throw new NotStandalone(`the options of "${op}" are not a literal with strict`);
1894
+ if (typeof opts !== "object" || opts === null || Object.keys(opts).some((k) => !names.includes(k))) throw new NotStandalone(`the options of "${op}" are not a literal with ${names.join(" or ")}`);
1836
1895
  return (opts as { readonly strict?: unknown }).strict === true;
1837
1896
  }
1838
1897
 
1898
+ /**
1899
+ * This method gives the option strict of a list op. For `reduce`, it also gives the op of each step: the first
1900
+ * argument, a literal text, and the value of the option `domain` (COMPILE.MODULE.REDUCE).
1901
+ */
1902
+ #foldOptions(op: string, rest: readonly Expr[]): { readonly strict: boolean; readonly step: Step | undefined } {
1903
+ if (op !== "reduce") return { strict: this.#strict(op, rest), step: undefined };
1904
+ const [name, ...options] = rest;
1905
+ const value = (name as { readonly value?: unknown } | undefined)?.value;
1906
+ if (name?.tag !== "lit" || typeof value !== "string") throw new NotStandalone('"reduce" without a literal text as its op');
1907
+ const strict = this.#strict(op, options, ["strict", "domain"]);
1908
+ return { strict, step: { op: value, domain: (options[0] as { readonly value?: { readonly domain?: unknown } } | undefined)?.value?.domain } };
1909
+ }
1910
+
1839
1911
  /**
1840
1912
  * A list op over an axis: one `for` loop with a running value. An item with an error is skipped, and with `strict` it
1841
1913
  * is an error of the list op. A value of the wrong kind is an error of the list op, as in the interpreter.
@@ -1902,6 +1974,13 @@ class Printer {
1902
1974
  const q = this.fresh("q");
1903
1975
  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 };
1904
1976
  }
1977
+ // 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.
1978
+ if (this.#graph && GRAPH_AXES.has(base.t)) {
1979
+ const range = this.#graphRange(base.t, f as string);
1980
+ const q = this.fresh("q");
1981
+ 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 };
1982
+ }
1983
+ if (this.#graph && base.t === "window") throw new NotStandalone('the axis "window" in a graph space');
1905
1984
  if (base.t === "others") skip = f;
1906
1985
  else if (base.t === "window") {
1907
1986
  const h = this.fresh("h");
@@ -1912,6 +1991,21 @@ class Printer {
1912
1991
  return { s, j, head: forHead(j, lo, hi, reverse), key: [], check: [], skip, fixed: f === undefined, start, startSafe, tests, inner };
1913
1992
  }
1914
1993
 
1994
+ /**
1995
+ * This method gives the targets of an axis of a graph space at the position `f` (AXIS.GRAPH). They are the positions
1996
+ * `a[q]` for `q` from `lo` up to `hi`. The first key of the search of `reachable` is the focus, which is not a target.
1997
+ */
1998
+ #graphRange(t: string, f: string): TreeRange {
1999
+ const a = this.fresh("A");
2000
+ const range = (code: string, lo = "0"): TreeRange => ({ s: [`const ${a} = ${code};`], a, lo, hi: `${a}.length`, skip: undefined });
2001
+ if (t === "successors") return range(`GO[${f}]`);
2002
+ if (t === "predecessors") {
2003
+ this.into = true;
2004
+ return range(`GN[${f}]`);
2005
+ }
2006
+ return range(`${this.use("RB")}(GO, ${f}, n)`, "1");
2007
+ }
2008
+
1915
2009
  /**
1916
2010
  * This method gives the targets of an axis of a tree space at the position `f`. They are the positions `a[q]` for `q`
1917
2011
  * from `lo` up to `hi`, without the key that the loop skips. The axes come from AXIS.TREE, AXIS.GRAPH and AXIS.WINDOW.
@@ -1950,7 +2044,7 @@ class Printer {
1950
2044
  }
1951
2045
 
1952
2046
  #list(op: string, target: ExprOf<"each">, rest: readonly Expr[], ctx: Ctx): Code {
1953
- const strict = this.#strict(op, rest);
2047
+ const { strict, step } = this.#foldOptions(op, rest);
1954
2048
  const at = target.at ?? [];
1955
2049
  const { s, j, head, key, check, skip, fixed, start, startSafe, tests, inner } = this.#targetLoop(target.axis, at, ctx);
1956
2050
  const { level } = inner;
@@ -1962,7 +2056,7 @@ class Printer {
1962
2056
  // itself gives `#CYCLE!`.
1963
2057
  if (op === "count" && fixed && tests.length === 0 && body.v.safe && !body.v.deps.has(CELLS)) return bare(plainValue("n", "number"));
1964
2058
  const deps = new Set([...start, ...[body, ...testCodes].flatMap((x) => [...x.v.deps])].filter((d) => d !== level));
1965
- const r = this.#reduction(op, body.v.kind);
2059
+ const r = this.#reduction(op, body.v.kind, step);
1966
2060
  const { v } = r;
1967
2061
  s.push(r.init);
1968
2062
  const item = [...check, ...testCodes.flatMap((t) => [...t.s, `if (!${this.#boolean(t.v)}) continue;`]), ...body.s];
@@ -1975,7 +2069,7 @@ class Printer {
1975
2069
  const x = this.fresh("x");
1976
2070
  const all = [...key, ...(skip === undefined ? [] : [`if (${j} === ${skip}) continue;`]), `let ${x};`, "try {", ...ind(item), ` ${x} = ${body.v.code};`, "} catch {", ` ${x} = E;`, "}", `${list}.push(${x});`];
1977
2071
  const reduce = [`for (const ${v} of ${list}) {`, ` if (${v} === E) ${strict ? `${this.use("F")}();` : "continue;"}`, ` ${r.step}`, "}"];
1978
- return { s: [...s, `const ${list} = [];`, head, ...ind(all), "}", ...reduce], v: { code: r.result, kind: listKind(op, body.v.kind), safe: false, deps } };
2072
+ return { s: [...s, `const ${list} = [];`, head, ...ind(all), "}", ...reduce], v: { code: r.result, kind: r.kind, safe: false, deps } };
1979
2073
  }
1980
2074
  const loop = [
1981
2075
  ...key,
@@ -1989,17 +2083,18 @@ class Printer {
1989
2083
  // A count without strict, and any, all and none over booleans without strict, cannot fail. The address of the axis
1990
2084
  // can fail, except at the focus or at the origin.
1991
2085
  const safe = startSafe && !strict && (op === "count" || (BOOLEAN_LIST_OPS.has(op) && body.v.kind === "boolean"));
1992
- return { s, v: { code: r.result, kind: listKind(op, body.v.kind), safe, deps } };
2086
+ return { s, v: { code: r.result, kind: r.kind, safe, deps } };
1993
2087
  }
1994
2088
 
1995
2089
  /**
1996
2090
  * This method gives the parts of a list op that reduces the values of its items. The parts are the variable `v` of
1997
2091
  * 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.
1998
2092
  */
1999
- #reduction(op: string, kind: Kind | undefined): { readonly v: string; readonly init: string; readonly step: string; readonly result: string } {
2093
+ #reduction(op: string, kind: Kind | undefined, step?: Step): { readonly v: string; readonly init: string; readonly step: string; readonly result: string; readonly kind: Kind | undefined } {
2000
2094
  const a = this.fresh("a");
2001
2095
  const n = this.fresh("n");
2002
2096
  const v = this.fresh("x");
2097
+ if (step !== undefined) return { v, init: `let ${a}, ${n} = 0;`, ...this.#reduceStep(step, kind, a, n, v) };
2003
2098
  const num = kind === "number" ? v : `${this.use("U")}(${v})`;
2004
2099
  const bool = kind === "boolean" ? v : `${this.use("B")}(${v})`;
2005
2100
  const inits: Readonly<Record<string, string>> = {
@@ -2030,7 +2125,40 @@ class Printer {
2030
2125
  all: a,
2031
2126
  none: `!${a}`,
2032
2127
  };
2033
- return { v, init: inits[op] ?? `let ${a}, ${n} = 0;`, step: steps[op] as string, result: results[op] ?? `(${n} === 0 ? ${F}() : ${a})` };
2128
+ return { v, init: inits[op] ?? `let ${a}, ${n} = 0;`, step: steps[op] as string, result: results[op] ?? `(${n} === 0 ? ${F}() : ${a})`, kind: listKind(op, kind) };
2129
+ }
2130
+
2131
+ /**
2132
+ * This method gives the step and the result of `reduce` (COMPILE.MODULE.REDUCE), as in the interpreter. The first item
2133
+ * is the first running value. Each later item goes into the op of the domain of the running value. The kinds of the
2134
+ * items decide that op, and the op must give a value of the same kind. No items give the identity of the op.
2135
+ */
2136
+ #reduceStep(step: Step, kind: Kind | undefined, a: string, n: string, v: string): { readonly step: string; readonly result: string; readonly kind: Kind | undefined } {
2137
+ const arg = (code: string): Code => bare({ code, kind, safe: true, deps: NO_DEPS, plain: true });
2138
+ const opCode = this.#opCall(step.op, [arg(a), arg(v)], NO_DEPS);
2139
+ if (opCode.v.kind !== kind) throw new NotStandalone(`the op "${step.op}" of "reduce" gives a value of the kind ${kindText(opCode.v.kind)}, not of the kind ${kindText(kind)} of the items`);
2140
+ const empty = this.#identity(step);
2141
+ // The identity of another domain is a value of another kind, so the kind of the result is not known.
2142
+ return { step: `${a} = ${n}++ === 0 ? ${v} : ${opCode.v.code};`, result: `(${n} === 0 ? ${empty.code} : ${a})`, kind: empty.kind === undefined || empty.kind === kind ? kind : undefined };
2143
+ }
2144
+
2145
+ /**
2146
+ * This method gives the code of `reduce` over no items, as in the interpreter. The code is the identity of the op in
2147
+ * the one domain that has one, or in the domain of the option `domain`. Another case is an error. The kind is the kind
2148
+ * of the domain.
2149
+ */
2150
+ #identity(step: Step): { readonly code: string; readonly kind: Kind | undefined } {
2151
+ const { op, domain } = step;
2152
+ const fail = { code: `${this.use("F")}()`, kind: undefined };
2153
+ // A name of a domain that the program does not have leaves no domain, so it gives the error too.
2154
+ const found = [...this.#domains.entries()].filter(([, d]) => Object.hasOwn(d.ops, op) && (d.ops[op] as { readonly identity?: unknown }).identity !== undefined && (domain === undefined || d.name === domain));
2155
+ const [only, second] = found;
2156
+ if (only === undefined || second !== undefined) return fail;
2157
+ const [i, d] = only;
2158
+ const name = `id_${String(i)}_${String(this.#opIndex(op))}`;
2159
+ // Stryker disable next-line ConditionalExpression: the copy of an identity is always the same, so the test only saves time
2160
+ 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}`)};`);
2161
+ return { code: `${name}()`, kind: kindOfDomain(d) };
2034
2162
  }
2035
2163
 
2036
2164
  /**
@@ -2109,7 +2237,7 @@ class Printer {
2109
2237
  const list = this.#listOf(head, ctx);
2110
2238
  // A missing position is the literal null, which is not a whole number, so nth gives its error.
2111
2239
  const exprs = [head, ...(op === "nth" ? [rest[0] ?? lit(null)] : [])];
2112
- const strict = this.#strict(op, rest.slice(exprs.length - 1));
2240
+ const { strict, step } = this.#foldOptions(op, rest.slice(exprs.length - 1));
2113
2241
  const raw = [list, ...exprs.slice(1).map((x) => this.expr(x, ctx))];
2114
2242
  const deps = depsOf(...raw);
2115
2243
  const parts = this.#inOrder(this.#settle(raw, deps, exprs), true);
@@ -2117,10 +2245,10 @@ class Printer {
2117
2245
  const { item, inner } = list.v.list as ListInfo;
2118
2246
  // The value of an item of a list of lists is a list, so nth and first give a list (LIST.FLAT).
2119
2247
  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 } };
2120
- const r = this.#reduction(op, item);
2248
+ const r = this.#reduction(op, item, step);
2121
2249
  const { v } = r;
2122
2250
  const s = [...l.s, r.init, `for (const [, ${v}] of ${l.v.code}) {`, ` if (${v} === E) ${strict ? `${this.use("F")}();` : "continue;"}`, ` ${r.step}`, "}"];
2123
- return { s, v: { code: r.result, kind: listKind(op, item), safe: false, deps, list: op === "first" ? inner : undefined } };
2251
+ return { s, v: { code: r.result, kind: r.kind, safe: false, deps, list: op === "first" ? inner : undefined } };
2124
2252
  }
2125
2253
 
2126
2254
  /**
@@ -2395,12 +2523,19 @@ class Printer {
2395
2523
  }
2396
2524
 
2397
2525
  /** This function gives the name of the function of a module, and its space, or the reason that the options are not valid. */
2398
- function runOf(options: ModuleOptions): { readonly name: string; readonly tree: boolean } | { readonly reason: string } {
2526
+ function runOf(options: ModuleOptions): Run | { readonly reason: string } {
2399
2527
  const name = options.name ?? "run";
2400
2528
  if (!/^[A-Za-z_$][\w$]*$/.test(name)) return { reason: `the name "${name}" is not a JavaScript name` };
2401
- const tree = options.space === "tree";
2402
- if (!tree && options.space !== undefined && options.space !== "array") return { reason: `the space "${String(options.space)}" is not "array" or "tree"` };
2403
- return { name, tree };
2529
+ const space = options.space ?? "array";
2530
+ if (space !== "array" && space !== "tree" && space !== "graph") return { reason: `the space "${String(space)}" is not "array", "tree" or "graph"` };
2531
+ return { name, tree: space === "tree", graph: space === "graph" };
2532
+ }
2533
+
2534
+ /** The function of a module: its name, and its space. */
2535
+ interface Run {
2536
+ readonly name: string;
2537
+ readonly tree: boolean;
2538
+ readonly graph: boolean;
2404
2539
  }
2405
2540
 
2406
2541
  /** This function gives the reason of an error of the printer. Another exception is a defect, so it goes to the caller. */
@@ -2413,7 +2548,7 @@ function reasonOf(thrown: unknown): Emitted {
2413
2548
  * This function gives the text of a module: the declarations, the helpers, and the function of the run. The run checks
2414
2549
  * its input, computes the parts of the tree and the constants of the run, and then gives the statements `body`.
2415
2550
  */
2416
- function printModule(p: Printer, options: ModuleOptions, run: { readonly name: string; readonly tree: boolean }, body: readonly string[]): Emitted {
2551
+ function printModule(p: Printer, options: ModuleOptions, run: Run, body: readonly string[]): Emitted {
2417
2552
  p.use("C");
2418
2553
  const helpers = new Set<Helper>();
2419
2554
  // A helper comes after the helpers that it needs. A set keeps the first place of each helper.
@@ -2431,13 +2566,16 @@ function printModule(p: Printer, options: ModuleOptions, run: { readonly name: s
2431
2566
  } catch (thrown) {
2432
2567
  return reasonOf(thrown);
2433
2568
  }
2434
- const { name, tree } = run;
2569
+ const { name, tree, graph } = run;
2435
2570
  // A tree checks its parents, and it computes the parts that the program reads. The siblings and the order need the
2436
2571
  // children.
2437
2572
  if (tree) p.use("PT");
2438
2573
  if (p.treeParts.size > 0) p.treeParts.add("children");
2439
2574
  const parts = (["children", "siblings", "order"] as const).filter((x) => p.treeParts.has(x));
2440
2575
  for (const x of parts) p.use(TREE_PARTS[x][0]);
2576
+ // A graph checks its edges, and it computes the predecessors if the program reads them.
2577
+ if (graph) p.use("GR");
2578
+ if (p.into) p.use("GI");
2441
2579
  [...p.helpers].toSorted().forEach(add);
2442
2580
  // The names that this module declares at its top: the constants, the helpers and the declarations of the printer.
2443
2581
  const declared = new Set<string>(["VexContractError", "VEX_ERROR", "E", ...(p.memos ? ["Z"] : []), ...(helpers.has("S") ? ["N", "W"] : []), ...helpers, ...p.top.keys()]);
@@ -2455,7 +2593,7 @@ function printModule(p: Printer, options: ModuleOptions, run: { readonly name: s
2455
2593
  ...(helpers.has("S") ? ["const N = {}, W = {};"] : []),
2456
2594
  ...[...helpers].map((h) => (h === "S" ? helperS(p.features) : HELPERS[h])),
2457
2595
  ...p.top.values(),
2458
- `export function ${name}(records, vars${tree ? ", parents" : ""}) {`,
2596
+ `export function ${name}(records, vars${tree ? ", parents" : graph ? ", edges" : ""}) {`,
2459
2597
  ' if (!Array.isArray(records)) C("the records are not an array");',
2460
2598
  " const R = records;",
2461
2599
  " const n = R.length;",
@@ -2465,6 +2603,7 @@ function printModule(p: Printer, options: ModuleOptions, run: { readonly name: s
2465
2603
  " }",
2466
2604
  ` if (typeof vars !== "object" || vars === null${varChecks}) C("the variables do not keep the schema");`,
2467
2605
  ...(tree ? [" const P = PT(parents, n);", ...parts.map((x) => ` ${TREE_PARTS[x][1]}`)] : []),
2606
+ ...(graph ? [" const GO = GR(edges, n);", ...(p.into ? [" const GN = GI(GO, n);"] : [])] : []),
2468
2607
  ...[...p.vars].map(([v, code]) => ` const ${code} = vars[${JSON.stringify(v)}];`),
2469
2608
  ...ind(p.run),
2470
2609
  ...ind(body),
@@ -2550,7 +2689,10 @@ export function emitSheetModule(columns: ReadonlyMap<string, Expr>, options: She
2550
2689
  const kinds = new Map<string, Kind | undefined>(Object.entries(options.kinds ?? {}));
2551
2690
  const index = new Map(names.map((c, i) => [c, i]));
2552
2691
  // The memo of the printer covers each formula, so the formulas share their nodes of the memo.
2553
- const p = new Printer(rec(Object.fromEntries(formulas.map((f, i) => [`f${String(i)}`, f.expr]))), options, { columns: index, kinds });
2692
+ // A sheet whose reads all read finished cells needs no search: each cell is the value of its formula
2693
+ // (COMPILE.MODULE.SHEET.DIRECT). A sheet with formulas of cells always has the search.
2694
+ const direct = formulas.every((f) => f.key === undefined) && order.every((c) => readsFinished(columns, order, c, run.tree));
2695
+ const p = new Printer(rec(Object.fromEntries(formulas.map((f, i) => [`f${String(i)}`, f.expr]))), options, { columns: index, kinds, direct });
2554
2696
  const fns: string[] = [];
2555
2697
  const decls: string[] = [];
2556
2698
  try {
@@ -2578,29 +2720,33 @@ export function emitSheetModule(columns: ReadonlyMap<string, Expr>, options: She
2578
2720
  const i = formulas.findIndex((f) => f.column === c && f.key === undefined);
2579
2721
  return i < 0 ? "undefined" : entry(i);
2580
2722
  });
2581
- p.use("SH");
2723
+ p.use(direct ? "DO" : "SH");
2724
+ // The function of the formula of each column, for a direct fill. A direct fill has no formulas of cells.
2725
+ const fnOf = new Map(formulas.map((f, i) => [f.column, fns[i] as string]));
2726
+ const fillOf = (c: string, at: string): string => (direct ? `D[${at}][o] = ${fnOf.get(c) as string}(o);` : `SS.f(${at}, o);`);
2582
2727
  // A tree gives the keys in the order of a fill with the helper KO, once for each order.
2583
2728
  const orders = new Map<string, string>();
2584
2729
  const fill = order.map((c) => {
2585
2730
  const { reverse, post, back } = keyOrderOf(readsOf(columns, cells, c).directions);
2586
2731
  const at = String(index.get(c));
2587
- if (!run.tree) return reverse ? `for (let o = n - 1; o >= 0; o--) SS.f(${at}, o);` : `for (let o = 0; o < n; o++) SS.f(${at}, o);`;
2732
+ if (!run.tree) return reverse ? `for (let o = n - 1; o >= 0; o--) ${fillOf(c, at)}` : `for (let o = 0; o < n; o++) ${fillOf(c, at)}`;
2588
2733
  const args = `${p.use("KO")}(H, RT, ${String(post)}, ${String(back)})`;
2589
2734
  let keys = orders.get(args);
2590
2735
  if (keys === undefined) {
2591
2736
  keys = p.fresh("K");
2592
2737
  orders.set(args, keys);
2593
2738
  }
2594
- return `for (const o of ${keys}) SS.f(${at}, o);`;
2739
+ return `for (const o of ${keys}) ${fillOf(c, at)}`;
2595
2740
  });
2596
2741
  if (run.tree) p.treeParts.add("children");
2597
2742
  const body = [
2598
2743
  ...decls,
2599
- `const SS = SH(n, [${cols.join(", ")}], [${own.join(", ")}], ${String(budget)});`,
2600
- `const ${READ_CELL} = SS.r;`,
2744
+ ...(direct
2745
+ ? [`const D = [${names.map(() => "new Array(n)").join(", ")}];`, `const ${READ_CELL} = (c, k) => D[c][k];`]
2746
+ : [`const SS = SH(n, [${cols.join(", ")}], [${own.join(", ")}], ${String(budget)});`, `const ${READ_CELL} = SS.r;`]),
2601
2747
  ...[...orders].map(([args, keys]) => `const ${keys} = ${args};`),
2602
2748
  ...fill,
2603
- `return { ${names.map((c, i) => `${JSON.stringify(c)}: SS.o(${String(i)})`).join(", ")} };`,
2749
+ `return { ${names.map((c, i) => `${JSON.stringify(c)}: ${direct ? `DO(D[${String(i)}])` : `SS.o(${String(i)})`}`).join(", ")} };`,
2604
2750
  ];
2605
2751
  return printModule(p, options, run, body);
2606
2752
  }
package/src/runtime.ts CHANGED
@@ -237,6 +237,10 @@ export function createRuntime(options: RuntimeOptions): Runtime {
237
237
  });
238
238
  if (r !== undefined) return r;
239
239
  }
240
+ // LIST.ARRAY: after the domains and the function of the host, a list op on an array is a list op on a list.
241
+ // FALLBACK is an error, and a list op skips an error item, so an exception must stop the program (V-064).
242
+ // Stryker disable next-line StringLiteral: the program catches the exception, so no one reads its message
243
+ if (listOp && fn === undefined && Array.isArray(values[0])) throw new Error("tier 1 gives a list op on an array");
240
244
  try {
241
245
  // Stryker disable next-line ConditionalExpression: a call of undefined throws, and the catch also gives F
242
246
  return fn === undefined ? F : checked(fn(...values));
@@ -121,3 +121,59 @@ export function keyOrderOf(d: ReadonlySet<Direction>): KeyOrder {
121
121
  const post = d.has("down");
122
122
  return { reverse, post, back: post !== reverse };
123
123
  }
124
+
125
+ /**
126
+ * The place of a read of a cell, relative to the key of the formula. The place `key` is the key itself. The place
127
+ * `children` is the body or a test of the axis `children` of the key. The place `unknown` is each other place.
128
+ */
129
+ type ReadPlace = "key" | "children" | "unknown";
130
+
131
+ /** This function gives the axis under the tests of `where` and under `reverse`. Both read the targets of that axis. */
132
+ function baseOf(axis: Axis): Axis {
133
+ let base = axis;
134
+ while (base.t === "where" || base.t === "reverse") base = base.axis;
135
+ return base;
136
+ }
137
+
138
+ /**
139
+ * This function tells if each read of a cell of the column `self` reads a finished cell in the static order of the
140
+ * fill (COMPILE.MODULE.SHEET.DIRECT). A read of a column before `self` in `order` reads a finished cell. A read of a
141
+ * column that the sheet does not have also reads a finished cell. A read of `self` reads a finished cell only in
142
+ * these three forms:
143
+ * - in a tree in pre-order, at the move `parent` from the key,
144
+ * - in an array in key order, at an offset of one negative step from the key,
145
+ * - in a tree in post-order, at the key of a target of the axis `children` of the key.
146
+ *
147
+ * A read in the body of a function can evaluate at each place of a call, so it is not one of these forms.
148
+ */
149
+ export function readsFinished(columns: ReadonlyMap<string, Expr>, order: readonly string[], self: string, tree: boolean): boolean {
150
+ const formula = columns.get(self);
151
+ if (formula === undefined || shapeError(formula) !== undefined) return false;
152
+ const { reverse, post } = keyOrderOf(readsOf(columns, new Map(), self).directions);
153
+ const position = order.indexOf(self);
154
+ const todo: [Expr, ReadPlace][] = [[formula, "key"]];
155
+ for (let item = todo.pop(); item !== undefined; item = todo.pop()) {
156
+ const [e, place] = item;
157
+ if (e.tag === "each" || e.tag === "fold") {
158
+ const inner: ReadPlace = place === "key" && (e.at === undefined || e.at.length === 0) && baseOf(e.axis).t === "children" ? "children" : "unknown";
159
+ const { tests } = partsOf(e.axis);
160
+ for (const x of [...(e.tag === "each" ? [e.body] : Object.values(e.step)), ...tests]) todo.push([x, inner]);
161
+ const list = listOf(e.axis);
162
+ for (const x of [...(e.tag === "fold" ? [...Object.values(e.init), e.result] : []), ...addrExprs(e.at), ...(list === undefined ? [] : [list])]) todo.push([x, place]);
163
+ } else if (e.tag === "fn") todo.push([e.body, "unknown"]);
164
+ else if (e.tag !== "ext") for (const child of children(e)) todo.push([child, place]);
165
+ else if (e.kind === CELL_KIND && isCellRef(e.data)) {
166
+ const { column, at } = e.data;
167
+ const index = order.indexOf(column);
168
+ if (index > position) return false;
169
+ if (column !== self) continue;
170
+ const [move, ...rest] = at;
171
+ const ok =
172
+ place === "key"
173
+ ? move !== undefined && rest.length === 0 && ((tree && !post && move.t === "parent") || (!tree && !reverse && move.t === "offset" && move.d.length === 1 && (move.d[0] ?? 0) < 0))
174
+ : place === "children" && tree && post && at.length === 0;
175
+ if (!ok) return false;
176
+ }
177
+ }
178
+ return true;
179
+ }