@mark1russell7/vex-compiler 0.13.4 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package",
3
3
  "name": "@mark1russell7/vex-compiler",
4
- "version": "0.13.4",
4
+ "version": "0.14.0",
5
5
  "description": "The Vex compiler: generated JavaScript for Vex programs, at run time and at build time, with the results of the interpreter.",
6
6
  "keywords": [
7
7
  "vex",
@@ -43,15 +43,15 @@
43
43
  },
44
44
  "devDependencies": {
45
45
  "@mark1russell7/cue": "github:mark1russell7/cue",
46
- "@mark1russell7/vex-domains": "0.13.4",
47
- "@mark1russell7/vex-testkit": "0.13.4",
46
+ "@mark1russell7/vex-domains": "0.14.0",
47
+ "@mark1russell7/vex-testkit": "0.14.0",
48
48
  "@types/node": "^26.6.4",
49
49
  "fast-check": "^4.10.2",
50
50
  "typescript": "^7.0.2",
51
51
  "vitest": "^5.0.3"
52
52
  },
53
53
  "dependencies": {
54
- "@mark1russell7/vex": "0.13.4"
54
+ "@mark1russell7/vex": "0.14.0"
55
55
  },
56
56
  "scripts": {
57
57
  "build": "tsdown",
package/src/module.ts CHANGED
@@ -31,7 +31,7 @@
31
31
  * starts the search of `SheetRun`. Thus each cell on a cycle gives the error of Vex. A cell can hold a list, and a
32
32
  * formula reads it with the list ops (COMPILE.MODULE.SHEET.LIST).
33
33
  */
34
- import { addrExprs, app, CELL_KIND, children, fromDocument, isDocument, isFieldName, isListOp, isVexList, lit, moveExpr, nestingOf, rec, shapeError, vexList, type AnyDomain, type Axis, type CellFormulas, type Envelope, type Expr, type ExprOf, type Move, type Names, type PrimitiveKind, type VexList } from "@mark1russell7/vex";
34
+ import { addrExprs, app, CELL_KIND, children, fromDocument, isDocument, isFieldName, isListOp, isVexList, lit, moveExpr, nestingOf, rec, shapeError, vexList, type AnyDomain, type Axis, type CellFormulas, type Envelope, type Expr, type ExprOf, type ItemNames, type Move, type Names, type PrimitiveKind, type VexList } from "@mark1russell7/vex";
35
35
  import { factsOf, kindOfDomain, primitiveOf, type Facts, type Kind, type ListKind, type Schema } from "./facts.ts";
36
36
  import { memoNodes } from "./memo.ts";
37
37
  import { columnOrder, isCellRef, keyOrderOf, readsFinished, readsOf } from "./sheet-order.ts";
@@ -144,6 +144,12 @@ interface Arg {
144
144
  /** The levels of a constant of the run. */
145
145
  const NO_DEPS: ReadonlySet<number> = new Set();
146
146
 
147
+ /** The names of the items of a loop without `as` (COMPILE.MODULE.LIST.ITEM). */
148
+ const NO_NAMES: ReadonlyMap<string, Name> = new Map();
149
+
150
+ /** This function gives the names of a body or of a step: the names `as` of the items hide the names outside (AXIS.LIST.SCOPE). */
151
+ const withNames = (env: ReadonlyMap<string, Name>, items: ReadonlyMap<string, Name>): ReadonlyMap<string, Name> => new Map([...env, ...items]);
152
+
147
153
  /**
148
154
  * 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
149
155
  * a cell is not a constant or a column of the run. The level is far from the other levels.
@@ -194,6 +200,16 @@ interface Ctx {
194
200
  readonly fns: ReadonlyMap<string, BoundFn>;
195
201
  }
196
202
 
203
+ /**
204
+ * A name of a loop whose step appends to its own list (COMPILE.MODULE.APPEND.OWN). It has the name, its read in the
205
+ * loop and the variable of the array of its last append. The printer makes the variable at the first append that uses it.
206
+ */
207
+ interface Owner {
208
+ readonly name: string;
209
+ readonly read: Name;
210
+ w: string | undefined;
211
+ }
212
+
197
213
  /**
198
214
  * A bound function of the printer (FN.BIND): its node and the context of its binding. It also has one printed
199
215
  * JavaScript function for each signature of the arguments of its calls.
@@ -249,10 +265,10 @@ interface Spec {
249
265
  }
250
266
 
251
267
  /** The name of a helper of the generated code. */
252
- type Helper = "F" | "C" | "T" | "L" | "Q" | "G" | "B" | "U" | "X" | "I" | "K" | "M" | "M1" | "S" | "V" | "SB" | "SK" | "TK" | "NT" | "FI" | "LI" | BuildHelper | TreeHelper | GraphHelper | SheetHelper;
268
+ type Helper = "F" | "C" | "T" | "L" | "Q" | "G" | "B" | "U" | "X" | "I" | "K" | "M" | "M1" | "S" | "V" | "SB" | "SK" | "TK" | "VW" | "NT" | "CT" | "FS" | "FI" | "LI" | BuildHelper | TreeHelper | GraphHelper | SheetHelper;
253
269
 
254
270
  /** The helpers of the list ops that build a list (LIST.BUILD), of `get` (LIST.GET) and of `indexOf` (LIST.INDEXOF). */
255
- type BuildHelper = "DR" | "AP" | "WO" | "FL" | "GT" | "IX";
271
+ type BuildHelper = "DR" | "AP" | "AO" | "WO" | "FL" | "GT" | "IX";
256
272
 
257
273
  /** The helpers of a tree space (COMPILE.MODULE.TREE). */
258
274
  type TreeHelper = "PT" | "CH" | "SG" | "PR" | "UP" | "SO" | "AN" | "BF";
@@ -302,19 +318,28 @@ const HELPERS: Readonly<Record<Exclude<Helper, "S">, string>> = {
302
318
  "}",
303
319
  ].join("\n"),
304
320
  TK: "function TK(l, n, s) { const o = V(l, s); return Number.isSafeInteger(n) && n >= 0 ? o.slice(0, n) : F(); }",
305
- // nth keeps the items with values on the array, as GT keeps its index. Thus a loop that reads each item of a list of n
306
- // items costs O(n), not O(n squared) (COMPILE.MODULE.NTH.INDEX).
307
- NT: [
308
- "function NT(l, i, s) {",
321
+ // The items with values of a list stay on its array, as GT keeps its index. Thus a loop that reads each item of a list
322
+ // of n items with nth costs O(n), not O(n squared). count and first read them too (COMPILE.MODULE.NTH.INDEX).
323
+ VW: [
324
+ "function VW(l) {",
309
325
  " let o = l.vw;",
310
326
  " if (o === undefined) {",
311
327
  " o = l.filter((x) => x[1] !== E);",
312
328
  " l.vw = o;",
313
329
  " }",
330
+ " return o;",
331
+ "}",
332
+ ].join("\n"),
333
+ NT: [
334
+ "function NT(l, i, s) {",
335
+ " const o = VW(l);",
314
336
  " if (s && o.length < l.length) F();",
315
337
  " return Number.isSafeInteger(i) && i >= 0 && i < o.length ? o[i][1] : F();",
316
338
  "}",
317
339
  ].join("\n"),
340
+ // count and first of a list that is not an each. With strict, an error item is the error of the op.
341
+ CT: "function CT(l, s) { const o = VW(l); return s && o.length < l.length ? F() : o.length; }",
342
+ FS: "function FS(l, s) { const o = VW(l); return (s && o.length < l.length) || o.length === 0 ? F() : o[0][1]; }",
318
343
  // fill (LIST.FILL, COMPILE.MODULE.FILL): n items with the value v, and the keys 0 to n - 1. A count that is not a whole
319
344
  // number from 0 to 100000, or a missing value, is the error of the interpreter. Each item can share the array of a list.
320
345
  FI: [
@@ -351,8 +376,13 @@ const HELPERS: Readonly<Record<Exclude<Helper, "S">, string>> = {
351
376
  ].join("\n"),
352
377
  // The ops that build a list (LIST.BUILD) keep the key and the value of each item. A key is a position or a text, so
353
378
  // `without` and `get` compare the text of each key. A list is an array that does not change after the op that makes it.
379
+ // The one exception is the array of AO during its loop, which no other part reads (COMPILE.MODULE.APPEND.OWN).
354
380
  DR: "function DR(l, n, s) { const o = V(l, s); return Number.isSafeInteger(n) && n >= 0 ? o.slice(n) : F(); }",
355
381
  AP: "function AP(l, o, s) { return V(l, s).concat(V(o, s)); }",
382
+ // append into the list of a name of a loop (COMPILE.MODULE.APPEND.OWN). w is the array of the last append of the name
383
+ // in this run of the loop, and no other part reads it. Such an array has no error items, so V(l, s) is a copy of l.
384
+ // Each other list gets the copy of AP. V(o, s) throws before the first push, so an error does not change l.
385
+ AO: "function AO(l, o, s, w) { if (l !== w) return AP(l, o, s); for (const x of V(o, s)) l.push(x); return l; }",
356
386
  WO: [
357
387
  "function WO(l, o, s) {",
358
388
  " const a = V(l, s), g = new Map();",
@@ -794,8 +824,8 @@ const NEEDS: Readonly<Record<Helper, readonly Helper[]>> = {
794
824
  // Only the helpers of the list ops use V, and each of them needs F too, so the need of V only completes the list.
795
825
  // Stryker disable next-line ArrayDeclaration: see the comment above
796
826
  V: ["F"],
797
- SB: ["V", "F"], SK: ["V", "F"], TK: ["V", "F"], NT: ["V", "F"], FI: ["F"], LI: [],
798
- DR: ["V", "F"], AP: ["V"], WO: ["V"], FL: ["V"], GT: ["F"], IX: ["V", "F"],
827
+ SB: ["V", "F"], SK: ["V", "F"], TK: ["V", "F"], VW: [], NT: ["VW", "F"], CT: ["VW", "F"], FS: ["VW", "F"], FI: ["F"], LI: [],
828
+ DR: ["V", "F"], AP: ["V"], AO: ["AP", "V"], WO: ["V"], FL: ["V"], GT: ["F"], IX: ["V", "F"],
799
829
  // Each module has C, and each move uses F (#move), so these needs only complete the list.
800
830
  // Stryker disable next-line ArrayDeclaration: see the comment above
801
831
  PT: ["C"], GR: ["C"], UP: ["F"], SO: ["F"],
@@ -982,6 +1012,25 @@ const listKind = (op: string, item: Kind | undefined): Kind | undefined => (NUMB
982
1012
 
983
1013
  const LOOPS = new WeakMap<Expr, boolean>();
984
1014
 
1015
+ /**
1016
+ * This function tells if the step of the name `name` of a loop appends to the list of the name (COMPILE.MODULE.APPEND.OWN).
1017
+ * It puts the append nodes of the form into `out`. The form is a read of the name,
1018
+ * `append(form, X)`, `if(c, form, form)` or a let with the form as its body. No other part of the form reads the name:
1019
+ * not `X`, not `c` and not a binding of a let.
1020
+ */
1021
+ function ownForm(e: Expr, name: string, out: Expr[]): boolean {
1022
+ const free = (x: Expr): boolean => !namesOf(x).has(name);
1023
+ if (e.tag === "var") return e.name === name;
1024
+ if (e.tag === "let") return Object.values(e.bind).every(free) && ownForm(e.body, name, out);
1025
+ if (e.tag !== "app" || e.args.length === 0) return false;
1026
+ const [head, ...rest] = e.args as [Expr, ...Expr[]];
1027
+ // An if without three arguments gives a reason (#if), so the form does not check the count.
1028
+ if (e.op === "if") return free(head) && rest.every((x) => ownForm(x, name, out));
1029
+ if (e.op !== "append" || !rest.every(free) || !ownForm(head, name, out)) return false;
1030
+ out.push(e);
1031
+ return true;
1032
+ }
1033
+
985
1034
  /** This function gives the names that an expression reads, also the names that it binds itself. */
986
1035
  function namesOf(e: Expr, out = new Set<string>()): Set<string> {
987
1036
  if (e.tag === "var") out.add(e.name);
@@ -1278,6 +1327,8 @@ class Printer {
1278
1327
  #loops = 1_000_000;
1279
1328
  /** The node of the memo whose function the printer prints, so it prints the node itself. */
1280
1329
  #inside: Expr | undefined;
1330
+ /** The owner of each append node of the step of a loop that the printer prints (COMPILE.MODULE.APPEND.OWN). */
1331
+ readonly #own = new Map<Expr, Owner>();
1281
1332
  readonly #structures = new Map<string, string>();
1282
1333
  readonly #kinds = new Map<string, Kind | undefined>();
1283
1334
  readonly #ops = new Map<string, number>();
@@ -1504,6 +1555,19 @@ class Printer {
1504
1555
  return listy(e, this.#scopeOf(ctx));
1505
1556
  }
1506
1557
 
1558
+ /**
1559
+ * This method tells if the body of an each can give a list. The facts of the names `as` of its items come from its
1560
+ * list, which the printer prints only in the loop. So here each such name can hold a list. Then a list op goes over the
1561
+ * array of the each, and that array gives the value of the interpreter too (COMPILE.MODULE.LIST.ITEM).
1562
+ */
1563
+ #bodyList(e: ExprOf<"each">, ctx: Ctx): boolean {
1564
+ if (e.as === undefined) return this.#isList(e.body, ctx);
1565
+ // A list of the axis list is not in the memo, so the body is not a key of a node of the memo.
1566
+ const scope = this.#scopeOf(ctx);
1567
+ const names: readonly string[] = e.as;
1568
+ return listy(e.body, { ...scope, name: (name) => names.includes(name) || scope.name(name) });
1569
+ }
1570
+
1507
1571
  /** This method gives the scope of `listy` at a node: the names and the bound functions of its context. */
1508
1572
  #scopeOf(ctx: Ctx): ListScope {
1509
1573
  return {
@@ -1995,13 +2059,13 @@ class Printer {
1995
2059
  const [head] = args;
1996
2060
  const rest = args.slice(1);
1997
2061
  // An each whose body is a list gives a list of lists (LIST.FLAT), so a list op over it goes over its array.
1998
- if (FOLD_OPS.has(op) && head?.tag === "each" && !this.#isList(head.body, ctx)) return this.#list(op, head, rest, ctx);
2062
+ if (FOLD_OPS.has(op) && head?.tag === "each" && !this.#bodyList(head, ctx)) return this.#list(op, head, rest, ctx);
1999
2063
  // A list op over a let with only literal options is the list op over the body of the let, so an each in the body
2000
2064
  // is one loop with a running value, not an array. A builder sheet prints such a let, for example `sum(let($0 = 0, each(…)))`.
2001
2065
  if (FOLD_OPS.has(op) && head?.tag === "let" && rest.every((x) => x.tag === "lit")) return this.#let(head, ctx, (body) => app(op, body, ...rest));
2002
2066
  // sortBy and take are list ops for each receiver. Each other list op needs a list, and a domain can have its name.
2003
2067
  if (head !== undefined && (op === "sortBy" || op === "take" || (op === "drop" && this.#isList(head, ctx)))) return this.#order(op, head, rest, ctx);
2004
- if (head !== undefined && BUILD_OPS.has(op) && this.#isList(head, ctx)) return this.#build(op, head, rest, ctx);
2068
+ if (head !== undefined && BUILD_OPS.has(op) && this.#isList(head, ctx)) return this.#build(op, head, rest, ctx, this.#own.get(e));
2005
2069
  if (head !== undefined && (FOLD_OPS.has(op) || op === "nth") && this.#isList(head, ctx)) return this.#overList(op, head, rest, ctx);
2006
2070
  // An argument can be a list (COMPILE.MODULE.LIST.ARG).
2007
2071
  for (const x of args) this.#wantList.add(x);
@@ -2161,9 +2225,10 @@ class Printer {
2161
2225
  /**
2162
2226
  * This method gives the loop over the targets of an axis: the statements before it, its bounds and the key that it
2163
2227
  * skips. `start` has the levels of the address, and `inner` is the position at a target. The axes all, others,
2164
- * window and list have a loop. In a tree space, the axes of a tree have a loop too.
2228
+ * window and list have a loop. In a tree space, the axes of a tree have a loop too. With `as`, a loop over the axis
2229
+ * list binds the value and the index of each item after its check (COMPILE.MODULE.LIST.ITEM).
2165
2230
  */
2166
- #targetLoop(axis: Axis, at: readonly Move[], ctx: Ctx): {
2231
+ #targetLoop(axis: Axis, at: readonly Move[], ctx: Ctx, as?: ItemNames): {
2167
2232
  readonly s: string[];
2168
2233
  readonly j: string;
2169
2234
  /** The head of the loop, and the statements at the start of each item before the try and inside it. */
@@ -2179,6 +2244,9 @@ class Printer {
2179
2244
  readonly inner: Ctx;
2180
2245
  /** True when a target can be a key that is not the position of a record: a key of a literal or of `fill`. */
2181
2246
  readonly texts: boolean;
2247
+ /** The names `as` of the items, and their level. Only the body of an each and the steps of a fold read them. */
2248
+ readonly items: ReadonlyMap<string, Name>;
2249
+ readonly item: number | undefined;
2182
2250
  } {
2183
2251
  const { base: outer, tests } = testsOf(axis);
2184
2252
  // The reverse order of an axis is a loop from its end (AXIS.REVERSE). The validation keeps a base axis inside.
@@ -2198,7 +2266,13 @@ class Printer {
2198
2266
  const head = reverse ? `for (let ${q} = ${a}.length - 1; ${q} >= 0; ${q}--) {` : `for (let ${q} = 0; ${q} < ${a}.length; ${q}++) {`;
2199
2267
  const key = [`const ${j} = ${a}[${q}][0];`];
2200
2268
  const check = [`if (${a}[${q}][1] === E) ${this.use("F")}();`];
2201
- return { s: [...list.s, `const ${a} = ${list.v.code};`], j, head, key, check, skip: undefined, fixed: false, start: list.v.deps, startSafe: list.v.safe, tests, inner, texts };
2269
+ const s = [...list.s, `const ${a} = ${list.v.code};`];
2270
+ const named = as === undefined ? undefined : this.#itemNames(as, list.v.list as ListInfo, `${a}[${q}][1]`, a, reverse);
2271
+ if (named !== undefined) {
2272
+ s.push(...named.s);
2273
+ check.push(...named.check);
2274
+ }
2275
+ return { s, j, head, key, check, skip: undefined, fixed: false, start: list.v.deps, startSafe: list.v.safe, tests, inner, texts, items: named?.items ?? NO_NAMES, item: named?.level };
2202
2276
  }
2203
2277
  const s: string[] = [];
2204
2278
  let lo = "0";
@@ -2220,13 +2294,13 @@ class Printer {
2220
2294
  if (this.#tree && isTreeAxis(base)) {
2221
2295
  const range = this.#treeRange(base, f as string);
2222
2296
  const q = this.fresh("q");
2223
- return { s: [...s, ...range.s], j, head: forHead(q, range.lo, range.hi, reverse), key: [`const ${j} = ${range.a}[${q}];`], check: [], skip: range.skip, fixed: false, start, startSafe, tests, inner, texts: false };
2297
+ return { s: [...s, ...range.s], j, head: forHead(q, range.lo, range.hi, reverse), key: [`const ${j} = ${range.a}[${q}];`], check: [], skip: range.skip, fixed: false, start, startSafe, tests, inner, texts: false, items: NO_NAMES, item: undefined };
2224
2298
  }
2225
2299
  // In a graph space, the targets of an axis of a graph are an array of positions. A graph has no offsets and no tree.
2226
2300
  if (this.#graph && GRAPH_AXES.has(base.t)) {
2227
2301
  const range = this.#graphRange(base.t, f as string);
2228
2302
  const q = this.fresh("q");
2229
- return { s: [...s, ...range.s], j, head: forHead(q, range.lo, range.hi, reverse), key: [`const ${j} = ${range.a}[${q}];`], check: [], skip: undefined, fixed: false, start, startSafe, tests, inner, texts: false };
2303
+ return { s: [...s, ...range.s], j, head: forHead(q, range.lo, range.hi, reverse), key: [`const ${j} = ${range.a}[${q}];`], check: [], skip: undefined, fixed: false, start, startSafe, tests, inner, texts: false, items: NO_NAMES, item: undefined };
2230
2304
  }
2231
2305
  if (this.#graph && base.t === "window") throw new NotStandalone('the axis "window" in a graph space');
2232
2306
  if (base.t === "others") skip = f;
@@ -2236,7 +2310,34 @@ class Printer {
2236
2310
  s.push(`const ${h} = Math.min(n, ${f as string} + Math.min(${base.to}, n) + 1);`);
2237
2311
  hi = h;
2238
2312
  } else if (base.t !== "all") throw new NotStandalone(`the axis "${base.t}"`);
2239
- return { s, j, head: forHead(j, lo, hi, reverse), key: [], check: [], skip, fixed: f === undefined, start, startSafe, tests, inner, texts: false };
2313
+ return { s, j, head: forHead(j, lo, hi, reverse), key: [], check: [], skip, fixed: f === undefined, start, startSafe, tests, inner, texts: false, items: NO_NAMES, item: undefined };
2314
+ }
2315
+
2316
+ /**
2317
+ * This method binds the names `as` of a loop over the axis list (COMPILE.MODULE.LIST.ITEM). The statements come after
2318
+ * the check of the item, so an error item fails before they bind a name (AXIS.LIST.ITEM). The first name holds the
2319
+ * value of the item, with the facts of its list. The index counts the items with a value in the order of the list, as
2320
+ * `nth` does (AXIS.LIST.INDEX). In the reverse order, it counts down from the number of these items. The names have a
2321
+ * level of their own. Thus a part that reads them stays in the loop, and a key of a literal can still be a target.
2322
+ */
2323
+ #itemNames(as: ItemNames, info: ListInfo, value: string, a: string, reverse: boolean): { readonly s: readonly string[]; readonly check: readonly string[]; readonly items: ReadonlyMap<string, Name>; readonly level: number } {
2324
+ // Stryker disable next-line UpdateOperator: a level of a loop is a name, so a count down gives other names, and the same code
2325
+ const level = this.#loops++;
2326
+ const deps = new Set([level]);
2327
+ const [item, index] = as;
2328
+ const y = this.fresh("y");
2329
+ const items = new Map<string, Name>([[item, { code: y, kind: info.item, lazy: false, deps, list: info.inner }]]);
2330
+ const check = [`const ${y} = ${value};`];
2331
+ const s: string[] = [];
2332
+ if (index !== undefined) {
2333
+ const i = this.fresh("i");
2334
+ const z = this.fresh("z");
2335
+ // The check before the index throws for an error item, so the count skips it.
2336
+ s.push(`let ${z} = ${reverse ? `${this.use("CT")}(${a}, false)` : "0"};`);
2337
+ check.push(`const ${i} = ${reverse ? `--${z}` : `${z}++`};`);
2338
+ items.set(index, { code: i, kind: "number", lazy: false, deps });
2339
+ }
2340
+ return { s, check, items, level };
2240
2341
  }
2241
2342
 
2242
2343
  /**
@@ -2302,17 +2403,18 @@ class Printer {
2302
2403
  #list(op: string, target: ExprOf<"each">, rest: readonly Expr[], ctx: Ctx): Code {
2303
2404
  const { strict, step } = this.#foldOptions(op, rest);
2304
2405
  const at = target.at ?? [];
2305
- const { s, j, head, key, check, skip, fixed, start, startSafe, tests, inner, texts } = this.#targetLoop(target.axis, at, ctx);
2406
+ const { s, j, head, key, check, skip, fixed, start, startSafe, tests, inner, texts, items, item: own } = this.#targetLoop(target.axis, at, ctx, target.as);
2306
2407
  const { level } = inner;
2307
- // Inside the loop, a constant of the run evaluates once, before the loop over the keys of the run.
2408
+ // Inside the loop, a constant of the run evaluates once, before the loop over the keys of the run. The tests do not
2409
+ // see the names of the items, and the body sees them (AXIS.LIST.SCOPE).
2308
2410
  const testCodes = tests.map((t) => this.#hoist(this.expr(t, inner), hasLoop(t)));
2309
- const body = this.#hoist(this.expr(target.body, inner), hasLoop(target.body));
2411
+ const body = this.#hoist(this.expr(target.body, { ...inner, env: withNames(inner.env, items) }), hasLoop(target.body));
2310
2412
  this.#readsNoTarget(texts, level, [body, ...testCodes].map((x) => x.v.deps));
2311
2413
  // A count of all the items, whose body cannot fail, is the count of the records. A safe body covers its statements.
2312
2414
  // V-063: a body that reads a cell keeps its loop. The search of the run must see each read, so a cell that reads
2313
2415
  // itself gives `#CYCLE!`.
2314
2416
  if (op === "count" && fixed && tests.length === 0 && body.v.safe && !body.v.deps.has(CELLS)) return bare(plainValue("n", "number"));
2315
- const deps = new Set([...start, ...[body, ...testCodes].flatMap((x) => [...x.v.deps])].filter((d) => d !== level));
2417
+ const deps = new Set([...start, ...[body, ...testCodes].flatMap((x) => [...x.v.deps])].filter((d) => d !== level && d !== own));
2316
2418
  const r = this.#reduction(op, body.v.kind, step);
2317
2419
  const { v } = r;
2318
2420
  s.push(r.init);
@@ -2424,13 +2526,14 @@ class Printer {
2424
2526
  */
2425
2527
  #eachList(e: ExprOf<"each">, ctx: Ctx): Code {
2426
2528
  const at = e.at ?? [];
2427
- const { s, j, head, key, check, skip, start, startSafe, tests, inner, texts } = this.#targetLoop(e.axis, at, ctx);
2529
+ const { s, j, head, key, check, skip, start, startSafe, tests, inner, texts, items, item: own } = this.#targetLoop(e.axis, at, ctx, e.as);
2428
2530
  const testCodes = tests.map((t) => this.#hoist(this.expr(t, inner), hasLoop(t)));
2429
2531
  // The value of an item can be a list, for flat (LIST.FLAT). The facts of the list tell it.
2430
2532
  if (this.#wantList.has(e)) this.#wantList.add(e.body);
2431
- const body = this.#hoist(this.expr(e.body, inner), hasLoop(e.body));
2533
+ // Only the body sees the names of the items (AXIS.LIST.SCOPE).
2534
+ const body = this.#hoist(this.expr(e.body, { ...inner, env: withNames(inner.env, items) }), hasLoop(e.body));
2432
2535
  this.#readsNoTarget(texts, inner.level, [body, ...testCodes].map((x) => x.v.deps));
2433
- const deps = new Set([...start, ...[body, ...testCodes].flatMap((x) => [...x.v.deps])].filter((d) => d !== inner.level));
2536
+ const deps = new Set([...start, ...[body, ...testCodes].flatMap((x) => [...x.v.deps])].filter((d) => d !== inner.level && d !== own));
2434
2537
  const list = this.fresh("L");
2435
2538
  const v = this.fresh("x");
2436
2539
  const item = [...check, ...testCodes.flatMap((t) => [...t.s, `if (!${this.#boolean(t.v)}) continue;`]), ...body.s];
@@ -2480,9 +2583,10 @@ class Printer {
2480
2583
 
2481
2584
  /**
2482
2585
  * This method prints append, without and flat (LIST.BUILD), get (LIST.GET) and indexOf (LIST.INDEXOF) over the array
2483
- * of a list. Each list that the op reads follows LIST.LENIENT, as in the interpreter.
2586
+ * of a list. Each list that the op reads follows LIST.LENIENT, as in the interpreter. An append with an owner appends
2587
+ * into the array of its name, if the name in the context is the name of the loop (COMPILE.MODULE.APPEND.OWN).
2484
2588
  */
2485
- #build(op: string, head: Expr, rest: readonly Expr[], ctx: Ctx): Code {
2589
+ #build(op: string, head: Expr, rest: readonly Expr[], ctx: Ctx, owner: Owner | undefined): Code {
2486
2590
  const list = this.#listOf(head, ctx);
2487
2591
  const info = list.v.list as ListInfo;
2488
2592
  const two = op === "append" || op === "without";
@@ -2494,10 +2598,11 @@ class Printer {
2494
2598
  const deps = depsOf(...raw);
2495
2599
  const parts = this.#inOrder(this.#settle(raw, deps, exprs), true);
2496
2600
  const helper = BUILD_HELPERS[op] as BuildHelper;
2497
- const value = (kind: Kind | undefined, facts: ListInfo | undefined): Code => ({
2498
- s: stmtsOf(...parts),
2499
- v: { code: `${this.use(helper)}(${[...parts.map((x) => x.v.code), String(strict)].join(", ")})`, kind, safe: false, deps, list: facts },
2500
- });
2601
+ const args = [...parts.map((x) => x.v.code), String(strict)];
2602
+ // A function of the program can share a node with the step, but its body has its own names (FN.BIND).
2603
+ const w = owner !== undefined && ctx.env.get(owner.name) === owner.read ? (owner.w ??= this.fresh("w")) : undefined;
2604
+ const code = w === undefined ? `${this.use(helper)}(${args.join(", ")})` : `(${w} = ${this.use("AO")}(${[...args, w].join(", ")}))`;
2605
+ const value = (kind: Kind | undefined, facts: ListInfo | undefined): Code => ({ s: stmtsOf(...parts), v: { code, kind, safe: false, deps, list: facts } });
2501
2606
  if (op === "get") return value(info.item, info.inner);
2502
2607
  if (op === "indexOf") return value("number", undefined);
2503
2608
  if (op === "without") return value(undefined, info);
@@ -2521,6 +2626,10 @@ class Printer {
2521
2626
  const { item, inner } = list.v.list as ListInfo;
2522
2627
  // The value of an item of a list of lists is a list, so nth and first give a list (LIST.FLAT).
2523
2628
  if (op === "nth") return { s: stmtsOf(...parts), v: { code: `${this.use("NT")}(${[...parts.map((x) => x.v.code), String(strict)].join(", ")})`, kind: item, safe: false, deps, list: inner } };
2629
+ // count and first read the items with values on the array of the list, as nth does (COMPILE.MODULE.NTH.INDEX). Thus
2630
+ // a step of a loop that counts a list of n items costs O(1) after the first count.
2631
+ if (op === "count") return { s: l.s, v: { code: `${this.use("CT")}(${l.v.code}, ${String(strict)})`, kind: "number", safe: false, deps, list: undefined } };
2632
+ if (op === "first") return { s: l.s, v: { code: `${this.use("FS")}(${l.v.code}, ${String(strict)})`, kind: item, safe: false, deps, list: inner } };
2524
2633
  const r = this.#reduction(op, item, step);
2525
2634
  const { v } = r;
2526
2635
  const s = [...l.s, r.init, `for (const [, ${v}] of ${l.v.code}) {`, ` if (${v} === E) ${strict ? `${this.use("F")}();` : "continue;"}`, ` ${r.step}`, "}"];
@@ -2556,8 +2665,35 @@ class Printer {
2556
2665
  return { s, env, vars, deps };
2557
2666
  }
2558
2667
 
2559
- /** This method gives the statements of one step of a loop: each new value first, and then each name gets its value. */
2560
- #loopStep(step: Names, inner: Ctx, vars: ReadonlyMap<string, Name>): { readonly s: string[]; readonly deps: ReadonlySet<number> } {
2668
+ /**
2669
+ * This method gives the statements of one step of a loop: each new value first, and then each name gets its value.
2670
+ * `init` has the statements before the loop: the variable of each name that appends to its own list
2671
+ * (COMPILE.MODULE.APPEND.OWN). Each such name has the form of `ownForm`, and no step of another name and no `until`
2672
+ * reads it. The tests of a fold read only the names outside the fold, so they cannot read it.
2673
+ */
2674
+ #loopStep(step: Names, inner: Ctx, vars: ReadonlyMap<string, Name>, until?: Expr): { readonly s: string[]; readonly deps: ReadonlySet<number>; readonly init: readonly string[] } {
2675
+ const owners: Owner[] = [];
2676
+ const nodes: Expr[] = [];
2677
+ const steps = Object.entries(step);
2678
+ for (const [name, x] of steps) {
2679
+ const own: Expr[] = [];
2680
+ const others = [...steps.filter(([k]) => k !== name).map(([, y]) => y), ...(until === undefined ? [] : [until])];
2681
+ if (!ownForm(x, name, own) || others.some((y) => namesOf(y).has(name))) continue;
2682
+ const owner: Owner = { name, read: vars.get(name) as Name, w: undefined };
2683
+ for (const node of own) this.#own.set(node, owner);
2684
+ owners.push(owner);
2685
+ nodes.push(...own);
2686
+ }
2687
+ try {
2688
+ const { s, deps } = this.#steps(step, inner, vars);
2689
+ return { s, deps, init: owners.flatMap((o) => (o.w === undefined ? [] : [`let ${o.w} = null;`])) };
2690
+ } finally {
2691
+ for (const node of nodes) this.#own.delete(node);
2692
+ }
2693
+ }
2694
+
2695
+ /** This method gives the statements of one step of a loop, without the variables of COMPILE.MODULE.APPEND.OWN. */
2696
+ #steps(step: Names, inner: Ctx, vars: ReadonlyMap<string, Name>): { readonly s: string[]; readonly deps: ReadonlySet<number> } {
2561
2697
  const s: string[] = [];
2562
2698
  const sets: string[] = [];
2563
2699
  const deps = new Set<number>();
@@ -2587,7 +2723,7 @@ class Printer {
2587
2723
  // A loop at a place that takes a list gives its result there (LOOP.LIST).
2588
2724
  if (this.#wantList.has(e)) this.#wantList.add(e.result);
2589
2725
  const until = e.until === undefined ? undefined : this.expr(e.until, inner);
2590
- const step = this.#loopStep(e.step, inner, names.vars);
2726
+ const step = this.#loopStep(e.step, inner, names.vars, e.until);
2591
2727
  const result = this.expr(e.result, inner);
2592
2728
  const k = this.fresh("k");
2593
2729
  const body = [
@@ -2597,7 +2733,7 @@ class Printer {
2597
2733
  ];
2598
2734
  const inside = [...(until?.v.deps ?? []), ...step.deps, ...result.v.deps].filter((d) => d !== loop);
2599
2735
  const deps = new Set([...names.deps, ...inside]);
2600
- return { s: [...names.s, `for (let ${k} = 0; ; ${k}++) {`, ...ind(body), "}", ...result.s], v: { code: result.v.code, kind: result.v.kind, safe: false, deps, list: result.v.list } };
2736
+ return { s: [...names.s, ...step.init, `for (let ${k} = 0; ; ${k}++) {`, ...ind(body), "}", ...result.s], v: { code: result.v.code, kind: result.v.kind, safe: false, deps, list: result.v.list } };
2601
2737
  }
2602
2738
 
2603
2739
  /**
@@ -2609,11 +2745,13 @@ class Printer {
2609
2745
  const loop = this.#loops++;
2610
2746
  const names = this.#loopNames(e.init, e.step, ctx, loop);
2611
2747
  if (this.#wantList.has(e)) this.#wantList.add(e.result);
2612
- const t = this.#targetLoop(e.axis, e.at ?? [], ctx);
2748
+ const t = this.#targetLoop(e.axis, e.at ?? [], ctx, e.as);
2613
2749
  const tests = t.tests.map((x) => this.#hoist(this.expr(x, t.inner), hasLoop(x)));
2614
2750
  // The interpreter evaluates the tests at each target before the first step, so a module of a sheet does not have them.
2615
2751
  if (tests.some((x) => x.v.deps.has(CELLS))) throw new NotStandalone("a test of the axis of a fold reads a cell");
2616
- const step = this.#loopStep(e.step, { ...t.inner, env: names.env }, names.vars);
2752
+ // Only the steps see the names of the items (AXIS.LIST.SCOPE). A name of `as` is not a name of `init`, so the read of
2753
+ // each name of the fold stays its read, and an append into its own list keeps its owner (COMPILE.MODULE.APPEND.OWN).
2754
+ const step = this.#loopStep(e.step, { ...t.inner, env: withNames(names.env, t.items) }, names.vars);
2617
2755
  this.#readsNoTarget(t.texts, t.inner.level, [...tests.map((x) => x.v.deps), step.deps]);
2618
2756
  const result = this.expr(e.result, { ...ctx, env: names.env });
2619
2757
  const body = [
@@ -2623,9 +2761,9 @@ class Printer {
2623
2761
  ...tests.flatMap((c) => [...c.s, `if (!${this.#boolean(c.v)}) continue;`]),
2624
2762
  ...step.s,
2625
2763
  ];
2626
- const inside = [...tests.flatMap((c) => [...c.v.deps]), ...step.deps].filter((d) => d !== loop && d !== t.inner.level);
2764
+ const inside = [...tests.flatMap((c) => [...c.v.deps]), ...step.deps].filter((d) => d !== loop && d !== t.inner.level && d !== t.item);
2627
2765
  const deps = new Set([...names.deps, ...t.start, ...inside, ...[...result.v.deps].filter((d) => d !== loop)]);
2628
- return { s: [...names.s, ...t.s, t.head, ...ind(body), "}", ...result.s], v: { code: result.v.code, kind: result.v.kind, safe: false, deps, list: result.v.list } };
2766
+ return { s: [...names.s, ...step.init, ...t.s, t.head, ...ind(body), "}", ...result.s], v: { code: result.v.code, kind: result.v.kind, safe: false, deps, list: result.v.list } };
2629
2767
  }
2630
2768
 
2631
2769
  /**