@mark1russell7/vex-compiler 0.13.2 → 0.13.4

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/build/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { CELL_KIND, MAX_NESTING, addrExprs, app, axisTargets, children, compile, findMethod, fixAddr, fromDocument, isDocument, isFieldName, isListOp, isMove, isOpName, isStackOverflow, isVexList, liftsAt, listOf, lit, matchesKind, moveExpr, nestingOf, ok, rec, resolveAddr, safeIs, shapeError, vexList } from "@mark1russell7/vex";
2
- //#region src/facts.ts
2
+ // src/facts.ts
3
3
  /**
4
4
  * The facts of the options that the printer uses (docs/COMPILER.md §13.2). For each op site, they give the domain
5
5
  * whose op the interpreter takes first, and the kinds and the lifts of its parameters. The facts come from the op
@@ -42,7 +42,7 @@ function listReason(expr) {
42
42
  }
43
43
  /** This function gives the kind of the values of a domain. */
44
44
  const kindOfDomain = (d) => d.primitive ?? `domain:${d.name}`;
45
- /** This function gives a kind if it is a primitive type, else `undefined`. */
45
+ /** This function gives a kind if it is a primitive type, else `undefined`. A kind of a list is not a primitive type. */
46
46
  const primitiveOf = (k) => k === "number" || k === "string" || k === "boolean" ? k : void 0;
47
47
  const NO_SPEC = Object.freeze({});
48
48
  /** This function gives the op of a name in a domain, or `undefined` for a domain without the op. */
@@ -62,14 +62,20 @@ function entryOf(domain, name) {
62
62
  }
63
63
  const FREE$1 = Object.freeze({ t: "free" });
64
64
  const STATIC_FREE = Object.freeze({ t: "free" });
65
+ /** The positions of the lists of a site without lists. */
66
+ const NO_LISTS = /* @__PURE__ */ new Set();
65
67
  /** This function gives the kind of the result of an op of a domain, if the op declares it. */
66
68
  function returnsOf(domain, kind) {
67
69
  if (kind === "domain") return kindOfDomain(domain);
68
70
  return kind === "any" ? void 0 : kind;
69
71
  }
