@mark1russell7/vex-compiler 0.13.0 → 0.13.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/build/index.js CHANGED
@@ -1,4 +1,4 @@
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";
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
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
@@ -68,7 +68,7 @@ function returnsOf(domain, kind) {
68
68
  return kind === "any" ? void 0 : kind;
69
69
  }
70
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(domain, param, arg) {
71
+ function fits$1(domain, param, arg) {
72
72
  if (param === void 0 || param === "any") return true;
73
73
  if (arg === void 0) return void 0;
74
74
  return arg === (param === "domain" ? kindOfDomain(domain) : param);
@@ -100,7 +100,7 @@ function factsOf(options) {
100
100
  continue;
101
101
  }
102
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(d, e.spec.params?.[j], a));
103
+ const ok = args.map((a, j) => fits$1(d, e.spec.params?.[j], a));
104
104
  if (ok.includes(void 0)) return void 0;
105
105
  return {
106
106
  t: "fn",
@@ -1672,6 +1672,7 @@ function createRuntime(options) {
1672
1672
  });
1673
1673
  if (r !== void 0) return r;
1674
1674
  }
1675
+ if (listOp && fn === void 0 && Array.isArray(values[0])) throw new Error("tier 1 gives a list op on an array");
1675
1676
  try {
1676
1677
  return fn === void 0 ? F : checked(fn(...values));
1677
1678
  } catch (thrown) {
@@ -1940,6 +1941,53 @@ function keyOrderOf(d) {
1940
1941
  back: post !== reverse
1941
1942
  };
1942
1943
  }
1944
+ /** This function gives the axis under the tests of `where` and under `reverse`. Both read the targets of that axis. */
1945
+ function baseOf(axis) {
1946
+ let base = axis;
1947
+ while (base.t === "where" || base.t === "reverse") base = base.axis;
1948
+ return base;
1949
+ }
1950
+ /**
1951
+ * This function tells if each read of a cell of the column `self` reads a finished cell in the static order of the
1952
+ * fill (COMPILE.MODULE.SHEET.DIRECT). A read of a column before `self` in `order` reads a finished cell. A read of a
1953
+ * column that the sheet does not have also reads a finished cell. A read of `self` reads a finished cell only in
1954
+ * these three forms:
1955
+ * - in a tree in pre-order, at the move `parent` from the key,
1956
+ * - in an array in key order, at an offset of one negative step from the key,
1957
+ * - in a tree in post-order, at the key of a target of the axis `children` of the key.
1958
+ *
1959
+ * A read in the body of a function can evaluate at each place of a call, so it is not one of these forms.
1960
+ */
1961
+ function readsFinished(columns, order, self, tree) {
1962
+ const formula = columns.get(self);
1963
+ if (formula === void 0 || shapeError(formula) !== void 0) return false;
1964
+ const { reverse, post } = keyOrderOf(readsOf(columns, /* @__PURE__ */ new Map(), self).directions);
1965
+ const position = order.indexOf(self);
1966
+ const todo = [[formula, "key"]];
1967
+ for (let item = todo.pop(); item !== void 0; item = todo.pop()) {
1968
+ const [e, place] = item;
1969
+ if (e.tag === "each" || e.tag === "fold") {
1970
+ const inner = place === "key" && (e.at === void 0 || e.at.length === 0) && baseOf(e.axis).t === "children" ? "children" : "unknown";
1971
+ const { tests } = partsOf$1(e.axis);
1972
+ for (const x of [...e.tag === "each" ? [e.body] : Object.values(e.step), ...tests]) todo.push([x, inner]);
1973
+ const list = listOf(e.axis);
1974
+ for (const x of [
1975
+ ...e.tag === "fold" ? [...Object.values(e.init), e.result] : [],
1976
+ ...addrExprs(e.at),
1977
+ ...list === void 0 ? [] : [list]
1978
+ ]) todo.push([x, place]);
1979
+ } else if (e.tag === "fn") todo.push([e.body, "unknown"]);
1980
+ else if (e.tag !== "ext") for (const child of children(e)) todo.push([child, place]);
1981
+ else if (e.kind === CELL_KIND && isCellRef(e.data)) {
1982
+ const { column, at } = e.data;
1983
+ if (order.indexOf(column) > position) return false;
1984
+ if (column !== self) continue;
1985
+ const [move, ...rest] = at;
1986
+ if (!(place === "key" ? move !== void 0 && rest.length === 0 && (tree && !post && move.t === "parent" || !tree && !reverse && move.t === "offset" && move.d.length === 1 && (move.d[0] ?? 0) < 0) : place === "children" && tree && post && at.length === 0)) return false;
1987
+ }
1988
+ }
1989
+ return true;
1990
+ }
1943
1991
  //#endregion
1944
1992
  //#region src/module.ts
