@mark1russell7/vex-compiler 0.13.3 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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
@@ -1992,8 +1994,7 @@ function readsFinished(columns, order, self, tree, fused = /* @__PURE__ */ new S
1992
1994
  }
1993
1995
  return true;
1994
1996
  }
1995
- //#endregion
1996
- //#region src/module.ts
1997
+ // src/module.ts
1997
1998
  /**
1998
1999
  * Standalone modules (docs/COMPILER.md §4.4 and §6). `emitModule` prints a program as an ES module that has no import of
1999
2000
  * Vex. A host that guarantees the kinds of its input uses it without the interpreter, for example ireko at build time.
@@ -2016,7 +2017,10 @@ function readsFinished(columns, order, self, tree, fused = /* @__PURE__ */ new S
2016
2017
  * move `parent` and the axes of a tree (COMPILE.MODULE.TREE). A graph space has the axes of a graph
2017
2018
  * (COMPILE.MODULE.GRAPH). A list is an array of pairs of a key and a value. The list ops, `reduce`, list literals and
2018
2019
  * lists as names of loops are in a module (COMPILE.MODULE.LIST, COMPILE.MODULE.REDUCE). The value of a program can be a
2019
- * list, and the run gives it as a `vex.list` (COMPILE.MODULE.LIST.RESULT). The kinds of each op site must decide its op.
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.
2020
2024
  * Another construct gives a reason, not code.
2021
2025
  *
2022
2026
  * `emitSheetModule` prints the formula columns of a sheet as one module (COMPILE.MODULE.SHEET). Each column is an array
@@ -2028,6 +2032,10 @@ function readsFinished(columns, order, self, tree, fused = /* @__PURE__ */ new S
2028
2032
  var NotStandalone = class extends Error {};
2029
2033
  /** The levels of a constant of the run. */
2030
2034
  const NO_DEPS = /* @__PURE__ */ new Set();
2035
+ /** The names of the items of a loop without `as` (COMPILE.MODULE.LIST.ITEM). */
2036
+ const NO_NAMES = /* @__PURE__ */ new Map();
2037
+ /** This function gives the names of a body or of a step: the names `as` of the items hide the names outside (AXIS.LIST.SCOPE). */
2038
+ const withNames = (env, items) => new Map([...env, ...items]);
2031
2039
  /**
2032
2040
  * The level of a read of a cell (COMPILE.MODULE.SHEET). The results of the cells change in a run. Thus a value that reads
2033
2041
  * a cell is not a constant or a column of the run. The level is far from the other levels.
@@ -2065,10 +2073,66 @@ const HELPERS = {
2065
2073
  " return o.sort((a, b) => (a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0));",
2066
2074
  "}"
2067
2075
  ].join("\n"),
2076
+ SK: [
2077
+ "function SK(l, s, f) {",
2078
+ " const o = V(l, s).map((x) => [x, f(x[1])]);",
2079
+ " const t = o.length > 0 ? typeof o[0][1] : \"number\";",
2080
+ " for (const [, v] of o) if (typeof v !== t || (t !== \"number\" && t !== \"string\") || v !== v) F();",
2081
+ " return o.sort((a, b) => (a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0)).map((x) => x[0]);",
2082
+ "}"
2083
+ ].join("\n"),
2068
2084
  TK: "function TK(l, n, s) { const o = V(l, s); return Number.isSafeInteger(n) && n >= 0 ? o.slice(0, n) : F(); }",
2069
- NT: "function NT(l, i, s) { const o = V(l, s); return Number.isSafeInteger(i) && i >= 0 && i < o.length ? o[i][1] : F(); }",
2085
+ VW: [
2086
+ "function VW(l) {",
2087
+ " let o = l.vw;",
2088
+ " if (o === undefined) {",
2089
+ " o = l.filter((x) => x[1] !== E);",
2090
+ " l.vw = o;",
2091
+ " }",
2092
+ " return o;",
2093
+ "}"
2094
+ ].join("\n"),
2095
+ NT: [
2096
+ "function NT(l, i, s) {",
2097
+ " const o = VW(l);",
2098
+ " if (s && o.length < l.length) F();",
2099
+ " return Number.isSafeInteger(i) && i >= 0 && i < o.length ? o[i][1] : F();",
2100
+ "}"
2101
+ ].join("\n"),
2102
+ CT: "function CT(l, s) { const o = VW(l); return s && o.length < l.length ? F() : o.length; }",
2103
+ FS: "function FS(l, s) { const o = VW(l); return (s && o.length < l.length) || o.length === 0 ? F() : o[0][1]; }",
2104
+ FI: [
2105
+ "function FI(n, v) {",
2106
+ " if (!(Number.isSafeInteger(n) && n >= 0 && n <= 100000 && v !== undefined)) F();",
2107
+ " const o = [];",
2108
+ " for (let i = 0; i < n; i++) o.push([i, v]);",
2109
+ " return o;",
2110
+ "}"
2111
+ ].join("\n"),
2112
+ LI: [
2113
+ "function LI(x, h, t) {",
2114
+ " if (typeof x !== \"object\" || x === null || x.kind !== \"vex.list\" || !Array.isArray(x.items)) return undefined;",
2115
+ " const o = [];",
2116
+ " for (let i = 0; i < x.items.length; i++) {",
2117
+ " const it = x.items[i];",
2118
+ " const r = typeof it === \"object\" && it !== null ? it.result : undefined;",
2119
+ " if (typeof r !== \"object\" || r === null || typeof it.key !== \"string\") return undefined;",
2120
+ " if (r.ok === true) {",
2121
+ " const v = h > 0 ? LI(r.value, h - 1, t) : r.value !== undefined && t(r.value) ? r.value : undefined;",
2122
+ " if (v === undefined) return undefined;",
2123
+ " o.push([it.key, v]);",
2124
+ " } else {",
2125
+ " const e = r.error;",
2126
+ " 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;",
2127
+ " o.push([it.key, E]);",
2128
+ " }",
2129
+ " }",
2130
+ " return o;",
2131
+ "}"
2132
+ ].join("\n"),
2070
2133
  DR: "function DR(l, n, s) { const o = V(l, s); return Number.isSafeInteger(n) && n >= 0 ? o.slice(n) : F(); }",
2071
2134
  AP: "function AP(l, o, s) { return V(l, s).concat(V(o, s)); }",
2135
+ AO: "function AO(l, o, s, w) { if (l !== w) return AP(l, o, s); for (const x of V(o, s)) l.push(x); return l; }",
2072
2136
  WO: [
2073
2137
  "function WO(l, o, s) {",
2074
2138
  " const a = V(l, s), g = new Map();",
@@ -2189,6 +2253,16 @@ const HELPERS = {
2189
2253
  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; }",
2190
2254
  DO: "function DO(d) { for (let k = 0; k < d.length; k++) if (d[k] === E) d[k] = VEX_ERROR; return d; }",
2191
2255
  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 } })) }; }",
2256
+ LV: [
2257
+ "function LV(l, h) {",
2258
+ " let o = l.vl;",
2259
+ " if (o === undefined) {",
2260
+ " 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 } }))) });",
2261
+ " l.vl = o;",
2262
+ " }",
2263
+ " return o;",
2264
+ "}"
2265
+ ].join("\n"),
2192
2266
  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; }",
2193
2267
  SH: [
2194
2268
  "function SH(n, cols, own, budget) {",
@@ -2452,10 +2526,17 @@ const NEEDS = {
2452
2526
  S: ["M1", "F"],
2453
2527
  V: ["F"],
2454
2528
  SB: ["V", "F"],
2529
+ SK: ["V", "F"],
2455
2530
  TK: ["V", "F"],
2456
- NT: ["V", "F"],
2531
+ VW: [],
2532
+ NT: ["VW", "F"],
2533
+ CT: ["VW", "F"],
2534
+ FS: ["VW", "F"],
2535
+ FI: ["F"],
2536
+ LI: [],
2457
2537
  DR: ["V", "F"],
2458
2538
  AP: ["V"],
2539
+ AO: ["AP", "V"],
2459
2540
  WO: ["V"],
2460
2541
  FL: ["V"],
2461
2542
  GT: ["F"],
@@ -2475,7 +2556,8 @@ const NEEDS = {
2475
2556
  KO: [],
2476
2557
  DO: [],
2477
2558
  LO: [],
2478
- LC: ["LO"]
2559
+ LC: ["LO"],
2560
+ LV: []
2479
2561
  };
2480
2562
  /** The statement of each part of a tree in a run, with the helper that computes it. */
2481
2563
  const TREE_PARTS = {
@@ -2543,43 +2625,80 @@ const BUILD_HELPERS = {
2543
2625
  get: "GT",
2544
2626
  indexOf: "IX"
2545
2627
  };
2546
- /** The list ops whose value is a list (LIST.SORT, LIST.TAKE and LIST.BUILD). */
2628
+ /**
2629
+ * The ops whose value is a list: the list ops of LIST.SORT, LIST.TAKE and LIST.BUILD, and `fill` (LIST.FILL). A domain
2630
+ * can have the op `fill`. Then the op of the domain gives no list, and the place of a list gives a reason.
2631
+ */
2547
2632
  const LIST_RESULTS = /* @__PURE__ */ new Set([
2548
2633
  "sortBy",
2549
2634
  "take",
2550
2635
  "drop",
2551
2636
  "append",
2552
2637
  "without",
2553
- "flat"
2638
+ "flat",
2639
+ "fill"
2554
2640
  ]);
2555
2641
  /**
2556
2642
  * This function tells if an expression gives a list. An each, a list literal and a list op of `LIST_RESULTS` give a
2557
- * 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.
2643
+ * 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
2644
+ * body of its function gives one (COMPILE.MODULE.LIST.CALL). The scope tells the names and the functions outside the expression.
2558
2645
  */
2559
- function listy(e, isName, isCell) {
2646
+ function listy(e, scope) {
2560
2647
  switch (e.tag) {
2561
2648
  case "each": return true;
2562
2649
  case "lit": return isVexList(e.value);
2563
- 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, isName, isCell));
2564
- case "var": return isName(e.name);
2565
- case "let": return listy(e.body, namesIn(e.bind, isName, isCell), isCell);
2650
+ 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));
2651
+ case "var": return scope.name(e.name);
2652
+ case "let": return listy(e.body, scopeIn(e.bind, scope));
2566
2653
  case "fold":
2567
- case "iterate": return listy(e.result, namesIn(e.init, isName, isCell), isCell);
2568
- case "ext": return isCell(e);
2569
- case "call":
2654
+ case "iterate": return listy(e.result, scopeIn(e.init, scope));
2655
+ case "ext": return scope.cell(e);
2656
+ case "ref": return scope.field(e);
2657
+ case "call": {
2658
+ const f = scope.fn(e.fn);
2659
+ return f !== void 0 && listy(f.fn.body, paramsIn(f, e.args, scope));
2660
+ }
2570
2661
  case "fn":
2571
- case "rec":
2572
- case "ref": return false;
2662
+ case "rec": return false;
2663
+ }
2664
+ }
2665
+ /**
2666
+ * This function gives the scope of some bindings. A value hides a name outside, and a function is not a list. A
2667
+ * function sees the scope outside the bindings, so it cannot call itself.
2668
+ */
2669
+ function scopeIn(bind, scope) {
2670
+ const lists = /* @__PURE__ */ new Map();
2671
+ const fns = /* @__PURE__ */ new Map();
2672
+ for (const [name, x] of Object.entries(bind)) {
2673
+ if (x.tag === "fn") fns.set(name, {
2674
+ fn: x,
2675
+ scope
2676
+ });
2677
+ lists.set(name, listy(x, scope));
2573
2678
  }
2679
+ return {
2680
+ ...scope,
2681
+ name: (name) => lists.get(name) ?? scope.name(name),
2682
+ fn: (name) => fns.get(name) ?? scope.fn(name)
2683
+ };
2574
2684
  }