70
- /** This function tells if an argument of a kind fits a parameter, or `undefined` if the kind of the argument is unknown. */
71
- function fits$1(domain, param, arg) {
72
+ /**
73
+ * This function tells if an argument of a kind fits a parameter, or `undefined` if the kind of the argument is unknown.
74
+ * A list fits only `any`, and the test `is` of a domain without a primitive type can accept it (COMPILE.MODULE.LIST.ARG).
75
+ */
76
+ function fits$1(domain, param, arg, list) {
72
77
  if (param === void 0 || param === "any") return true;
78
+ if (list) return param === "domain" && domain.primitive === void 0 ? void 0 : false;
73
79
  if (arg === void 0) return void 0;
74
80
  return arg === (param === "domain" ? kindOfDomain(domain) : param);
75
81
  }
@@ -88,7 +94,7 @@ function factsOf(options) {
88
94
  const last = domains.findLastIndex((d) => d.valid !== void 0);
89
95
  return {
90
96
  checks: domains.slice(0, last + 1).map((d) => d.valid !== void 0),
91
- staticSite(name, kinds) {
97
+ staticSite(name, kinds, lists = NO_LISTS) {
92
98
  const [self, ...args] = kinds;
93
99
  if (self === void 0) return void 0;
94
100
  for (const [i, d] of domains.entries()) {
@@ -99,8 +105,8 @@ function factsOf(options) {
99
105
  if (takes && d.primitive === void 0) return void 0;
100
106
  continue;
101
107
  }
102
- if (d.fromScalar !== void 0 && args.some((a, j) => a !== "string" && a !== "boolean" && liftsAt(e.spec.liftScalar, j))) return void 0;
103
- const ok = args.map((a, j) => fits$1(d, e.spec.params?.[j], a));
108
+ if (d.fromScalar !== void 0 && args.some((a, j) => a !== "string" && a !== "boolean" && !lists.has(j + 1) && liftsAt(e.spec.liftScalar, j))) return void 0;
109
+ const ok = args.map((a, j) => fits$1(d, e.spec.params?.[j], a, lists.has(j + 1)));
104
110
  if (ok.includes(void 0)) return void 0;
105
111
  return {
106
112
  t: "fn",
@@ -119,6 +125,9 @@ function factsOf(options) {
119
125
  }
120
126
  return -1;
121
127
  },
128
+ own(name) {
129
+ return domains.every((d) => entryOf(d, name) === void 0) && !(fns !== void 0 && Object.hasOwn(fns, name));
130
+ },
122
131
  site(name, arity) {
123
132
  if (arity === 0 || isListOp(name)) return void 0;
124
133
  const index = domains.findIndex((d) => entryOf(d, name) !== void 0);
@@ -134,8 +143,7 @@ function factsOf(options) {
134
143
  }
135
144
  };
136
145
  }
137
- //#endregion
138
- //#region src/loop.ts
146
+ // src/loop.ts
139
147
  const local = (n) => ({
140
148
  t: "local",
141
149
  n
@@ -168,8 +176,7 @@ const call$1 = (fn, ...args) => ({
168
176
  fn,
169
177
  args
170
178
  });
171
- //#endregion
172
- //#region src/js.ts
179
+ // src/js.ts
173
180
  /**
174
181
  * The back end of JavaScript source (docs/COMPILER.md §3.4). It prints a program of the loop IR as the body of a
175
182
  * function with the parameters `K` (the constants) and `R` (the runtime).
@@ -461,8 +468,7 @@ function printJs(p, facts) {
461
468
  ...tail
462
469
  ].join("\n");
463
470
  }
464
- //#endregion
465
- //#region src/memo.ts
471
+ // src/memo.ts
466
472
  /**
467
473
  * The memo of a program (docs/COMPILER.md §7.2 and §7.3). The value of some nodes depends only on the space and on a
468
474
  * few values that the node reads from outside: its keys. A program keeps the value of such a node for each space and
@@ -650,8 +656,7 @@ function memoNodes(expr) {
650
656
  visit(expr);
651
657
  return out;
652
658
  }
653
- //#endregion
654
- //#region src/lower.ts
659
+ // src/lower.ts
655
660
  /**
656
661
  * The lowering: a Vex expression becomes a program of the loop IR (docs/COMPILER.md §3.3). A list op over a direct
657
662
  * `each` becomes one loop with a running value, so it makes no list.
@@ -1550,8 +1555,7 @@ var Lowerer = class {
1550
1555
  const NEGATIVE_ZERO$1 = Symbol("-0");
1551
1556
  /** This function gives the flag of a bound value: its local, or `true` for a value without a flag. */
1552
1557
  const flag = (b) => b.ok ?? bool(true);
1553
- //#endregion
1554
- //#region src/runtime.ts
1558
+ // src/runtime.ts
1555
1559
  /**
1556
1560
  * The runtime of generated code. Each function follows the rule of the interpreter of the core. Where the interpreter
1557
1561
  * gives an error value, the function gives `FALLBACK`, and tier 1 then does the evaluation again (docs/COMPILER.md §4.1).
@@ -1764,8 +1768,7 @@ function createRuntime(options) {
1764
1768
  }
1765
1769
  };
1766
1770
  }
1767
- //#endregion
1768
- //#region src/tiers.ts
1771
+ // src/tiers.ts
1769
1772
  /**
1770
1773
  * The tiers (docs/COMPILER.md §2.1). Tier 2 is generated JavaScript. Tier 1 is the closure compiler of the core, and it
1771
1774
  * gives each result that tier 2 cannot give. Thus a tiered program gives the results of the interpreter.
@@ -1840,8 +1843,7 @@ function tiered(source, options = {}) {
1840
1843
  explain: (r) => slow.explain(r)
1841
1844
  };
1842
1845
  }
1843
- //#endregion
1844
- //#region src/sheet-order.ts
1846
+ // src/sheet-order.ts
1845
1847
  /**
1846
1848
  * The static order of the cells of a sheet in a module (COMPILE.MODULE.SHEET). It is the order of `SheetRun.fill` in
1847
1849
  * `packages/core/src/sheet.ts` (SHEET.FILL). Each column comes after the columns that it reads. The keys of a column
@@ -1957,8 +1959,12 @@ function baseOf(axis) {
1957
1959
  * - in a tree in post-order, at the key of a target of the axis `children` of the key.
1958
1960
  *
1959
1961
  * A read in the body of a function can evaluate at each place of a call, so it is not one of these forms.
1962
+ *
1963
+ * The columns of `fused` come before `self` in one loop over the keys (COMPILE.MODULE.ONCE). The loop evaluates each of
1964
+ * them at a key before `self` at that key. Thus a read of one of them reads a finished cell only at the key itself, or
1965
+ * in one of the three forms.
1960
1966
  */
1961
- function readsFinished(columns, order, self, tree) {
1967
+ function readsFinished(columns, order, self, tree, fused = /* @__PURE__ */ new Set()) {
1962
1968
  const formula = columns.get(self);
1963
1969
  if (formula === void 0 || shapeError(formula) !== void 0) return false;
1964
1970
  const { reverse, post } = keyOrderOf(readsOf(columns, /* @__PURE__ */ new Map(), self).directions);
@@ -1981,15 +1987,14 @@ function readsFinished(columns, order, self, tree) {
1981
1987
  else if (e.kind === CELL_KIND && isCellRef(e.data)) {
1982
1988
  const { column, at } = e.data;
1983
1989
  if (order.indexOf(column) > position) return false;
1984
- if (column !== self) continue;
1990
+ if (column !== self && !fused.has(column)) continue;
1985
1991
  const [move, ...rest] = at;
1986
- if (!(place === "key" ? move !== void 0 && rest.length === 0 && (tree && !post && move.t === "parent" || !tree && !reverse && move.t === "offset" && move.d.length === 1 && (move.d[0] ?? 0) < 0) : place === "children" && tree && post && at.length === 0)) return false;
1992
+ if (!(column !== self && place === "key" && at.every((m) => m.t === "origin") || (place === "key" ? move !== void 0 && rest.length === 0 && (tree && !post && move.t === "parent" || !tree && !reverse && move.t === "offset" && move.d.length === 1 && (move.d[0] ?? 0) < 0) : place === "children" && tree && post && at.length === 0))) return false;
1987
1993
  }
1988
1994
  }
1989
1995
  return true;
1990
1996
  }
1991
- //#endregion
1992
- //#region src/module.ts
1997
+ // src/module.ts
1993
1998
  /**
1994
1999
  * Standalone modules (docs/COMPILER.md §4.4 and §6). `emitModule` prints a program as an ES module that has no import of
1995
2000
  * Vex. A host that guarantees the kinds of its input uses it without the interpreter, for example ireko at build time.
@@ -2011,12 +2016,17 @@ function readsFinished(columns, order, self, tree) {
2011
2016
  * the fields and the variables of the schema. It takes the axes `all`, `others` and `window`. A tree space also has the
2012
2017
  * move `parent` and the axes of a tree (COMPILE.MODULE.TREE). A graph space has the axes of a graph
2013
2018
  * (COMPILE.MODULE.GRAPH). A list is an array of pairs of a key and a value. The list ops, `reduce`, list literals and
2014
- * lists as names of loops are in a module (COMPILE.MODULE.LIST, COMPILE.MODULE.REDUCE). The kinds of each op site must
2015
- * decide its op. Another construct gives a reason, not code.
2019
+ * lists as names of loops are in a module (COMPILE.MODULE.LIST, COMPILE.MODULE.REDUCE). The value of a program can be a
2020
+ * list, and the run gives it as a `vex.list` (COMPILE.MODULE.LIST.RESULT). An op and a record get each list of an
2021
+ * argument or a field as a `vex.list` too (COMPILE.MODULE.LIST.ARG, COMPILE.MODULE.LIST.FIELD). The value of a call
2022
+ * can be a list (COMPILE.MODULE.LIST.CALL). A field of the schema can have a list kind, and the record then holds a
2023
+ * `vex.list` (COMPILE.MODULE.LIST.INPUT). The kinds of each op site must decide its op.
2024
+ * Another construct gives a reason, not code.
2016
2025
  *
2017
2026
  * `emitSheetModule` prints the formula columns of a sheet as one module (COMPILE.MODULE.SHEET). Each column is an array
2018
2027
  * of results, and the run fills the arrays in the static order of `SheetRun.fill`. A read of a cell that is not finished
2019
- * starts the search of `SheetRun`. Thus each cell on a cycle gives the error of Vex.
2028
+ * starts the search of `SheetRun`. Thus each cell on a cycle gives the error of Vex. A cell can hold a list, and a
2029
+ * formula reads it with the list ops (COMPILE.MODULE.SHEET.LIST).
2020
2030
  */
2021
2031
  /** The error of a construct that a standalone module does not have. */
2022
2032
  var NotStandalone = class extends Error {};
@@ -2059,8 +2069,55 @@ const HELPERS = {
2059
2069
  " return o.sort((a, b) => (a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0));",
2060
2070
  "}"
2061
2071
  ].join("\n"),
2072
+ SK: [
2073
+ "function SK(l, s, f) {",
2074
+ " const o = V(l, s).map((x) => [x, f(x[1])]);",
2075
+ " const t = o.length > 0 ? typeof o[0][1] : \"number\";",
2076
+ " for (const [, v] of o) if (typeof v !== t || (t !== \"number\" && t !== \"string\") || v !== v) F();",
2077
+ " return o.sort((a, b) => (a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0)).map((x) => x[0]);",
2078
+ "}"
2079
+ ].join("\n"),
2062
2080
  TK: "function TK(l, n, s) { const o = V(l, s); return Number.isSafeInteger(n) && n >= 0 ? o.slice(0, n) : F(); }",
2063
- NT: "function NT(l, i, s) { const o = V(l, s); return Number.isSafeInteger(i) && i >= 0 && i < o.length ? o[i][1] : F(); }",
2081
+ NT: [
2082
+ "function NT(l, i, s) {",
2083
+ " let o = l.vw;",
2084
+ " if (o === undefined) {",
2085
+ " o = l.filter((x) => x[1] !== E);",
2086
+ " l.vw = o;",
2087
+ " }",
2088
+ " if (s && o.length < l.length) F();",
2089
+ " return Number.isSafeInteger(i) && i >= 0 && i < o.length ? o[i][1] : F();",
2090
+ "}"
2091
+ ].join("\n"),
2092
+ FI: [
2093
+ "function FI(n, v) {",
2094
+ " if (!(Number.isSafeInteger(n) && n >= 0 && n <= 100000 && v !== undefined)) F();",
2095
+ " const o = [];",
2096
+ " for (let i = 0; i < n; i++) o.push([i, v]);",
2097
+ " return o;",
2098
+ "}"
2099
+ ].join("\n"),
2100
+ LI: [
2101
+ "function LI(x, h, t) {",
2102
+ " if (typeof x !== \"object\" || x === null || x.kind !== \"vex.list\" || !Array.isArray(x.items)) return undefined;",
2103
+ " const o = [];",
2104
+ " for (let i = 0; i < x.items.length; i++) {",
2105
+ " const it = x.items[i];",
2106
+ " const r = typeof it === \"object\" && it !== null ? it.result : undefined;",
2107
+ " if (typeof r !== \"object\" || r === null || typeof it.key !== \"string\") return undefined;",
2108
+ " if (r.ok === true) {",
2109
+ " const v = h > 0 ? LI(r.value, h - 1, t) : r.value !== undefined && t(r.value) ? r.value : undefined;",
2110
+ " if (v === undefined) return undefined;",
2111
+ " o.push([it.key, v]);",
2112
+ " } else {",
2113
+ " const e = r.error;",
2114
+ " if (r.ok !== false || typeof e !== \"object\" || e === null || typeof e.code !== \"string\" || typeof e.kind !== \"string\" || typeof e.message !== \"string\" || !Array.isArray(e.path) || e.kind === \"depth\") return undefined;",
2115
+ " o.push([it.key, E]);",
2116
+ " }",
2117
+ " }",
2118
+ " return o;",
2119
+ "}"
2120
+ ].join("\n"),
2064
2121
  DR: "function DR(l, n, s) { const o = V(l, s); return Number.isSafeInteger(n) && n >= 0 ? o.slice(n) : F(); }",
2065
2122
  AP: "function AP(l, o, s) { return V(l, s).concat(V(o, s)); }",
2066
2123
  WO: [
@@ -2182,6 +2239,18 @@ const HELPERS = {
2182
2239
  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; }",
2183
2240
  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; }",
2184
2241
  DO: "function DO(d) { for (let k = 0; k < d.length; k++) if (d[k] === E) d[k] = VEX_ERROR; return d; }",
2242
+ 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 } })) }; }",
2243
+ LV: [
2244
+ "function LV(l, h) {",
2245
+ " let o = l.vl;",
2246
+ " if (o === undefined) {",
2247
+ " 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 } }))) });",
2248
+ " l.vl = o;",
2249
+ " }",
2250
+ " return o;",
2251
+ "}"
2252
+ ].join("\n"),
2253
+ 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; }",
2185
2254
  SH: [
2186
2255
  "function SH(n, cols, own, budget) {",
2187
2256
  " const pg = (c, k) => {",
@@ -2444,8 +2513,11 @@ const NEEDS = {
2444
2513
  S: ["M1", "F"],
2445
2514
  V: ["F"],
2446
2515
  SB: ["V", "F"],
2516
+ SK: ["V", "F"],
2447
2517
  TK: ["V", "F"],
2448
2518
  NT: ["V", "F"],
2519
+ FI: ["F"],
2520
+ LI: [],
2449
2521
  DR: ["V", "F"],
2450
2522
  AP: ["V"],
2451
2523
  WO: ["V"],
@@ -2465,7 +2537,10 @@ const NEEDS = {
2465
2537
  RB: [],
2466
2538
  SH: [],
2467
2539
  KO: [],
2468
- DO: []
2540
+ DO: [],
2541
+ LO: [],
2542
+ LC: ["LO"],
2543
+ LV: []
2469
2544
  };
2470
2545
  /** The statement of each part of a tree in a run, with the helper that computes it. */
2471
2546
  const TREE_PARTS = {
@@ -2533,56 +2608,102 @@ const BUILD_HELPERS = {
2533
2608
  get: "GT",
2534
2609
  indexOf: "IX"
2535
2610
  };
2536
- /** The list ops whose value is a list (LIST.SORT, LIST.TAKE and LIST.BUILD). */
2611
+ /**
2612
+ * The ops whose value is a list: the list ops of LIST.SORT, LIST.TAKE and LIST.BUILD, and `fill` (LIST.FILL). A domain
2613
+ * can have the op `fill`. Then the op of the domain gives no list, and the place of a list gives a reason.
2614
+ */
2537
2615
  const LIST_RESULTS = /* @__PURE__ */ new Set([
2538
2616
  "sortBy",
2539
2617
  "take",
2540
2618
  "drop",
2541
2619
  "append",
2542
2620
  "without",
2543
- "flat"
2621
+ "flat",
2622
+ "fill"
2544
2623
  ]);
2545
2624
  /**
2546
2625
  * This function tells if an expression gives a list. An each, a list literal and a list op of `LIST_RESULTS` give a
2547
- * list. A name of a list, and a let or a loop whose result is a list, give a list too. `isName` tells if a name outside the expression holds a list.
2626
+ * 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
2627
+ * body of its function gives one (COMPILE.MODULE.LIST.CALL). The scope tells the names and the functions outside the expression.
2548
2628
  */
2549
- function listy(e, isName) {
2629
+ function listy(e, scope) {
2550
2630
  switch (e.tag) {
2551
2631
  case "each": return true;
2552
2632
  case "lit": return isVexList(e.value);
2553
- case "app": return LIST_RESULTS.has(e.op);
2554
- case "var": return isName(e.name);
2555
- case "let": return listy(e.body, namesIn(e.bind, isName));
2633
+ case "app": 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));
2634
+ case "var": return scope.name(e.name);
2635
+ case "let": return listy(e.body, scopeIn(e.bind, scope));
2556
2636
  case "fold":
2557
- case "iterate": return listy(e.result, namesIn(e.init, isName));
2558
- case "call":
2559
- case "ext":
2637
+ case "iterate": return listy(e.result, scopeIn(e.init, scope));
2638
+ case "ext": return scope.cell(e);
2639
+ case "ref": return scope.field(e);
2640
+ case "call": {
2641
+ const f = scope.fn(e.fn);
2642
+ return f !== void 0 && listy(f.fn.body, paramsIn(f, e.args, scope));
2643
+ }
2560
2644
  case "fn":
2561
- case "rec":
2562
- case "ref": return false;
2645
+ case "rec": return false;
2563
2646
  }
2564
2647
  }
2565
- /** This function tells if a name holds a list in the scope of some bindings. A binding hides a name outside, and a function is not a list. */
2566
- function namesIn(bind, isName) {
2567
- const lists = new Map(Object.entries(bind).map(([name, x]) => [name, x.tag !== "fn" && listy(x, isName)]));
2568
- return (name) => lists.get(name) ?? isName(name);
2648
+ /**
2649
+ * This function gives the scope of some bindings. A value hides a name outside, and a function is not a list. A
2650
+ * function sees the scope outside the bindings, so it cannot call itself.
2651
+ */
2652
+ function scopeIn(bind, scope) {
2653
+ const lists = /* @__PURE__ */ new Map();
2654
+ const fns = /* @__PURE__ */ new Map();
2655
+ for (const [name, x] of Object.entries(bind)) {
2656
+ if (x.tag === "fn") fns.set(name, {
2657
+ fn: x,
2658
+ scope
2659
+ });
2660
+ lists.set(name, listy(x, scope));
2661
+ }
2662
+ return {
2663
+ ...scope,
2664
+ name: (name) => lists.get(name) ?? scope.name(name),
2665
+ fn: (name) => fns.get(name) ?? scope.fn(name)
2666
+ };
2667
+ }
2668
+ /**
2669
+ * This function gives the scope of the body of a function at a call. The body sees the scope of the binding of the
2670
+ * function, and each parameter holds a list when its argument does.
2671
+ */
2672
+ function paramsIn(f, args, scope) {
2673
+ const lists = new Map(args.map((x, i) => [f.fn.params[i], listy(x, scope)]));
2674
+ return {
2675
+ ...f.scope,
2676
+ name: (name) => lists.get(name) ?? f.scope.name(name)
2677
+ };
2569
2678
  }
2570
- /** This function tells if an expression has a list literal with an item, so a key of the list can be a text (LIST.LITERAL). */
2571
- function hasKeyedLiteral(e) {
2572
- return e.tag === "lit" && isVexList(e.value) && e.value.items.length > 0 || children(e).some(hasKeyedLiteral);
2679
+ /**
2680
+ * This function tells if an expression has a list literal with an item (LIST.LITERAL), or `fill` (LIST.FILL). Then a key
2681
+ * of a list of the expression can be a key that is not the position of a record.
2682
+ */
2683
+ function hasTextKeys(e) {
2684
+ return e.tag === "lit" && isVexList(e.value) && e.value.items.length > 0 || e.tag === "app" && e.op === "fill" || children(e).some(hasTextKeys);
2573
2685
  }
2574
- /** This function gives the facts of the list of `append` from the facts of its two lists. An empty list fits each list. */
2575
- function joinLists(a, b) {
2686
+ /**
2687
+ * This function gives the facts of the list of `append` from the facts of its two lists. It also gives the list of
2688
+ * `if` from its two branches. An empty list fits each list. The op `op` names the op in the reason.
2689
+ */
2690
+ function joinLists(a, b, op) {
2576
2691
  if (a.empty === true) return b;
2577
2692
  if (b.empty === true) return a;
2578
- if (a.inner === void 0 !== (b.inner === void 0)) throw new NotStandalone("\"append\" of a list of lists and a list of values");
2693
+ if (a.inner === void 0 !== (b.inner === void 0)) throw new NotStandalone(`"${op}" of a list of lists and a list of values`);
2579
2694
  const texts = a.texts === true || b.texts === true;
2580
2695
  return {
2581
2696
  item: join(a.item, b.item),
2582
- inner: a.inner === void 0 ? void 0 : joinLists(a.inner, b.inner),
2697
+ inner: a.inner === void 0 ? void 0 : joinLists(a.inner, b.inner, op),
2583
2698
  texts
2584
2699
  };
2585
2700
  }
2701
+ /** This function gives the facts of the list of `if` or `ifError` from its two branches. Two values that are not lists give undefined. */
2702
+ function branchLists(op, a, b) {
2703
+ if (a === void 0 && b === void 0) return void 0;
2704
+ if (a === void 0 || b === void 0) throw new NotStandalone(`"${op}" of a list and a value that is not a list`);
2705
+ return joinLists(a, b, op);
2706
+ }
2586
2707
  /**
2587
2708
  * This function tells if a list of a step fits the list of a name of a loop (LOOP.LIST). The items of the step have the
2588
2709
  * kind of the items of the name, if the name has one. The name also has the text keys and the lists of lists of the step.
@@ -2860,6 +2981,8 @@ var Printer = class {
2860
2981
  helpers = /* @__PURE__ */ new Set();
2861
2982
  /** The declarations at the top of the module: the functions of the domains and the checks of the results. */
2862
2983
  top = /* @__PURE__ */ new Map();
2984
+ /** The array of the lists of each field of the input that the program reads (COMPILE.MODULE.LIST.INPUT). */
2985
+ inputs = /* @__PURE__ */ new Map();
2863
2986
  /** The statements at the start of a run: the constants of the run and the functions of the memo. */
2864
2987
  run = [];
2865
2988
  /** The variables of the schema that the program reads. */
@@ -2974,7 +3097,21 @@ var Printer = class {
2974
3097
  */
2975
3098
  against(kind, input) {
2976
3099
  const primitive = primitiveOf(kind);
2977
- if (primitive !== void 0) return `typeof ${input} !== "${primitive}"`;
3100
+ return primitive === void 0 ? `!${this.#isOf(kind)}(${input})` : `typeof ${input} !== "${primitive}"`;
3101
+ }
3102
+ /**
3103
+ * This method gives the name of a test of the kind of an item of a list of the input (COMPILE.MODULE.LIST.INPUT). The
3104
+ * test of a primitive type checks the JavaScript type, and the test of a domain is the copy of its `is`.
3105
+ */
3106
+ test(kind) {
3107
+ const primitive = primitiveOf(kind);
3108
+ if (primitive === void 0) return this.#isOf(kind);
3109
+ const name = `is_${primitive}`;
3110
+ this.top.set(name, `const ${name} = (x) => typeof x === "${primitive}";`);
3111
+ return name;
3112
+ }
3113
+ /** This method gives the name of the copy of the test `is` of the domain of a kind. */
3114
+ #isOf(kind) {
2978
3115
  const d = this.#domains.findIndex((x) => kindOfDomain(x) === kind);
2979
3116
  const domain = this.#domains[d];
2980
3117
  if (domain === void 0) throw new NotStandalone(`the schema has the kind ${kind}, and no domain has it`);
@@ -2991,7 +3128,7 @@ var Printer = class {
2991
3128
  ]], `the test "is" of the domain ${domain.name}`);
2992
3129
  this.top.set(name, `const ${name} = ${src};`);
2993
3130
  }
2994
- return `!${name}(${input})`;
3131
+ return name;
2995
3132
  }
2996
3133
  /** This method gives a new name for the code. */
2997
3134
  fresh(prefix) {
@@ -3109,7 +3246,28 @@ var Printer = class {
3109
3246
  }
3110
3247
  /** This method tells if an expression gives a list at a place that takes one (`listy`). */
3111
3248
  #isList(e, ctx) {
3112
- return listy(e, (name) => ctx.env.get(name)?.list !== void 0);
3249
+ const key = ctx.keys.get(e);
3250
+ if (key !== void 0) return key.list !== void 0;
3251
+ return listy(e, this.#scopeOf(ctx));
3252
+ }
3253
+ /** This method gives the scope of `listy` at a node: the names and the bound functions of its context. */
3254
+ #scopeOf(ctx) {
3255
+ return {
3256
+ name: (name) => ctx.env.get(name)?.list !== void 0,
3257
+ fn: (name) => {
3258
+ const bound = ctx.fns.get(name);
3259
+ return bound === void 0 ? void 0 : {
3260
+ fn: bound.fn,
3261
+ scope: this.#scopeOf(bound.ctx)
3262
+ };
3263
+ },
3264
+ cell: (x) => this.#cellList(x) !== void 0,
3265
+ field: (x) => typeof this.#schema.fields?.[x.path.join(".")] === "object"
3266
+ };
3267
+ }
3268
+ /** This method gives the facts of the list of a read of a cell. A read of a column that holds no list gives undefined. */
3269
+ #cellList(e) {
3270
+ return e.kind === CELL_KIND && isCellRef(e.data) ? this.#sheet?.lists.get(e.data.column) : void 0;
3113
3271
  }
3114
3272
  /** 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. */
3115
3273
  #listLiteral(l) {
@@ -3218,10 +3376,12 @@ var Printer = class {
3218
3376
  case "call": return this.#call(e, ctx);
3219
3377
  case "rec": {
3220
3378
  const names = Object.keys(e.fields);
3221
- const raw = Object.values(e.fields).map((x) => this.expr(x, ctx));
3379
+ const exprs = Object.values(e.fields);
3380
+ for (const x of exprs) this.#wantList.add(x);
3381
+ const raw = exprs.map((x) => this.expr(x, ctx));
3222
3382
  const deps = depsOf(...raw);
3223
- const fields = this.#inOrder(this.#settle(raw, deps, Object.values(e.fields)), true);
3224
- const code = `({ ${fields.map((x, i) => `${names[i] === "__proto__" ? "[\"__proto__\"]" : JSON.stringify(names[i])}: ${x.v.code}`).join(", ")} })`;
3383
+ const fields = this.#inOrder(this.#settle(raw, deps, exprs), true);
3384
+ const code = `({ ${fields.map((x, i) => `${names[i] === "__proto__" ? "[\"__proto__\"]" : JSON.stringify(names[i])}: ${this.#plain(x.v)}`).join(", ")} })`;
3225
3385
  return {
3226
3386
  s: stmtsOf(...fields),
3227
3387
  v: {
@@ -3257,19 +3417,23 @@ var Printer = class {
3257
3417
  const { column, at } = e.data;
3258
3418
  const deps = /* @__PURE__ */ new Set([...this.#addressDeps(at, ctx, []), CELLS]);
3259
3419
  const index = sheet.columns.get(column);
3420
+ const list = sheet.lists.get(column);
3260
3421
  if (index === void 0) return bare({
3261
3422
  code: `${F}()`,
3262
3423
  kind: sheet.kinds.get(column),
3263
3424
  safe: false,
3264
- deps
3425
+ deps,
3426
+ list
3265
3427
  });
3266
3428
  if (!sheet.kinds.has(column)) throw new NotStandalone(`a formula reads the column "${column}" before its formula, so the column needs its kind in the option kinds`);
3267
- const read = `${READ_CELL}(${String(index)}, ${this.#address(at, ctx, [])})`;
3429
+ const address = this.#address(at, ctx, []);
3430
+ const read = sheet.direct ? `D[${String(index)}][${address}]` : `${READ_CELL}(${String(index)}, ${address})`;
3268
3431
  const v = {
3269
3432
  code: `${this.use("G")}(${read})`,
3270
3433
  kind: sheet.kinds.get(column),
3271
3434
  safe: false,
3272
- deps
3435
+ deps,
3436
+ list
3273
3437
  };
3274
3438
  return bare(at.every((m) => m.t === "origin") ? {
3275
3439
  ...v,
@@ -3371,21 +3535,41 @@ var Printer = class {
3371
3535
  const [field, ...more] = e.path;
3372
3536
  const kind = field === void 0 ? void 0 : this.#schema.fields?.[field];
3373
3537
  if (field === void 0 || more.length > 0 || !isFieldName(field) || kind === void 0) throw new NotStandalone(`a read of a field that is not in the schema: "${e.path.join(".")}"`);
3538
+ const input = typeof kind === "object" ? this.#input(field) : void 0;
3374
3539
  const at = e.at ?? [];
3375
3540
  const safe = at.every((m) => m.t === "origin");
3376
3541
  const values = this.#addressValues(at, ctx);
3377
3542
  const deps = this.#addressDeps(at, ctx, values);
3378
3543
  const parts = this.#inOrder(this.#settle(values, deps), false);
3544
+ const address = this.#address(at, ctx, parts);
3545
+ if (typeof kind === "object") return {
3546
+ s: stmtsOf(...parts),
3547
+ v: {
3548
+ code: `${input}[${address}]`,
3549
+ kind: void 0,
3550
+ safe,
3551
+ deps,
3552
+ list: listOfKind(kind, true)
3553
+ }
3554
+ };
3379
3555
  return {
3380
3556
  s: stmtsOf(...parts),
3381
3557
  v: {
3382
- code: `R[${this.#address(at, ctx, parts)}][${JSON.stringify(field)}]`,
3558
+ code: `R[${address}][${JSON.stringify(field)}]`,
3383
3559
  kind,
3384
3560
  safe,
3385
3561
  deps
3386
3562
  }
3387
3563
  };
3388
3564
  }
3565
+ /** This method gives the name of the array of the lists of a field of the input. */
3566
+ #input(field) {
3567
+ const known = this.inputs.get(field);
3568
+ if (known !== void 0) return known;
3569
+ const name = this.fresh("LF");
3570
+ this.inputs.set(field, name);
3571
+ return name;
3572
+ }
3389
3573
  /** This method gives the code of the expressions of the computed moves of an address. They evaluate at the node. */
3390
3574
  #addressValues(at, ctx) {
3391
3575
  return addrExprs(at).map((x) => this.expr(x, ctx));
@@ -3496,29 +3680,34 @@ var Printer = class {
3496
3680
  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)}`);
3497
3681
  const s = [];
3498
3682
  const args = e.args.map((x) => {
3683
+ this.#wantList.add(x);
3499
3684
  const c = this.#hoist(this.expr(x, ctx), hasLoop(x));
3685
+ const { kind, deps, list } = c.v;
3500
3686
  if (c.v.safe) {
3501
3687
  s.push(...c.s);
3502
3688
  return {
3503
3689
  code: c.v.code,
3504
- kind: c.v.kind,
3505
- deps: c.v.deps
3690
+ kind,
3691
+ deps,
3692
+ list
3506
3693
  };
3507
3694
  }
3508
3695
  if (c.s.length === 0 && c.v.held !== void 0) return {
3509
3696
  code: c.v.held,
3510
- kind: c.v.kind,
3511
- deps: c.v.deps
3697
+ kind,
3698
+ deps,
3699
+ list
3512
3700
  };
3513
3701
  const b = this.fresh("b");
3514
3702
  s.push(...this.#store(b, c));
3515
3703
  return {
3516
3704
  code: b,
3517
- kind: c.v.kind,
3518
- deps: c.v.deps
3705
+ kind,
3706
+ deps,
3707
+ list
3519
3708
  };
3520
3709
  });
3521
- const sig = JSON.stringify(args.map((a) => a.kind ?? null));
3710
+ const sig = JSON.stringify(args.map((a) => a.list === void 0 ? a.kind ?? null : { list: a.list }));
3522
3711
  const spec = bound.specs.get(sig) ?? this.#printFn(bound, args, sig);
3523
3712
  const levels = (d) => d === spec.origin ? [ctx.originLevel] : d === spec.focus ? [ctx.level] : d === spec.param ? [] : [d];
3524
3713
  const deps = /* @__PURE__ */ new Set([...args.flatMap((a) => [...a.deps]), ...[...spec.deps].flatMap(levels)]);
@@ -3529,7 +3718,8 @@ var Printer = class {
3529
3718
  code: `${spec.name}(${[...args.map((a) => a.code), ...position].join(", ")})`,
3530
3719
  kind: spec.kind,
3531
3720
  safe: spec.safe,
3532
- deps
3721
+ deps,
3722
+ list: spec.list
3533
3723
  }
3534
3724
  };
3535
3725
  }
@@ -3550,7 +3740,8 @@ var Printer = class {
3550
3740
  code: names[i],
3551
3741
  kind: args[i].kind,
3552
3742
  lazy: true,
3553
- deps: /* @__PURE__ */ new Set([param])
3743
+ deps: /* @__PURE__ */ new Set([param]),
3744
+ list: args[i].list
3554
3745
  }));
3555
3746
  const scope = {
3556
3747
  param,
@@ -3561,6 +3752,7 @@ var Printer = class {
3561
3752
  root: bound.fn.body
3562
3753
  };
3563
3754
  this.#scopes.push(scope);
3755
+ this.#wantList.add(bound.fn.body);
3564
3756
  const body = this.expr(bound.fn.body, {
3565
3757
  origin: o,
3566
3758
  focus: k,
@@ -3593,6 +3785,7 @@ var Printer = class {
3593
3785
  const spec = {
3594
3786
  name,
3595
3787
  kind: body.v.kind,
3788
+ list: body.v.list,
3596
3789
  safe: body.v.safe,
3597
3790
  deps: body.v.deps,
3598
3791
  origin,
@@ -3612,6 +3805,7 @@ var Printer = class {
3612
3805
  }
3613
3806
  #app(e, ctx) {
3614
3807
  const { op, args } = e;
3808
+ if ((op === "if" || op === "ifError") && this.#wantList.has(e)) for (const x of args.slice(op === "if" ? 1 : 0)) this.#wantList.add(x);
3615
3809
  if (op === "if") return this.#if(args, ctx);
3616
3810
  if (op === "and" || op === "or") return this.#andOr(op === "and", args, ctx);
3617
3811
  if (op === "ifError") return this.#ifError(args, ctx);
@@ -3622,14 +3816,69 @@ var Printer = class {
3622
3816
  if (head !== void 0 && (op === "sortBy" || op === "take" || op === "drop" && this.#isList(head, ctx))) return this.#order(op, head, rest, ctx);
3623
3817
  if (head !== void 0 && BUILD_OPS.has(op) && this.#isList(head, ctx)) return this.#build(op, head, rest, ctx);
3624
3818
  if (head !== void 0 && (FOLD_OPS.has(op) || op === "nth") && this.#isList(head, ctx)) return this.#overList(op, head, rest, ctx);
3819
+ for (const x of args) this.#wantList.add(x);
3625
3820
  const raw = args.map((x) => this.expr(x, ctx));
3626
3821
  const deps = depsOf(...raw);
3627
3822
  const values = this.#inOrder(this.#settle(raw, deps, args), true);
3823
+ if (op === "fill" && this.#facts.own(op)) return this.#fill(values, deps);
3628
3824
  return this.#opCall(op, values, deps);
3629
3825
  }
3826
+ /**
3827
+ * This method prints `fill(n, value)` without a domain with the op (LIST.FILL, COMPILE.MODULE.FILL). The helper `FI`
3828
+ * gets each value, so an error of an argument after the value is the error of the op. The keys are not the positions
3829
+ * of records, so the axis `list` over the list cannot read a record at its keys.
3830
+ */
3831
+ #fill(values, deps) {
3832
+ const value = values[1]?.v;
3833
+ const list = {
3834
+ item: value?.kind,
3835
+ inner: value?.list,
3836
+ texts: true
3837
+ };
3838
+ return {
3839
+ s: stmtsOf(...values),
3840
+ v: {
3841
+ code: `${this.use("FI")}(${values.map((x) => x.v.code).join(", ")})`,
3842
+ kind: void 0,
3843
+ safe: false,
3844
+ deps,
3845
+ list
3846
+ }
3847
+ };
3848
+ }
3849
+ /**
3850
+ * This method gives the code of a value outside the list ops: a list is a `vex.list`, as in the interpreter
3851
+ * (COMPILE.MODULE.LIST.ARG, COMPILE.MODULE.LIST.FIELD). An error item has the error `VEX_ERROR`.
3852
+ */
3853
+ #plain(v) {
3854
+ return v.list === void 0 ? v.code : `${this.use("LV")}(${v.code}, ${String(depthOf(v.list))})`;
3855
+ }
3856
+ /** This method gives the samples of a list of the facts `l`: no items, items with values, and an error item. */
3857
+ #listSamples(l) {
3858
+ const items = (l.inner !== void 0 ? [vexList([])] : l.item === void 0 ? SAMPLES.number : this.#samples(l.item)).map((value, i) => ({
3859
+ key: String(i),
3860
+ result: {
3861
+ ok: true,
3862
+ value
3863
+ }
3864
+ }));
3865
+ return [
3866
+ vexList([]),
3867
+ vexList(items),
3868
+ vexList([{
3869
+ key: "0",
3870
+ result: {
3871
+ ok: false,
3872
+ error: { vexError: true }
3873
+ }
3874
+ }])
3875
+ ];
3876
+ }
3630
3877
  /** This method prints the call of the op of a domain on some values, from the static site of their kinds. */
3631
3878
  #opCall(op, values, deps) {
3632
- const site = this.#facts.staticSite(op, values.map((x) => x.v.kind));
3879
+ const lists = new Set(values.flatMap((x, i) => x.v.list === void 0 ? [] : [i]));
3880
+ if (lists.has(0)) throw new NotStandalone(isListOp(op) ? `the list op "${op}"` : `a list as the receiver of the op "${op}"`);
3881
+ const site = this.#facts.staticSite(op, values.map((x) => x.v.kind), lists);
3633
3882
  if (site?.t !== "fn") throw new NotStandalone(`the kinds of the values of "${op}" do not decide its op`);
3634
3883
  if (site.bad) return {
3635
3884
  s: stmtsOf(...values),
@@ -3646,12 +3895,12 @@ var Printer = class {
3646
3895
  if (!this.#forms.has(name)) {
3647
3896
  const fn = d.ops[op].fn;
3648
3897
  const kinds = values.map((x) => x.v.kind).filter((k) => k !== void 0);
3649
- const src = copied(fn, kinds.map((k) => this.#samples(k)), `the op "${op}" of the domain ${d.name}`);
3650
- this.#forms.set(name, kinds.every((k) => primitiveOf(k) !== void 0) ? inlineForm(src) : void 0);
3898
+ const src = copied(fn, values.flatMap((x) => x.v.list !== void 0 ? [this.#listSamples(x.v.list)] : x.v.kind === void 0 ? [] : [this.#samples(x.v.kind)]), `the op "${op}" of the domain ${d.name}`);
3899
+ this.#forms.set(name, lists.size === 0 && kinds.every((k) => primitiveOf(k) !== void 0) ? inlineForm(src) : void 0);
3651
3900
  this.top.set(name, `const ${name} = ${src};`);
3652
3901
  }
3653
3902
  const form = this.#forms.get(name);
3654
- if (form !== void 0 && form.params.length === values.length && values.every((x, i) => form.uses[i] === 1 || x.v.plain === true && x.v.safe && form.uses[i] > 0)) {
3903
+ if (form !== void 0 && 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] > 0)) {
3655
3904
  const text = form.parts.map((x) => typeof x === "number" ? `(${values[x].v.code})` : x).join("");
3656
3905
  const checked = this.check(site.returns);
3657
3906
  const code = checked === void 0 ? `(${text})` : `${checked}(${text})`;
@@ -3666,7 +3915,7 @@ var Printer = class {
3666
3915
  };
3667
3916
  }
3668
3917
  this.#called.add(name);
3669
- const code = this.#checked(site.returns, `${name}(${values.map((x) => x.v.code).join(", ")})`);
3918
+ const code = this.#checked(site.returns, `${name}(${values.map((x) => this.#plain(x.v)).join(", ")})`);
3670
3919
  return {
3671
3920
  s: stmtsOf(...values),
3672
3921
  v: {
@@ -3695,7 +3944,8 @@ var Printer = class {
3695
3944
  const v = {
3696
3945
  kind: join(yes.v.kind, no.v.kind),
3697
3946
  safe: this.#safeBoolean(cond.v) && yes.v.safe && no.v.safe,
3698
- deps
3947
+ deps,
3948
+ list: branchLists("if", yes.v.list, no.v.list)
3699
3949
  };
3700
3950
  if (yes.s.length === 0 && no.s.length === 0) return {
3701
3951
  s: cond.s,
@@ -3777,7 +4027,8 @@ var Printer = class {
3777
4027
  code: t,
3778
4028
  kind: join(first.v.kind, second.v.kind),
3779
4029
  safe: second.v.safe,
3780
- deps
4030
+ deps,
4031
+ list: branchLists("ifError", first.v.list, second.v.list)
3781
4032
  }
3782
4033
  };
3783
4034
  }
@@ -3843,7 +4094,7 @@ var Printer = class {
3843
4094
  if (base.t === "list") {
3844
4095
  if (at.length > 0) throw new NotStandalone("the axis \"list\" with an address");
3845
4096
  const list = this.#hoist(this.#listOf(base.list, ctx), hasLoop(base.list));
3846
- if (list.v.list.texts === true) throw new NotStandalone("the axis \"list\" over a list with the keys of a literal");
4097
+ const texts = list.v.list.texts === true;
3847
4098
  const a = this.fresh("A");
3848
4099
  const q = this.fresh("q");
3849
4100
  const head = reverse ? `for (let ${q} = ${a}.length - 1; ${q} >= 0; ${q}--) {` : `for (let ${q} = 0; ${q} < ${a}.length; ${q}++) {`;
@@ -3860,7 +4111,8 @@ var Printer = class {
3860
4111
  start: list.v.deps,
3861
4112
  startSafe: list.v.safe,
3862
4113
  tests,
3863
- inner
4114
+ inner,
4115
+ texts
3864
4116
  };
3865
4117
  }
3866
4118
  const s = [];
@@ -3891,7 +4143,8 @@ var Printer = class {
3891
4143
  start,
3892
4144
  startSafe,
3893
4145
  tests,
3894
- inner
4146
+ inner,
4147
+ texts: false
3895
4148
  };
3896
4149
  }
3897
4150
  if (this.#graph && GRAPH_AXES.has(base.t)) {
@@ -3908,7 +4161,8 @@ var Printer = class {
3908
4161
  start,
3909
4162
  startSafe,
3910
4163
  tests,
3911
- inner
4164
+ inner,
4165
+ texts: false
3912
4166
  };
3913
4167
  }
3914
4168
  if (this.#graph && base.t === "window") throw new NotStandalone("the axis \"window\" in a graph space");
@@ -3930,10 +4184,18 @@ var Printer = class {
3930
4184
  start,
3931
4185
  startSafe,
3932
4186
  tests,
3933
- inner
4187
+ inner,
4188
+ texts: false
3934
4189
  };
3935
4190
  }
3936
4191
  /**
4192
+ * This method gives a reason when a part of a loop of the axis `list` reads at a target that is not a record. The
4193
+ * interpreter reads the record of such a key, and a module has no record for it.
4194
+ */
4195
+ #readsNoTarget(texts, level, deps) {
4196
+ if (texts && deps.some((d) => d.has(level))) throw new NotStandalone("the axis \"list\" reads a record at a key of a literal or of \"fill\"");
4197
+ }
4198
+ /**
3937
4199
  * This method gives the targets of an axis of a graph space at the position `f` (AXIS.GRAPH). They are the positions
3938
4200
  * `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.
3939
4201
  */
@@ -4004,10 +4266,11 @@ var Printer = class {
4004
4266
  #list(op, target, rest, ctx) {
4005
4267
  const { strict, step } = this.#foldOptions(op, rest);
4006
4268
  const at = target.at ?? [];
4007
- const { s, j, head, key, check, skip, fixed, start, startSafe, tests, inner } = this.#targetLoop(target.axis, at, ctx);
4269
+ const { s, j, head, key, check, skip, fixed, start, startSafe, tests, inner, texts } = this.#targetLoop(target.axis, at, ctx);
4008
4270
  const { level } = inner;
4009
4271
  const testCodes = tests.map((t) => this.#hoist(this.expr(t, inner), hasLoop(t)));
4010
4272
  const body = this.#hoist(this.expr(target.body, inner), hasLoop(target.body));
4273
+ this.#readsNoTarget(texts, level, [body, ...testCodes].map((x) => x.v.deps));
4011
4274
  if (op === "count" && fixed && tests.length === 0 && body.v.safe && !body.v.deps.has(CELLS)) return bare(plainValue("n", "number"));
4012
4275
  const deps = new Set([...start, ...[body, ...testCodes].flatMap((x) => [...x.v.deps])].filter((d) => d !== level));
4013
4276
  const r = this.#reduction(op, body.v.kind, step);
@@ -4183,10 +4446,11 @@ var Printer = class {
4183
4446
  */
4184
4447
  #eachList(e, ctx) {
4185
4448
  const at = e.at ?? [];
4186
- const { s, j, head, key, check, skip, start, startSafe, tests, inner } = this.#targetLoop(e.axis, at, ctx);
4449
+ const { s, j, head, key, check, skip, start, startSafe, tests, inner, texts } = this.#targetLoop(e.axis, at, ctx);
4187
4450
  const testCodes = tests.map((t) => this.#hoist(this.expr(t, inner), hasLoop(t)));
4188
4451
  if (this.#wantList.has(e)) this.#wantList.add(e.body);
4189
4452
  const body = this.#hoist(this.expr(e.body, inner), hasLoop(e.body));
4453
+ this.#readsNoTarget(texts, inner.level, [body, ...testCodes].map((x) => x.v.deps));
4190
4454
  const deps = new Set([...start, ...[body, ...testCodes].flatMap((x) => [...x.v.deps])].filter((d) => d !== inner.level));
4191
4455
  const list = this.fresh("L");
4192
4456
  const v = this.fresh("x");
@@ -4225,7 +4489,8 @@ var Printer = class {
4225
4489
  deps,
4226
4490
  list: {
4227
4491
  item: body.v.kind,
4228
- inner: body.v.list
4492
+ inner: body.v.list,
4493
+ texts
4229
4494
  }
4230
4495
  }
4231
4496
  };
@@ -4237,15 +4502,22 @@ var Printer = class {
4237
4502
  #order(op, head, rest, ctx) {
4238
4503
  const list = this.#listOf(head, ctx);
4239
4504
  const exprs = [head, ...op === "sortBy" ? [] : [rest[0] ?? lit(null)]];
4240
- const strict = this.#strict(op, rest.slice(exprs.length - 1));
4505
+ const options = rest.slice(exprs.length - 1);
4506
+ const strict = this.#strict(op, options, op === "sortBy" ? ["strict", "by"] : ["strict"]);
4507
+ const by = op === "sortBy" ? this.#sortValue(options, list.v.list) : void 0;
4241
4508
  const raw = [list, ...exprs.slice(1).map((x) => this.expr(x, ctx))];
4242
4509
  const deps = depsOf(...raw);
4243
4510
  const parts = this.#inOrder(this.#settle(raw, deps, exprs), true);
4244
- const helper = op === "sortBy" ? "SB" : op === "take" ? "TK" : "DR";
4511
+ const helper = by !== void 0 ? "SK" : op === "sortBy" ? "SB" : op === "take" ? "TK" : "DR";
4512
+ const args = [
4513
+ ...parts.map((x) => x.v.code),
4514
+ String(strict),
4515
+ ...by === void 0 ? [] : [by]
4516
+ ];
4245
4517
  return {
4246
4518
  s: stmtsOf(...parts),
4247
4519
  v: {
4248
- code: `${this.use(helper)}(${[...parts.map((x) => x.v.code), String(strict)].join(", ")})`,
4520
+ code: `${this.use(helper)}(${args.join(", ")})`,
4249
4521
  kind: void 0,
4250
4522
  safe: false,
4251
4523
  deps,
@@ -4254,6 +4526,25 @@ var Printer = class {
4254
4526
  };
4255
4527
  }
4256
4528
  /**
4529
+ * This method gives the function of the option `by` of `sortBy` (COMPILE.MODULE.SORT.BY), or undefined without the
4530
+ * option. The function applies the op of the static site of the kind of the items. An empty list applies no op.
4531
+ */
4532
+ #sortValue(options, info) {
4533
+ const by = options[0]?.value?.by;
4534
+ if (by === void 0) return void 0;
4535
+ if (typeof by !== "string") throw new NotStandalone("the option \"by\" of \"sortBy\" is not a literal text");
4536
+ if (info.empty === true) return void 0;
4537
+ if (info.item === void 0) throw new NotStandalone(`the kinds of the items of "sortBy" do not decide the op "${by}" of the option by`);
4538
+ const x = this.fresh("x");
4539
+ return `((${x}) => ${this.#opCall(by, [bare({
4540
+ code: x,
4541
+ kind: info.item,
4542
+ safe: true,
4543
+ deps: NO_DEPS,
4544
+ plain: true
4545
+ })], NO_DEPS).v.code})`;
4546
+ }
4547
+ /**
4257
4548
  * This method prints append, without and flat (LIST.BUILD), get (LIST.GET) and indexOf (LIST.INDEXOF) over the array
4258
4549
  * of a list. Each list that the op reads follows LIST.LENIENT, as in the interpreter.
4259
4550
  */
@@ -4280,7 +4571,7 @@ var Printer = class {
4280
4571
  if (op === "get") return value(info.item, info.inner);
4281
4572
  if (op === "indexOf") return value("number", void 0);
4282
4573
  if (op === "without") return value(void 0, info);
4283
- if (op === "append") return value(void 0, joinLists(info, parts[1].v.list));
4574
+ if (op === "append") return value(void 0, joinLists(info, parts[1].v.list, op));
4284
4575
  if (info.empty === true) return value(void 0, info);
4285
4576
  if (info.inner === void 0) throw new NotStandalone("\"flat\" over a list whose items are not lists");
4286
4577
  return value(void 0, info.inner);
@@ -4335,7 +4626,7 @@ var Printer = class {
4335
4626
  const env = new Map(ctx.env);
4336
4627
  const vars = /* @__PURE__ */ new Map();
4337
4628
  const deps = /* @__PURE__ */ new Set();
4338
- const keyed = Object.values(step).some(hasKeyedLiteral);
4629
+ const keyed = Object.values(step).some(hasTextKeys);
4339
4630
  for (const [name, x] of Object.entries(init)) {
4340
4631
  this.#wantList.add(x);
4341
4632
  const c = this.expr(x, ctx);
@@ -4446,6 +4737,7 @@ var Printer = class {
4446
4737
  ...t.inner,
4447
4738
  env: names.env
4448
4739
  }, names.vars);
4740
+ this.#readsNoTarget(t.texts, t.inner.level, [...tests.map((x) => x.v.deps), step.deps]);
4449
4741
  const result = this.expr(e.result, {
4450
4742
  ...ctx,
4451
4743
  env: names.env
@@ -4488,6 +4780,7 @@ var Printer = class {
4488
4780
  * is a constant of the run itself.
4489
4781
  */
4490
4782
  #memoized(e, keys, ctx) {
4783
+ for (const k of keys) this.#wantList.add(k);
4491
4784
  const values = keys.map((k) => this.#hoist(this.expr(k, ctx)));
4492
4785
  const varying = keys.filter((_k, i) => values[i].v.deps.size > 0);
4493
4786
  const params = varying.map(() => this.fresh("q"));
@@ -4498,7 +4791,8 @@ var Printer = class {
4498
4791
  code: params[p],
4499
4792
  kind: x.kind,
4500
4793
  lazy: true,
4501
- deps: /* @__PURE__ */ new Set([1])
4794
+ deps: /* @__PURE__ */ new Set([1]),
4795
+ list: x.list
4502
4796
  }];
4503
4797
  }));
4504
4798
  const outer = this.#inside;
@@ -4519,7 +4813,8 @@ var Printer = class {
4519
4813
  }
4520
4814
  const tokens = new Map(keys.map((k, i) => [k, varying.includes(k) ? {
4521
4815
  "#": varying.indexOf(k),
4522
- kind: values[i].v.kind
4816
+ kind: values[i].v.kind,
4817
+ list: values[i].v.list
4523
4818
  } : { "@": names.get(k).code }]));
4524
4819
  const structure = canonical(e, (x) => tokens.get(x));
4525
4820
  let fn = this.#structures.get(structure);
@@ -4665,6 +4960,7 @@ var Printer = class {
4665
4960
  /** This method gives the code of the program at the key of the run. A constant of the run evaluates once. */
4666
4961
  /** This method gives the code of a program at the key `o` of the run. A sheet has one program for each formula. */
4667
4962
  root(expr) {
4963
+ this.#wantList.add(expr);
4668
4964
  return this.#hoist(this.expr(expr, {
4669
4965
  origin: "o",
4670
4966
  focus: "o",
@@ -4718,6 +5014,18 @@ function reasonOf(thrown) {
4718
5014
  };
4719
5015
  }
4720
5016
  /**
5017
+ * 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
5018
+ * the array of the list when the program reads the field (COMPILE.MODULE.LIST.INPUT). The code is true for a field
5019
+ * against the schema.
5020
+ */
5021
+ function fieldCheck(p, field, kind) {
5022
+ const input = `r[${JSON.stringify(field)}]`;
5023
+ if (typeof kind !== "object") return p.against(kind, input);
5024
+ const read = `${p.use("LI")}(${input}, ${String(depthOf(listOfKind(kind)))}, ${p.test(leafOf(kind))})`;
5025
+ const keep = p.inputs.get(field);
5026
+ return `${keep === void 0 ? read : `(${keep}[i] = ${read})`} === undefined`;
5027
+ }
5028
+ /**
4721
5029
  * This function gives the text of a module: the declarations, the helpers, and the function of the run. The run checks
4722
5030
  * its input, computes the parts of the tree and the constants of the run, and then gives the statements `body`.
4723
5031
  */
@@ -4733,7 +5041,7 @@ function printModule(p, options, run, body) {
4733
5041
  let fieldChecks;
4734
5042
  let varChecks;
4735
5043
  try {
4736
- fieldChecks = fields.map(([f, k]) => ` || ${p.against(k, `r[${JSON.stringify(f)}]`)}`).join("");
5044
+ fieldChecks = fields.map(([f, k]) => ` || ${fieldCheck(p, f, k)}`).join("");
4737
5045
  varChecks = vars.map(([v, k]) => ` || ${p.against(k, `vars[${JSON.stringify(v)}]`)}`).join("");
4738
5046
  } catch (thrown) {
4739
5047
  return reasonOf(thrown);
@@ -4780,6 +5088,7 @@ function printModule(p, options, run, body) {
4780
5088
  " if (!Array.isArray(records)) C(\"the records are not an array\");",
4781
5089
  " const R = records;",
4782
5090
  " const n = R.length;",
5091
+ ...[...p.inputs.values()].map((x) => ` const ${x} = [];`),
4783
5092
  " for (let i = 0; i < n; i++) {",
4784
5093
  " const r = R[i];",
4785
5094
  ` if (typeof r !== "object" || r === null${fieldChecks}) C(\`the record \${i} does not keep the schema\`);`,
@@ -4829,12 +5138,13 @@ function emitModule(source, options) {
4829
5138
  } catch (thrown) {
4830
5139
  return reasonOf(thrown);
4831
5140
  }
5141
+ const result = value.v.list === void 0 ? value.v.code : `${p.use("LO")}(${value.v.code}, ${String(depthOf(value.v.list))})`;
4832
5142
  return printModule(p, options, run, [
4833
5143
  "const out = [];",
4834
5144
  "for (let o = 0; o < n; o++) {",
4835
5145
  " try {",
4836
5146
  ...ind(ind(value.s)),
4837
- ` out.push(${value.v.code});`,
5147
+ ` out.push(${result});`,
4838
5148
  " } catch {",
4839
5149
  " out.push(VEX_ERROR);",
4840
5150
  " }",
@@ -4846,8 +5156,33 @@ function emitModule(source, options) {
4846
5156
  const SHEET_BUDGET = 3e3;
4847
5157
  /** This function gives the words for a formula in a reason: the formula of a column, or of one cell. */
4848
5158
  const formulaText = (f) => f.key === void 0 ? `the formula of the column "${f.column}"` : `the formula of the cell "${f.column}" at "${String(f.key)}"`;
4849
- /** This function gives the words for a kind in a reason. */
4850
- const kindText = (k) => k ?? "that the printer does not know";
5159
+ /** This function gives the words for a kind in a reason. A list gives the kind of its items. */
5160
+ const kindText = (k, l) => l === void 0 ? k ?? "that the printer does not know" : `list of ${l.inner === void 0 ? kindText(l.item) : kindText(void 0, l.inner)}`;
5161
+ /** This function gives the number of the levels of lists in the items of a list: 0 for a list of values. */
5162
+ const depthOf = (l) => l.inner === void 0 ? 0 : 1 + depthOf(l.inner);
5163
+ /** This function gives the facts of the lists of a column from the kind of the option `kinds` (COMPILE.MODULE.SHEET.LIST). */
5164
+ const listOfKind = (k, all = false) => {
5165
+ const texts = all || k.texts === true;
5166
+ return typeof k.list === "object" ? {
5167
+ item: void 0,
5168
+ inner: listOfKind(k.list, all),
5169
+ texts
5170
+ } : {
5171
+ item: k.list,
5172
+ texts
5173
+ };
5174
+ };
5175
+ /** This function gives the kind of the items at the bottom of a list kind. */
5176
+ const leafOf = (k) => typeof k.list === "object" ? leafOf(k.list) : k.list;
5177
+ /**
5178
+ * This function gives the facts of the lists of a column from the list of its first formula. The other cells of the
5179
+ * column can have other formulas. Thus a list without items does not tell that each list of the column is empty.
5180
+ */
5181
+ const columnList = (l) => ({
5182
+ item: l.item,
5183
+ inner: l.inner === void 0 ? void 0 : columnList(l.inner),
5184
+ texts: l.texts === true
5185
+ });
4851
5186
  /**
4852
5187
  * This function prints the formula columns of a sheet as a standalone ES module (COMPILE.MODULE.SHEET). The function of
4853
5188
  * the module takes the records and the variables, and the parents for a tree. It gives an object with an array for
@@ -4891,22 +5226,46 @@ function emitSheetModule(columns, options) {
4891
5226
  reason: `${formulaText(f)}: ${shape}`
4892
5227
  };
4893
5228
  }
4894
- const kinds = new Map(Object.entries(options.kinds ?? {}));
5229
+ const kinds = /* @__PURE__ */ new Map();
5230
+ const lists = /* @__PURE__ */ new Map();
5231
+ for (const [c, k] of Object.entries(options.kinds ?? {})) {
5232
+ kinds.set(c, typeof k === "object" ? void 0 : k);
5233
+ if (typeof k === "object") lists.set(c, listOfKind(k));
5234
+ }
4895
5235
  const index = new Map(names.map((c, i) => [c, i]));
4896
5236
  const direct = formulas.every((f) => f.key === void 0) && order.every((c) => readsFinished(columns, order, c, run.tree));
4897
5237
  const p = new Printer(rec(Object.fromEntries(formulas.map((f, i) => [`f${String(i)}`, f.expr]))), options, {
4898
5238
  columns: index,
4899
5239
  kinds,
5240
+ lists,
4900
5241
  direct
4901
5242
  });
4902
5243
  const fns = [];
4903
5244
  const decls = [];
5245
+ const blocks = /* @__PURE__ */ new Map();
4904
5246
  try {
4905
5247
  for (const f of formulas) {
4906
5248
  const code = p.root(f.expr);
4907
- const kind = code.v.kind;
4908
- if (!kinds.has(f.column)) kinds.set(f.column, kind);
4909
- else if (kinds.get(f.column) !== kind) throw new NotStandalone(`${formulaText(f)} gives a value of the kind ${kindText(kind)}, not of the kind ${kindText(kinds.get(f.column))} of its column`);
5249
+ const { kind, list } = code.v;
5250
+ if (!kinds.has(f.column)) {
5251
+ kinds.set(f.column, kind);
5252
+ if (list !== void 0) lists.set(f.column, columnList(list));
5253
+ } else {
5254
+ const known = lists.get(f.column);
5255
+ if (kinds.get(f.column) !== kind || known === void 0 !== (list === void 0) || known !== void 0 && !fits(known, list)) throw new NotStandalone(`${formulaText(f)} gives a value of the kind ${kindText(kind, list)}, not of the kind ${kindText(kinds.get(f.column), known)} of its column`);
5256
+ }
5257
+ if (direct) {
5258
+ const at = `D[${String(index.get(f.column))}][o]`;
5259
+ blocks.set(f.column, code.v.safe && code.s.length === 0 ? [`${at} = ${code.v.code};`] : [
5260
+ "try {",
5261
+ ...ind(code.s),
5262
+ ` ${at} = ${code.v.code};`,
5263
+ "} catch {",
5264
+ ` ${at} = E;`,
5265
+ "}"
5266
+ ]);
5267
+ continue;
5268
+ }
4910
5269
  const fn = p.fresh("cf");
4911
5270
  fns.push(fn);
4912
5271
  decls.push(...code.v.safe && code.s.length === 0 ? [`const ${fn} = (o) => ${code.v.code};`] : [
@@ -4924,41 +5283,58 @@ function emitSheetModule(columns, options) {
4924
5283
  } catch (thrown) {
4925
5284
  return reasonOf(thrown);
4926
5285
  }
4927
- const entry = (i) => `[${fns[i]}, ${String(3 * nestingOf(formulas[i].expr) + 16)}]`;
4928
- const own = names.map((c) => {
4929
- const at = formulas.flatMap((f, i) => f.column === c && f.key !== void 0 ? [`${String(f.key)}: ${entry(i)}`] : []);
4930
- return at.length === 0 ? "undefined" : `{ ${at.join(", ")} }`;
4931
- });
4932
- const cols = names.map((c) => {
4933
- const i = formulas.findIndex((f) => f.column === c && f.key === void 0);
4934
- return i < 0 ? "undefined" : entry(i);
4935
- });
4936
5286
  p.use(direct ? "DO" : "SH");
4937
- const fnOf = new Map(formulas.map((f, i) => [f.column, fns[i]]));
4938
- const fillOf = (c, at) => direct ? `D[${at}][o] = ${fnOf.get(c)}(o);` : `SS.f(${at}, o);`;
4939
5287
  const orders = /* @__PURE__ */ new Map();
4940
- const fill = order.map((c) => {
5288
+ const headOf = (c) => {
4941
5289
  const { reverse, post, back } = keyOrderOf(readsOf(columns, cells, c).directions);
4942
- const at = String(index.get(c));
4943
- 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)}`;
5290
+ if (!run.tree) return reverse ? "for (let o = n - 1; o >= 0; o--)" : "for (let o = 0; o < n; o++)";
4944
5291
  const args = `${p.use("KO")}(H, RT, ${String(post)}, ${String(back)})`;
4945
5292
  let keys = orders.get(args);
4946
5293
  if (keys === void 0) {
4947
5294
  keys = p.fresh("K");
4948
5295
  orders.set(args, keys);
4949
5296
  }
4950
- return `for (const o of ${keys}) ${fillOf(c, at)}`;
4951
- });
5297
+ return `for (const o of ${keys})`;
5298
+ };
5299
+ let fill;
5300
+ if (direct) {
5301
+ const loops = [];
5302
+ for (const c of order) {
5303
+ const head = headOf(c);
5304
+ const last = loops.at(-1);
5305
+ if (last?.head === head && readsFinished(columns, order, c, run.tree, new Set(last.columns))) last.columns.push(c);
5306
+ else loops.push({
5307
+ head,
5308
+ columns: [c]
5309
+ });
5310
+ }
5311
+ fill = [];
5312
+ for (const { head, columns: cs } of loops) fill.push(`${head} {`, ...cs.flatMap((c) => ind(blocks.get(c))), "}");
5313
+ } else {
5314
+ const entry = (i) => `[${fns[i]}, ${String(3 * nestingOf(formulas[i].expr) + 16)}]`;
5315
+ const own = names.map((c) => {
5316
+ const at = formulas.flatMap((f, i) => f.column === c && f.key !== void 0 ? [`${String(f.key)}: ${entry(i)}`] : []);
5317
+ return at.length === 0 ? "undefined" : `{ ${at.join(", ")} }`;
5318
+ });
5319
+ const cols = names.map((c) => {
5320
+ const i = formulas.findIndex((f) => f.column === c && f.key === void 0);
5321
+ return i < 0 ? "undefined" : entry(i);
5322
+ });
5323
+ decls.push(`const SS = SH(n, [${cols.join(", ")}], [${own.join(", ")}], ${String(budget)});`, `const ${READ_CELL} = SS.r;`);
5324
+ fill = order.map((c) => `${headOf(c)} SS.f(${String(index.get(c))}, o);`);
5325
+ }
4952
5326
  if (run.tree) p.treeParts.add("children");
5327
+ const resultOf = (c, read) => {
5328
+ const l = lists.get(c);
5329
+ return l === void 0 ? read : `${p.use("LC")}(${read}, ${String(depthOf(l))})`;
5330
+ };
4953
5331
  return printModule(p, options, run, [
4954
- ...decls,
4955
- ...direct ? [`const D = [${names.map(() => "new Array(n)").join(", ")}];`, `const ${READ_CELL} = (c, k) => D[c][k];`] : [`const SS = SH(n, [${cols.join(", ")}], [${own.join(", ")}], ${String(budget)});`, `const ${READ_CELL} = SS.r;`],
5332
+ ...direct ? [`const D = [${names.map(() => "new Array(n)").join(", ")}];`] : decls,
4956
5333
  ...[...orders].map(([args, keys]) => `const ${keys} = ${args};`),
4957
5334
  ...fill,
4958
- `return { ${names.map((c, i) => `${JSON.stringify(c)}: ${direct ? `DO(D[${String(i)}])` : `SS.o(${String(i)})`}`).join(", ")} };`
5335
+ `return { ${names.map((c, i) => `${JSON.stringify(c)}: ${resultOf(c, direct ? `DO(D[${String(i)}])` : `SS.o(${String(i)})`)}`).join(", ")} };`
4959
5336
  ]);
4960
5337
  }
4961
- //#endregion
4962
5338
  export { FALLBACK, createRuntime, emitModule, emitSheetModule, generate, load, tiered };
4963
5339
 
4964
5340
  //# sourceMappingURL=index.js.map