1945
1993
  /**
@@ -1959,10 +2007,12 @@ function keyOrderOf(d) {
1959
2007
  * 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
1960
2008
  * nodes with the same expression share the function.
1961
2009
  *
1962
- * The printer takes a part of the language. It takes an array space or a tree space of records, and the fields and
1963
- * the variables of the schema. It takes the axes `all`, `others` and `window`. A tree space also has the move `parent` and the
1964
- * axes of a tree (COMPILE.MODULE.TREE). The kinds of each op site must decide its op. Another construct gives a
1965
- * reason, not code.
2010
+ * The printer takes a part of the language. It takes an array space, a tree space or a graph space of records, and
2011
+ * the fields and the variables of the schema. It takes the axes `all`, `others` and `window`. A tree space also has the
2012
+ * move `parent` and the axes of a tree (COMPILE.MODULE.TREE). A graph space has the axes of a graph
2013
+ * (COMPILE.MODULE.GRAPH). A list is an array of pairs of a key and a value. The list ops, `reduce`, list literals and
2014
+ * lists as names of loops are in a module (COMPILE.MODULE.LIST, COMPILE.MODULE.REDUCE). The kinds of each op site must
2015
+ * decide its op. Another construct gives a reason, not code.
1966
2016
  *
1967
2017
  * `emitSheetModule` prints the formula columns of a sheet as one module (COMPILE.MODULE.SHEET). Each column is an array
1968
2018
  * of results, and the run fills the arrays in the static order of `SheetRun.fill`. A read of a cell that is not finished
@@ -2011,6 +2061,45 @@ const HELPERS = {
2011
2061
  ].join("\n"),
2012
2062
  TK: "function TK(l, n, s) { const o = V(l, s); return Number.isSafeInteger(n) && n >= 0 ? o.slice(0, n) : F(); }",
2013
2063
  NT: "function NT(l, i, s) { const o = V(l, s); return Number.isSafeInteger(i) && i >= 0 && i < o.length ? o[i][1] : F(); }",
2064
+ DR: "function DR(l, n, s) { const o = V(l, s); return Number.isSafeInteger(n) && n >= 0 ? o.slice(n) : F(); }",
2065
+ AP: "function AP(l, o, s) { return V(l, s).concat(V(o, s)); }",
2066
+ WO: [
2067
+ "function WO(l, o, s) {",
2068
+ " const a = V(l, s), g = new Map();",
2069
+ " for (const [k] of V(o, s)) g.set(`${k}`, 1);",
2070
+ " return a.filter((x) => !g.has(`${x[0]}`));",
2071
+ "}"
2072
+ ].join("\n"),
2073
+ FL: [
2074
+ "function FL(l, s) {",
2075
+ " const o = [];",
2076
+ " for (const [, v] of V(l, s)) for (const x of V(v, s)) o.push(x);",
2077
+ " return o;",
2078
+ "}"
2079
+ ].join("\n"),
2080
+ GT: [
2081
+ "function GT(l, k, s) {",
2082
+ " let x = l.ix;",
2083
+ " if (x === undefined) {",
2084
+ " x = new Map();",
2085
+ " for (const [q, v] of l) {",
2086
+ " const t = `${q}`;",
2087
+ " if (v === E) x.set(E, E);",
2088
+ " else if (!x.has(t)) x.set(t, v);",
2089
+ " }",
2090
+ " l.ix = x;",
2091
+ " }",
2092
+ " return (s && x.has(E)) || typeof k !== \"string\" || !x.has(k) ? F() : x.get(k);",
2093
+ "}"
2094
+ ].join("\n"),
2095
+ IX: [
2096
+ "function IX(l, x, s) {",
2097
+ " const o = V(l, s);",
2098
+ " if (typeof x !== \"number\" && typeof x !== \"string\" && typeof x !== \"boolean\") F();",
2099
+ " for (let i = 0; i < o.length; i++) if (o[i][1] === x) return i;",
2100
+ " return F();",
2101
+ "}"
2102
+ ].join("\n"),
2014
2103
  PT: [
2015
2104
  "function PT(p, n) {",
2016
2105
  " if (!Array.isArray(p) || p.length !== n) C(\"the parents are not an array with one parent for each record\");",
@@ -2070,6 +2159,29 @@ const HELPERS = {
2070
2159
  SO: "function SO(g, s, k, d) { const t = g[k][s[k] + d]; return t === undefined ? F() : t; }",
2071
2160
  AN: "function AN(P, k) { const o = []; for (let p = P[k]; p >= 0; p = P[p]) o.push(p); return o; }",
2072
2161
  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; }",
2162
+ GR: [
2163
+ "function GR(e, n) {",
2164
+ " if (!Array.isArray(e) || e.length !== n) C(\"the edges are not an array with the ends of the edges of each record\");",
2165
+ " const O = [], s = new Int32Array(n);",
2166
+ " for (let i = 0; i < n; i++) {",
2167
+ " const x = e[i];",
2168
+ " if (!Array.isArray(x)) C(`the edges of the record ${i} are not an array`);",
2169
+ " const o = [];",
2170
+ " for (const t of x) {",
2171
+ " if (!(Number.isInteger(t) && t >= 0 && t < n)) C(`an edge of the record ${i} does not go to the position of a record`);",
2172
+ " if (s[t] !== i + 1) {",
2173
+ " s[t] = i + 1;",
2174
+ " o.push(t);",
2175
+ " }",
2176
+ " }",
2177
+ " O.push(o);",
2178
+ " }",
2179
+ " return O;",
2180
+ "}"
2181
+ ].join("\n"),
2182
+ GI: "function GI(O, n) { const I = []; for (let i = 0; i < n; i++) I.push([]); for (let i = 0; i < n; i++) for (const t of O[i]) I[t].push(i); return I; }",
2183
+ RB: "function RB(O, k, n) { const s = new Uint8Array(n), o = [k]; s[k] = 1; for (let i = 0; i < o.length; i++) for (const c of O[o[i]]) if (s[c] === 0) { s[c] = 1; o.push(c); } return o; }",
2184
+ DO: "function DO(d) { for (let k = 0; k < d.length; k++) if (d[k] === E) d[k] = VEX_ERROR; return d; }",
2073
2185
  SH: [
2074
2186
  "function SH(n, cols, own, budget) {",
2075
2187
  " const pg = (c, k) => {",
@@ -2334,7 +2446,14 @@ const NEEDS = {
2334
2446
  SB: ["V", "F"],
2335
2447
  TK: ["V", "F"],
2336
2448
  NT: ["V", "F"],
2449
+ DR: ["V", "F"],
2450
+ AP: ["V"],
2451
+ WO: ["V"],
2452
+ FL: ["V"],
2453
+ GT: ["F"],
2454
+ IX: ["V", "F"],
2337
2455
  PT: ["C"],
2456
+ GR: ["C"],
2338
2457
  UP: ["F"],
2339
2458
  SO: ["F"],
2340
2459
  CH: [],
@@ -2342,8 +2461,11 @@ const NEEDS = {
2342
2461
  PR: [],
2343
2462
  AN: [],
2344
2463
  BF: [],
2464
+ GI: [],
2465
+ RB: [],
2345
2466
  SH: [],
2346
- KO: []
2467
+ KO: [],
2468
+ DO: []
2347
2469
  };
2348
2470
  /** The statement of each part of a tree in a run, with the helper that computes it. */
