@mark1russell7/vex-compiler 0.11.1 → 0.11.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/build/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { MAX_NESTING, addrExprs, axisTargets, children, compile, findMethod, fixAddr, fromDocument, isDocument, isFieldName, isListOp, isOpName, isStackOverflow, isVexList, liftsAt, listOf, lit, matchesKind, moveExpr, nestingOf, ok, resolveAddr, safeIs, shapeError, vexList } from "@mark1russell7/vex";
1
+ import { CELL_KIND, MAX_NESTING, addrExprs, 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
2
  //#region 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
@@ -321,7 +321,7 @@ function printJs(p, facts) {
321
321
  const f = `f${x.name}_${st.domain}`;
322
322
  fns.set(f, `${domain(st.domain)}.ops[${expr(constant(x.name))}].fn`);
323
323
  attempt(`${f}(${values.join(", ")})`, indent);
324
- const kind = st.returns;
324
+ const kind = primitiveOf(st.returns);
325
325
  if (kind === void 0) {
326
326
  resultChecks(out, facts.checks, indent);
327
327
  return;
@@ -1733,13 +1733,7 @@ function createRuntime(options) {
1733
1733
  }
1734
1734
  },
1735
1735
  opts: (value) => value?.strict,
1736
- rec(names, values) {
1737
- const out = {};
1738
- names.forEach((n, i) => {
1739
- out[n] = values[i];
1740
- });
1741
- return Object.freeze(out);
1742
- },
1736
+ rec: (names, values) => Object.freeze(Object.fromEntries(names.map((n, i) => [n, values[i]]))),
1743
1737
  list: (keys, values) => vexList(keys.map((key, i) => ({
1744
1738
  key,
1745
1739
  result: {
@@ -1843,6 +1837,107 @@ function tiered(source, options = {}) {
1843
1837
  };
1844
1838
  }
1845
1839
  //#endregion
1840
+ //#region src/sheet-order.ts
1841
+ /**
1842
+ * The static order of the cells of a sheet in a module (COMPILE.MODULE.SHEET). It is the order of `SheetRun.fill` in
1843
+ * `packages/core/src/sheet.ts` (SHEET.FILL). Each column comes after the columns that it reads. The keys of a column
1844
+ * follow its reads from itself. The order changes only the speed, not a result (SHEET.ORDER).
1845
+ */
1846
+ /** This function tells if the data of an extension is a cell reference: a column, and an address of fixed moves. */
1847
+ const isCellRef = (u) => typeof u === "object" && u !== null && typeof u.column === "string" && Array.isArray(u.at) && u.at.every((m) => isMove(m) && moveExpr(m) === void 0);
1848
+ /** This function adds the direction of one move or one axis of a read of a column from itself. */
1849
+ function addDirection(d, m) {
1850
+ if (m.t === "reverse") {
1851
+ addDirection(d, m.axis);
1852
+ return;
1853
+ }
1854
+ if (m.t === "offset" || m.t === "window") {
1855
+ const steps = m.t === "offset" ? [m.d.find((x) => x !== 0) ?? 0] : [m.from, m.to];
1856
+ if (steps.some((x) => x < 0)) d.add("before");
1857
+ if (steps.some((x) => x > 0)) d.add("after");
1858
+ } else if (m.t === "children" || m.t === "descendants") d.add("down");
1859
+ }
1860
+ /** This function gives the base axis of an axis, and the tests of its `where` axes. */
1861
+ function partsOf$1(axis) {
1862
+ const tests = [];
1863
+ let base = axis;
1864
+ while (base.t === "where") {
1865
+ tests.push(base.test);
1866
+ base = base.axis;
1867
+ }
1868
+ return {
1869
+ base,
1870
+ tests
1871
+ };
1872
+ }
1873
+ /**
1874
+ * This function gives the columns that the formulas of the column `self` read with a cell reference: its formula and
1875
+ * the formulas of its cells. It also gives the directions of their reads of the column itself. A read in the body or
1876
+ * in a test of an axis also has the direction of that axis.
1877
+ */
1878
+ function readsOf(columns, cells, self) {
1879
+ const read = /* @__PURE__ */ new Set();
1880
+ const directions = /* @__PURE__ */ new Set();
1881
+ const formula = columns.get(self);
1882
+ const todo = [...formula === void 0 ? [] : [formula], ...cells.get(self)?.values() ?? []].filter((e) => shapeError(e) === void 0).map((e) => [e, void 0]);
1883
+ for (let item = todo.pop(); item !== void 0; item = todo.pop()) {
1884
+ const [e, axis] = item;
1885
+ if (e.tag === "each" || e.tag === "fold") {
1886
+ const { base, tests } = partsOf$1(e.axis);
1887
+ for (const x of [...e.tag === "each" ? [e.body] : Object.values(e.step), ...tests]) todo.push([x, base]);
1888
+ const list = listOf(e.axis);
1889
+ for (const x of [
1890
+ ...e.tag === "fold" ? [...Object.values(e.init), e.result] : [],
1891
+ ...addrExprs(e.at),
1892
+ ...list === void 0 ? [] : [list]
1893
+ ]) todo.push([x, axis]);
1894
+ } else if (e.tag !== "ext") for (const child of children(e)) todo.push([child, axis]);
1895
+ else if (e.kind === CELL_KIND && isCellRef(e.data)) {
1896
+ read.add(e.data.column);
1897
+ if (e.data.column === self) for (const m of [...axis === void 0 ? [] : [axis], ...e.data.at]) addDirection(directions, m);
1898
+ }
1899
+ }
1900
+ return {
1901
+ columns: read,
1902
+ directions
1903
+ };
1904
+ }
1905
+ /**
1906
+ * This function gives the columns of a sheet in an order where each column comes after the columns that it reads. The
1907
+ * columns of a cycle keep their order. The columns with formulas of cells only come last.
1908
+ */
1909
+ function columnOrder(columns, cells) {
1910
+ const names = /* @__PURE__ */ new Set([...columns.keys(), ...cells.keys()]);
1911
+ let left = [...names].map((c) => ({
1912
+ c,
1913
+ needs: [...readsOf(columns, cells, c).columns].filter((x) => x !== c && names.has(x))
1914
+ }));
1915
+ const order = [];
1916
+ const placed = /* @__PURE__ */ new Set();
1917
+ while (left.length > 0) {
1918
+ const ready = left.filter((x) => x.needs.every((n) => placed.has(n)));
1919
+ for (const x of ready.length > 0 ? ready : left.slice(0, 1)) {
1920
+ order.push(x.c);
1921
+ placed.add(x.c);
1922
+ }
1923
+ left = left.filter((x) => !placed.has(x.c));
1924
+ }
1925
+ return order;
1926
+ }
1927
+ /**
1928
+ * This function gives the order of the keys of a column. A read of a later key reverses the order. In a tree, a read of
1929
+ * the children puts the children before their parent, as `keyOrder` of `SheetRun` does.
1930
+ */
1931
+ function keyOrderOf(d) {
1932
+ const reverse = d.has("after") && !d.has("before");
1933
+ const post = d.has("down");
1934
+ return {
1935
+ reverse,
1936
+ post,
1937
+ back: post !== reverse
1938
+ };
1939
+ }
1940
+ //#endregion
1846
1941
  //#region src/module.ts
1847
1942
  /**
1848
1943
  * Standalone modules (docs/COMPILER.md §4.4 and §6). `emitModule` prints a program as an ES module that has no import of
@@ -1861,14 +1956,28 @@ function tiered(source, options = {}) {
1861
1956
  * before the loop over the keys. A node of the memo is one function of its other keys, with a map of its values. The
1862
1957
  * nodes with the same expression share the function.
1863
1958
  *
1864
- * The printer takes a part of the language. It takes an array space of records, the fields and the variables of the
1865
- * schema, and the axes `all`, `others` and `window`. The kinds of each op site must decide its op. Another construct
1866
- * gives a reason, not code.
1959
+ * The printer takes a part of the language. It takes an array space or a tree space of records, and the fields and
1960
+ * the variables of the schema. It takes the axes `all`, `others` and `window`. A tree space also has the move `parent` and the
1961
+ * axes of a tree (COMPILE.MODULE.TREE). The kinds of each op site must decide its op. Another construct gives a
1962
+ * reason, not code.
1963
+ *
1964
+ * `emitSheetModule` prints the formula columns of a sheet as one module (COMPILE.MODULE.SHEET). Each column is an array
1965
+ * of results, and the run fills the arrays in the static order of `SheetRun.fill`. A read of a cell that is not finished
1966
+ * starts the search of `SheetRun`. Thus each cell on a cycle gives the error of Vex.
1867
1967
  */
1868
1968
  /** The error of a construct that a standalone module does not have. */
1869
1969
  var NotStandalone = class extends Error {};
1870
1970
  /** The levels of a constant of the run. */
1871
1971
  const NO_DEPS = /* @__PURE__ */ new Set();
1972
+ /**
1973
+ * 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
1974
+ * a cell is not a constant or a column of the run. The level is far from the other levels.
1975
+ */
1976
+ const CELLS = -1;
1977
+ /** The name of the function of a run of a sheet that reads a cell: its column and its position. */
1978
+ const READ_CELL = "RC";
1979
+ /** This pattern finds a read of a cell in the code of a value: the read, or a printed function that can read a cell. */
1980
+ const READS_IN_CODE = /\b(RC|fn\d+)\(/;
1872
1981
  /** This function gives the levels of some codes together. */
1873
1982
  const depsOf = (...xs) => new Set(xs.flatMap((x) => [...x.v.deps]));
1874
1983
  /** This function gives the statements of some codes, in order. */
@@ -1899,6 +2008,183 @@ const HELPERS = {
1899
2008
  ].join("\n"),
1900
2009
  TK: "function TK(l, n, s) { const o = V(l, s); return Number.isSafeInteger(n) && n >= 0 ? o.slice(0, n) : F(); }",
1901
2010
  NT: "function NT(l, i, s) { const o = V(l, s); return Number.isSafeInteger(i) && i >= 0 && i < o.length ? o[i][1] : F(); }",
2011
+ PT: [
2012
+ "function PT(p, n) {",
2013
+ " if (!Array.isArray(p) || p.length !== n) C(\"the parents are not an array with one parent for each record\");",
2014
+ " const P = new Int32Array(n), s = new Uint8Array(n);",
2015
+ " for (let i = 0; i < n; i++) {",
2016
+ " const x = p[i];",
2017
+ " if (x !== -1 && !(Number.isInteger(x) && x >= 0 && x < n)) C(`the parent of the record ${i} is not -1 or the position of a record`);",
2018
+ " P[i] = x;",
2019
+ " }",
2020
+ " for (let i = 0; i < n; i++) {",
2021
+ " let k = i;",
2022
+ " while (k >= 0 && s[k] === 0) {",
2023
+ " s[k] = 1;",
2024
+ " k = P[k];",
2025
+ " }",
2026
+ " if (k >= 0 && s[k] === 1) C(`the parents of the record ${i} make a cycle`);",
2027
+ " for (k = i; k >= 0 && s[k] === 1; k = P[k]) s[k] = 2;",
2028
+ " }",
2029
+ " return P;",
2030
+ "}"
2031
+ ].join("\n"),
2032
+ CH: [
2033
+ "function CH(P, n) {",
2034
+ " const h = [], r = [];",
2035
+ " for (let i = 0; i < n; i++) h.push([]);",
2036
+ " for (let i = 0; i < n; i++) (P[i] < 0 ? r : h[P[i]]).push(i);",
2037
+ " return [h, r];",
2038
+ "}"
2039
+ ].join("\n"),
2040
+ SG: [
2041
+ "function SG(P, h, r, n) {",
2042
+ " const g = [], s = new Int32Array(n);",
2043
+ " for (let i = 0; i < n; i++) g.push(P[i] < 0 ? r : h[P[i]]);",
2044
+ " for (const x of [r, ...h]) for (let q = 0; q < x.length; q++) s[x[q]] = q;",
2045
+ " return [g, s];",
2046
+ "}"
2047
+ ].join("\n"),
2048
+ PR: [
2049
+ "function PR(h, r, n) {",
2050
+ " const o = [], at = new Int32Array(n), z = new Int32Array(n), st = [];",
2051
+ " for (let q = r.length - 1; q >= 0; q--) st.push(r[q]);",
2052
+ " while (st.length > 0) {",
2053
+ " const k = st.pop();",
2054
+ " at[k] = o.length;",
2055
+ " o.push(k);",
2056
+ " for (let q = h[k].length - 1; q >= 0; q--) st.push(h[k][q]);",
2057
+ " }",
2058
+ " for (let q = n - 1; q >= 0; q--) {",
2059
+ " const k = o[q];",
2060
+ " z[k] = 1;",
2061
+ " for (const c of h[k]) z[k] += z[c];",
2062
+ " }",
2063
+ " return [o, at, z];",
2064
+ "}"
2065
+ ].join("\n"),
2066
+ UP: "function UP(P, k) { const p = P[k]; return p < 0 ? F() : p; }",
2067
+ SO: "function SO(g, s, k, d) { const t = g[k][s[k] + d]; return t === undefined ? F() : t; }",
2068
+ AN: "function AN(P, k) { const o = []; for (let p = P[k]; p >= 0; p = P[p]) o.push(p); return o; }",
2069
+ BF: "function BF(h, k) { const o = [k]; for (let i = 0; i < o.length; i++) for (const c of h[o[i]]) o.push(c); return o; }",
2070
+ SH: [
2071
+ "function SH(n, cols, own, budget) {",
2072
+ " const pg = (c, k) => {",
2073
+ " const o = own[c];",
2074
+ " const g = o === undefined ? undefined : o[k];",
2075
+ " return g === undefined ? cols[c] : g;",
2076
+ " };",
2077
+ " const D = [];",
2078
+ " for (let c = 0; c < cols.length; c++) {",
2079
+ " const d = new Array(n);",
2080
+ " for (let k = 0; k < n; k++) if (pg(c, k) === undefined) d[k] = E;",
2081
+ " D.push(d);",
2082
+ " }",
2083
+ " const seen = new Map(), stack = [], FILL = {};",
2084
+ " let top = FILL, missed = false, next = 0, used = 0;",
2085
+ " const start = (c, k) => {",
2086
+ " const i = next++;",
2087
+ " const v = { id: c * n + k, c, k, i, low: i, re: false, r: E, p: false, need: undefined };",
2088
+ " seen.set(v.id, v);",
2089
+ " stack.push(v);",
2090
+ " return v;",
2091
+ " };",
2092
+ " const ev = (v, g) => {",
2093
+ " const caller = top;",
2094
+ " v.p = false;",
2095
+ " v.need = undefined;",
2096
+ " top = v;",
2097
+ " used += g[1];",
2098
+ " const x = g[0](v.k);",
2099
+ " used -= g[1];",
2100
+ " top = caller;",
2101
+ " if (!v.p) v.r = x;",
2102
+ " };",
2103
+ " const end = (v, caller) => {",
2104
+ " if (v.low === v.i) {",
2105
+ " const ms = stack.splice(stack.lastIndexOf(v));",
2106
+ " const cycle = ms.length > 1 || v.re;",
2107
+ " for (const m of ms) {",
2108
+ " seen.delete(m.id);",
2109
+ " D[m.c][m.k] = cycle ? E : m.r;",
2110
+ " }",
2111
+ " } else if (caller !== undefined) caller.low = Math.min(caller.low, v.low);",
2112
+ " };",
2113
+ " const r = (c, k) => {",
2114
+ " const d = D[c][k];",
2115
+ " if (d !== undefined) return d;",
2116
+ " const caller = top;",
2117
+ " if (caller === FILL) {",
2118
+ " missed = true;",
2119
+ " return E;",
2120
+ " }",
2121
+ " if (caller.p) return E;",
2122
+ " const s = seen.get(c * n + k);",
2123
+ " if (s !== undefined) {",
2124
+ " caller.low = Math.min(caller.low, s.i);",
2125
+ " s.re = true;",
2126
+ " return E;",
2127
+ " }",
2128
+ " const g = pg(c, k);",
2129
+ " const v = start(c, k);",
2130
+ " if (used + g[1] > budget) {",
2131
+ " caller.p = true;",
2132
+ " caller.need = v;",
2133
+ " return E;",
2134
+ " }",
2135
+ " ev(v, g);",
2136
+ " if (v.p) {",
2137
+ " caller.p = true;",
2138
+ " caller.need = v;",
2139
+ " return E;",
2140
+ " }",
2141
+ " end(v, caller);",
2142
+ " const x = D[c][k];",
2143
+ " return x === undefined ? E : x;",
2144
+ " };",
2145
+ " const drive = (c, k) => {",
2146
+ " const work = [start(c, k)];",
2147
+ " for (let v = work[0]; v !== undefined; v = work[work.length - 1]) {",
2148
+ " ev(v, pg(v.c, v.k));",
2149
+ " if (v.p) {",
2150
+ " for (let q = v.need; q !== undefined; q = q.need) work.push(q);",
2151
+ " continue;",
2152
+ " }",
2153
+ " work.pop();",
2154
+ " end(v, work[work.length - 1]);",
2155
+ " }",
2156
+ " };",
2157
+ " const f = (c, k) => {",
2158
+ " if (D[c][k] !== undefined) return;",
2159
+ " missed = false;",
2160
+ " const x = pg(c, k)[0](k);",
2161
+ " if (missed) drive(c, k);",
2162
+ " else D[c][k] = x;",
2163
+ " };",
2164
+ " const o = (c) => {",
2165
+ " const d = D[c], out = [];",
2166
+ " for (let k = 0; k < n; k++) out.push(d[k] === E ? VEX_ERROR : d[k]);",
2167
+ " return out;",
2168
+ " };",
2169
+ " return { r, f, o };",
2170
+ "}"
2171
+ ].join("\n"),
2172
+ KO: [
2173
+ "function KO(h, r, post, back) {",
2174
+ " const o = [], st = [];",
2175
+ " const push = (x) => {",
2176
+ " if (back) for (let q = 0; q < x.length; q++) st.push(x[q]);",
2177
+ " else for (let q = x.length - 1; q >= 0; q--) st.push(x[q]);",
2178
+ " };",
2179
+ " push(r);",
2180
+ " while (st.length > 0) {",
2181
+ " const k = st.pop();",
2182
+ " o.push(k);",
2183
+ " push(h[k]);",
2184
+ " }",
2185
+ " return post ? o.reverse() : o;",
2186
+ "}"
2187
+ ].join("\n"),
1902
2188
  M1: [
1903
2189
  "function M1(f) {",
1904
2190
  " const m = new Map();",
@@ -1937,6 +2223,11 @@ const HELPERS = {
1937
2223
  ].join("\n")
1938
2224
  };
1939
2225
  /**
2226
+ * This list has the globals of JavaScript that the code of a module reads. This code is the helpers, the run and the
2227
+ * copies of the ops of the test domains. A test reads the text of the modules of the golden files and checks this list (V-060).
2228
+ */
2229
+ const MODULE_GLOBALS = new Set("Array Error Int32Array Map Math Number Object Uint8Array undefined".split(" "));
2230
+ /**
1940
2231
  * This function gives the code of the helper S, a node of the memo that keeps its items (Printer.#cached). The helper
1941
2232
  * has only the parts that the nodes of the module need:
1942
2233
  *
@@ -2039,8 +2330,36 @@ const NEEDS = {
2039
2330
  V: ["F"],
2040
2331
  SB: ["V", "F"],
2041
2332
  TK: ["V", "F"],
2042
- NT: ["V", "F"]
2333
+ NT: ["V", "F"],
2334
+ PT: ["C"],
2335
+ UP: ["F"],
2336
+ SO: ["F"],
2337
+ CH: [],
2338
+ SG: [],
2339
+ PR: [],
2340
+ AN: [],
2341
+ BF: [],
2342
+ SH: [],
2343
+ KO: []
2043
2344
  };
2345
+ /** The statement of each part of a tree in a run, with the helper that computes it. */
2346
+ const TREE_PARTS = {
2347
+ children: ["CH", "const [H, RT] = CH(P, n);"],
2348
+ siblings: ["SG", "const [GP, SI] = SG(P, H, RT, n);"],
2349
+ order: ["PR", "const [PO, PI, SZ] = PR(H, RT, n);"]
2350
+ };
2351
+ /** The axes of a tree space in a module, and the axes that a module of an array space does not have. */
2352
+ const TREE_AXES = /* @__PURE__ */ new Set([
2353
+ "children",
2354
+ "ancestors",
2355
+ "descendants",
2356
+ "siblings",
2357
+ "successors",
2358
+ "predecessors",
2359
+ "reachable"
2360
+ ]);
2361
+ /** This function tells if an axis has its targets in a range of an array of positions in a tree space. */
2362
+ const isTreeAxis = (a) => a.t === "window" || TREE_AXES.has(a.t);
2044
2363
  /** The list ops of a standalone module. */
2045
2364
  const LIST_OPS = /* @__PURE__ */ new Set([
2046
2365
  "count",
@@ -2073,6 +2392,15 @@ const BUILD_OPS = /* @__PURE__ */ new Set([
2073
2392
  "without",
2074
2393
  "get"
2075
2394
  ]);
2395
+ /** This function tells if the step of a list op throws for a value of the kind `kind`, which is the wrong kind. */
2396
+ const stepThrows = (op, kind) => NUMBER_STEPS.has(op) && kind !== "number" || BOOLEAN_LIST_OPS.has(op) && kind !== "boolean";
2397
+ /** The list ops whose step takes a number. */
2398
+ const NUMBER_STEPS = /* @__PURE__ */ new Set([
2399
+ "sum",
2400
+ "mean",
2401
+ "min",
2402
+ "max"
2403
+ ]);
2076
2404
  /** This function gives the kind of the result of a list op: first gives the kind of its items. */
2077
2405
  const listKind = (op, item) => NUMBER_LIST_OPS.has(op) ? "number" : BOOLEAN_LIST_OPS.has(op) ? "boolean" : item;
2078
2406
  const LOOPS = /* @__PURE__ */ new WeakMap();
@@ -2311,6 +2639,18 @@ function inlineForm(src) {
2311
2639
  }
2312
2640
  /** This function gives the text of an inline form without spaces, with `#i` for the parameter `at(i)`. */
2313
2641
  const patternOf = (form, at) => form.parts.map((p) => typeof p === "number" ? `#${at(p)}` : p.replaceAll(/\s/g, "")).join("");
2642
+ /** The reserved words of the strict code of a module, and the two names that strict code does not bind. */
2643
+ const RESERVED = new Set("await break case catch class const continue debugger default delete do else enum export extends false finally for function if implements import in instanceof interface let new null package private protected public return static super switch this throw true try typeof var void while with yield arguments eval".split(" "));
2644
+ /**
2645
+ * This function gives the reason that a name cannot be the name of the run, or `undefined` for a good name (V-060). A
2646
+ * reserved word does not parse, and a second declaration of a name of the module does not parse. The function of the
2647
+ * run with the name of a global of `MODULE_GLOBALS` hides that global from the code of the module.
2648
+ */
2649
+ function nameReason(name, declared) {
2650
+ if (RESERVED.has(name)) return `the name "${name}" is a reserved word of JavaScript`;
2651
+ if (MODULE_GLOBALS.has(name)) return `the name "${name}" is a global that a module reads`;
2652
+ return declared.has(name) ? `the name "${name}" is a name of the module` : void 0;
2653
+ }
2314
2654
  var Printer = class {
2315
2655
  #facts;
2316
2656
  #domains;
@@ -2327,6 +2667,11 @@ var Printer = class {
2327
2667
  memos = false;
2328
2668
  /** The parts of the helper S that the nodes of the memo that keep their items need (helperS). */
2329
2669
  features = /* @__PURE__ */ new Set();
2670
+ /** True for a tree space, and the parts of the tree that the program reads (COMPILE.MODULE.TREE). */
2671
+ #tree;
2672
+ treeParts = /* @__PURE__ */ new Set();
2673
+ /** The columns of a sheet, for a module of a sheet (COMPILE.MODULE.SHEET). */
2674
+ #sheet;
2330
2675
  #names = 0;
2331
2676
  /** The number of the next bound function, and of the next printed function. */
2332
2677
  #fnIds = 0;
@@ -2361,26 +2706,34 @@ var Printer = class {
2361
2706
  #wantList = /* @__PURE__ */ new WeakSet();
2362
2707
  /** The facts of the list of each function of the memo whose value is a list. */
2363
2708
  #lists = /* @__PURE__ */ new Map();
2364
- constructor(expr, options) {
2709
+ constructor(expr, options, sheet) {
2365
2710
  this.#domains = options.domains ?? [];
2366
2711
  this.#facts = factsOf({ domains: this.#domains });
2367
2712
  this.#schema = options.schema;
2368
2713
  this.#memo = memoOf(expr);
2714
+ this.#tree = options.space === "tree";
2715
+ this.#sheet = sheet;
2369
2716
  }
2370
2717
  use(name) {
2371
2718
  this.helpers.add(name);
2372
2719
  return name;
2373
2720
  }
2721
+ /** This method gives the name of a part of the tree, for example `H` for the children, and marks the part as read. */
2722
+ #part(part, name) {
2723
+ this.treeParts.add(part);
2724
+ return name;
2725
+ }
2374
2726
  /**
2375
2727
  * This method gives the check of a result of a kind, or undefined for a result that needs no check. A number must be
2376
2728
  * finite, and the domain of the kind can check the value with valid. The law checker of the test kit checks the
2377
2729
  * declaration `returns` of each op (KIND.RETURNS), so the module trusts the kind itself.
2378
2730
  */
2379
2731
  check(kind) {
2380
- const name = `k_${kind.replace(":", "_")}`;
2732
+ const d = this.#facts.checkOf(kind);
2733
+ if (d === void 0) throw new NotStandalone(`a domain without a primitive type comes before the domain of a ${kind}`);
2734
+ const plain = `k_${kind.replace(":", "_")}`;
2735
+ const name = /^[\w$]+$/.test(plain) ? plain : `k_d${String(d)}`;
2381
2736
  if (!this.top.has(name)) {
2382
- const d = this.#facts.checkOf(kind);
2383
- if (d === void 0) throw new NotStandalone(`a domain without a primitive type comes before the domain of a ${kind}`);
2384
2737
  const domain = this.#domains[d];
2385
2738
  const valid = domain?.valid === void 0 ? void 0 : this.#valid(d, domain.name, kind, domain.valid);
2386
2739
  const conds = [...kind === "number" ? ["Number.isFinite(x)"] : [], ...valid === void 0 ? [] : [`${valid}(x)`]];
@@ -2561,7 +2914,7 @@ var Printer = class {
2561
2914
  * from outside is a constant of the run, so its code can be outside the loop.
2562
2915
  */
2563
2916
  #columnar(e, c, ctx) {
2564
- if (ctx.level < 2 || !c.v.deps.has(ctx.level) || this.#work(e, ctx.fns) < COLUMN_WORK) return false;
2917
+ if (ctx.level < 2 || c.v.deps.has(CELLS) || !c.v.deps.has(ctx.level) || this.#work(e, ctx.fns) < COLUMN_WORK) return false;
2565
2918
  const scope = this.#callScope(c, ctx);
2566
2919
  if (c.v.deps.size !== 1 && scope === void 0) return false;
2567
2920
  if (this.#keyed(e)) return false;
@@ -2646,8 +2999,8 @@ var Printer = class {
2646
2999
  const names = Object.keys(e.fields);
2647
3000
  const raw = Object.values(e.fields).map((x) => this.expr(x, ctx));
2648
3001
  const deps = depsOf(...raw);
2649
- const fields = this.#settle(raw, deps, Object.values(e.fields));
2650
- const code = `({ ${fields.map((x, i) => `${JSON.stringify(names[i])}: ${x.v.code}`).join(", ")} })`;
3002
+ const fields = this.#inOrder(this.#settle(raw, deps, Object.values(e.fields)), true);
3003
+ const code = `({ ${fields.map((x, i) => `${names[i] === "__proto__" ? "[\"__proto__\"]" : JSON.stringify(names[i])}: ${x.v.code}`).join(", ")} })`;
2651
3004
  return {
2652
3005
  s: stmtsOf(...fields),
2653
3006
  v: {
@@ -2662,10 +3015,87 @@ var Printer = class {
2662
3015
  case "each": return this.#eachList(e, ctx);
2663
3016
  case "fold": return this.#fold(e, ctx);
2664
3017
  case "iterate": return this.#iterate(e, ctx);
2665
- case "ext": throw new NotStandalone(`the extension "${e.kind}"`);
3018
+ case "ext": return this.#cell(e, ctx);
2666
3019
  }
2667
3020
  }
2668
3021
  /**
3022
+ * This method gives the code of a read of a cell in a module of a sheet (COMPILE.MODULE.SHEET). The value is the result
3023
+ * of the cell, which can be the error sentinel, so the read throws its error. A read that is not a cell reference, or
3024
+ * of a column that the sheet does not have, gives an error, as in `SheetRun`.
3025
+ */
3026
+ #cell(e, ctx) {
3027
+ const sheet = this.#sheet;
3028
+ if (sheet === void 0 || e.kind !== CELL_KIND) throw new NotStandalone(`the extension "${e.kind}"`);
3029
+ const F = this.use("F");
3030
+ if (!isCellRef(e.data)) return bare({
3031
+ code: `${F}()`,
3032
+ kind: void 0,
3033
+ safe: false,
3034
+ deps: /* @__PURE__ */ new Set([CELLS])
3035
+ });
3036
+ const { column, at } = e.data;
3037
+ const deps = /* @__PURE__ */ new Set([...this.#addressDeps(at, ctx, []), CELLS]);
3038
+ const index = sheet.columns.get(column);
3039
+ if (index === void 0) return bare({
3040
+ code: `${F}()`,
3041
+ kind: sheet.kinds.get(column),
3042
+ safe: false,
3043
+ deps
3044
+ });
3045
+ 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`);
3046
+ const read = `${READ_CELL}(${String(index)}, ${this.#address(at, ctx, [])})`;
3047
+ const v = {
3048
+ code: `${this.use("G")}(${read})`,
3049
+ kind: sheet.kinds.get(column),
3050
+ safe: false,
3051
+ deps
3052
+ };
3053
+ return bare(at.every((m) => m.t === "origin") ? {
3054
+ ...v,
3055
+ held: read
3056
+ } : v);
3057
+ }
3058
+ /**
3059
+ * This method gives the parts of a node in the order of the interpreter, when a part reads a cell (COMPILE.MODULE.SHEET).
3060
+ * A read of a cell can start the search of the run, and the search decides the cycles. So the module must read each
3061
+ * cell that the interpreter reads. With `all`, the interpreter evaluates each part also after an error, so each part
3062
+ * goes into a variable that can hold the error. Else the first error stops the parts, so each part goes into a
3063
+ * variable before the next part starts.
3064
+ *
3065
+ * The statements of the parts come before the code of their values. The last part that reads a cell keeps its place
3066
+ * only if no statement after it can throw. Also, with `all`, a value before it must not throw, or the code of its value
3067
+ * must read no cell.
3068
+ */
3069
+ #inOrder(parts, all) {
3070
+ const last = parts.findLastIndex((x) => x.v.deps.has(CELLS));
3071
+ const after = parts.slice(last + 1).every((x) => x.s.length === 0 || x.v.safe);
3072
+ const before = !all || parts.slice(0, Math.max(last, 0)).every((x) => x.v.safe) || !READS_IN_CODE.test(parts[last].v.code);
3073
+ return parts.map((x, i) => {
3074
+ if (i > last || x.v.safe && !x.v.deps.has(CELLS) || i === last && after && before) return x;
3075
+ const b = this.fresh("b");
3076
+ if (all && !x.v.safe) return {
3077
+ s: this.#store(b, x),
3078
+ v: {
3079
+ ...x.v,
3080
+ code: `${this.use("G")}(${b})`,
3081
+ held: b,
3082
+ plain: false
3083
+ }
3084
+ };
3085
+ return {
3086
+ s: [...x.s, `const ${b} = ${x.v.code};`],
3087
+ v: {
3088
+ kind: x.v.kind,
3089
+ deps: x.v.deps,
3090
+ list: x.v.list,
3091
+ code: b,
3092
+ safe: true,
3093
+ plain: true
3094
+ }
3095
+ };
3096
+ });
3097
+ }
3098
+ /**
2669
3099
  * This method gives the code of the index of an address from the focus. `values` has the code of the value of each
2670
3100
  * computed move, in order (NAV.COMPUTED).
2671
3101
  */
@@ -2675,7 +3105,7 @@ var Printer = class {
2675
3105
  let fails = false;
2676
3106
  const checks = [];
2677
3107
  for (const m of at) {
2678
- if (fails && index !== void 0 && m.t !== "offset" && m.t !== "other") checks.push(index);
3108
+ if (fails && index !== void 0 && m.t !== "offset" && m.t !== "other" && (m.t !== "parent" || !this.#tree)) checks.push(index);
2679
3109
  index = moveExpr(m) === void 0 ? this.#move(m, index, ctx.origin) : this.#computed(m, values[next++]);
2680
3110
  fails = m.t !== "origin";
2681
3111
  }
@@ -2701,13 +3131,18 @@ var Printer = class {
2701
3131
  /* v8 ignore next -- @preserve */
2702
3132
  if (focus === void 0) throw new NotStandalone("a node of the memo reads its focus");
2703
3133
  if (d === void 0 || more.length > 0 || !Number.isInteger(d)) return `${F}()`;
3134
+ if (this.#tree) return `${this.use("SO")}(${this.#part("siblings", "GP")}, SI, ${focus}, ${d})`;
2704
3135
  return `${this.use("X")}(${focus} + ${d}, n)`;
2705
3136
  }
2706
3137
  case "other":
2707
3138
  /* v8 ignore next -- @preserve */
2708
3139
  if (focus === void 0) throw new NotStandalone("a node of the memo reads its focus");
2709
3140
  return `(n === 2 ? 1 - ${focus} : ${F}())`;
2710
- case "parent": return `${F}()`;
3141
+ case "parent":
3142
+ if (!this.#tree) return `${F}()`;
3143
+ /* v8 ignore next -- @preserve */
3144
+ if (focus === void 0) throw new NotStandalone("a node of the memo reads its focus");
3145
+ return `${this.use("UP")}(P, ${focus})`;
2711
3146
  }
2712
3147
  }
2713
3148
  #ref(e, ctx) {
@@ -2718,7 +3153,7 @@ var Printer = class {
2718
3153
  const safe = at.every((m) => m.t === "origin");
2719
3154
  const values = this.#addressValues(at, ctx);
2720
3155
  const deps = this.#addressDeps(at, ctx, values);
2721
- const parts = this.#settle(values, deps);
3156
+ const parts = this.#inOrder(this.#settle(values, deps), false);
2722
3157
  return {
2723
3158
  s: stmtsOf(...parts),
2724
3159
  v: {
@@ -2746,7 +3181,7 @@ var Printer = class {
2746
3181
  if (fails) for (const d of deps) kept.add(d);
2747
3182
  if (moveExpr(m) !== void 0) deps = values[next++].v.deps;
2748
3183
  else if (m.t === "origin") deps = /* @__PURE__ */ new Set([ctx.originLevel]);
2749
- else if (m.t === "key" || m.t === "index" || m.t === "parent") deps = NO_DEPS;
3184
+ else if (m.t === "key" || m.t === "index" || m.t === "parent" && !this.#tree) deps = NO_DEPS;
2750
3185
  fails = m.t !== "origin";
2751
3186
  }
2752
3187
  return /* @__PURE__ */ new Set([...deps, ...kept]);
@@ -2963,7 +3398,7 @@ var Printer = class {
2963
3398
  if (head !== void 0 && (LIST_OPS.has(op) || op === "nth") && this.#isList(head, ctx)) return this.#overList(op, head, args.slice(1), ctx);
2964
3399
  const raw = args.map((x) => this.expr(x, ctx));
2965
3400
  const deps = depsOf(...raw);
2966
- const values = this.#settle(raw, deps, args);
3401
+ const values = this.#inOrder(this.#settle(raw, deps, args), true);
2967
3402
  const site = this.#facts.staticSite(op, values.map((x) => x.v.kind));
2968
3403
  if (site?.t !== "fn") throw new NotStandalone(`the kinds of the values of "${op}" do not decide its op`);
2969
3404
  if (site.bad) return {
@@ -3142,8 +3577,8 @@ var Printer = class {
3142
3577
  */
3143
3578
  /**
3144
3579
  * This method gives the loop over the targets of an axis: the statements before it, its bounds and the key that it
3145
- * skips. `start` has the levels of the address, and `inner` is the position at a target. The axes all, others and
3146
- * window have a loop.
3580
+ * skips. `start` has the levels of the address, and `inner` is the position at a target. The axes all, others,
3581
+ * window and list have a loop. In a tree space, the axes of a tree have a loop too.
3147
3582
  */
3148
3583
  #targetLoop(axis, at, ctx) {
3149
3584
  const { base: outer, tests } = testsOf(axis);
@@ -3186,18 +3621,35 @@ var Printer = class {
3186
3621
  if (f !== void 0) {
3187
3622
  const values = this.#addressValues(at, ctx);
3188
3623
  start = this.#addressDeps(at, ctx, values);
3189
- const parts = this.#settle(values, start);
3624
+ const parts = this.#inOrder(this.#settle(values, start), false);
3190
3625
  s.push(...stmtsOf(...parts), `const ${f} = ${this.#address(at, ctx, parts)};`);
3191
3626
  }
3627
+ const startSafe = at.every((m) => m.t === "origin");
3628
+ if (base.t === "window" && (!Number.isInteger(base.from) || !Number.isInteger(base.to))) throw new NotStandalone("the axis \"window\" with a bound that is not an integer");
3629
+ if (this.#tree && isTreeAxis(base)) {
3630
+ const range = this.#treeRange(base, f);
3631
+ const q = this.fresh("q");
3632
+ return {
3633
+ s: [...s, ...range.s],
3634
+ j,
3635
+ head: forHead(q, range.lo, range.hi, reverse),
3636
+ key: [`const ${j} = ${range.a}[${q}];`],
3637
+ check: [],
3638
+ skip: range.skip,
3639
+ fixed: false,
3640
+ start,
3641
+ startSafe,
3642
+ tests,
3643
+ inner
3644
+ };
3645
+ }
3192
3646
  if (base.t === "others") skip = f;
3193
3647
  else if (base.t === "window") {
3194
- if (!Number.isInteger(base.from) || !Number.isInteger(base.to)) throw new NotStandalone("the axis \"window\" with a bound that is not an integer");
3195
3648
  const h = this.fresh("h");
3196
3649
  lo = `Math.max(0, ${f} + Math.max(${base.from}, -n))`;
3197
3650
  s.push(`const ${h} = Math.min(n, ${f} + Math.min(${base.to}, n) + 1);`);
3198
3651
  hi = h;
3199
3652
  } else if (base.t !== "all") throw new NotStandalone(`the axis "${base.t}"`);
3200
- const startSafe = at.every((m) => m.t === "origin");
3201
3653
  return {
3202
3654
  s,
3203
3655
  j,
@@ -3212,6 +3664,54 @@ var Printer = class {
3212
3664
  inner
3213
3665
  };
3214
3666
  }
3667
+ /**
3668
+ * This method gives the targets of an axis of a tree space at the position `f`. They are the positions `a[q]` for `q`
3669
+ * from `lo` up to `hi`, without the key that the loop skips. The axes come from AXIS.TREE, AXIS.GRAPH and AXIS.WINDOW.
3670
+ */
3671
+ #treeRange(base, f) {
3672
+ const a = this.fresh("A");
3673
+ const all = (code, lo = "0", skip) => ({
3674
+ s: [`const ${a} = ${code};`],
3675
+ a,
3676
+ lo,
3677
+ hi: `${a}.length`,
3678
+ skip
3679
+ });
3680
+ switch (base.t) {
3681
+ case "children":
3682
+ case "successors": return all(`${this.#part("children", "H")}[${f}]`);
3683
+ case "siblings": return all(`${this.#part("siblings", "GP")}[${f}]`, "0", f);
3684
+ case "ancestors": return all(`${this.use("AN")}(P, ${f})`);
3685
+ case "predecessors": return all(`(P[${f}] < 0 ? [] : [P[${f}]])`);
3686
+ case "reachable": return all(`${this.use("BF")}(${this.#part("children", "H")}, ${f})`, "1");
3687
+ case "descendants": {
3688
+ const h = this.fresh("h");
3689
+ return {
3690
+ s: [`const ${a} = ${this.#part("order", "PI")}[${f}] + 1;`, `const ${h} = ${a} + SZ[${f}] - 1;`],
3691
+ a: "PO",
3692
+ lo: a,
3693
+ hi: h,
3694
+ skip: void 0
3695
+ };
3696
+ }
3697
+ case "window": {
3698
+ const { from, to } = base;
3699
+ const l = this.fresh("h");
3700
+ const h = this.fresh("h");
3701
+ return {
3702
+ s: [
3703
+ `const ${a} = ${this.#part("siblings", "GP")}[${f}];`,
3704
+ `const ${l} = Math.max(0, SI[${f}] + ${String(from)});`,
3705
+ `const ${h} = Math.min(${a}.length, SI[${f}] + ${String(to)} + 1);`
3706
+ ],
3707
+ a,
3708
+ lo: l,
3709
+ hi: h,
3710
+ skip: void 0
3711
+ };
3712
+ }
3713
+ }
3714
+ }
3215
3715
  #list(op, target, rest, ctx) {
3216
3716
  const strict = this.#strict(op, rest);
3217
3717
  const at = target.at ?? [];
@@ -3230,6 +3730,44 @@ var Printer = class {
3230
3730
  ...body.s
3231
3731
  ];
3232
3732
  const safeItem = check.length === 0 && body.v.safe && testCodes.every((t) => this.#safeBoolean(t.v));
3733
+ if ([body, ...testCodes].some((x) => x.v.deps.has(CELLS)) && (strict || stepThrows(op, body.v.kind))) {
3734
+ const list = this.fresh("L");
3735
+ const x = this.fresh("x");
3736
+ const all = [
3737
+ ...key,
3738
+ ...skip === void 0 ? [] : [`if (${j} === ${skip}) continue;`],
3739
+ `let ${x};`,
3740
+ "try {",
3741
+ ...ind(item),
3742
+ ` ${x} = ${body.v.code};`,
3743
+ "} catch {",
3744
+ ` ${x} = E;`,
3745
+ "}",
3746
+ `${list}.push(${x});`
3747
+ ];
3748
+ const reduce = [
3749
+ `for (const ${v} of ${list}) {`,
3750
+ ` if (${v} === E) ${strict ? `${this.use("F")}();` : "continue;"}`,
3751
+ ` ${r.step}`,
3752
+ "}"
3753
+ ];
3754
+ return {
3755
+ s: [
3756
+ ...s,
3757
+ `const ${list} = [];`,
3758
+ head,
3759
+ ...ind(all),
3760
+ "}",
3761
+ ...reduce
3762
+ ],
3763
+ v: {
3764
+ code: r.result,
3765
+ kind: listKind(op, body.v.kind),
3766
+ safe: false,
3767
+ deps
3768
+ }
3769
+ };
3770
+ }
3233
3771
  const loop = [
3234
3772
  ...key,
3235
3773
  ...skip === void 0 ? [] : [`if (${j} === ${skip}) continue;`],
@@ -3360,7 +3898,7 @@ var Printer = class {
3360
3898
  const strict = this.#strict(op, rest.slice(exprs.length - 1));
3361
3899
  const raw = [list, ...exprs.slice(1).map((x) => this.expr(x, ctx))];
3362
3900
  const deps = depsOf(...raw);
3363
- const parts = this.#settle(raw, deps, exprs);
3901
+ const parts = this.#inOrder(this.#settle(raw, deps, exprs), true);
3364
3902
  const item = list.v.list.item;
3365
3903
  return {
3366
3904
  s: stmtsOf(...parts),
@@ -3380,7 +3918,7 @@ var Printer = class {
3380
3918
  const strict = this.#strict(op, rest.slice(exprs.length - 1));
3381
3919
  const raw = [list, ...exprs.slice(1).map((x) => this.expr(x, ctx))];
3382
3920
  const deps = depsOf(...raw);
3383
- const parts = this.#settle(raw, deps, exprs);
3921
+ const parts = this.#inOrder(this.#settle(raw, deps, exprs), true);
3384
3922
  const [l] = parts;
3385
3923
  const item = list.v.list.item;
3386
3924
  if (op === "nth") return {
@@ -3513,6 +4051,7 @@ var Printer = class {
3513
4051
  const names = this.#loopNames(e.init, ctx, loop);
3514
4052
  const t = this.#targetLoop(e.axis, e.at ?? [], ctx);
3515
4053
  const tests = t.tests.map((x) => this.#hoist(this.expr(x, t.inner), hasLoop(x)));
4054
+ if (tests.some((x) => x.v.deps.has(CELLS))) throw new NotStandalone("a test of the axis of a fold reads a cell");
3516
4055
  const step = this.#loopStep(e.step, {
3517
4056
  ...t.inner,
3518
4057
  env: names.env
@@ -3733,8 +4272,9 @@ var Printer = class {
3733
4272
  };
3734
4273
  }
3735
4274
  /** This method gives the code of the program at the key of the run. A constant of the run evaluates once. */
4275
+ /** This method gives the code of a program at the key `o` of the run. A sheet has one program for each formula. */
3736
4276
  root(expr) {
3737
- const c = this.#hoist(this.expr(expr, {
4277
+ return this.#hoist(this.expr(expr, {
3738
4278
  origin: "o",
3739
4279
  focus: "o",
3740
4280
  level: 1,
@@ -3743,8 +4283,10 @@ var Printer = class {
3743
4283
  fns: /* @__PURE__ */ new Map(),
3744
4284
  keys: /* @__PURE__ */ new Map()
3745
4285
  }));
4286
+ }
4287
+ /** This method removes the declarations that no code reads, after the last program. */
4288
+ finish() {
3746
4289
  for (const [name, form] of this.#forms) if (form !== void 0 && !this.#called.has(name)) this.top.delete(name);
3747
- return c;
3748
4290
  }
3749
4291
  /**
3750
4292
  * This method gives a text that is the same for two expressions with the same structure and the same reads. A name
@@ -3764,42 +4306,30 @@ var Printer = class {
3764
4306
  });
3765
4307
  }
3766
4308
  };
3767
- /**
3768
- * This function prints a program as a standalone ES module. The module exports `VexContractError`, `VEX_ERROR` and a
3769
- * function that takes the records and the variables and gives the value at each key. It is pure, so a build can use it.
3770
- * The program can be an expression or a document (DOC.ENTRY).
3771
- */
3772
- function emitModule(source, options) {
4309
+ /** This function gives the name of the function of a module, and its space, or the reason that the options are not valid. */
4310
+ function runOf(options) {
3773
4311
  const name = options.name ?? "run";
3774
- if (!/^[A-Za-z_$][\w$]*$/.test(name)) return {
3775
- ok: false,
3776
- reason: `the name "${name}" is not a JavaScript name`
3777
- };
3778
- const read = isDocument(source) ? fromDocument(source, options.domains) : {
3779
- ok: true,
3780
- value: source
3781
- };
3782
- if (!read.ok) return {
3783
- ok: false,
3784
- reason: read.error.message
4312
+ if (!/^[A-Za-z_$][\w$]*$/.test(name)) return { reason: `the name "${name}" is not a JavaScript name` };
4313
+ const tree = options.space === "tree";
4314
+ if (!tree && options.space !== void 0 && options.space !== "array") return { reason: `the space "${String(options.space)}" is not "array" or "tree"` };
4315
+ return {
4316
+ name,
4317
+ tree
3785
4318
  };
3786
- const expr = read.value;
3787
- const shape = shapeError(expr);
3788
- if (shape !== void 0) return {
4319
+ }
4320
+ /** This function gives the reason of an error of the printer. Another exception is a defect, so it goes to the caller. */
4321
+ function reasonOf(thrown) {
4322
+ if (!(thrown instanceof NotStandalone)) throw thrown;
4323
+ return {
3789
4324
  ok: false,
3790
- reason: shape
4325
+ reason: thrown.message
3791
4326
  };
3792
- const p = new Printer(expr, options);
3793
- let value;
3794
- try {
3795
- value = p.root(expr);
3796
- } catch (thrown) {
3797
- if (!(thrown instanceof NotStandalone)) throw thrown;
3798
- return {
3799
- ok: false,
3800
- reason: thrown.message
3801
- };
3802
- }
4327
+ }
4328
+ /**
4329
+ * This function gives the text of a module: the declarations, the helpers, and the function of the run. The run checks
4330
+ * its input, computes the parts of the tree and the constants of the run, and then gives the statements `body`.
4331
+ */
4332
+ function printModule(p, options, run, body) {
3803
4333
  p.use("C");
3804
4334
  const helpers = /* @__PURE__ */ new Set();
3805
4335
  const add = (h) => {
@@ -3814,13 +4344,31 @@ function emitModule(source, options) {
3814
4344
  fieldChecks = fields.map(([f, k]) => ` || ${p.against(k, `r[${JSON.stringify(f)}]`)}`).join("");
3815
4345
  varChecks = vars.map(([v, k]) => ` || ${p.against(k, `vars[${JSON.stringify(v)}]`)}`).join("");
3816
4346
  } catch (thrown) {
3817
- if (!(thrown instanceof NotStandalone)) throw thrown;
3818
- return {
3819
- ok: false,
3820
- reason: thrown.message
3821
- };
4347
+ return reasonOf(thrown);
3822
4348
  }
4349
+ const { name, tree } = run;
4350
+ if (tree) p.use("PT");
4351
+ if (p.treeParts.size > 0) p.treeParts.add("children");
4352
+ const parts = [
4353
+ "children",
4354
+ "siblings",
4355
+ "order"
4356
+ ].filter((x) => p.treeParts.has(x));
4357
+ for (const x of parts) p.use(TREE_PARTS[x][0]);
3823
4358
  [...p.helpers].toSorted().forEach(add);
4359
+ const bad = nameReason(name, /* @__PURE__ */ new Set([
4360
+ "VexContractError",
4361
+ "VEX_ERROR",
4362
+ "E",
4363
+ ...p.memos ? ["Z"] : [],
4364
+ ...helpers.has("S") ? ["N", "W"] : [],
4365
+ ...helpers,
4366
+ ...p.top.keys()
4367
+ ]));
4368
+ if (bad !== void 0) return {
4369
+ ok: false,
4370
+ reason: bad
4371
+ };
3824
4372
  return {
3825
4373
  ok: true,
3826
4374
  source: [
@@ -3834,7 +4382,7 @@ function emitModule(source, options) {
3834
4382
  ...helpers.has("S") ? ["const N = {}, W = {};"] : [],
3835
4383
  ...[...helpers].map((h) => h === "S" ? helperS(p.features) : HELPERS[h]),
3836
4384
  ...p.top.values(),
3837
- `export function ${name}(records, vars) {`,
4385
+ `export function ${name}(records, vars${tree ? ", parents" : ""}) {`,
3838
4386
  " if (!Array.isArray(records)) C(\"the records are not an array\");",
3839
4387
  " const R = records;",
3840
4388
  " const n = R.length;",
@@ -3843,24 +4391,176 @@ function emitModule(source, options) {
3843
4391
  ` if (typeof r !== "object" || r === null${fieldChecks}) C(\`the record \${i} does not keep the schema\`);`,
3844
4392
  " }",
3845
4393
  ` if (typeof vars !== "object" || vars === null${varChecks}) C("the variables do not keep the schema");`,
4394
+ ...tree ? [" const P = PT(parents, n);", ...parts.map((x) => ` ${TREE_PARTS[x][1]}`)] : [],
3846
4395
  ...[...p.vars].map(([v, code]) => ` const ${code} = vars[${JSON.stringify(v)}];`),
3847
4396
  ...ind(p.run),
3848
- " const out = [];",
3849
- " for (let o = 0; o < n; o++) {",
3850
- " try {",
3851
- ...ind(ind(ind(value.s))),
3852
- ` out.push(${value.v.code});`,
3853
- " } catch {",
3854
- " out.push(VEX_ERROR);",
3855
- " }",
3856
- " }",
3857
- " return out;",
4397
+ ...ind(body),
3858
4398
  "}",
3859
4399
  ""
3860
4400
  ].join("\n")
3861
4401
  };
3862
4402
  }
4403
+ /**
4404
+ * This function prints a program as a standalone ES module. The module exports `VexContractError`, `VEX_ERROR` and a
4405
+ * function that takes the records and the variables and gives the value at each key. A module of a tree space takes
4406
+ * the parents too. The function is pure, so a build can use it. The program can be an expression or a document
4407
+ * (DOC.ENTRY).
4408
+ */
4409
+ function emitModule(source, options) {
4410
+ const run = runOf(options);
4411
+ if ("reason" in run) return {
4412
+ ok: false,
4413
+ reason: run.reason
4414
+ };
4415
+ const read = isDocument(source) ? fromDocument(source, options.domains) : {
4416
+ ok: true,
4417
+ value: source
4418
+ };
4419
+ if (!read.ok) return {
4420
+ ok: false,
4421
+ reason: read.error.message
4422
+ };
4423
+ const expr = read.value;
4424
+ const shape = shapeError(expr);
4425
+ if (shape !== void 0) return {
4426
+ ok: false,
4427
+ reason: shape
4428
+ };
4429
+ const p = new Printer(expr, options);
4430
+ let value;
4431
+ try {
4432
+ value = p.root(expr);
4433
+ p.finish();
4434
+ } catch (thrown) {
4435
+ return reasonOf(thrown);
4436
+ }
4437
+ return printModule(p, options, run, [
4438
+ "const out = [];",
4439
+ "for (let o = 0; o < n; o++) {",
4440
+ " try {",
4441
+ ...ind(ind(value.s)),
4442
+ ` out.push(${value.v.code});`,
4443
+ " } catch {",
4444
+ " out.push(VEX_ERROR);",
4445
+ " }",
4446
+ "}",
4447
+ "return out;"
4448
+ ]);
4449
+ }
4450
+ /** The budget of the stack of the search of a run of a sheet, as `STACK_BUDGET` of `SheetRun`. */
4451
+ const SHEET_BUDGET = 3e3;
4452
+ /** This function gives the words for a formula in a reason: the formula of a column, or of one cell. */
4453
+ 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)}"`;
4454
+ /** This function gives the words for a kind in a reason. */
4455
+ const kindText = (k) => k ?? "that the printer does not know";
4456
+ /**
4457
+ * This function prints the formula columns of a sheet as a standalone ES module (COMPILE.MODULE.SHEET). The function of
4458
+ * the module takes the records and the variables, and the parents for a tree. It gives an object with an array for
4459
+ * each column: the result of the column at each key, or `VEX_ERROR`. The results are the results of `SheetRun`.
4460
+ *
4461
+ * The run fills the columns in the order of `SheetRun.fill`. A read of a finished cell is the read of an array. A read
4462
+ * of a cell that is not finished starts the search of `SheetRun`, with the same budget of the stack. Each cell on a
4463
+ * cycle of reads gives `VEX_ERROR`.
4464
+ */
4465
+ function emitSheetModule(columns, options) {
4466
+ const run = runOf(options);
4467
+ if ("reason" in run) return {
4468
+ ok: false,
4469
+ reason: run.reason
4470
+ };
4471
+ const budget = options.budget ?? SHEET_BUDGET;
4472
+ if (!Number.isSafeInteger(budget) || budget < 0) return {
4473
+ ok: false,
4474
+ reason: `the budget ${String(budget)} is not a whole number of 0 or more`
4475
+ };
4476
+ const cells = options.cells ?? /* @__PURE__ */ new Map();
4477
+ const names = [.../* @__PURE__ */ new Set([...columns.keys(), ...cells.keys()])];
4478
+ const order = columnOrder(columns, cells);
4479
+ const formulas = order.flatMap((column) => {
4480
+ const own = [...cells.get(column) ?? []].filter(([k]) => /^(0|[1-9]\d*)$/.test(k) && Number.isSafeInteger(Number(k)));
4481
+ const formula = columns.get(column);
4482
+ return [...formula === void 0 ? [] : [{
4483
+ column,
4484
+ key: void 0,
4485
+ expr: formula
4486
+ }], ...own.map(([k, expr]) => ({
4487
+ column,
4488
+ key: Number(k),
4489
+ expr
4490
+ }))];
4491
+ });
4492
+ for (const f of formulas) {
4493
+ const shape = shapeError(f.expr);
4494
+ if (shape !== void 0) return {
4495
+ ok: false,
4496
+ reason: `${formulaText(f)}: ${shape}`
4497
+ };
4498
+ }
4499
+ const kinds = new Map(Object.entries(options.kinds ?? {}));
4500
+ const index = new Map(names.map((c, i) => [c, i]));
4501
+ const p = new Printer(rec(Object.fromEntries(formulas.map((f, i) => [`f${String(i)}`, f.expr]))), options, {
4502
+ columns: index,
4503
+ kinds
4504
+ });
4505
+ const fns = [];
4506
+ const decls = [];
4507
+ try {
4508
+ for (const f of formulas) {
4509
+ const code = p.root(f.expr);
4510
+ const kind = code.v.kind;
4511
+ if (!kinds.has(f.column)) kinds.set(f.column, kind);
4512
+ 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`);
4513
+ const fn = p.fresh("cf");
4514
+ fns.push(fn);
4515
+ decls.push(...code.v.safe && code.s.length === 0 ? [`const ${fn} = (o) => ${code.v.code};`] : [
4516
+ `const ${fn} = (o) => {`,
4517
+ " try {",
4518
+ ...ind(ind(code.s)),
4519
+ ` return ${code.v.code};`,
4520
+ " } catch {",
4521
+ " return E;",
4522
+ " }",
4523
+ "};"
4524
+ ]);
4525
+ }
4526
+ p.finish();
4527
+ } catch (thrown) {
4528
+ return reasonOf(thrown);
4529
+ }
4530
+ const entry = (i) => `[${fns[i]}, ${String(3 * nestingOf(formulas[i].expr) + 16)}]`;
4531
+ const own = names.map((c) => {
4532
+ const at = formulas.flatMap((f, i) => f.column === c && f.key !== void 0 ? [`${String(f.key)}: ${entry(i)}`] : []);
4533
+ return at.length === 0 ? "undefined" : `{ ${at.join(", ")} }`;
4534
+ });
4535
+ const cols = names.map((c) => {
4536
+ const i = formulas.findIndex((f) => f.column === c && f.key === void 0);
4537
+ return i < 0 ? "undefined" : entry(i);
4538
+ });
4539
+ p.use("SH");
4540
+ const orders = /* @__PURE__ */ new Map();
4541
+ const fill = order.map((c) => {
4542
+ const { reverse, post, back } = keyOrderOf(readsOf(columns, cells, c).directions);
4543
+ const at = String(index.get(c));
4544
+ if (!run.tree) return reverse ? `for (let o = n - 1; o >= 0; o--) SS.f(${at}, o);` : `for (let o = 0; o < n; o++) SS.f(${at}, o);`;
4545
+ const args = `${p.use("KO")}(H, RT, ${String(post)}, ${String(back)})`;
4546
+ let keys = orders.get(args);
4547
+ if (keys === void 0) {
4548
+ keys = p.fresh("K");
4549
+ orders.set(args, keys);
4550
+ }
4551
+ return `for (const o of ${keys}) SS.f(${at}, o);`;
4552
+ });
4553
+ if (run.tree) p.treeParts.add("children");
4554
+ return printModule(p, options, run, [
4555
+ ...decls,
4556
+ `const SS = SH(n, [${cols.join(", ")}], [${own.join(", ")}], ${String(budget)});`,
4557
+ `const ${READ_CELL} = SS.r;`,
4558
+ ...[...orders].map(([args, keys]) => `const ${keys} = ${args};`),
4559
+ ...fill,
4560
+ `return { ${names.map((c, i) => `${JSON.stringify(c)}: SS.o(${String(i)})`).join(", ")} };`
4561
+ ]);
4562
+ }
3863
4563
  //#endregion
3864
- export { FALLBACK, createRuntime, emitModule, generate, load, tiered };
4564
+ export { FALLBACK, createRuntime, emitModule, emitSheetModule, generate, load, tiered };
3865
4565
 
3866
4566
  //# sourceMappingURL=index.js.map