2575
- /** 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. */
2576
- function namesIn(bind, isName, isCell) {
2577
- const lists = new Map(Object.entries(bind).map(([name, x]) => [name, x.tag !== "fn" && listy(x, isName, isCell)]));
2578
- return (name) => lists.get(name) ?? isName(name);
2685
+ /**
2686
+ * This function gives the scope of the body of a function at a call. The body sees the scope of the binding of the
2687
+ * function, and each parameter holds a list when its argument does.
2688
+ */
2689
+ function paramsIn(f, args, scope) {
2690
+ const lists = new Map(args.map((x, i) => [f.fn.params[i], listy(x, scope)]));
2691
+ return {
2692
+ ...f.scope,
2693
+ name: (name) => lists.get(name) ?? f.scope.name(name)
2694
+ };
2579
2695
  }
2580
- /** 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). */
2581
- function hasKeyedLiteral(e) {
2582
- return e.tag === "lit" && isVexList(e.value) && e.value.items.length > 0 || children(e).some(hasKeyedLiteral);
2696
+ /**
2697
+ * This function tells if an expression has a list literal with an item (LIST.LITERAL), or `fill` (LIST.FILL). Then a key
2698
+ * of a list of the expression can be a key that is not the position of a record.
2699
+ */
2700
+ function hasTextKeys(e) {
2701
+ return e.tag === "lit" && isVexList(e.value) && e.value.items.length > 0 || e.tag === "app" && e.op === "fill" || children(e).some(hasTextKeys);
2583
2702
  }
2584
2703
  /**
2585
2704
  * This function gives the facts of the list of `append` from the facts of its two lists. It also gives the list of
@@ -2624,6 +2743,23 @@ const NUMBER_STEPS = /* @__PURE__ */ new Set([
2624
2743
  /** This function gives the kind of the result of a list op: first gives the kind of its items. */
2625
2744
  const listKind = (op, item) => NUMBER_LIST_OPS.has(op) ? "number" : BOOLEAN_LIST_OPS.has(op) ? "boolean" : item;
2626
2745
  const LOOPS = /* @__PURE__ */ new WeakMap();
2746
+ /**
2747
+ * This function tells if the step of the name `name` of a loop appends to the list of the name (COMPILE.MODULE.APPEND.OWN).
2748
+ * It puts the append nodes of the form into `out`. The form is a read of the name,
2749
+ * `append(form, X)`, `if(c, form, form)` or a let with the form as its body. No other part of the form reads the name:
2750
+ * not `X`, not `c` and not a binding of a let.
2751
+ */
2752
+ function ownForm(e, name, out) {
2753
+ const free = (x) => !namesOf(x).has(name);
2754
+ if (e.tag === "var") return e.name === name;
2755
+ if (e.tag === "let") return Object.values(e.bind).every(free) && ownForm(e.body, name, out);
2756
+ if (e.tag !== "app" || e.args.length === 0) return false;
2757
+ const [head, ...rest] = e.args;
2758
+ if (e.op === "if") return free(head) && rest.every((x) => ownForm(x, name, out));
2759
+ if (e.op !== "append" || !rest.every(free) || !ownForm(head, name, out)) return false;
2760
+ out.push(e);
2761
+ return true;
2762
+ }
2627
2763
  /** This function gives the names that an expression reads, also the names that it binds itself. */
2628
2764
  function namesOf(e, out = /* @__PURE__ */ new Set()) {
2629
2765
  if (e.tag === "var") out.add(e.name);
@@ -2879,6 +3015,8 @@ var Printer = class {
2879
3015
  helpers = /* @__PURE__ */ new Set();
2880
3016
  /** The declarations at the top of the module: the functions of the domains and the checks of the results. */
2881
3017
  top = /* @__PURE__ */ new Map();
3018
+ /** The array of the lists of each field of the input that the program reads (COMPILE.MODULE.LIST.INPUT). */
3019
+ inputs = /* @__PURE__ */ new Map();
2882
3020
  /** The statements at the start of a run: the constants of the run and the functions of the memo. */
2883
3021
  run = [];
2884
3022
  /** The variables of the schema that the program reads. */
@@ -2903,6 +3041,8 @@ var Printer = class {
2903
3041
  #loops = 1e6;
2904
3042
  /** The node of the memo whose function the printer prints, so it prints the node itself. */
2905
3043
  #inside;
3044
+ /** The owner of each append node of the step of a loop that the printer prints (COMPILE.MODULE.APPEND.OWN). */
3045
+ #own = /* @__PURE__ */ new Map();
2906
3046
  #structures = /* @__PURE__ */ new Map();
2907
3047
  #kinds = /* @__PURE__ */ new Map();
2908
3048
  #ops = /* @__PURE__ */ new Map();
@@ -2993,7 +3133,21 @@ var Printer = class {
2993
3133
  */
2994
3134
  against(kind, input) {
2995
3135
  const primitive = primitiveOf(kind);
2996
- if (primitive !== void 0) return `typeof ${input} !== "${primitive}"`;
3136
+ return primitive === void 0 ? `!${this.#isOf(kind)}(${input})` : `typeof ${input} !== "${primitive}"`;
3137
+ }
3138
+ /**
3139
+ * 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
3140
+ * test of a primitive type checks the JavaScript type, and the test of a domain is the copy of its `is`.
3141
+ */
3142
+ test(kind) {
3143
+ const primitive = primitiveOf(kind);
3144
+ if (primitive === void 0) return this.#isOf(kind);
3145
+ const name = `is_${primitive}`;
3146
+ this.top.set(name, `const ${name} = (x) => typeof x === "${primitive}";`);
3147
+ return name;
3148
+ }
3149
+ /** This method gives the name of the copy of the test `is` of the domain of a kind. */
3150
+ #isOf(kind) {
2997
3151
  const d = this.#domains.findIndex((x) => kindOfDomain(x) === kind);
2998
3152
  const domain = this.#domains[d];
2999
3153
  if (domain === void 0) throw new NotStandalone(`the schema has the kind ${kind}, and no domain has it`);
@@ -3010,7 +3164,7 @@ var Printer = class {
3010
3164
  ]], `the test "is" of the domain ${domain.name}`);
3011
3165
  this.top.set(name, `const ${name} = ${src};`);
3012
3166
  }
3013
- return `!${name}(${input})`;
3167
+ return name;
3014
3168
  }
3015
3169
  /** This method gives a new name for the code. */
3016
3170
  fresh(prefix) {
@@ -3128,7 +3282,38 @@ var Printer = class {
3128
3282
  }
3129
3283
  /** This method tells if an expression gives a list at a place that takes one (`listy`). */
3130
3284
  #isList(e, ctx) {
3131
- return listy(e, (name) => ctx.env.get(name)?.list !== void 0, (x) => this.#cellList(x) !== void 0);
3285
+ const key = ctx.keys.get(e);
3286
+ if (key !== void 0) return key.list !== void 0;
3287
+ return listy(e, this.#scopeOf(ctx));
3288
+ }
3289
+ /**
3290
+ * This method tells if the body of an each can give a list. The facts of the names `as` of its items come from its
3291
+ * list, which the printer prints only in the loop. So here each such name can hold a list. Then a list op goes over the
3292
+ * array of the each, and that array gives the value of the interpreter too (COMPILE.MODULE.LIST.ITEM).
3293
+ */
3294
+ #bodyList(e, ctx) {
3295
+ if (e.as === void 0) return this.#isList(e.body, ctx);
3296
+ const scope = this.#scopeOf(ctx);
3297
+ const names = e.as;
3298
+ return listy(e.body, {
3299
+ ...scope,
3300
+ name: (name) => names.includes(name) || scope.name(name)
3301
+ });
3302
+ }
3303
+ /** This method gives the scope of `listy` at a node: the names and the bound functions of its context. */
3304
+ #scopeOf(ctx) {
3305
+ return {
3306
+ name: (name) => ctx.env.get(name)?.list !== void 0,
3307
+ fn: (name) => {
3308
+ const bound = ctx.fns.get(name);
3309
+ return bound === void 0 ? void 0 : {
3310
+ fn: bound.fn,
3311
+ scope: this.#scopeOf(bound.ctx)
3312
+ };
3313
+ },
3314
+ cell: (x) => this.#cellList(x) !== void 0,
3315
+ field: (x) => typeof this.#schema.fields?.[x.path.join(".")] === "object"
3316
+ };
3132
3317
  }
3133
3318
  /** 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. */
3134
3319
  #cellList(e) {
@@ -3241,10 +3426,12 @@ var Printer = class {
3241
3426
  case "call": return this.#call(e, ctx);
3242
3427
  case "rec": {
3243
3428
  const names = Object.keys(e.fields);
3244
- const raw = Object.values(e.fields).map((x) => this.expr(x, ctx));
3429
+ const exprs = Object.values(e.fields);
3430
+ for (const x of exprs) this.#wantList.add(x);
3431
+ const raw = exprs.map((x) => this.expr(x, ctx));
3245
3432
  const deps = depsOf(...raw);
3246
- const fields = this.#inOrder(this.#settle(raw, deps, Object.values(e.fields)), true);
3247
- const code = `({ ${fields.map((x, i) => `${names[i] === "__proto__" ? "[\"__proto__\"]" : JSON.stringify(names[i])}: ${x.v.code}`).join(", ")} })`;
3433
+ const fields = this.#inOrder(this.#settle(raw, deps, exprs), true);
3434
+ const code = `({ ${fields.map((x, i) => `${names[i] === "__proto__" ? "[\"__proto__\"]" : JSON.stringify(names[i])}: ${this.#plain(x.v)}`).join(", ")} })`;
3248
3435
  return {
3249
3436
  s: stmtsOf(...fields),
3250
3437
  v: {
@@ -3398,21 +3585,41 @@ var Printer = class {
3398
3585
  const [field, ...more] = e.path;
3399
3586
  const kind = field === void 0 ? void 0 : this.#schema.fields?.[field];
3400
3587
  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(".")}"`);
3588
+ const input = typeof kind === "object" ? this.#input(field) : void 0;
3401
3589
  const at = e.at ?? [];
3402
3590
  const safe = at.every((m) => m.t === "origin");
3403
3591
  const values = this.#addressValues(at, ctx);
3404
3592
  const deps = this.#addressDeps(at, ctx, values);
3405
3593
  const parts = this.#inOrder(this.#settle(values, deps), false);
3594
+ const address = this.#address(at, ctx, parts);
3595
+ if (typeof kind === "object") return {
3596
+ s: stmtsOf(...parts),
3597
+ v: {
3598
+ code: `${input}[${address}]`,
3599
+ kind: void 0,
3600
+ safe,
3601
+ deps,
3602
+ list: listOfKind(kind, true)
3603
+ }
3604
+ };
3406
3605
  return {
3407
3606
  s: stmtsOf(...parts),
3408
3607
  v: {
3409
- code: `R[${this.#address(at, ctx, parts)}][${JSON.stringify(field)}]`,
3608
+ code: `R[${address}][${JSON.stringify(field)}]`,
3410
3609
  kind,
3411
3610
  safe,
3412
3611
  deps
3413
3612
  }
3414
3613
  };
3415
3614
  }
3615
+ /** This method gives the name of the array of the lists of a field of the input. */
3616
+ #input(field) {
3617
+ const known = this.inputs.get(field);
3618
+ if (known !== void 0) return known;
3619
+ const name = this.fresh("LF");
3620
+ this.inputs.set(field, name);
3621
+ return name;
3622
+ }
3416
3623
  /** This method gives the code of the expressions of the computed moves of an address. They evaluate at the node. */
3417
3624
  #addressValues(at, ctx) {
3418
3625
  return addrExprs(at).map((x) => this.expr(x, ctx));
@@ -3523,29 +3730,34 @@ var Printer = class {
3523
3730
  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)}`);
3524
3731
  const s = [];
3525
3732
  const args = e.args.map((x) => {
3733
+ this.#wantList.add(x);
3526
3734
  const c = this.#hoist(this.expr(x, ctx), hasLoop(x));
3735
+ const { kind, deps, list } = c.v;
3527
3736
  if (c.v.safe) {
3528
3737
  s.push(...c.s);
3529
3738
  return {
3530
3739
  code: c.v.code,
3531
- kind: c.v.kind,
3532
- deps: c.v.deps
3740
+ kind,
3741
+ deps,
3742
+ list
3533
3743
  };
3534
3744
  }
3535
3745
  if (c.s.length === 0 && c.v.held !== void 0) return {
3536
3746
  code: c.v.held,
3537
- kind: c.v.kind,
3538
- deps: c.v.deps
3747
+ kind,
3748
+ deps,
3749
+ list
3539
3750
  };
3540
3751
  const b = this.fresh("b");
3541
3752
  s.push(...this.#store(b, c));
3542
3753
  return {
3543
3754
  code: b,
3544
- kind: c.v.kind,
3545
- deps: c.v.deps
3755
+ kind,
3756
+ deps,
3757
+ list
3546
3758
  };
3547
3759
  });
3548
- const sig = JSON.stringify(args.map((a) => a.kind ?? null));
3760
+ const sig = JSON.stringify(args.map((a) => a.list === void 0 ? a.kind ?? null : { list: a.list }));
3549
3761
  const spec = bound.specs.get(sig) ?? this.#printFn(bound, args, sig);
3550
3762
  const levels = (d) => d === spec.origin ? [ctx.originLevel] : d === spec.focus ? [ctx.level] : d === spec.param ? [] : [d];
3551
3763
  const deps = /* @__PURE__ */ new Set([...args.flatMap((a) => [...a.deps]), ...[...spec.deps].flatMap(levels)]);
@@ -3556,7 +3768,8 @@ var Printer = class {
3556
3768
  code: `${spec.name}(${[...args.map((a) => a.code), ...position].join(", ")})`,
3557
3769
  kind: spec.kind,
3558
3770
  safe: spec.safe,
3559
- deps
3771
+ deps,
3772
+ list: spec.list
3560
3773
  }
3561
3774
  };
3562
3775
  }
@@ -3577,7 +3790,8 @@ var Printer = class {
3577
3790
  code: names[i],
3578
3791
  kind: args[i].kind,
3579
3792
  lazy: true,
3580
- deps: /* @__PURE__ */ new Set([param])
3793
+ deps: /* @__PURE__ */ new Set([param]),
3794
+ list: args[i].list
3581
3795
  }));
3582
3796
  const scope = {
3583
3797
  param,
@@ -3588,6 +3802,7 @@ var Printer = class {
3588
3802
  root: bound.fn.body
3589
3803
  };
3590
3804
  this.#scopes.push(scope);
3805
+ this.#wantList.add(bound.fn.body);
3591
3806
  const body = this.expr(bound.fn.body, {
3592
3807
  origin: o,
3593
3808
  focus: k,
@@ -3620,6 +3835,7 @@ var Printer = class {
3620
3835
  const spec = {
3621
3836
  name,
3622
3837
  kind: body.v.kind,
3838
+ list: body.v.list,
3623
3839
  safe: body.v.safe,
3624
3840
  deps: body.v.deps,
3625
3841
  origin,
@@ -3645,19 +3861,74 @@ var Printer = class {
3645
3861
  if (op === "ifError") return this.#ifError(args, ctx);
3646
3862
  const [head] = args;
3647
3863
  const rest = args.slice(1);
3648
- if (FOLD_OPS.has(op) && head?.tag === "each" && !this.#isList(head.body, ctx)) return this.#list(op, head, rest, ctx);
3864
+ if (FOLD_OPS.has(op) && head?.tag === "each" && !this.#bodyList(head, ctx)) return this.#list(op, head, rest, ctx);
3649
3865
  if (FOLD_OPS.has(op) && head?.tag === "let" && rest.every((x) => x.tag === "lit")) return this.#let(head, ctx, (body) => app(op, body, ...rest));
3650
3866
  if (head !== void 0 && (op === "sortBy" || op === "take" || op === "drop" && this.#isList(head, ctx))) return this.#order(op, head, rest, ctx);
3651
- if (head !== void 0 && BUILD_OPS.has(op) && this.#isList(head, ctx)) return this.#build(op, head, rest, ctx);
3867
+ if (head !== void 0 && BUILD_OPS.has(op) && this.#isList(head, ctx)) return this.#build(op, head, rest, ctx, this.#own.get(e));
3652
3868
  if (head !== void 0 && (FOLD_OPS.has(op) || op === "nth") && this.#isList(head, ctx)) return this.#overList(op, head, rest, ctx);
3869
+ for (const x of args) this.#wantList.add(x);
3653
3870
  const raw = args.map((x) => this.expr(x, ctx));
3654
3871
  const deps = depsOf(...raw);
3655
3872
  const values = this.#inOrder(this.#settle(raw, deps, args), true);
3873
+ if (op === "fill" && this.#facts.own(op)) return this.#fill(values, deps);
3656
3874
  return this.#opCall(op, values, deps);
3657
3875
  }
3876
+ /**
3877
+ * This method prints `fill(n, value)` without a domain with the op (LIST.FILL, COMPILE.MODULE.FILL). The helper `FI`
3878
+ * gets each value, so an error of an argument after the value is the error of the op. The keys are not the positions
3879
+ * of records, so the axis `list` over the list cannot read a record at its keys.
3880
+ */
3881
+ #fill(values, deps) {
3882
+ const value = values[1]?.v;
3883
+ const list = {
3884
+ item: value?.kind,
3885
+ inner: value?.list,
3886
+ texts: true
3887
+ };
3888
+ return {
3889
+ s: stmtsOf(...values),
3890
+ v: {
3891
+ code: `${this.use("FI")}(${values.map((x) => x.v.code).join(", ")})`,
3892
+ kind: void 0,
3893
+ safe: false,
3894
+ deps,
3895
+ list
3896
+ }
3897
+ };
3898
+ }
3899
+ /**
3900
+ * This method gives the code of a value outside the list ops: a list is a `vex.list`, as in the interpreter
3901
+ * (COMPILE.MODULE.LIST.ARG, COMPILE.MODULE.LIST.FIELD). An error item has the error `VEX_ERROR`.
3902
+ */
3903
+ #plain(v) {
3904
+ return v.list === void 0 ? v.code : `${this.use("LV")}(${v.code}, ${String(depthOf(v.list))})`;
3905
+ }
3906
+ /** This method gives the samples of a list of the facts `l`: no items, items with values, and an error item. */
3907
+ #listSamples(l) {
3908
+ const items = (l.inner !== void 0 ? [vexList([])] : l.item === void 0 ? SAMPLES.number : this.#samples(l.item)).map((value, i) => ({
3909
+ key: String(i),
3910
+ result: {
3911
+ ok: true,
3912
+ value
3913
+ }
3914
+ }));
3915
+ return [
3916
+ vexList([]),
3917
+ vexList(items),
3918
+ vexList([{
3919
+ key: "0",
3920
+ result: {
3921
+ ok: false,
3922
+ error: { vexError: true }
3923
+ }
3924
+ }])
3925
+ ];
3926
+ }
3658
3927
  /** This method prints the call of the op of a domain on some values, from the static site of their kinds. */
3659
3928
  #opCall(op, values, deps) {
3660
- const site = this.#facts.staticSite(op, values.map((x) => x.v.kind));
3929
+ const lists = new Set(values.flatMap((x, i) => x.v.list === void 0 ? [] : [i]));
3930
+ if (lists.has(0)) throw new NotStandalone(isListOp(op) ? `the list op "${op}"` : `a list as the receiver of the op "${op}"`);
3931
+ const site = this.#facts.staticSite(op, values.map((x) => x.v.kind), lists);
3661
3932
  if (site?.t !== "fn") throw new NotStandalone(`the kinds of the values of "${op}" do not decide its op`);
3662
3933
  if (site.bad) return {
3663
3934
  s: stmtsOf(...values),
@@ -3674,12 +3945,12 @@ var Printer = class {
3674
3945
  if (!this.#forms.has(name)) {
3675
3946
  const fn = d.ops[op].fn;
3676
3947
  const kinds = values.map((x) => x.v.kind).filter((k) => k !== void 0);
3677
- const src = copied(fn, kinds.map((k) => this.#samples(k)), `the op "${op}" of the domain ${d.name}`);
3678
- this.#forms.set(name, kinds.every((k) => primitiveOf(k) !== void 0) ? inlineForm(src) : void 0);
3948
+ 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}`);
3949
+ this.#forms.set(name, lists.size === 0 && kinds.every((k) => primitiveOf(k) !== void 0) ? inlineForm(src) : void 0);
3679
3950
  this.top.set(name, `const ${name} = ${src};`);
3680
3951
  }
3681
3952
  const form = this.#forms.get(name);
3682
- 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)) {
3953
+ 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)) {
3683
3954
  const text = form.parts.map((x) => typeof x === "number" ? `(${values[x].v.code})` : x).join("");
3684
3955
  const checked = this.check(site.returns);
3685
3956
  const code = checked === void 0 ? `(${text})` : `${checked}(${text})`;
@@ -3694,7 +3965,7 @@ var Printer = class {
3694
3965
  };
3695
3966
  }
3696
3967
  this.#called.add(name);
3697
- const code = this.#checked(site.returns, `${name}(${values.map((x) => x.v.code).join(", ")})`);
3968
+ const code = this.#checked(site.returns, `${name}(${values.map((x) => this.#plain(x.v)).join(", ")})`);
3698
3969
  return {
3699
3970
  s: stmtsOf(...values),
3700
3971
  v: {
@@ -3858,9 +4129,10 @@ var Printer = class {
3858
4129
  /**
3859
4130
  * This method gives the loop over the targets of an axis: the statements before it, its bounds and the key that it
3860
4131
  * skips. `start` has the levels of the address, and `inner` is the position at a target. The axes all, others,
3861
- * window and list have a loop. In a tree space, the axes of a tree have a loop too.
4132
+ * window and list have a loop. In a tree space, the axes of a tree have a loop too. With `as`, a loop over the axis
4133
+ * list binds the value and the index of each item after its check (COMPILE.MODULE.LIST.ITEM).
3862
4134
  */
3863
- #targetLoop(axis, at, ctx) {
4135
+ #targetLoop(axis, at, ctx, as) {
3864
4136
  const { base: outer, tests } = testsOf(axis);
3865
4137
  const reverse = outer.t === "reverse";
3866
4138
  const base = outer.t === "reverse" ? outer.axis : outer;
@@ -3873,14 +4145,20 @@ var Printer = class {
3873
4145
  if (base.t === "list") {
3874
4146
  if (at.length > 0) throw new NotStandalone("the axis \"list\" with an address");
3875
4147
  const list = this.#hoist(this.#listOf(base.list, ctx), hasLoop(base.list));
3876
- if (list.v.list.texts === true) throw new NotStandalone("the axis \"list\" over a list with the keys of a literal");
4148
+ const texts = list.v.list.texts === true;
3877
4149
  const a = this.fresh("A");
3878
4150
  const q = this.fresh("q");
3879
4151
  const head = reverse ? `for (let ${q} = ${a}.length - 1; ${q} >= 0; ${q}--) {` : `for (let ${q} = 0; ${q} < ${a}.length; ${q}++) {`;
3880
4152
  const key = [`const ${j} = ${a}[${q}][0];`];
3881
4153
  const check = [`if (${a}[${q}][1] === E) ${this.use("F")}();`];
4154
+ const s = [...list.s, `const ${a} = ${list.v.code};`];
4155
+ const named = as === void 0 ? void 0 : this.#itemNames(as, list.v.list, `${a}[${q}][1]`, a, reverse);
4156
+ if (named !== void 0) {
4157
+ s.push(...named.s);
4158
+ check.push(...named.check);
4159
+ }
3882
4160
  return {
3883
- s: [...list.s, `const ${a} = ${list.v.code};`],
4161
+ s,
3884
4162
  j,
3885
4163
  head,
3886
4164
  key,
@@ -3890,7 +4168,10 @@ var Printer = class {
3890
4168
  start: list.v.deps,
3891
4169
  startSafe: list.v.safe,
3892
4170
  tests,
3893
- inner
4171
+ inner,
4172
+ texts,
4173
+ items: named?.items ?? NO_NAMES,
4174
+ item: named?.level
3894
4175
  };
3895
4176
  }
3896
4177
  const s = [];
@@ -3921,7 +4202,10 @@ var Printer = class {
3921
4202
  start,
3922
4203
  startSafe,
3923
4204
  tests,
3924
- inner
4205
+ inner,
4206
+ texts: false,
4207
+ items: NO_NAMES,
4208
+ item: void 0
3925
4209
  };
3926
4210
  }
3927
4211
  if (this.#graph && GRAPH_AXES.has(base.t)) {
@@ -3938,7 +4222,10 @@ var Printer = class {
3938
4222
  start,
3939
4223
  startSafe,
3940
4224
  tests,
3941
- inner
4225
+ inner,
4226
+ texts: false,
4227
+ items: NO_NAMES,
4228
+ item: void 0
3942
4229
  };
3943
4230
  }
3944
4231
  if (this.#graph && base.t === "window") throw new NotStandalone("the axis \"window\" in a graph space");
@@ -3960,10 +4247,60 @@ var Printer = class {
3960
4247
  start,
3961
4248
  startSafe,
3962
4249
  tests,
3963
- inner
4250
+ inner,
4251
+ texts: false,
4252
+ items: NO_NAMES,
4253
+ item: void 0
4254
+ };
4255
+ }
4256
+ /**
4257
+ * This method binds the names `as` of a loop over the axis list (COMPILE.MODULE.LIST.ITEM). The statements come after
4258
+ * the check of the item, so an error item fails before they bind a name (AXIS.LIST.ITEM). The first name holds the
4259
+ * value of the item, with the facts of its list. The index counts the items with a value in the order of the list, as
4260
+ * `nth` does (AXIS.LIST.INDEX). In the reverse order, it counts down from the number of these items. The names have a
4261
+ * level of their own. Thus a part that reads them stays in the loop, and a key of a literal can still be a target.
4262
+ */
4263
+ #itemNames(as, info, value, a, reverse) {
4264
+ const level = this.#loops++;
4265
+ const deps = /* @__PURE__ */ new Set([level]);
4266
+ const [item, index] = as;
4267
+ const y = this.fresh("y");
4268
+ const items = /* @__PURE__ */ new Map([[item, {
4269
+ code: y,
4270
+ kind: info.item,
4271
+ lazy: false,
4272
+ deps,
4273
+ list: info.inner
4274
+ }]]);
4275
+ const check = [`const ${y} = ${value};`];
4276
+ const s = [];
4277
+ if (index !== void 0) {
4278
+ const i = this.fresh("i");
4279
+ const z = this.fresh("z");
4280
+ s.push(`let ${z} = ${reverse ? `${this.use("CT")}(${a}, false)` : "0"};`);
4281
+ check.push(`const ${i} = ${reverse ? `--${z}` : `${z}++`};`);
4282
+ items.set(index, {
4283
+ code: i,
4284
+ kind: "number",
4285
+ lazy: false,
4286
+ deps
4287
+ });
4288
+ }
4289
+ return {
4290
+ s,
4291
+ check,
4292
+ items,
4293
+ level
3964
4294
  };
3965
4295
  }
3966
4296
  /**
4297
+ * 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
4298
+ * interpreter reads the record of such a key, and a module has no record for it.
4299
+ */
4300
+ #readsNoTarget(texts, level, deps) {
4301
+ 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\"");
4302
+ }
4303
+ /**
3967
4304
  * This method gives the targets of an axis of a graph space at the position `f` (AXIS.GRAPH). They are the positions
3968
4305
  * `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.
3969
4306
  */
@@ -4034,12 +4371,16 @@ var Printer = class {
4034
4371
  #list(op, target, rest, ctx) {
4035
4372
  const { strict, step } = this.#foldOptions(op, rest);
4036
4373
  const at = target.at ?? [];
4037
- const { s, j, head, key, check, skip, fixed, start, startSafe, tests, inner } = this.#targetLoop(target.axis, at, ctx);
4374
+ const { s, j, head, key, check, skip, fixed, start, startSafe, tests, inner, texts, items, item: own } = this.#targetLoop(target.axis, at, ctx, target.as);
4038
4375
  const { level } = inner;
4039
4376
  const testCodes = tests.map((t) => this.#hoist(this.expr(t, inner), hasLoop(t)));
4040
- const body = this.#hoist(this.expr(target.body, inner), hasLoop(target.body));
4377
+ const body = this.#hoist(this.expr(target.body, {
4378
+ ...inner,
4379
+ env: withNames(inner.env, items)
4380
+ }), hasLoop(target.body));
4381
+ this.#readsNoTarget(texts, level, [body, ...testCodes].map((x) => x.v.deps));
4041
4382
  if (op === "count" && fixed && tests.length === 0 && body.v.safe && !body.v.deps.has(CELLS)) return bare(plainValue("n", "number"));
4042
- const deps = new Set([...start, ...[body, ...testCodes].flatMap((x) => [...x.v.deps])].filter((d) => d !== level));
4383
+ const deps = new Set([...start, ...[body, ...testCodes].flatMap((x) => [...x.v.deps])].filter((d) => d !== level && d !== own));
4043
4384
  const r = this.#reduction(op, body.v.kind, step);
4044
4385
  const { v } = r;
4045
4386
  s.push(r.init);
@@ -4213,11 +4554,15 @@ var Printer = class {
4213
4554
  */
4214
4555
  #eachList(e, ctx) {
4215
4556
  const at = e.at ?? [];
4216
- const { s, j, head, key, check, skip, start, startSafe, tests, inner } = this.#targetLoop(e.axis, at, ctx);
4557
+ const { s, j, head, key, check, skip, start, startSafe, tests, inner, texts, items, item: own } = this.#targetLoop(e.axis, at, ctx, e.as);
4217
4558
  const testCodes = tests.map((t) => this.#hoist(this.expr(t, inner), hasLoop(t)));
4218
4559
  if (this.#wantList.has(e)) this.#wantList.add(e.body);
4219
- const body = this.#hoist(this.expr(e.body, inner), hasLoop(e.body));
4220
- const deps = new Set([...start, ...[body, ...testCodes].flatMap((x) => [...x.v.deps])].filter((d) => d !== inner.level));
4560
+ const body = this.#hoist(this.expr(e.body, {
4561
+ ...inner,
4562
+ env: withNames(inner.env, items)
4563
+ }), hasLoop(e.body));
4564
+ this.#readsNoTarget(texts, inner.level, [body, ...testCodes].map((x) => x.v.deps));
4565
+ const deps = new Set([...start, ...[body, ...testCodes].flatMap((x) => [...x.v.deps])].filter((d) => d !== inner.level && d !== own));
4221
4566
  const list = this.fresh("L");
4222
4567
  const v = this.fresh("x");
4223
4568
  const item = [
@@ -4255,7 +4600,8 @@ var Printer = class {
4255
4600
  deps,
4256
4601
  list: {
4257
4602
  item: body.v.kind,
4258
- inner: body.v.list
4603
+ inner: body.v.list,
4604
+ texts
4259
4605
  }
4260
4606
  }
4261
4607
  };
@@ -4267,15 +4613,22 @@ var Printer = class {
4267
4613
  #order(op, head, rest, ctx) {
4268
4614
  const list = this.#listOf(head, ctx);
4269
4615
  const exprs = [head, ...op === "sortBy" ? [] : [rest[0] ?? lit(null)]];
4270
- const strict = this.#strict(op, rest.slice(exprs.length - 1));
4616
+ const options = rest.slice(exprs.length - 1);
4617
+ const strict = this.#strict(op, options, op === "sortBy" ? ["strict", "by"] : ["strict"]);
4618
+ const by = op === "sortBy" ? this.#sortValue(options, list.v.list) : void 0;
4271
4619
  const raw = [list, ...exprs.slice(1).map((x) => this.expr(x, ctx))];
4272
4620
  const deps = depsOf(...raw);
4273
4621
  const parts = this.#inOrder(this.#settle(raw, deps, exprs), true);
4274
- const helper = op === "sortBy" ? "SB" : op === "take" ? "TK" : "DR";
4622
+ const helper = by !== void 0 ? "SK" : op === "sortBy" ? "SB" : op === "take" ? "TK" : "DR";
4623
+ const args = [
4624
+ ...parts.map((x) => x.v.code),
4625
+ String(strict),
4626
+ ...by === void 0 ? [] : [by]
4627
+ ];
4275
4628
  return {
4276
4629
  s: stmtsOf(...parts),
4277
4630
  v: {
4278
- code: `${this.use(helper)}(${[...parts.map((x) => x.v.code), String(strict)].join(", ")})`,
4631
+ code: `${this.use(helper)}(${args.join(", ")})`,
4279
4632
  kind: void 0,
4280
4633
  safe: false,
4281
4634
  deps,
@@ -4284,10 +4637,30 @@ var Printer = class {
4284
4637
  };
4285
4638
  }
4286
4639
  /**
4640
+ * This method gives the function of the option `by` of `sortBy` (COMPILE.MODULE.SORT.BY), or undefined without the
4641
+ * option. The function applies the op of the static site of the kind of the items. An empty list applies no op.
4642
+ */
4643
+ #sortValue(options, info) {
4644
+ const by = options[0]?.value?.by;
4645
+ if (by === void 0) return void 0;
4646
+ if (typeof by !== "string") throw new NotStandalone("the option \"by\" of \"sortBy\" is not a literal text");
4647
+ if (info.empty === true) return void 0;
4648
+ 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`);
4649
+ const x = this.fresh("x");
4650
+ return `((${x}) => ${this.#opCall(by, [bare({
4651
+ code: x,
4652
+ kind: info.item,
4653
+ safe: true,
4654
+ deps: NO_DEPS,
4655
+ plain: true
4656
+ })], NO_DEPS).v.code})`;
4657
+ }
4658
+ /**
4287
4659
  * This method prints append, without and flat (LIST.BUILD), get (LIST.GET) and indexOf (LIST.INDEXOF) over the array
4288
- * of a list. Each list that the op reads follows LIST.LENIENT, as in the interpreter.
4660
+ * of a list. Each list that the op reads follows LIST.LENIENT, as in the interpreter. An append with an owner appends
4661
+ * into the array of its name, if the name in the context is the name of the loop (COMPILE.MODULE.APPEND.OWN).
4289
4662
  */
4290
- #build(op, head, rest, ctx) {
4663
+ #build(op, head, rest, ctx, owner) {
4291
4664
  const list = this.#listOf(head, ctx);
4292
4665
  const info = list.v.list;
4293
4666
  const two = op === "append" || op === "without";
@@ -4297,10 +4670,13 @@ var Printer = class {
4297
4670
  const deps = depsOf(...raw);
4298
4671
  const parts = this.#inOrder(this.#settle(raw, deps, exprs), true);
4299
4672
  const helper = BUILD_HELPERS[op];
4673
+ const args = [...parts.map((x) => x.v.code), String(strict)];
4674
+ const w = owner !== void 0 && ctx.env.get(owner.name) === owner.read ? owner.w ??= this.fresh("w") : void 0;
4675
+ const code = w === void 0 ? `${this.use(helper)}(${args.join(", ")})` : `(${w} = ${this.use("AO")}(${[...args, w].join(", ")}))`;
4300
4676
  const value = (kind, facts) => ({
4301
4677
  s: stmtsOf(...parts),
4302
4678
  v: {
4303
- code: `${this.use(helper)}(${[...parts.map((x) => x.v.code), String(strict)].join(", ")})`,
4679
+ code,
4304
4680
  kind,
4305
4681
  safe: false,
4306
4682
  deps,
@@ -4335,6 +4711,26 @@ var Printer = class {
4335
4711
  list: inner
4336
4712
  }
4337
4713
  };
4714
+ if (op === "count") return {
4715
+ s: l.s,
4716
+ v: {
4717
+ code: `${this.use("CT")}(${l.v.code}, ${String(strict)})`,
4718
+ kind: "number",
4719
+ safe: false,
4720
+ deps,
4721
+ list: void 0
4722
+ }
4723
+ };
4724
+ if (op === "first") return {
4725
+ s: l.s,
4726
+ v: {
4727
+ code: `${this.use("FS")}(${l.v.code}, ${String(strict)})`,
4728
+ kind: item,
4729
+ safe: false,
4730
+ deps,
4731
+ list: inner
4732
+ }
4733
+ };
4338
4734
  const r = this.#reduction(op, item, step);
4339
4735
  const { v } = r;
4340
4736
  return {
@@ -4365,7 +4761,7 @@ var Printer = class {
4365
4761
  const env = new Map(ctx.env);
4366
4762
  const vars = /* @__PURE__ */ new Map();
4367
4763
  const deps = /* @__PURE__ */ new Set();
4368
- const keyed = Object.values(step).some(hasKeyedLiteral);
4764
+ const keyed = Object.values(step).some(hasTextKeys);
4369
4765
  for (const [name, x] of Object.entries(init)) {
4370
4766
  this.#wantList.add(x);
4371
4767
  const c = this.expr(x, ctx);
@@ -4396,8 +4792,42 @@ var Printer = class {
4396
4792
  deps
4397
4793
  };
4398
4794
  }
4399
- /** This method gives the statements of one step of a loop: each new value first, and then each name gets its value. */
4400
- #loopStep(step, inner, vars) {
4795
+ /**
4796
+ * This method gives the statements of one step of a loop: each new value first, and then each name gets its value.
4797
+ * `init` has the statements before the loop: the variable of each name that appends to its own list
4798
+ * (COMPILE.MODULE.APPEND.OWN). Each such name has the form of `ownForm`, and no step of another name and no `until`
4799
+ * reads it. The tests of a fold read only the names outside the fold, so they cannot read it.
4800
+ */
4801
+ #loopStep(step, inner, vars, until) {
4802
+ const owners = [];
4803
+ const nodes = [];
4804
+ const steps = Object.entries(step);
4805
+ for (const [name, x] of steps) {
4806
+ const own = [];
4807
+ const others = [...steps.filter(([k]) => k !== name).map(([, y]) => y), ...until === void 0 ? [] : [until]];
4808
+ if (!ownForm(x, name, own) || others.some((y) => namesOf(y).has(name))) continue;
4809
+ const owner = {
4810
+ name,
4811
+ read: vars.get(name),
4812
+ w: void 0
4813
+ };
4814
+ for (const node of own) this.#own.set(node, owner);
4815
+ owners.push(owner);
4816
+ nodes.push(...own);
4817
+ }
4818
+ try {
4819
+ const { s, deps } = this.#steps(step, inner, vars);
4820
+ return {
4821
+ s,
4822
+ deps,
4823
+ init: owners.flatMap((o) => o.w === void 0 ? [] : [`let ${o.w} = null;`])
4824
+ };
4825
+ } finally {
4826
+ for (const node of nodes) this.#own.delete(node);
4827
+ }
4828
+ }
4829
+ /** This method gives the statements of one step of a loop, without the variables of COMPILE.MODULE.APPEND.OWN. */
4830
+ #steps(step, inner, vars) {
4401
4831
  const s = [];
4402
4832
  const sets = [];
4403
4833
  const deps = /* @__PURE__ */ new Set();
@@ -4430,7 +4860,7 @@ var Printer = class {
4430
4860
  };
4431
4861
  if (this.#wantList.has(e)) this.#wantList.add(e.result);
4432
4862
  const until = e.until === void 0 ? void 0 : this.expr(e.until, inner);
4433
- const step = this.#loopStep(e.step, inner, names.vars);
4863
+ const step = this.#loopStep(e.step, inner, names.vars, e.until);
4434
4864
  const result = this.expr(e.result, inner);
4435
4865
  const k = this.fresh("k");
4436
4866
  const body = [
@@ -4447,6 +4877,7 @@ var Printer = class {
4447
4877
  return {
4448
4878
  s: [
4449
4879
  ...names.s,
4880
+ ...step.init,
4450
4881
  `for (let ${k} = 0; ; ${k}++) {`,
4451
4882
  ...ind(body),
4452
4883
  "}",
@@ -4469,13 +4900,14 @@ var Printer = class {
4469
4900
  const loop = this.#loops++;
4470
4901
  const names = this.#loopNames(e.init, e.step, ctx, loop);
4471
4902
  if (this.#wantList.has(e)) this.#wantList.add(e.result);
4472
- const t = this.#targetLoop(e.axis, e.at ?? [], ctx);
4903
+ const t = this.#targetLoop(e.axis, e.at ?? [], ctx, e.as);
4473
4904
  const tests = t.tests.map((x) => this.#hoist(this.expr(x, t.inner), hasLoop(x)));
4474
4905
  if (tests.some((x) => x.v.deps.has(CELLS))) throw new NotStandalone("a test of the axis of a fold reads a cell");
4475
4906
  const step = this.#loopStep(e.step, {
4476
4907
  ...t.inner,
4477
- env: names.env
4908
+ env: withNames(names.env, t.items)
4478
4909
  }, names.vars);
4910
+ this.#readsNoTarget(t.texts, t.inner.level, [...tests.map((x) => x.v.deps), step.deps]);
4479
4911
  const result = this.expr(e.result, {
4480
4912
  ...ctx,
4481
4913
  env: names.env
@@ -4487,7 +4919,7 @@ var Printer = class {
4487
4919
  ...tests.flatMap((c) => [...c.s, `if (!${this.#boolean(c.v)}) continue;`]),
4488
4920
  ...step.s
4489
4921
  ];
4490
- const inside = [...tests.flatMap((c) => [...c.v.deps]), ...step.deps].filter((d) => d !== loop && d !== t.inner.level);
4922
+ const inside = [...tests.flatMap((c) => [...c.v.deps]), ...step.deps].filter((d) => d !== loop && d !== t.inner.level && d !== t.item);
4491
4923
  const deps = /* @__PURE__ */ new Set([
4492
4924
  ...names.deps,
4493
4925
  ...t.start,
@@ -4497,6 +4929,7 @@ var Printer = class {
4497
4929
  return {
4498
4930
  s: [
4499
4931
  ...names.s,
4932
+ ...step.init,
4500
4933
  ...t.s,
4501
4934
  t.head,
4502
4935
  ...ind(body),
@@ -4518,6 +4951,7 @@ var Printer = class {
4518
4951
  * is a constant of the run itself.
4519
4952
  */
4520
4953
  #memoized(e, keys, ctx) {
4954
+ for (const k of keys) this.#wantList.add(k);
4521
4955
  const values = keys.map((k) => this.#hoist(this.expr(k, ctx)));
4522
4956
  const varying = keys.filter((_k, i) => values[i].v.deps.size > 0);
4523
4957
  const params = varying.map(() => this.fresh("q"));
@@ -4528,7 +4962,8 @@ var Printer = class {
4528
4962
  code: params[p],
4529
4963
  kind: x.kind,
4530
4964
  lazy: true,
4531
- deps: /* @__PURE__ */ new Set([1])
4965
+ deps: /* @__PURE__ */ new Set([1]),
4966
+ list: x.list
4532
4967
  }];
4533
4968
  }));
4534
4969
  const outer = this.#inside;
@@ -4549,7 +4984,8 @@ var Printer = class {
4549
4984
  }
4550
4985
  const tokens = new Map(keys.map((k, i) => [k, varying.includes(k) ? {
4551
4986
  "#": varying.indexOf(k),
4552
- kind: values[i].v.kind
4987
+ kind: values[i].v.kind,
4988
+ list: values[i].v.list
4553
4989
  } : { "@": names.get(k).code }]));
4554
4990
  const structure = canonical(e, (x) => tokens.get(x));
4555
4991
  let fn = this.#structures.get(structure);
@@ -4749,6 +5185,18 @@ function reasonOf(thrown) {
4749
5185
  };
4750
5186
  }
4751
5187
  /**
5188
+ * 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
5189
+ * the array of the list when the program reads the field (COMPILE.MODULE.LIST.INPUT). The code is true for a field
5190
+ * against the schema.
5191
+ */
5192
+ function fieldCheck(p, field, kind) {
5193
+ const input = `r[${JSON.stringify(field)}]`;
5194
+ if (typeof kind !== "object") return p.against(kind, input);
5195
+ const read = `${p.use("LI")}(${input}, ${String(depthOf(listOfKind(kind)))}, ${p.test(leafOf(kind))})`;
5196
+ const keep = p.inputs.get(field);
5197
+ return `${keep === void 0 ? read : `(${keep}[i] = ${read})`} === undefined`;
5198
+ }
5199
+ /**
4752
5200
  * This function gives the text of a module: the declarations, the helpers, and the function of the run. The run checks
4753
5201
  * its input, computes the parts of the tree and the constants of the run, and then gives the statements `body`.
4754
5202
  */
@@ -4764,7 +5212,7 @@ function printModule(p, options, run, body) {
4764
5212
  let fieldChecks;
4765
5213
  let varChecks;
4766
5214
  try {
4767
- fieldChecks = fields.map(([f, k]) => ` || ${p.against(k, `r[${JSON.stringify(f)}]`)}`).join("");
5215
+ fieldChecks = fields.map(([f, k]) => ` || ${fieldCheck(p, f, k)}`).join("");
4768
5216
  varChecks = vars.map(([v, k]) => ` || ${p.against(k, `vars[${JSON.stringify(v)}]`)}`).join("");
4769
5217
  } catch (thrown) {
4770
5218
  return reasonOf(thrown);
@@ -4811,6 +5259,7 @@ function printModule(p, options, run, body) {
4811
5259
  " if (!Array.isArray(records)) C(\"the records are not an array\");",
4812
5260
  " const R = records;",
4813
5261
  " const n = R.length;",
5262
+ ...[...p.inputs.values()].map((x) => ` const ${x} = [];`),
4814
5263
  " for (let i = 0; i < n; i++) {",
4815
5264
  " const r = R[i];",
4816
5265
  ` if (typeof r !== "object" || r === null${fieldChecks}) C(\`the record \${i} does not keep the schema\`);`,
@@ -4883,17 +5332,19 @@ const kindText = (k, l) => l === void 0 ? k ?? "that the printer does not know"
4883
5332
  /** This function gives the number of the levels of lists in the items of a list: 0 for a list of values. */
4884
5333
  const depthOf = (l) => l.inner === void 0 ? 0 : 1 + depthOf(l.inner);
4885
5334
  /** This function gives the facts of the lists of a column from the kind of the option `kinds` (COMPILE.MODULE.SHEET.LIST). */
4886
- const listOfKind = (k) => {
4887
- const texts = k.texts === true;
5335
+ const listOfKind = (k, all = false) => {
5336
+ const texts = all || k.texts === true;
4888
5337
  return typeof k.list === "object" ? {
4889
5338
  item: void 0,
4890
- inner: listOfKind(k.list),
5339
+ inner: listOfKind(k.list, all),
4891
5340
  texts
4892
5341
  } : {
4893
5342
  item: k.list,
4894
5343
  texts
4895
5344
  };
4896
5345
  };
5346
+ /** This function gives the kind of the items at the bottom of a list kind. */
5347
+ const leafOf = (k) => typeof k.list === "object" ? leafOf(k.list) : k.list;
4897
5348
  /**
4898
5349
  * This function gives the facts of the lists of a column from the list of its first formula. The other cells of the
4899
5350
  * column can have other formulas. Thus a list without items does not tell that each list of the column is empty.
@@ -5055,7 +5506,6 @@ function emitSheetModule(columns, options) {
5055
5506
  `return { ${names.map((c, i) => `${JSON.stringify(c)}: ${resultOf(c, direct ? `DO(D[${String(i)}])` : `SS.o(${String(i)})`)}`).join(", ")} };`
5056
5507
  ]);
5057
5508
  }
5058
- //#endregion
5059
5509
  export { FALLBACK, createRuntime, emitModule, emitSheetModule, generate, load, tiered };
5060
5510
 
5061
5511
  //# sourceMappingURL=index.js.map