2349
2471
  const TREE_PARTS = {
@@ -2363,6 +2485,12 @@ const TREE_AXES = /* @__PURE__ */ new Set([
2363
2485
  ]);
2364
2486
  /** This function tells if an axis has its targets in a range of an array of positions in a tree space. */
2365
2487
  const isTreeAxis = (a) => a.t === "window" || TREE_AXES.has(a.t);
2488
+ /** The axes of a graph space in a module (COMPILE.MODULE.GRAPH), other than the axes of each space. */
2489
+ const GRAPH_AXES = /* @__PURE__ */ new Set([
2490
+ "successors",
2491
+ "predecessors",
2492
+ "reachable"
2493
+ ]);
2366
2494
  /** The list ops of a standalone module. */
2367
2495
  const LIST_OPS = /* @__PURE__ */ new Set([
2368
2496
  "count",
@@ -2375,6 +2503,8 @@ const LIST_OPS = /* @__PURE__ */ new Set([
2375
2503
  "none",
2376
2504
  "first"
2377
2505
  ]);
2506
+ /** The list ops with a running value in a module: the list ops above, and `reduce` with the op of a domain (COMPILE.MODULE.REDUCE). */
2507
+ const FOLD_OPS = /* @__PURE__ */ new Set([...LIST_OPS, "reduce"]);
2378
2508
  const NUMBER_LIST_OPS = /* @__PURE__ */ new Set([
2379
2509
  "count",
2380
2510
  "sum",
@@ -2387,17 +2517,84 @@ const BOOLEAN_LIST_OPS = /* @__PURE__ */ new Set([
2387
2517
  "all",
2388
2518
  "none"
2389
2519
  ]);
2390
- /** The list ops that build a list from lists (LIST.BUILD), `get` (LIST.GET) and `indexOf` (LIST.INDEXOF). A module gives a reason for them. */
2520
+ /** The list ops over lists of `#build`: append, without and flat (LIST.BUILD), get (LIST.GET) and indexOf (LIST.INDEXOF). */
2391
2521
  const BUILD_OPS = /* @__PURE__ */ new Set([
2392
- "drop",
2393
2522
  "append",
2394
- "flat",
2395
2523
  "without",
2524
+ "flat",
2396
2525
  "get",
2397
2526
  "indexOf"
2398
2527
  ]);
2528
+ /** The helper of each op of `#build`. */
2529
+ const BUILD_HELPERS = {
2530
+ append: "AP",
2531
+ without: "WO",
2532
+ flat: "FL",
2533
+ get: "GT",
2534
+ indexOf: "IX"
2535
+ };
2536
+ /** The list ops whose value is a list (LIST.SORT, LIST.TAKE and LIST.BUILD). */
2537
+ const LIST_RESULTS = /* @__PURE__ */ new Set([
2538
+ "sortBy",
2539
+ "take",
2540
+ "drop",
2541
+ "append",
2542
+ "without",
2543
+ "flat"
2544
+ ]);
2545
+ /**
2546
+ * This function tells if an expression gives a list. An each, a list literal and a list op of `LIST_RESULTS` give a
2547
+ * list. A name of a list, and a let or a loop whose result is a list, give a list too. `isName` tells if a name outside the expression holds a list.
2548
+ */
2549
+ function listy(e, isName) {
2550
+ switch (e.tag) {
2551
+ case "each": return true;
2552
+ case "lit": return isVexList(e.value);
2553
+ case "app": return LIST_RESULTS.has(e.op);
2554
+ case "var": return isName(e.name);
2555
+ case "let": return listy(e.body, namesIn(e.bind, isName));
2556
+ case "fold":
2557
+ case "iterate": return listy(e.result, namesIn(e.init, isName));
2558
+ case "call":
2559
+ case "ext":
2560
+ case "fn":
2561
+ case "rec":
2562
+ case "ref": return false;
2563
+ }
2564
+ }
2565
+ /** This function tells if a name holds a list in the scope of some bindings. A binding hides a name outside, and a function is not a list. */
2566
+ function namesIn(bind, isName) {
2567
+ const lists = new Map(Object.entries(bind).map(([name, x]) => [name, x.tag !== "fn" && listy(x, isName)]));
2568
+ return (name) => lists.get(name) ?? isName(name);
2569
+ }
2570
+ /** This function tells if an expression has a list literal with an item, so a key of the list can be a text (LIST.LITERAL). */
2571
+ function hasKeyedLiteral(e) {
2572
+ return e.tag === "lit" && isVexList(e.value) && e.value.items.length > 0 || children(e).some(hasKeyedLiteral);
2573
+ }
2574
+ /** This function gives the facts of the list of `append` from the facts of its two lists. An empty list fits each list. */
2575
+ function joinLists(a, b) {
2576
+ if (a.empty === true) return b;
2577
+ if (b.empty === true) return a;
2578
+ if (a.inner === void 0 !== (b.inner === void 0)) throw new NotStandalone("\"append\" of a list of lists and a list of values");
2579
+ const texts = a.texts === true || b.texts === true;
2580
+ return {
2581
+ item: join(a.item, b.item),
2582
+ inner: a.inner === void 0 ? void 0 : joinLists(a.inner, b.inner),
2583
+ texts
2584
+ };
2585
+ }
2586
+ /**
2587
+ * This function tells if a list of a step fits the list of a name of a loop (LOOP.LIST). The items of the step have the
2588
+ * kind of the items of the name, if the name has one. The name also has the text keys and the lists of lists of the step.
2589
+ */
2590
+ function fits(name, step) {
2591
+ if (step.empty === true) return true;
2592
+ if (name.item !== void 0 && step.item !== name.item) return false;
2593
+ if (step.texts === true && name.texts !== true) return false;
2594
+ return name.inner === void 0 ? step.inner === void 0 : step.inner !== void 0 && fits(name.inner, step.inner);
2595
+ }
2399
2596
  /** This function tells if the step of a list op throws for a value of the kind `kind`, which is the wrong kind. */
2400
- const stepThrows = (op, kind) => NUMBER_STEPS.has(op) && kind !== "number" || BOOLEAN_LIST_OPS.has(op) && kind !== "boolean";
2597
+ const stepThrows = (op, kind) => op === "reduce" || NUMBER_STEPS.has(op) && kind !== "number" || BOOLEAN_LIST_OPS.has(op) && kind !== "boolean";
2401
2598
  /** The list ops whose step takes a number. */
2402
2599
  const NUMBER_STEPS = /* @__PURE__ */ new Set([
2403
2600
  "sum",
@@ -2674,6 +2871,9 @@ var Printer = class {
2674
2871
  /** True for a tree space, and the parts of the tree that the program reads (COMPILE.MODULE.TREE). */
2675
2872
  #tree;
2676
2873
  treeParts = /* @__PURE__ */ new Set();
2874
+ /** True for a graph space, and true when the program reads the predecessors of a graph (COMPILE.MODULE.GRAPH). */
2875
+ #graph;
2876
+ into = false;
2677
2877
  /** The columns of a sheet, for a module of a sheet (COMPILE.MODULE.SHEET). */
2678
2878
  #sheet;
2679
2879
  #names = 0;
@@ -2716,6 +2916,7 @@ var Printer = class {
2716
2916
  this.#schema = options.schema;
2717
2917
  this.#memo = memoOf(expr);
2718
2918
  this.#tree = options.space === "tree";
2919
+ this.#graph = options.space === "graph";
2719
2920
  this.#sheet = sheet;
2720
2921
  }
2721
2922
  use(name) {
@@ -2906,11 +3107,27 @@ var Printer = class {
2906
3107
  if (c.v.list === void 0) throw new NotStandalone("a list op on a value that is not a list");
2907
3108
  return c;
2908
3109
  }
2909
- /** This method tells if an expression gives a list at a place that takes one: an each, sortBy, take or a name of a list. */
3110
+ /** This method tells if an expression gives a list at a place that takes one (`listy`). */
2910
3111
  #isList(e, ctx) {
2911
- if (e.tag === "each") return true;
2912
- if (e.tag === "app") return e.op === "sortBy" || e.op === "take";
2913
- return e.tag === "var" && ctx.env.get(e.name)?.list !== void 0;
3112
+ return listy(e, (name) => ctx.env.get(name)?.list !== void 0);
3113
+ }
3114
+ /** This method prints a list literal (LIST.LITERAL) as an array of pairs of a key and a value. An error item holds the sentinel. */
3115
+ #listLiteral(l) {
3116
+ const values = l.items.map((it) => it.result.ok ? literal(it.result.value) : void 0);
3117
+ const kinds = values.flatMap((x) => x === void 0 ? [] : [x.kind]);
3118
+ const code = `[${l.items.map((it, i) => `[${JSON.stringify(it.key)}, ${values[i]?.code ?? "E"}]`).join(", ")}]`;
3119
+ const has = l.items.length > 0;
3120
+ return bare({
3121
+ code,
3122
+ kind: void 0,
3123
+ safe: true,
3124
+ deps: NO_DEPS,
3125
+ list: {
3126
+ item: kinds.reduce(join, kinds[0]),
3127
+ texts: has,
3128
+ empty: !has
3129
+ }
3130
+ });
2914
3131
  }
2915
3132
  /**
2916
3133
  * This method tells if a part of a loop over the targets is a column of the run. Its value depends only on the
@@ -2992,7 +3209,7 @@ var Printer = class {
2992
3209
  }
2993
3210
  #node(e, ctx) {
2994
3211
  switch (e.tag) {
2995
- case "lit": return bare(literal(e.value));
3212
+ case "lit": return isVexList(e.value) ? this.#listLiteral(e.value) : bare(literal(e.value));
2996
3213
  case "ref": return this.#ref(e, ctx);
2997
3214
  case "var": return bare(this.#var(e.name, ctx));
2998
3215
  case "let": return this.#let(e, ctx);
@@ -3071,6 +3288,7 @@ var Printer = class {
3071
3288
  * must read no cell.
3072
3289
  */
3073
3290
  #inOrder(parts, all) {
3291
+ if (this.#sheet?.direct === true) return parts;
3074
3292
  const last = parts.findLastIndex((x) => x.v.deps.has(CELLS));
3075
3293
  const after = parts.slice(last + 1).every((x) => x.s.length === 0 || x.v.safe);
3076
3294
  const before = !all || parts.slice(0, Math.max(last, 0)).every((x) => x.v.safe) || !READS_IN_CODE.test(parts[last].v.code);
@@ -3134,7 +3352,7 @@ var Printer = class {
3134
3352
  const [d, ...more] = m.d;
3135
3353
  /* v8 ignore next -- @preserve */
3136
3354
  if (focus === void 0) throw new NotStandalone("a node of the memo reads its focus");
3137
- if (d === void 0 || more.length > 0 || !Number.isInteger(d)) return `${F}()`;
3355
+ if (this.#graph || d === void 0 || more.length > 0 || !Number.isInteger(d)) return `${F}()`;
3138
3356
  if (this.#tree) return `${this.use("SO")}(${this.#part("siblings", "GP")}, SI, ${focus}, ${d})`;
3139
3357
  return `${this.use("X")}(${focus} + ${d}, n)`;
3140
3358
  }
@@ -3207,7 +3425,7 @@ var Printer = class {
3207
3425
  * A binding is a variable. A binding with an error is an error only where the body reads its name, so the variable
3208
3426
  * can hold the sentinel. A binding that is a constant of the run is the variable of that constant.
3209
3427
  */
3210
- #let(e, ctx) {
3428
+ #let(e, ctx, wrap) {
3211
3429
  const env = new Map(ctx.env);
3212
3430
  const fns = new Map(ctx.fns);
3213
3431
  const s = [];
@@ -3248,8 +3466,10 @@ var Printer = class {
3248
3466
  root?.names.add(b);
3249
3467
  deps = /* @__PURE__ */ new Set([...deps, ...c.v.deps]);
3250
3468
  }
3251
- if (root !== void 0) root.root = e.body;
3252
- const body = this.expr(e.body, {
3469
+ const inner = wrap === void 0 ? e.body : wrap(e.body);
3470
+ if (this.#wantList.has(e)) this.#wantList.add(inner);
3471
+ if (root !== void 0) root.root = inner;
3472
+ const body = this.expr(inner, {
3253
3473
  ...ctx,
3254
3474
  env,
3255
3475
  fns
@@ -3396,13 +3616,19 @@ var Printer = class {
3396
3616
  if (op === "and" || op === "or") return this.#andOr(op === "and", args, ctx);
3397
3617
  if (op === "ifError") return this.#ifError(args, ctx);
3398
3618
  const [head] = args;
3399
- if (LIST_OPS.has(op) && head?.tag === "each") return this.#list(op, head, args.slice(1), ctx);
3400
- if (head !== void 0 && (op === "sortBy" || op === "take")) return this.#order(op, head, args.slice(1), ctx);
3401
- if (head !== void 0 && BUILD_OPS.has(op) && this.#isList(head, ctx)) throw new NotStandalone(`the list op "${op}" is not in a module yet`);
3402
- if (head !== void 0 && (LIST_OPS.has(op) || op === "nth") && this.#isList(head, ctx)) return this.#overList(op, head, args.slice(1), ctx);
3619
+ const rest = args.slice(1);
3620
+ if (FOLD_OPS.has(op) && head?.tag === "each" && !this.#isList(head.body, ctx)) return this.#list(op, head, rest, ctx);
3621
+ if (FOLD_OPS.has(op) && head?.tag === "let" && rest.every((x) => x.tag === "lit")) return this.#let(head, ctx, (body) => app(op, body, ...rest));
3622
+ if (head !== void 0 && (op === "sortBy" || op === "take" || op === "drop" && this.#isList(head, ctx))) return this.#order(op, head, rest, ctx);
3623
+ if (head !== void 0 && BUILD_OPS.has(op) && this.#isList(head, ctx)) return this.#build(op, head, rest, ctx);
3624
+ if (head !== void 0 && (FOLD_OPS.has(op) || op === "nth") && this.#isList(head, ctx)) return this.#overList(op, head, rest, ctx);
3403
3625
  const raw = args.map((x) => this.expr(x, ctx));
3404
3626
  const deps = depsOf(...raw);
3405
3627
  const values = this.#inOrder(this.#settle(raw, deps, args), true);
3628
+ return this.#opCall(op, values, deps);
3629
+ }
3630
+ /** This method prints the call of the op of a domain on some values, from the static site of their kinds. */
3631
+ #opCall(op, values, deps) {
3406
3632
  const site = this.#facts.staticSite(op, values.map((x) => x.v.kind));
3407
3633
  if (site?.t !== "fn") throw new NotStandalone(`the kinds of the values of "${op}" do not decide its op`);
3408
3634
  if (site.bad) return {
@@ -3567,15 +3793,35 @@ var Printer = class {
3567
3793
  * This method gives the option strict of a list op. The options must be one literal with only strict. Only a literal
3568
3794
  * has a value, so another expression gives the reason too.
3569
3795
  */
3570
- #strict(op, rest) {
3796
+ #strict(op, rest, names = ["strict"]) {
3571
3797
  const [options, ...more] = rest;
3572
3798
  if (more.length > 0) throw new NotStandalone(`"${op}" with more than one option`);
3573
3799
  if (options === void 0) return false;
3574
3800
  const opts = options.value;
3575
- if (typeof opts !== "object" || opts === null || Object.keys(opts).some((k) => k !== "strict")) throw new NotStandalone(`the options of "${op}" are not a literal with strict`);
3801
+ if (typeof opts !== "object" || opts === null || Object.keys(opts).some((k) => !names.includes(k))) throw new NotStandalone(`the options of "${op}" are not a literal with ${names.join(" or ")}`);
3576
3802
  return opts.strict === true;
3577
3803
  }
3578
3804
  /**
3805
+ * This method gives the option strict of a list op. For `reduce`, it also gives the op of each step: the first
3806
+ * argument, a literal text, and the value of the option `domain` (COMPILE.MODULE.REDUCE).
3807
+ */
3808
+ #foldOptions(op, rest) {
3809
+ if (op !== "reduce") return {
3810
+ strict: this.#strict(op, rest),
3811
+ step: void 0
3812
+ };
3813
+ const [name, ...options] = rest;
3814
+ const value = name?.value;
3815
+ if (name?.tag !== "lit" || typeof value !== "string") throw new NotStandalone("\"reduce\" without a literal text as its op");
3816
+ return {
3817
+ strict: this.#strict(op, options, ["strict", "domain"]),
3818
+ step: {
3819
+ op: value,
3820
+ domain: options[0]?.value?.domain
3821
+ }
3822
+ };
3823
+ }
3824
+ /**
3579
3825
  * A list op over an axis: one `for` loop with a running value. An item with an error is skipped, and with `strict` it
3580
3826
  * is an error of the list op. A value of the wrong kind is an error of the list op, as in the interpreter.
3581
3827
  */
@@ -3597,6 +3843,7 @@ var Printer = class {
3597
3843
  if (base.t === "list") {
3598
3844
  if (at.length > 0) throw new NotStandalone("the axis \"list\" with an address");
3599
3845
  const list = this.#hoist(this.#listOf(base.list, ctx), hasLoop(base.list));
3846
+ if (list.v.list.texts === true) throw new NotStandalone("the axis \"list\" over a list with the keys of a literal");
3600
3847
  const a = this.fresh("A");
3601
3848
  const q = this.fresh("q");
3602
3849
  const head = reverse ? `for (let ${q} = ${a}.length - 1; ${q} >= 0; ${q}--) {` : `for (let ${q} = 0; ${q} < ${a}.length; ${q}++) {`;
@@ -3647,6 +3894,24 @@ var Printer = class {
3647
3894
  inner
3648
3895
  };
3649
3896
  }
3897
+ if (this.#graph && GRAPH_AXES.has(base.t)) {
3898
+ const range = this.#graphRange(base.t, f);
3899
+ const q = this.fresh("q");
3900
+ return {
3901
+ s: [...s, ...range.s],
3902
+ j,
3903
+ head: forHead(q, range.lo, range.hi, reverse),
3904
+ key: [`const ${j} = ${range.a}[${q}];`],
3905
+ check: [],
3906
+ skip: void 0,
3907
+ fixed: false,
3908
+ start,
3909
+ startSafe,
3910
+ tests,
3911
+ inner
3912
+ };
3913
+ }
3914
+ if (this.#graph && base.t === "window") throw new NotStandalone("the axis \"window\" in a graph space");
3650
3915
  if (base.t === "others") skip = f;
3651
3916
  else if (base.t === "window") {
3652
3917
  const h = this.fresh("h");
@@ -3669,6 +3934,26 @@ var Printer = class {
3669
3934
  };
3670
3935
  }
3671
3936
  /**
3937
+ * This method gives the targets of an axis of a graph space at the position `f` (AXIS.GRAPH). They are the positions
3938
+ * `a[q]` for `q` from `lo` up to `hi`. The first key of the search of `reachable` is the focus, which is not a target.
3939
+ */
3940
+ #graphRange(t, f) {
3941
+ const a = this.fresh("A");
3942
+ const range = (code, lo = "0") => ({
3943
+ s: [`const ${a} = ${code};`],
3944
+ a,
3945
+ lo,
3946
+ hi: `${a}.length`,
3947
+ skip: void 0
3948
+ });
3949
+ if (t === "successors") return range(`GO[${f}]`);
3950
+ if (t === "predecessors") {
3951
+ this.into = true;
3952
+ return range(`GN[${f}]`);
3953
+ }
3954
+ return range(`${this.use("RB")}(GO, ${f}, n)`, "1");
3955
+ }
3956
+ /**
3672
3957
  * This method gives the targets of an axis of a tree space at the position `f`. They are the positions `a[q]` for `q`
3673
3958
  * from `lo` up to `hi`, without the key that the loop skips. The axes come from AXIS.TREE, AXIS.GRAPH and AXIS.WINDOW.
3674
3959
  */
@@ -3717,7 +4002,7 @@ var Printer = class {
3717
4002
  }
3718
4003
  }
3719
4004
  #list(op, target, rest, ctx) {
3720
- const strict = this.#strict(op, rest);
4005
+ const { strict, step } = this.#foldOptions(op, rest);
3721
4006
  const at = target.at ?? [];
3722
4007
  const { s, j, head, key, check, skip, fixed, start, startSafe, tests, inner } = this.#targetLoop(target.axis, at, ctx);
3723
4008
  const { level } = inner;
@@ -3725,7 +4010,7 @@ var Printer = class {
3725
4010
  const body = this.#hoist(this.expr(target.body, inner), hasLoop(target.body));
3726
4011
  if (op === "count" && fixed && tests.length === 0 && body.v.safe && !body.v.deps.has(CELLS)) return bare(plainValue("n", "number"));
3727
4012
  const deps = new Set([...start, ...[body, ...testCodes].flatMap((x) => [...x.v.deps])].filter((d) => d !== level));
3728
- const r = this.#reduction(op, body.v.kind);
4013
+ const r = this.#reduction(op, body.v.kind, step);
3729
4014
  const { v } = r;
3730
4015
  s.push(r.init);
3731
4016
  const item = [
@@ -3766,7 +4051,7 @@ var Printer = class {
3766
4051
  ],
3767
4052
  v: {
3768
4053
  code: r.result,
3769
- kind: listKind(op, body.v.kind),
4054
+ kind: r.kind,
3770
4055
  safe: false,
3771
4056
  deps
3772
4057
  }
@@ -3792,7 +4077,7 @@ var Printer = class {
3792
4077
  s,
3793
4078
  v: {
3794
4079
  code: r.result,
3795
- kind: listKind(op, body.v.kind),
4080
+ kind: r.kind,
3796
4081
  safe,
3797
4082
  deps
3798
4083
  }
@@ -3802,10 +4087,15 @@ var Printer = class {
3802
4087
  * This method gives the parts of a list op that reduces the values of its items. The parts are the variable `v` of
3803
4088
  * the value of an item, the first statement, the step and the result. A value of the wrong kind is an error of the op.
3804
4089
  */
3805
- #reduction(op, kind) {
4090
+ #reduction(op, kind, step) {
3806
4091
  const a = this.fresh("a");
3807
4092
  const n = this.fresh("n");
3808
4093
  const v = this.fresh("x");
4094
+ if (step !== void 0) return {
4095
+ v,
4096
+ init: `let ${a}, ${n} = 0;`,
4097
+ ...this.#reduceStep(step, kind, a, n, v)
4098
+ };
3809
4099
  const num = kind === "number" ? v : `${this.use("U")}(${v})`;
3810
4100
  const bool = kind === "boolean" ? v : `${this.use("B")}(${v})`;
3811
4101
  const inits = {
@@ -3840,7 +4130,51 @@ var Printer = class {
3840
4130
  v,
3841
4131
  init: inits[op] ?? `let ${a}, ${n} = 0;`,
3842
4132
  step: steps[op],
3843
- result: results[op] ?? `(${n} === 0 ? ${F}() : ${a})`
4133
+ result: results[op] ?? `(${n} === 0 ? ${F}() : ${a})`,
4134
+ kind: listKind(op, kind)
4135
+ };
4136
+ }
4137
+ /**
4138
+ * This method gives the step and the result of `reduce` (COMPILE.MODULE.REDUCE), as in the interpreter. The first item
4139
+ * is the first running value. Each later item goes into the op of the domain of the running value. The kinds of the
4140
+ * items decide that op, and the op must give a value of the same kind. No items give the identity of the op.
4141
+ */
4142
+ #reduceStep(step, kind, a, n, v) {
4143
+ const arg = (code) => bare({
4144
+ code,
4145
+ kind,
4146
+ safe: true,
4147
+ deps: NO_DEPS,
4148
+ plain: true
4149
+ });
4150
+ const opCode = this.#opCall(step.op, [arg(a), arg(v)], NO_DEPS);
4151
+ if (opCode.v.kind !== kind) throw new NotStandalone(`the op "${step.op}" of "reduce" gives a value of the kind ${kindText(opCode.v.kind)}, not of the kind ${kindText(kind)} of the items`);
4152
+ const empty = this.#identity(step);
4153
+ return {
4154
+ step: `${a} = ${n}++ === 0 ? ${v} : ${opCode.v.code};`,
4155
+ result: `(${n} === 0 ? ${empty.code} : ${a})`,
4156
+ kind: empty.kind === void 0 || empty.kind === kind ? kind : void 0
4157
+ };
4158
+ }
4159
+ /**
4160
+ * This method gives the code of `reduce` over no items, as in the interpreter. The code is the identity of the op in
4161
+ * the one domain that has one, or in the domain of the option `domain`. Another case is an error. The kind is the kind
4162
+ * of the domain.
4163
+ */
4164
+ #identity(step) {
4165
+ const { op, domain } = step;
4166
+ const fail = {
4167
+ code: `${this.use("F")}()`,
4168
+ kind: void 0
4169
+ };
4170
+ const [only, second] = [...this.#domains.entries()].filter(([, d]) => Object.hasOwn(d.ops, op) && d.ops[op].identity !== void 0 && (domain === void 0 || d.name === domain));
4171
+ if (only === void 0 || second !== void 0) return fail;
4172
+ const [i, d] = only;
4173
+ const name = `id_${String(i)}_${String(this.#opIndex(op))}`;
4174
+ if (!this.top.has(name)) this.top.set(name, `const ${name} = ${copied(d.ops[op].identity, [], `the identity of the op "${op}" of the domain ${d.name}`)};`);
4175
+ return {
4176
+ code: `${name}()`,
4177
+ kind: kindOfDomain(d)
3844
4178
  };
3845
4179
  }
3846
4180
  /**
@@ -3851,6 +4185,7 @@ var Printer = class {
3851
4185
  const at = e.at ?? [];
3852
4186
  const { s, j, head, key, check, skip, start, startSafe, tests, inner } = this.#targetLoop(e.axis, at, ctx);
3853
4187
  const testCodes = tests.map((t) => this.#hoist(this.expr(t, inner), hasLoop(t)));
4188
+ if (this.#wantList.has(e)) this.#wantList.add(e.body);
3854
4189
  const body = this.#hoist(this.expr(e.body, inner), hasLoop(e.body));
3855
4190
  const deps = new Set([...start, ...[body, ...testCodes].flatMap((x) => [...x.v.deps])].filter((d) => d !== inner.level));
3856
4191
  const list = this.fresh("L");
@@ -3888,53 +4223,89 @@ var Printer = class {
3888
4223
  kind: void 0,
3889
4224
  safe: startSafe,
3890
4225
  deps,
3891
- list: { item: body.v.kind }
4226
+ list: {
4227
+ item: body.v.kind,
4228
+ inner: body.v.list
4229
+ }
3892
4230
  }
3893
4231
  };
3894
4232
  }
3895
4233
  /**
3896
- * This method prints sortBy and take (LIST.SORT, LIST.TAKE): a new array from the array of a list. An error item is
3897
- * not in the new list, and with strict it is the error of the op.
4234
+ * This method prints sortBy, take and drop (LIST.SORT, LIST.TAKE, LIST.DROP): a new array from the array of a list. An
4235
+ * error item is not in the new list, and with strict it is the error of the op.
3898
4236
  */
3899
4237
  #order(op, head, rest, ctx) {
3900
4238
  const list = this.#listOf(head, ctx);
3901
- const exprs = [head, ...op === "take" ? [rest[0] ?? lit(null)] : []];
4239
+ const exprs = [head, ...op === "sortBy" ? [] : [rest[0] ?? lit(null)]];
3902
4240
  const strict = this.#strict(op, rest.slice(exprs.length - 1));
3903
4241
  const raw = [list, ...exprs.slice(1).map((x) => this.expr(x, ctx))];
3904
4242
  const deps = depsOf(...raw);
3905
4243
  const parts = this.#inOrder(this.#settle(raw, deps, exprs), true);
3906
- const item = list.v.list.item;
4244
+ const helper = op === "sortBy" ? "SB" : op === "take" ? "TK" : "DR";
3907
4245
  return {
3908
4246
  s: stmtsOf(...parts),
3909
4247
  v: {
3910
- code: `${this.use(op === "sortBy" ? "SB" : "TK")}(${[...parts.map((x) => x.v.code), String(strict)].join(", ")})`,
4248
+ code: `${this.use(helper)}(${[...parts.map((x) => x.v.code), String(strict)].join(", ")})`,
3911
4249
  kind: void 0,
3912
4250
  safe: false,
3913
4251
  deps,
3914
- list: { item }
4252
+ list: list.v.list
3915
4253
  }
3916
4254
  };
3917
4255
  }
4256
+ /**
4257
+ * This method prints append, without and flat (LIST.BUILD), get (LIST.GET) and indexOf (LIST.INDEXOF) over the array
4258
+ * of a list. Each list that the op reads follows LIST.LENIENT, as in the interpreter.
4259
+ */
4260
+ #build(op, head, rest, ctx) {
4261
+ const list = this.#listOf(head, ctx);
4262
+ const info = list.v.list;
4263
+ const two = op === "append" || op === "without";
4264
+ const exprs = [head, ...op === "flat" ? [] : [rest[0] ?? lit(null)]];
4265
+ const strict = this.#strict(op, rest.slice(exprs.length - 1));
4266
+ const raw = [list, ...exprs.slice(1).map((x) => two ? this.#listOf(x, ctx) : this.expr(x, ctx))];
4267
+ const deps = depsOf(...raw);
4268
+ const parts = this.#inOrder(this.#settle(raw, deps, exprs), true);
4269
+ const helper = BUILD_HELPERS[op];
4270
+ const value = (kind, facts) => ({
4271
+ s: stmtsOf(...parts),
4272
+ v: {
4273
+ code: `${this.use(helper)}(${[...parts.map((x) => x.v.code), String(strict)].join(", ")})`,
4274
+ kind,
4275
+ safe: false,
4276
+ deps,
4277
+ list: facts
4278
+ }
4279
+ });
4280
+ if (op === "get") return value(info.item, info.inner);
4281
+ if (op === "indexOf") return value("number", void 0);
4282
+ if (op === "without") return value(void 0, info);
4283
+ if (op === "append") return value(void 0, joinLists(info, parts[1].v.list));
4284
+ if (info.empty === true) return value(void 0, info);
4285
+ if (info.inner === void 0) throw new NotStandalone("\"flat\" over a list whose items are not lists");
4286
+ return value(void 0, info.inner);
4287
+ }
3918
4288
  /** This method prints a list op over a list that is not an each: a loop over its array, and nth (LIST.NTH). */
3919
4289
  #overList(op, head, rest, ctx) {
3920
4290
  const list = this.#listOf(head, ctx);
3921
4291
  const exprs = [head, ...op === "nth" ? [rest[0] ?? lit(null)] : []];
3922
- const strict = this.#strict(op, rest.slice(exprs.length - 1));
4292
+ const { strict, step } = this.#foldOptions(op, rest.slice(exprs.length - 1));
3923
4293
  const raw = [list, ...exprs.slice(1).map((x) => this.expr(x, ctx))];
3924
4294
  const deps = depsOf(...raw);
3925
4295
  const parts = this.#inOrder(this.#settle(raw, deps, exprs), true);
3926
4296
  const [l] = parts;
3927
- const item = list.v.list.item;
4297
+ const { item, inner } = list.v.list;
3928
4298
  if (op === "nth") return {
3929
4299
  s: stmtsOf(...parts),
3930
4300
  v: {
3931
4301
  code: `${this.use("NT")}(${[...parts.map((x) => x.v.code), String(strict)].join(", ")})`,
3932
4302
  kind: item,
3933
4303
  safe: false,
3934
- deps
4304
+ deps,
4305
+ list: inner
3935
4306
  }
3936
4307
  };
3937
- const r = this.#reduction(op, item);
4308
+ const r = this.#reduction(op, item, step);
3938
4309
  const { v } = r;
3939
4310
  return {
3940
4311
  s: [
@@ -3947,9 +4318,10 @@ var Printer = class {
3947
4318
  ],
3948
4319
  v: {
3949
4320
  code: r.result,
3950
- kind: listKind(op, item),
4321
+ kind: r.kind,
3951
4322
  safe: false,
3952
- deps
4323
+ deps,
4324
+ list: op === "first" ? inner : void 0
3953
4325
  }
3954
4326
  };
3955
4327
  }
@@ -3958,21 +4330,30 @@ var Printer = class {
3958
4330
  * node. Inside the loop, each name has the level `loop`. Thus a part that reads a name stays in the loop. A loop that
3959
4331
  * reads no key of the run is a constant of the run.
3960
4332
  */
3961
- #loopNames(init, ctx, loop) {
4333
+ #loopNames(init, step, ctx, loop) {
3962
4334
  const s = [];
3963
4335
  const env = new Map(ctx.env);
3964
4336
  const vars = /* @__PURE__ */ new Map();
3965
4337
  const deps = /* @__PURE__ */ new Set();
4338
+ const keyed = Object.values(step).some(hasKeyedLiteral);
3966
4339
  for (const [name, x] of Object.entries(init)) {
4340
+ this.#wantList.add(x);
3967
4341
  const c = this.expr(x, ctx);
3968
- if (c.v.kind === void 0) throw new NotStandalone(`the first value of the name "${name}" of a loop has no kind`);
4342
+ const facts = c.v.list;
4343
+ if (c.v.kind === void 0 && facts === void 0) throw new NotStandalone(`the first value of the name "${name}" of a loop has no kind`);
3969
4344
  const v = this.fresh("l");
3970
4345
  s.push(...c.s, `let ${v} = ${c.v.code};`);
4346
+ const list = facts === void 0 ? void 0 : {
4347
+ item: facts.item,
4348
+ inner: facts.inner,
4349
+ texts: facts.texts === true || keyed
4350
+ };
3971
4351
  const read = {
3972
4352
  code: v,
3973
4353
  kind: c.v.kind,
3974
4354
  lazy: false,
3975
- deps: /* @__PURE__ */ new Set([loop])
4355
+ deps: /* @__PURE__ */ new Set([loop]),
4356
+ list
3976
4357
  };
3977
4358
  env.set(name, read);
3978
4359
  vars.set(name, read);
@@ -3991,9 +4372,11 @@ var Printer = class {
3991
4372
  const sets = [];
3992
4373
  const deps = /* @__PURE__ */ new Set();
3993
4374
  for (const [name, x] of Object.entries(step)) {
4375
+ this.#wantList.add(x);
3994
4376
  const c = this.#hoist(this.expr(x, inner), hasLoop(x));
3995
4377
  const v = vars.get(name);
3996
- if (c.v.kind !== v.kind) throw new NotStandalone(`a step of a loop changes the kind of the name "${name}"`);
4378
+ if (c.v.kind !== v.kind || c.v.list === void 0 !== (v.list === void 0)) throw new NotStandalone(`a step of a loop changes the kind of the name "${name}"`);
4379
+ if (v.list !== void 0 && !fits(v.list, c.v.list)) throw new NotStandalone(`a step of a loop gives the name "${name}" a list that does not fit its first list`);
3997
4380
  const t = this.fresh("t");
3998
4381
  s.push(...c.s, `const ${t} = ${c.v.code};`);
3999
4382
  sets.push(`${v.code} = ${t};`);
@@ -4010,11 +4393,12 @@ var Printer = class {
4010
4393
  */
4011
4394
  #iterate(e, ctx) {
4012
4395
  const loop = this.#loops++;
4013
- const names = this.#loopNames(e.init, ctx, loop);
4396
+ const names = this.#loopNames(e.init, e.step, ctx, loop);
4014
4397
  const inner = {
4015
4398
  ...ctx,
4016
4399
  env: names.env
4017
4400
  };
4401
+ if (this.#wantList.has(e)) this.#wantList.add(e.result);
4018
4402
  const until = e.until === void 0 ? void 0 : this.expr(e.until, inner);
4019
4403
  const step = this.#loopStep(e.step, inner, names.vars);
4020
4404
  const result = this.expr(e.result, inner);
@@ -4042,7 +4426,8 @@ var Printer = class {
4042
4426
  code: result.v.code,
4043
4427
  kind: result.v.kind,
4044
4428
  safe: false,
4045
- deps
4429
+ deps,
4430
+ list: result.v.list
4046
4431
  }
4047
4432
  };
4048
4433
  }
@@ -4052,7 +4437,8 @@ var Printer = class {
4052
4437
  */
4053
4438
  #fold(e, ctx) {
4054
4439
  const loop = this.#loops++;
4055
- const names = this.#loopNames(e.init, ctx, loop);
4440
+ const names = this.#loopNames(e.init, e.step, ctx, loop);
4441
+ if (this.#wantList.has(e)) this.#wantList.add(e.result);
4056
4442
  const t = this.#targetLoop(e.axis, e.at ?? [], ctx);
4057
4443
  const tests = t.tests.map((x) => this.#hoist(this.expr(x, t.inner), hasLoop(x)));
4058
4444
  if (tests.some((x) => x.v.deps.has(CELLS))) throw new NotStandalone("a test of the axis of a fold reads a cell");
@@ -4091,7 +4477,8 @@ var Printer = class {
4091
4477
  code: result.v.code,
4092
4478
  kind: result.v.kind,
4093
4479
  safe: false,
4094
- deps
4480
+ deps,
4481
+ list: result.v.list
4095
4482
  }
4096
4483
  };
4097
4484
  }
@@ -4314,11 +4701,12 @@ var Printer = class {
4314
4701
  function runOf(options) {
4315
4702
  const name = options.name ?? "run";
4316
4703
  if (!/^[A-Za-z_$][\w$]*$/.test(name)) return { reason: `the name "${name}" is not a JavaScript name` };
4317
- const tree = options.space === "tree";
4318
- if (!tree && options.space !== void 0 && options.space !== "array") return { reason: `the space "${String(options.space)}" is not "array" or "tree"` };
4704
+ const space = options.space ?? "array";
4705
+ if (space !== "array" && space !== "tree" && space !== "graph") return { reason: `the space "${String(space)}" is not "array", "tree" or "graph"` };
4319
4706
  return {
4320
4707
  name,
4321
- tree
4708
+ tree: space === "tree",
4709
+ graph: space === "graph"
4322
4710
  };
4323
4711
  }
4324
4712
  /** This function gives the reason of an error of the printer. Another exception is a defect, so it goes to the caller. */
@@ -4350,7 +4738,7 @@ function printModule(p, options, run, body) {
4350
4738
  } catch (thrown) {
4351
4739
  return reasonOf(thrown);
4352
4740
  }
4353
- const { name, tree } = run;
4741
+ const { name, tree, graph } = run;
4354
4742
  if (tree) p.use("PT");
4355
4743
  if (p.treeParts.size > 0) p.treeParts.add("children");
4356
4744
  const parts = [
@@ -4359,6 +4747,8 @@ function printModule(p, options, run, body) {
4359
4747
  "order"
4360
4748
  ].filter((x) => p.treeParts.has(x));
4361
4749
  for (const x of parts) p.use(TREE_PARTS[x][0]);
4750
+ if (graph) p.use("GR");
4751
+ if (p.into) p.use("GI");
4362
4752
  [...p.helpers].toSorted().forEach(add);
4363
4753
  const bad = nameReason(name, /* @__PURE__ */ new Set([
4364
4754
  "VexContractError",
@@ -4386,7 +4776,7 @@ function printModule(p, options, run, body) {
4386
4776
  ...helpers.has("S") ? ["const N = {}, W = {};"] : [],
4387
4777
  ...[...helpers].map((h) => h === "S" ? helperS(p.features) : HELPERS[h]),
4388
4778
  ...p.top.values(),
4389
- `export function ${name}(records, vars${tree ? ", parents" : ""}) {`,
4779
+ `export function ${name}(records, vars${tree ? ", parents" : graph ? ", edges" : ""}) {`,
4390
4780
  " if (!Array.isArray(records)) C(\"the records are not an array\");",
4391
4781
  " const R = records;",
4392
4782
  " const n = R.length;",
@@ -4396,6 +4786,7 @@ function printModule(p, options, run, body) {
4396
4786
  " }",
4397
4787
  ` if (typeof vars !== "object" || vars === null${varChecks}) C("the variables do not keep the schema");`,
4398
4788
  ...tree ? [" const P = PT(parents, n);", ...parts.map((x) => ` ${TREE_PARTS[x][1]}`)] : [],
4789
+ ...graph ? [" const GO = GR(edges, n);", ...p.into ? [" const GN = GI(GO, n);"] : []] : [],
4399
4790
  ...[...p.vars].map(([v, code]) => ` const ${code} = vars[${JSON.stringify(v)}];`),
4400
4791
  ...ind(p.run),
4401
4792
  ...ind(body),
@@ -4502,9 +4893,11 @@ function emitSheetModule(columns, options) {
4502
4893
  }
4503
4894
  const kinds = new Map(Object.entries(options.kinds ?? {}));
4504
4895
  const index = new Map(names.map((c, i) => [c, i]));
4896
+ const direct = formulas.every((f) => f.key === void 0) && order.every((c) => readsFinished(columns, order, c, run.tree));
4505
4897
  const p = new Printer(rec(Object.fromEntries(formulas.map((f, i) => [`f${String(i)}`, f.expr]))), options, {
4506
4898
  columns: index,
4507
- kinds
4899
+ kinds,
4900
+ direct
4508
4901
  });
4509
4902
  const fns = [];
4510
4903
  const decls = [];
@@ -4540,28 +4933,29 @@ function emitSheetModule(columns, options) {
4540
4933
  const i = formulas.findIndex((f) => f.column === c && f.key === void 0);
4541
4934
  return i < 0 ? "undefined" : entry(i);
4542
4935
  });
4543
- p.use("SH");
4936
+ p.use(direct ? "DO" : "SH");
4937
+ const fnOf = new Map(formulas.map((f, i) => [f.column, fns[i]]));
4938
+ const fillOf = (c, at) => direct ? `D[${at}][o] = ${fnOf.get(c)}(o);` : `SS.f(${at}, o);`;
4544
4939
  const orders = /* @__PURE__ */ new Map();
4545
4940
  const fill = order.map((c) => {
4546
4941
  const { reverse, post, back } = keyOrderOf(readsOf(columns, cells, c).directions);
4547
4942
  const at = String(index.get(c));
4548
- 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);`;
4943
+ if (!run.tree) return reverse ? `for (let o = n - 1; o >= 0; o--) ${fillOf(c, at)}` : `for (let o = 0; o < n; o++) ${fillOf(c, at)}`;
4549
4944
  const args = `${p.use("KO")}(H, RT, ${String(post)}, ${String(back)})`;
4550
4945
  let keys = orders.get(args);
4551
4946
  if (keys === void 0) {
4552
4947
  keys = p.fresh("K");
4553
4948
  orders.set(args, keys);
4554
4949
  }
4555
- return `for (const o of ${keys}) SS.f(${at}, o);`;
4950
+ return `for (const o of ${keys}) ${fillOf(c, at)}`;
4556
4951
  });
4557
4952
  if (run.tree) p.treeParts.add("children");
4558
4953
  return printModule(p, options, run, [
4559
4954
  ...decls,
4560
- `const SS = SH(n, [${cols.join(", ")}], [${own.join(", ")}], ${String(budget)});`,
4561
- `const ${READ_CELL} = SS.r;`,
4955
+ ...direct ? [`const D = [${names.map(() => "new Array(n)").join(", ")}];`, `const ${READ_CELL} = (c, k) => D[c][k];`] : [`const SS = SH(n, [${cols.join(", ")}], [${own.join(", ")}], ${String(budget)});`, `const ${READ_CELL} = SS.r;`],
4562
4956
  ...[...orders].map(([args, keys]) => `const ${keys} = ${args};`),
4563
4957
  ...fill,
4564
- `return { ${names.map((c, i) => `${JSON.stringify(c)}: SS.o(${String(i)})`).join(", ")} };`
4958
+ `return { ${names.map((c, i) => `${JSON.stringify(c)}: ${direct ? `DO(D[${String(i)}])` : `SS.o(${String(i)})`}`).join(", ")} };`
4565
4959
  ]);
4566
4960
  }
4567
4961
  //#endregion