@mark1russell7/vex 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/build/index.js CHANGED
@@ -49,6 +49,7 @@ const CODE_OF = {
49
49
  unbound: "#NAME?",
50
50
  "not-finite": "#NUM!",
51
51
  "invalid-value": "#NUM!",
52
+ limit: "#NUM!",
52
53
  threw: "#CALC!",
53
54
  "undefined-result": "#CALC!",
54
55
  args: "#ARGS",
@@ -85,6 +86,8 @@ function vexError(kind, message, details = {}) {
85
86
  const formatError = (e) => `${e.code} ${e.kind}: ${e.message}`;
86
87
  //#endregion
87
88
  //#region src/ir.ts
89
+ /** The largest number of steps of `iterate` (ITERATE.LIMIT). */
90
+ const MAX_ITERATIONS = 1e5;
88
91
  /** This function makes a literal. */
89
92
  const lit = (value) => ({
90
93
  tag: "lit",
@@ -142,22 +145,73 @@ function each(axis, body, at) {
142
145
  at
143
146
  };
144
147
  }
148
+ /**
149
+ * This function makes a fold: a step at each target of `axis`, in order. `init` gives the names and their first
150
+ * values, and `step` gives the next values. `result` gives the value from the last values (LOOP.NAMES, FOLD.ORDER).
151
+ */
152
+ function fold(axis, init, step, result, at) {
153
+ return at === void 0 || at.length === 0 ? {
154
+ tag: "fold",
155
+ axis,
156
+ init,
157
+ step,
158
+ result
159
+ } : {
160
+ tag: "fold",
161
+ axis,
162
+ init,
163
+ step,
164
+ result,
165
+ at
166
+ };
167
+ }
168
+ /**
169
+ * This function makes an iteration: up to `limit` steps. `init` gives the names and their first values, and `step`
170
+ * gives the next values. A true `until` stops it, and `result` gives the value (ITERATE.LIMIT, ITERATE.UNTIL).
171
+ */
172
+ function iterate(limit, init, step, result, until) {
173
+ return until === void 0 ? {
174
+ tag: "iterate",
175
+ limit,
176
+ init,
177
+ step,
178
+ result
179
+ } : {
180
+ tag: "iterate",
181
+ limit,
182
+ init,
183
+ step,
184
+ until,
185
+ result
186
+ };
187
+ }
145
188
  /** This function makes an expression of an extension kind. */
146
189
  const ext = (kind, data) => ({
147
190
  tag: "ext",
148
191
  kind,
149
192
  data
150
193
  });
151
- /** The move to an absolute key. */
152
- const key = (k) => ({
153
- t: "key",
154
- key: k
155
- });
156
- /** The move to a position in the key order. */
157
- const index = (i) => ({
158
- t: "index",
159
- i
160
- });
194
+ function key(k) {
195
+ return {
196
+ t: "key",
197
+ key: k
198
+ };
199
+ }
200
+ function index(i) {
201
+ return {
202
+ t: "index",
203
+ i
204
+ };
205
+ }
206
+ /** This function gives the expression of a move with a computed key or position, or `undefined`. */
207
+ function moveExpr(m) {
208
+ if (m.t === "key") return typeof m.key === "string" ? void 0 : m.key;
209
+ return m.t === "index" && typeof m.i !== "number" ? m.i : void 0;
210
+ }
211
+ /** This function gives the expressions of the computed moves of an address, in the order of the moves. */
212
+ const addrExprs = (at) => (at ?? []).flatMap((m) => moveExpr(m) ?? []);
213
+ /** This function tells if each move of an address is fixed. */
214
+ const isFixedAddr = (at) => addrExprs(at).length === 0;
161
215
  /** The move to the other key of a space with two keys. */
162
216
  const other = Object.freeze({ t: "other" });
163
217
  /** The relative move in an array (one number) or a grid (two numbers). */
@@ -222,39 +276,102 @@ const axes = {
222
276
  };
223
277
  const isObject = (u) => typeof u === "object" && u !== null;
224
278
  const isStringArray = (u) => Array.isArray(u) && u.every((s) => typeof s === "string");
225
- /** This function tells if a value is a valid move. */
279
+ /** This function tells if a value is a valid move. The expression of a computed move must be valid too. */
226
280
  function isMove(u) {
227
- if (!isObject(u)) return false;
281
+ const exprs = moveParts(u);
282
+ return exprs !== void 0 && exprs.every(isExpr);
283
+ }
284
+ const anyNumber = (x) => typeof x === "number";
285
+ /** This function checks the fixed parts of a move. It gives the expressions of the move, or `undefined` for a bad move. */
286
+ function moveParts(u, isNumber = Number.isInteger) {
287
+ if (!isObject(u)) return void 0;
228
288
  switch (u["t"]) {
229
- case "key": return typeof u["key"] === "string";
230
- case "index": return Number.isInteger(u["i"]);
231
- case "offset": return Array.isArray(u["d"]) && u["d"].every((n) => Number.isInteger(n));
289
+ case "key": return typeof u["key"] === "string" ? [] : isObject(u["key"]) ? [u["key"]] : void 0;
290
+ case "index": return isNumber(u["i"]) ? [] : isObject(u["i"]) ? [u["i"]] : void 0;
291
+ case "offset": return Array.isArray(u["d"]) && u["d"].every((n) => isNumber(n)) ? [] : void 0;
232
292
  case "other":
233
293
  case "origin":
234
- case "parent": return true;
235
- default: return false;
294
+ case "parent": return [];
295
+ default: return;
236
296
  }
237
297
  }
238
298
  /** This function tells if a value is a valid axis. It checks the tests of `where` too. */
239
299
  function isAxis(u) {
240
- return validTree([{
300
+ return badPart([{
241
301
  axis: true,
242
302
  u
243
- }]);
303
+ }], true) === void 0;
244
304
  }
245
305
  /** This function tells if a value is a valid expression. It checks the whole tree. */
246
306
  function isExpr(u) {
247
- return validTree([{
307
+ return badPart([{
308
+ axis: false,
309
+ u
310
+ }], true) === void 0;
311
+ }
312
+ /** The tags of the expressions of this version of Vex. */
313
+ const TAGS = /* @__PURE__ */ new Set([
314
+ "lit",
315
+ "ref",
316
+ "app",
317
+ "let",
318
+ "var",
319
+ "rec",
320
+ "each",
321
+ "fold",
322
+ "iterate",
323
+ "ext"
324
+ ]);
325
+ /**
326
+ * This function gives the reason that a value is not a valid expression, or `undefined` for a valid expression
327
+ * (EVAL.SHAPE). An expression from a newer version of Vex can have a tag that this version does not know. Unlike
328
+ * `isExpr`, it accepts a number that is not whole in a move or in a window, because it has a meaning at run time.
329
+ */
330
+ function shapeError(u) {
331
+ const bad = badPart([{
248
332
  axis: false,
249
333
  u
250
- }]);
334
+ }], false);
335
+ if (bad === void 0) return void 0;
336
+ const tag = isObject(bad.u) ? bad.u["tag"] : void 0;
337
+ if (bad.axis) return "the expression has an axis that is not valid";
338
+ if (typeof tag === "string" && !TAGS.has(tag)) return `the expression has a node with the tag "${tag}", and this version of Vex does not know it`;
339
+ return typeof tag === "string" ? `the expression has a node "${tag}" with parts that are not valid` : "the expression has a part that is not a node";
251
340
  }
252
- const isAddr = (u) => u === void 0 || Array.isArray(u) && u.every(isMove);
253
341
  /**
254
- * This function checks a tree of expressions and axes. It uses a stack, not recursion, so the input can be deep. For
255
- * example, a deep JSON file from a stranger does not need a deep call stack (EVAL.NESTING).
342
+ * This function checks the names of a loop: `init` and `step` are records, and each name of `step` is a name of `init`.
343
+ * It gives the expressions of `init`, of `step` and `result`, or `undefined` (LOOP.NAMES).
256
344
  */
257
- function validTree(todo) {
345
+ function loopParts(u) {
346
+ const { init, step } = u;
347
+ if (!isObject(init) || Array.isArray(init) || !isObject(step) || Array.isArray(step)) return void 0;
348
+ if (!Object.keys(step).every((n) => Object.hasOwn(init, n))) return void 0;
349
+ return [
350
+ ...Object.values(init),
351
+ ...Object.values(step),
352
+ u["result"]
353
+ ];
354
+ }
355
+ /** This function checks the fixed parts of an address. It gives the expressions of its moves, or `undefined`. */
356
+ function addrParts(u, isNumber) {
357
+ if (u === void 0) return [];
358
+ if (!Array.isArray(u)) return void 0;
359
+ const out = [];
360
+ for (const m of u) {
361
+ const parts = moveParts(m, isNumber);
362
+ if (parts === void 0) return void 0;
363
+ out.push(...parts);
364
+ }
365
+ return out;
366
+ }
367
+ /**
368
+ * This function checks a tree of expressions and axes, and it gives the first part that is not valid. It uses a stack,
369
+ * not recursion, so the input can be deep. For example, a deep JSON file from a stranger does not need a deep call
370
+ * stack (EVAL.NESTING). With `whole`, the numbers of the moves and of the windows must be whole, as the JSON form needs.
371
+ */
372
+ function badPart(todo, whole) {
373
+ const moveNumber = whole ? Number.isInteger : anyNumber;
374
+ const windowNumber = whole ? Number.isSafeInteger : anyNumber;
258
375
  const push = (axis, values) => {
259
376
  for (const u of values) todo.push({
260
377
  axis,
@@ -263,15 +380,15 @@ function validTree(todo) {
263
380
  };
264
381
  for (let item = todo.pop(); item !== void 0; item = todo.pop()) {
265
382
  const { u } = item;
266
- if (!isObject(u)) return false;
383
+ if (!isObject(u)) return item;
267
384
  if (item.axis) {
268
385
  const t = u["t"];
269
386
  if (t === "neighbors") {
270
- if (u["n"] !== 4 && u["n"] !== 8) return false;
387
+ if (u["n"] !== 4 && u["n"] !== 8) return item;
271
388
  } else if (t === "window") {
272
- if (!Number.isSafeInteger(u["from"]) || !Number.isSafeInteger(u["to"])) return false;
389
+ if (!windowNumber(u["from"]) || !windowNumber(u["to"])) return item;
273
390
  } else if (t === "table") {
274
- if (typeof u["name"] !== "string") return false;
391
+ if (typeof u["name"] !== "string") return item;
275
392
  } else if (t === "where") {
276
393
  push(true, [u["axis"]]);
277
394
  push(false, [u["test"]]);
@@ -286,53 +403,92 @@ function validTree(todo) {
286
403
  "successors",
287
404
  "predecessors",
288
405
  "reachable"
289
- ].includes(t)) return false;
406
+ ].includes(t)) return item;
290
407
  continue;
291
408
  }
292
409
  switch (u["tag"]) {
293
410
  case "lit":
294
- if (!("value" in u)) return false;
411
+ if (!("value" in u)) return item;
295
412
  break;
296
- case "ref":
297
- if (!isStringArray(u["path"]) || !isAddr(u["at"])) return false;
413
+ case "ref": {
414
+ const at = addrParts(u["at"], moveNumber);
415
+ if (!isStringArray(u["path"]) || at === void 0) return item;
416
+ push(false, at);
298
417
  break;
418
+ }
299
419
  case "app":
300
- if (typeof u["op"] !== "string" || !Array.isArray(u["args"])) return false;
420
+ if (typeof u["op"] !== "string" || !Array.isArray(u["args"])) return item;
301
421
  push(false, u["args"]);
302
422
  break;
303
423
  case "let":
304
- if (!isObject(u["bind"]) || Array.isArray(u["bind"])) return false;
424
+ if (!isObject(u["bind"]) || Array.isArray(u["bind"])) return item;
305
425
  push(false, [...Object.values(u["bind"]), u["body"]]);
306
426
  break;
307
427
  case "var":
308
- if (typeof u["name"] !== "string") return false;
428
+ if (typeof u["name"] !== "string") return item;
309
429
  break;
310
430
  case "rec":
311
- if (!isObject(u["fields"]) || Array.isArray(u["fields"])) return false;
431
+ if (!isObject(u["fields"]) || Array.isArray(u["fields"])) return item;
312
432
  push(false, Object.values(u["fields"]));
313
433
  break;
314
- case "each":
315
- if (!isAddr(u["at"])) return false;
434
+ case "each": {
435
+ const at = addrParts(u["at"], moveNumber);
436
+ if (at === void 0) return item;
316
437
  push(true, [u["axis"]]);
317
- push(false, [u["body"]]);
438
+ push(false, [u["body"], ...at]);
439
+ break;
440
+ }
441
+ case "fold": {
442
+ const at = addrParts(u["at"], moveNumber);
443
+ const names = loopParts(u);
444
+ if (at === void 0 || names === void 0) return item;
445
+ push(true, [u["axis"]]);
446
+ push(false, [...names, ...at]);
447
+ break;
448
+ }
449
+ case "iterate": {
450
+ const limit = u["limit"];
451
+ const names = loopParts(u);
452
+ if (typeof limit !== "number" || !Number.isInteger(limit) || limit < 0 || limit > 1e5 || names === void 0) return item;
453
+ push(false, [...names, ...u["until"] === void 0 ? [] : [u["until"]]]);
318
454
  break;
455
+ }
319
456
  case "ext":
320
- if (typeof u["kind"] !== "string" || !("data" in u)) return false;
457
+ if (typeof u["kind"] !== "string" || !("data" in u)) return item;
321
458
  break;
322
- default: return false;
459
+ default: return item;
323
460
  }
324
461
  }
325
- return true;
326
462
  }
327
- /** This function gives the child expressions of an expression, in the order of their child index. */
463
+ /**
464
+ * This function gives the child expressions of an expression, in the order of their child index. The expressions of
465
+ * the computed moves of an address come last. They evaluate at the position of their node, also for an axis.
466
+ */
328
467
  function children(e) {
329
468
  switch (e.tag) {
330
469
  case "app": return e.args;
331
470
  case "let": return [...Object.values(e.bind), e.body];
332
471
  case "rec": return Object.values(e.fields);
333
- case "each": return [e.body, ...whereTests(e.axis)];
472
+ case "each": return [
473
+ e.body,
474
+ ...whereTests(e.axis),
475
+ ...addrExprs(e.at)
476
+ ];
477
+ case "fold": return [
478
+ ...Object.values(e.init),
479
+ ...Object.values(e.step),
480
+ ...whereTests(e.axis),
481
+ ...addrExprs(e.at),
482
+ e.result
483
+ ];
484
+ case "iterate": return [
485
+ ...Object.values(e.init),
486
+ ...Object.values(e.step),
487
+ ...e.until === void 0 ? [] : [e.until],
488
+ e.result
489
+ ];
490
+ case "ref": return addrExprs(e.at);
334
491
  case "lit":
335
- case "ref":
336
492
  case "var":
337
493
  case "ext": return [];
338
494
  }
@@ -348,10 +504,12 @@ function whereTests(a) {
348
504
  var RecordSpace = class {
349
505
  kind = "record";
350
506
  keys;
507
+ records;
351
508
  #records;
352
509
  constructor(records) {
353
510
  const entries = Object.entries(records);
354
511
  this.keys = Object.freeze(entries.map(([k]) => k));
512
+ this.records = Object.freeze(entries.map(([, o]) => o));
355
513
  this.#records = new Map(entries);
356
514
  }
357
515
  has(k) {
@@ -366,29 +524,28 @@ var RecordSpace = class {
366
524
  var ArraySpace = class {
367
525
  kind = "array";
368
526
  keys;
369
- #items;
527
+ records;
370
528
  constructor(items) {
371
- const entries = items.map((item, i) => [`${i}`, item]);
372
- this.keys = Object.freeze(entries.map(([k]) => k));
373
- this.#items = new Map(entries);
529
+ this.keys = Object.freeze(Array.from(items, (_item, i) => `${i}`));
530
+ this.records = Object.freeze(Array.from(items));
374
531
  }
375
532
  has(k) {
376
- return this.#items.has(k);
533
+ return this.keys[Number(k)] === k;
377
534
  }
378
535
  get(k) {
379
- return this.#items.get(k);
536
+ return this.has(k) ? this.records[Number(k)] : void 0;
380
537
  }
381
538
  coords(k) {
382
539
  return this.has(k) ? [Number(k)] : void 0;
383
540
  }
384
541
  keyAt(coords) {
385
- const k = String(coords[0]);
386
- return coords.length === 1 && this.has(k) ? k : void 0;
542
+ return coords.length === 1 ? this.keys[Number(coords[0])] : void 0;
387
543
  }
388
544
  };
389
545
  var GridSpace = class {
390
546
  kind = "grid";
391
547
  keys;
548
+ records;
392
549
  #cells;
393
550
  #coords;
394
551
  constructor(rows) {
@@ -398,6 +555,7 @@ var GridSpace = class {
398
555
  Object.freeze([i, j])
399
556
  ]));
400
557
  this.keys = Object.freeze(entries.map(([k]) => k));
558
+ this.records = Object.freeze(entries.map(([, o]) => o));
401
559
  this.#cells = new Map(entries.map(([k, cell]) => [k, cell]));
402
560
  this.#coords = new Map(entries.map(([k, , c]) => [k, c]));
403
561
  }
@@ -418,12 +576,14 @@ var GridSpace = class {
418
576
  var TreeSpace = class {
419
577
  kind = "tree";
420
578
  keys;
579
+ records;
421
580
  #records;
422
581
  #parents;
423
582
  #children;
424
583
  constructor(records, parents) {
425
584
  const entries = Object.entries(records);
426
585
  this.keys = Object.freeze(entries.map(([k]) => k));
586
+ this.records = Object.freeze(entries.map(([, o]) => o));
427
587
  this.#records = new Map(entries);
428
588
  const parentOf = /* @__PURE__ */ new Map();
429
589
  for (const [k, p] of Object.entries(parents)) {
@@ -477,12 +637,14 @@ const NO_KEYS = Object.freeze([]);
477
637
  var GraphSpace = class {
478
638
  kind = "graph";
479
639
  keys;
640
+ records;
480
641
  #records;
481
642
  #out;
482
643
  #in;
483
644
  constructor(records, edges) {
484
645
  const entries = Object.entries(records);
485
646
  this.keys = Object.freeze(entries.map(([k]) => k));
647
+ this.records = Object.freeze(entries.map(([, o]) => o));
486
648
  this.#records = new Map(entries);
487
649
  const out = /* @__PURE__ */ new Map();
488
650
  for (const [k, to] of Object.entries(edges)) {
@@ -586,6 +748,31 @@ function applyMove(s, at, m) {
586
748
  }
587
749
  }
588
750
  }
751
+ /**
752
+ * This function gives the fixed moves of an address. `values` has the value of the expression of each computed move,
753
+ * in order (NAV.COMPUTED). A key that is not a text, or a position that is not a number, gives `#VALUE!`.
754
+ */
755
+ function fixAddr(addr, values, at) {
756
+ const out = [];
757
+ let next = 0;
758
+ for (const m of addr) {
759
+ if (moveExpr(m) === void 0) {
760
+ out.push(m);
761
+ continue;
762
+ }
763
+ const u = values[next++];
764
+ if (m.t === "key" && typeof u === "string") out.push({
765
+ t: "key",
766
+ key: u
767
+ });
768
+ else if (m.t === "index" && typeof u === "number") out.push({
769
+ t: "index",
770
+ i: u
771
+ });
772
+ else return fail(vexError("kind-mismatch", m.t === "key" ? `the key of a move is a ${typeof u}, not a text` : `the position of a move is a ${typeof u}, not a number`, at));
773
+ }
774
+ return ok(out);
775
+ }
589
776
  /** This function applies the moves of an address in order. It gives the key where the address points. */
590
777
  function resolveAddr(s, at, addr) {
591
778
  let focus = at.focus;
@@ -830,12 +1017,14 @@ function nestingOf(e) {
830
1017
  return deepest;
831
1018
  }
832
1019
  function compile(expr, opts = {}) {
833
- const nesting = nestingOf(expr);
834
- const root = nesting > 500 ? (f) => fail(vexError("bad-expression", `the expression is nested ${nesting} levels deep, and the limit is 500`, {
1020
+ const shape = shapeError(expr);
1021
+ const nesting = shape === void 0 ? nestingOf(expr) : 0;
1022
+ const bad = shape ?? (nesting > 500 ? `the expression is nested ${nesting} levels deep, and the limit is 500` : void 0);
1023
+ const root = bad === void 0 ? new Compiler(opts).node(expr, []) : (f) => fail(vexError("bad-expression", bad, {
835
1024
  path: [],
836
1025
  origin: f.pos.origin,
837
1026
  focus: f.pos.focus
838
- })) : new Compiler(opts).node(expr, []);
1027
+ }));
839
1028
  const run = (r) => {
840
1029
  const { space, origin } = r;
841
1030
  if (!space.has(origin)) return fail(vexError("unknown-key", `the space has no key "${origin}"`, {
@@ -983,6 +1172,8 @@ var Compiler = class {
983
1172
  }
984
1173
  case "app": return isSpecialForm(e.op) ? this.#special(e.op, this.#nodes(e.args, path), info) : this.#app(e.op, this.#nodes(e.args, path), info);
985
1174
  case "each": return this.#each(e, info);
1175
+ case "fold": return this.#fold(e, info);
1176
+ case "iterate": return this.#iterate(e, info);
986
1177
  case "ext": {
987
1178
  const extensions = this.#extensions ?? {};
988
1179
  const handler = Object.hasOwn(extensions, e.kind) ? extensions[e.kind] : void 0;
@@ -1026,10 +1217,34 @@ var Compiler = class {
1026
1217
  thrown
1027
1218
  });
1028
1219
  }
1220
+ /**
1221
+ * This method compiles an address. Its function gives the key where the address points. The expressions of the
1222
+ * computed moves evaluate first, at the position of the node, and their child indexes start at `first`. An error of
1223
+ * an expression keeps its path, and an error of a move gets the path of the node.
1224
+ */
1225
+ #address(at, path, first) {
1226
+ const nodes = addrExprs(at).map((x, i) => this.node(x, [...path, first + i]));
1227
+ const moved = (r) => r.ok ? r : fail({
1228
+ ...r.error,
1229
+ path
1230
+ });
1231
+ if (nodes.length === 0) return (f, c) => moved(resolveAddr(c.space, f.pos, at));
1232
+ return (f, c) => {
1233
+ const values = [];
1234
+ for (const n of nodes) {
1235
+ const r = n(f, c);
1236
+ if (!r.ok) return r;
1237
+ values.push(r.value);
1238
+ }
1239
+ const fixed = fixAddr(at, values, f.pos);
1240
+ return fixed.ok ? moved(resolveAddr(c.space, f.pos, fixed.value)) : moved(fixed);
1241
+ };
1242
+ }
1029
1243
  #ref(e, info) {
1030
1244
  const { path } = info;
1031
1245
  const segs = e.path;
1032
1246
  const at = e.at ?? [];
1247
+ const address = this.#address(at, path, 0);
1033
1248
  const label = segs.join(".");
1034
1249
  const steps = segs.map((seg, i) => ({
1035
1250
  seg,
@@ -1039,11 +1254,8 @@ var Compiler = class {
1039
1254
  return (f, c) => {
1040
1255
  let key = f.pos.focus;
1041
1256
  if (at.length > 0) {
1042
- const where = resolveAddr(c.space, f.pos, at);
1043
- if (!where.ok) return this.#emit(c, info, f, fail({
1044
- ...where.error,
1045
- path
1046
- }));
1257
+ const where = address(f, c);
1258
+ if (!where.ok) return this.#emit(c, info, f, where);
1047
1259
  key = where.value;
1048
1260
  }
1049
1261
  const failed = (r) => this.#emit(c, info, f, r, [{
@@ -1089,16 +1301,15 @@ var Compiler = class {
1089
1301
  #each(e, info) {
1090
1302
  const { path } = info;
1091
1303
  const at = e.at ?? [];
1092
- const targets = this.#targets(e.axis, path, { next: 1 });
1304
+ const counter = { next: 1 };
1305
+ const targets = this.#targets(e.axis, path, counter);
1093
1306
  const body = this.node(e.body, [...path, 0]);
1307
+ const address = this.#address(at, path, counter.next);
1094
1308
  return (f, c) => {
1095
1309
  let from = f;
1096
1310
  if (at.length > 0) {
1097
- const where = resolveAddr(c.space, f.pos, at);
1098
- if (!where.ok) return this.#emit(c, info, f, fail({
1099
- ...where.error,
1100
- path
1101
- }));
1311
+ const where = address(f, c);
1312
+ if (!where.ok) return this.#emit(c, info, f, where);
1102
1313
  from = {
1103
1314
  pos: {
1104
1315
  origin: f.pos.origin,
@@ -1138,6 +1349,135 @@ var Compiler = class {
1138
1349
  return this.#emit(c, info, f, ok(vexList(items)));
1139
1350
  };
1140
1351
  }
1352
+ /**
1353
+ * This method compiles the names of a loop: `init` at the indexes from 0, and `step` after them (LOOP.NAMES). Its
1354
+ * functions give the first values, and the values after one step. The first error stops each of them.
1355
+ */
1356
+ #names(e, path) {
1357
+ const inits = Object.entries(e.init).map(([name, x], i) => [name, this.node(x, [...path, i])]);
1358
+ const steps = Object.entries(e.step).map(([name, x], i) => [name, this.node(x, [...path, inits.length + i])]);
1359
+ return {
1360
+ first: (f, c) => {
1361
+ const env = new Map(f.env);
1362
+ for (const [name, n] of inits) {
1363
+ const r = n(f, c);
1364
+ if (!r.ok) return r;
1365
+ env.set(name, r);
1366
+ }
1367
+ return ok(env);
1368
+ },
1369
+ next: (f, c) => {
1370
+ const values = [];
1371
+ for (const [name, n] of steps) {
1372
+ const r = n(f, c);
1373
+ if (!r.ok) return r;
1374
+ values.push([name, r]);
1375
+ }
1376
+ const env = new Map(f.env);
1377
+ for (const [name, r] of values) env.set(name, r);
1378
+ return ok(env);
1379
+ }
1380
+ };
1381
+ }
1382
+ /**
1383
+ * This method compiles a fold (FOLD.ORDER, FOLD.ERROR). `init` evaluates at the node, then the address and the
1384
+ * targets. A step evaluates at each target in order. `result` evaluates at the node with the last values.
1385
+ */
1386
+ #fold(e, info) {
1387
+ const { path } = info;
1388
+ const at = e.at ?? [];
1389
+ const names = this.#names(e, path);
1390
+ const counter = { next: Object.keys(e.init).length + Object.keys(e.step).length };
1391
+ const targets = this.#targets(e.axis, path, counter);
1392
+ const address = this.#address(at, path, counter.next);
1393
+ const result = this.node(e.result, [...path, counter.next + addrExprs(at).length]);
1394
+ const base = baseAxis(e.axis);
1395
+ return (f, c) => {
1396
+ const first = names.first(f, c);
1397
+ if (!first.ok) return this.#emit(c, info, f, first);
1398
+ let env = first.value;
1399
+ let from = f;
1400
+ if (at.length > 0) {
1401
+ const where = address(f, c);
1402
+ if (!where.ok) return this.#emit(c, info, f, where);
1403
+ from = {
1404
+ pos: {
1405
+ origin: f.pos.origin,
1406
+ focus: where.value
1407
+ },
1408
+ env: f.env
1409
+ };
1410
+ }
1411
+ let inner = c;
1412
+ if (base.t === "table") {
1413
+ const space = c.tables !== void 0 && Object.hasOwn(c.tables, base.name) ? c.tables[base.name] : void 0;
1414
+ if (space === void 0) return this.#emit(c, info, f, this.#err("no-table", `the evaluation has no table "${base.name}"`, f, path));
1415
+ inner = {
1416
+ ...c,
1417
+ space
1418
+ };
1419
+ }
1420
+ const ts = targets(from, inner);
1421
+ if (!ts.ok) return this.#emit(c, info, f, ts);
1422
+ for (const { key, test } of ts.value) {
1423
+ if (test !== void 0 && !test.ok) return this.#emit(c, info, f, test);
1424
+ const after = names.next({
1425
+ pos: {
1426
+ origin: base.t === "table" ? key : f.pos.origin,
1427
+ focus: key
1428
+ },
1429
+ env
1430
+ }, inner);
1431
+ if (!after.ok) return this.#emit(c, info, f, after);
1432
+ env = after.value;
1433
+ }
1434
+ return this.#emit(c, info, f, result({
1435
+ pos: f.pos,
1436
+ env
1437
+ }, c));
1438
+ };
1439
+ }
1440
+ /**
1441
+ * This method compiles an iteration (ITERATE.LIMIT, ITERATE.UNTIL, ITERATE.ERROR). The test `until` evaluates before
1442
+ * each step and after the last step. `result` evaluates with the last values.
1443
+ */
1444
+ #iterate(e, info) {
1445
+ const { path } = info;
1446
+ const names = this.#names(e, path);
1447
+ const untilAt = Object.keys(e.init).length + Object.keys(e.step).length;
1448
+ const untilPath = [...path, untilAt];
1449
+ const until = e.until === void 0 ? void 0 : this.node(e.until, untilPath);
1450
+ const result = this.node(e.result, [...path, untilAt + (until === void 0 ? 0 : 1)]);
1451
+ const { limit } = e;
1452
+ return (f, c) => {
1453
+ const first = names.first(f, c);
1454
+ if (!first.ok) return this.#emit(c, info, f, first);
1455
+ let env = first.value;
1456
+ for (let k = 0;; k++) {
1457
+ const frame = {
1458
+ pos: f.pos,
1459
+ env
1460
+ };
1461
+ if (until !== void 0) {
1462
+ const t = until(frame, c);
1463
+ if (!t.ok) return this.#emit(c, info, f, t);
1464
+ if (t.value === true) break;
1465
+ if (t.value !== false) return this.#emit(c, info, f, this.#err("kind-mismatch", `the test "until" of "iterate" gave a ${typeof t.value}, not a boolean`, f, untilPath));
1466
+ }
1467
+ if (k === limit) {
1468
+ if (until !== void 0) return this.#emit(c, info, f, this.#err("limit", `"iterate" made its ${String(limit)} steps, and its test "until" is not true`, f, path));
1469
+ break;
1470
+ }
1471
+ const after = names.next(frame, c);
1472
+ if (!after.ok) return this.#emit(c, info, f, after);
1473
+ env = after.value;
1474
+ }
1475
+ return this.#emit(c, info, f, result({
1476
+ pos: f.pos,
1477
+ env
1478
+ }, c));
1479
+ };
1480
+ }
1141
1481
  /** This method compiles the targets of an axis. For `where`, a failed test keeps the target with its error. */
1142
1482
  #targets(a, path, counter) {
1143
1483
  if (a.t === "table") return (_f, c) => ok(c.space.keys.map((key) => ({ key })));
@@ -1371,6 +1711,7 @@ const FORBIDDEN_FIELDS = /* @__PURE__ */ new Set([
1371
1711
  "constructor",
1372
1712
  "prototype"
1373
1713
  ]);
1714
+ /** This function tells if a segment of a path can name a field. A compiler uses the same rule as the interpreter. */
1374
1715
  const isFieldName = (seg) => seg.length > 0 && !FORBIDDEN_FIELDS.has(seg);
1375
1716
  /** This function runs the `is` test of a domain. A test that throws counts as `false`. */
1376
1717
  function safeIs(d, value) {
@@ -1380,6 +1721,7 @@ function safeIs(d, value) {
1380
1721
  return false;
1381
1722
  }
1382
1723
  }
1724
+ /** This function tells if an argument has the kind of a parameter of an op of the domain `domain`. */
1383
1725
  function matchesKind(kind, value, domain) {
1384
1726
  switch (kind) {
1385
1727
  case "domain": return safeIs(domain, value);
@@ -1409,15 +1751,17 @@ function labelOf(e) {
1409
1751
  case "let": return `let ${Object.keys(e.bind).join(", ")}`;
1410
1752
  case "var": return e.name;
1411
1753
  case "rec": return `{ ${Object.keys(e.fields).join(", ")} }`;
1412
- case "each": return e.at === void 0 ? `each ${e.axis.t}` : `each ${e.axis.t} from ${e.at.map(moveText).join(".")}`;
1754
+ case "each":
1755
+ case "fold": return e.at === void 0 ? `${e.tag} ${e.axis.t}` : `${e.tag} ${e.axis.t} from ${e.at.map(moveText).join(".")}`;
1756
+ case "iterate": return `iterate ${String(e.limit)}`;
1413
1757
  case "ext": return e.kind;
1414
1758
  }
1415
1759
  }
1416
1760
  /** This function gives a short text for a move, for the label of an axis with an address. */
1417
1761
  function moveText(m) {
1418
1762
  switch (m.t) {
1419
- case "key": return `key(${m.key})`;
1420
- case "index": return `index(${m.i})`;
1763
+ case "key": return `key(${typeof m.key === "string" ? m.key : labelOf(m.key)})`;
1764
+ case "index": return `index(${typeof m.i === "number" ? String(m.i) : labelOf(m.i)})`;
1421
1765
  case "offset": return `offset(${m.d.join(", ")})`;
1422
1766
  case "other":
1423
1767
  case "origin":
@@ -1465,7 +1809,8 @@ const sizeOf = (e) => 1 + children(e).reduce((s, c) => s + sizeOf(c), 0);
1465
1809
  //#region src/deps.ts
1466
1810
  /**
1467
1811
  * This function gives the static reads of an expression. A host can use them to recompute a program only
1468
- * when a field that it reads changes.
1812
+ * when a field that it reads changes. A computed move reads a key that only a run knows. Its address keeps the
1813
+ * expression, and the reads of that expression are in the list too (NAV.COMPUTED).
1469
1814
  */
1470
1815
  function deps(e) {
1471
1816
  const out = [];
@@ -1476,21 +1821,25 @@ function deps(e) {
1476
1821
  }];
1477
1822
  for (let item = todo.pop(); item !== void 0; item = todo.pop()) {
1478
1823
  const { x } = item;
1479
- if (x.tag === "ref") {
1480
- out.push({
1481
- at: x.at ?? [],
1482
- path: x.path,
1483
- axes: item.axes,
1484
- axisAt: item.axisAt
1485
- });
1486
- continue;
1487
- }
1488
- const axes = x.tag === "each" ? [...item.axes, x.axis.t] : item.axes;
1489
- const axisAt = x.tag === "each" ? [...item.axisAt, x.at ?? []] : item.axisAt;
1490
- for (const child of children(x).toReversed()) todo.push({
1491
- x: child,
1824
+ if (x.tag === "ref") out.push({
1825
+ at: x.at ?? [],
1826
+ path: x.path,
1827
+ axes: item.axes,
1828
+ axisAt: item.axisAt
1829
+ });
1830
+ const all = children(x);
1831
+ const axial = x.tag === "each" || x.tag === "fold";
1832
+ const first = x.tag === "fold" ? Object.keys(x.init).length : 0;
1833
+ const last = axial ? all.length - addrExprs(x.at).length - (x.tag === "fold" ? 1 : 0) : 0;
1834
+ const axes = axial ? [...item.axes, x.axis.t] : item.axes;
1835
+ const axisAt = axial ? [...item.axisAt, x.at ?? []] : item.axisAt;
1836
+ for (let i = all.length - 1; i >= 0; i--) todo.push(i >= first && i < last ? {
1837
+ x: all[i],
1492
1838
  axes,
1493
1839
  axisAt
1840
+ } : {
1841
+ ...item,
1842
+ x: all[i]
1494
1843
  });
1495
1844
  }
1496
1845
  return out;
@@ -1612,6 +1961,25 @@ function mapValues(u, f) {
1612
1961
  out[key] = rec;
1613
1962
  }
1614
1963
  };
1964
+ const address = () => {
1965
+ const at = u["at"];
1966
+ if (!Array.isArray(at)) return void 0;
1967
+ const moves = [];
1968
+ for (const m of at) {
1969
+ const field = isRecord(m) ? m["t"] === "key" ? "key" : m["t"] === "index" ? "i" : void 0 : void 0;
1970
+ if (field === void 0 || !isRecord(m) || !isRecord(m[field])) {
1971
+ moves.push(m);
1972
+ continue;
1973
+ }
1974
+ const r = mapValues(m[field], f);
1975
+ if (!r.ok) return r;
1976
+ moves.push({
1977
+ ...m,
1978
+ [field]: r.value
1979
+ });
1980
+ }
1981
+ out["at"] = moves;
1982
+ };
1615
1983
  const axis = (a) => {
1616
1984
  if (!isRecord(a) || a["t"] !== "where") return ok(a);
1617
1985
  const inner = axis(a["axis"]);
@@ -1638,8 +2006,16 @@ function mapValues(u, f) {
1638
2006
  const a = axis(u["axis"]);
1639
2007
  if (!a.ok) return a;
1640
2008
  out["axis"] = a.value;
1641
- return child("body") ?? ok(out);
2009
+ return child("body") ?? address() ?? ok(out);
2010
+ }
2011
+ case "fold": {
2012
+ const a = axis(u["axis"]);
2013
+ if (!a.ok) return a;
2014
+ out["axis"] = a.value;
2015
+ return each("init") ?? each("step") ?? child("result") ?? address() ?? ok(out);
1642
2016
  }
2017
+ case "iterate": return each("init") ?? each("step") ?? (u["until"] === void 0 ? void 0 : child("until")) ?? child("result") ?? ok(out);
2018
+ case "ref": return address() ?? ok(out);
1643
2019
  default: return ok(out);
1644
2020
  }
1645
2021
  }
@@ -1776,7 +2152,14 @@ const cell = (column, at = []) => ext(CELL_KIND, {
1776
2152
  column,
1777
2153
  at
1778
2154
  });
1779
- const isCellRef = (u) => typeof u === "object" && u !== null && typeof u.column === "string" && Array.isArray(u.at) && u.at.every(isMove);
2155
+ 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);
2156
+ /**
2157
+ * The compiled programs of the formulas of the columns: one entry for each formula, for the last compiler and options.
2158
+ * A compiled program reads the cells of the active run, so each run with the same compiler and options can use it.
2159
+ */
2160
+ const PROGRAMS = /* @__PURE__ */ new WeakMap();
2161
+ /** The key of the options without extensions, for the extensions of the compiled programs. */
2162
+ const NO_EXTENSIONS = {};
1780
2163
  const cycleError = (column, key) => fail(vexError("cycle", `the cell "${column}" at "${key}" is on a cycle of cell references`, {
1781
2164
  origin: key,
1782
2165
  focus: key
@@ -1791,8 +2174,113 @@ const tableState = (where, i, t) => ({
1791
2174
  columns: t.columns,
1792
2175
  cells: t.cells ?? /* @__PURE__ */ new Map(),
1793
2176
  warmed: /* @__PURE__ */ new Map(),
1794
- index: void 0
2177
+ index: void 0,
2178
+ done: /* @__PURE__ */ new Map()
1795
2179
  });
2180
+ /** This function gives the result of a finished cell, or `undefined`. */
2181
+ const doneOf = (t, column, key) => t.done.get(column)?.get(key);
2182
+ /** This function keeps the result of a finished cell. */
2183
+ function setDone(t, column, key, result) {
2184
+ let results = t.done.get(column);
2185
+ if (results === void 0) {
2186
+ results = /* @__PURE__ */ new Map();
2187
+ t.done.set(column, results);
2188
+ }
2189
+ results.set(key, result);
2190
+ }
2191
+ /** This function adds the direction of one move or one axis of a read of a column from itself. */
2192
+ function addDirection(d, m) {
2193
+ if (m.t === "offset" || m.t === "window") {
2194
+ const steps = m.t === "offset" ? [m.d.find((x) => x !== 0) ?? 0] : [m.from, m.to];
2195
+ if (steps.some((x) => x < 0)) d.add("before");
2196
+ if (steps.some((x) => x > 0)) d.add("after");
2197
+ } else if (m.t === "children" || m.t === "descendants") d.add("down");
2198
+ }
2199
+ /** This function gives the base axis of an axis, and the tests of its `where` axes. */
2200
+ function partsOf(axis) {
2201
+ const tests = [];
2202
+ let base = axis;
2203
+ while (base.t === "where") {
2204
+ tests.push(base.test);
2205
+ base = base.axis;
2206
+ }
2207
+ return {
2208
+ base,
2209
+ tests
2210
+ };
2211
+ }
2212
+ /**
2213
+ * This function gives the columns that the formulas of the column `self` read with a cell reference: its formula and
2214
+ * the formulas of its cells. It also gives the directions of their reads of the column itself. A read in the body or
2215
+ * in a test of an axis also has the direction of that axis. It walks each expression with a stack, not with recursion.
2216
+ */
2217
+ function readsOf(t, self) {
2218
+ const columns = /* @__PURE__ */ new Set();
2219
+ const directions = /* @__PURE__ */ new Set();
2220
+ const formula = t.columns.get(self);
2221
+ const todo = [...formula === void 0 ? [] : [formula], ...t.cells.get(self)?.values() ?? []].filter((e) => shapeError(e) === void 0).map((e) => [e, void 0]);
2222
+ for (let item = todo.pop(); item !== void 0; item = todo.pop()) {
2223
+ const [e, axis] = item;
2224
+ if (e.tag === "each" || e.tag === "fold") {
2225
+ const { base, tests } = partsOf(e.axis);
2226
+ for (const x of [...e.tag === "each" ? [e.body] : Object.values(e.step), ...tests]) todo.push([x, base]);
2227
+ for (const x of [...e.tag === "fold" ? [...Object.values(e.init), e.result] : [], ...addrExprs(e.at)]) todo.push([x, axis]);
2228
+ } else if (e.tag !== "ext") for (const child of children(e)) todo.push([child, axis]);
2229
+ else if (e.kind === "vex.cell" && isCellRef(e.data)) {
2230
+ columns.add(e.data.column);
2231
+ if (e.data.column === self) for (const m of [...axis === void 0 ? [] : [axis], ...e.data.at]) addDirection(directions, m);
2232
+ }
2233
+ }
2234
+ return {
2235
+ columns,
2236
+ directions
2237
+ };
2238
+ }
2239
+ /**
2240
+ * This function gives the columns of a table in an order where each column comes after the columns that it reads.
2241
+ * The columns of a cycle keep their order. The columns with formulas of cells only come last.
2242
+ */
2243
+ function columnOrder(t) {
2244
+ const names = /* @__PURE__ */ new Set([...t.columns.keys(), ...t.cells.keys()]);
2245
+ let left = [...names].map((c) => ({
2246
+ c,
2247
+ needs: [...readsOf(t, c).columns].filter((x) => x !== c && names.has(x))
2248
+ }));
2249
+ const order = [];
2250
+ const placed = /* @__PURE__ */ new Set();
2251
+ while (left.length > 0) {
2252
+ const ready = left.filter((x) => x.needs.every((n) => placed.has(n)));
2253
+ for (const x of ready.length > 0 ? ready : left.slice(0, 1)) {
2254
+ order.push(x.c);
2255
+ placed.add(x.c);
2256
+ }
2257
+ left = left.filter((x) => !placed.has(x.c));
2258
+ }
2259
+ return order;
2260
+ }
2261
+ /**
2262
+ * This function gives the keys of a space in the order of the reads of a column from itself. A read of a later key
2263
+ * reverses the order. In a tree, a read of the children puts the children before their parent.
2264
+ */
2265
+ function keyOrder(s, d) {
2266
+ const reverse = d.has("after") && !d.has("before");
2267
+ const childrenOf = s.childrenOf?.bind(s);
2268
+ if (childrenOf === void 0) return reverse ? s.keys.toReversed() : s.keys;
2269
+ const post = d.has("down");
2270
+ const backwards = post !== reverse;
2271
+ const push = (stack, keys) => {
2272
+ for (const k of backwards ? keys : keys.toReversed()) stack.push(k);
2273
+ };
2274
+ const isChild = new Set(s.keys.flatMap((k) => childrenOf(k)));
2275
+ const stack = [];
2276
+ push(stack, s.keys.filter((k) => !isChild.has(k)));
2277
+ const out = [];
2278
+ for (let k = stack.pop(); k !== void 0; k = stack.pop()) {
2279
+ out.push(k);
2280
+ push(stack, childrenOf(k));
2281
+ }
2282
+ return post ? out.toReversed() : out;
2283
+ }
1796
2284
  /**
1797
2285
  * The budget of the stack for the recursion of a run, in estimated frames. Each engine has more stack than this, so
1798
2286
  * the recursion of a run cannot fill the stack (SHEET.DEEP).
@@ -1816,22 +2304,27 @@ const STACK_BUDGET = 3e3;
1816
2304
  * A run can have more tables (SHEET.TABLES). Each table has its own space, and one search covers the cells of all
1817
2305
  * the tables. Thus a cycle across tables gives `#CYCLE!` too.
1818
2306
  */
1819
- var SheetRun = class {
2307
+ var SheetRun = class SheetRun {
1820
2308
  #main;
1821
2309
  #byName = /* @__PURE__ */ new Map();
1822
2310
  #bySpace = /* @__PURE__ */ new Map();
1823
2311
  #opts;
1824
- #done = /* @__PURE__ */ new Map();
1825
2312
  #visits = /* @__PURE__ */ new Map();
1826
2313
  #stack = [];
1827
2314
  #top;
2315
+ #filling;
2316
+ #missed = false;
1828
2317
  #next = 0;
1829
2318
  #used = 0;
1830
2319
  #cost = /* @__PURE__ */ new Map();
1831
2320
  #budget;
2321
+ #compile;
2322
+ #compileOptions;
2323
+ static #active;
2324
+ static #shared = /* @__PURE__ */ new WeakMap();
1832
2325
  /** `budget` is the budget of the stack in estimated frames. A test can make it small, so the run pauses often. */
1833
2326
  constructor(columns, opts, budget = STACK_BUDGET) {
1834
- const { cells, name, tables, space, ...rest } = opts;
2327
+ const { cells, name, tables, space, compile, ...rest } = opts;
1835
2328
  this.#main = {
1836
2329
  where: "the sheet",
1837
2330
  tag: "0",
@@ -1839,7 +2332,8 @@ var SheetRun = class {
1839
2332
  columns,
1840
2333
  cells: cells ?? /* @__PURE__ */ new Map(),
1841
2334
  warmed: /* @__PURE__ */ new Map(),
1842
- index: void 0
2335
+ index: void 0,
2336
+ done: /* @__PURE__ */ new Map()
1843
2337
  };
1844
2338
  this.#bySpace.set(space, this.#main);
1845
2339
  if (name !== void 0) this.#byName.set(name, this.#main);
@@ -1864,7 +2358,20 @@ var SheetRun = class {
1864
2358
  paused: false,
1865
2359
  need: void 0
1866
2360
  };
2361
+ this.#filling = {
2362
+ id: "",
2363
+ table: this.#main,
2364
+ column: "",
2365
+ key: "",
2366
+ index: 0,
2367
+ low: 0,
2368
+ reread: false,
2369
+ result: cycleError("", ""),
2370
+ paused: false,
2371
+ need: void 0
2372
+ };
1867
2373
  this.#budget = budget;
2374
+ this.#compile = compile;
1868
2375
  const spaces = Object.fromEntries([...this.#byName].map(([n, t]) => [n, t.space]));
1869
2376
  this.#opts = {
1870
2377
  ...rest,
@@ -1874,7 +2381,25 @@ var SheetRun = class {
1874
2381
  [CELL_KIND]: this.#handler
1875
2382
  }
1876
2383
  };
2384
+ const outer = rest.extensions ?? NO_EXTENSIONS;
2385
+ let shared = SheetRun.#shared.get(outer);
2386
+ if (shared === void 0) {
2387
+ shared = {
2388
+ ...rest.extensions,
2389
+ [CELL_KIND]: SheetRun.#cellOfActive
2390
+ };
2391
+ SheetRun.#shared.set(outer, shared);
2392
+ }
2393
+ this.#compileOptions = {
2394
+ ...this.#opts,
2395
+ extensions: shared
2396
+ };
1877
2397
  }
2398
+ /** The cell handler of the compiled programs: it reads the cells of the active run. */
2399
+ static #cellOfActive = (data, ctx) => {
2400
+ const run = SheetRun.#active;
2401
+ return run === void 0 ? fail(vexError("unbound", "a compiled formula reads cells only in the evaluation of a sheet run")) : run.#handler(data, ctx);
2402
+ };
1878
2403
  /** This method gives the program of a cell: its own formula, or the formula of its column (SHEET.CELL.FORMULA). */
1879
2404
  #programOf(t, column, key) {
1880
2405
  return (t.cells.size === 0 ? void 0 : t.cells.get(column)?.get(key)) ?? t.columns.get(column);
@@ -1896,7 +2421,7 @@ var SheetRun = class {
1896
2421
  }));
1897
2422
  }
1898
2423
  #handler = (data, ctx) => {
1899
- if (!isCellRef(data)) return fail(vexError("bad-expression", "a cell reference needs a column name and an address", { path: ctx.path }));
2424
+ if (!isCellRef(data)) return fail(vexError("bad-expression", "a cell reference needs a column name and an address of fixed moves"));
1900
2425
  const where = resolveAddr(ctx.space, ctx.position, data.at);
1901
2426
  if (!where.ok) return fail({
1902
2427
  ...where.error,
@@ -1914,6 +2439,8 @@ var SheetRun = class {
1914
2439
  const t = this.#named(table, key);
1915
2440
  if (!("space" in t)) return t;
1916
2441
  if (this.#top.index >= 0) return this.#read(t, column, key);
2442
+ const done = doneOf(t, column, key);
2443
+ if (done !== void 0) return done;
1917
2444
  this.#warmTo(t, column, key);
1918
2445
  return this.#drive(t, column, key);
1919
2446
  }
@@ -1931,7 +2458,7 @@ var SheetRun = class {
1931
2458
  #costOf(program) {
1932
2459
  let cost = this.#cost.get(program);
1933
2460
  if (cost === void 0) {
1934
- cost = 3 * nestingOf(program) + 16;
2461
+ cost = 3 * (shapeError(program) === void 0 ? nestingOf(program) : 1) + 16;
1935
2462
  this.#cost.set(program, cost);
1936
2463
  }
1937
2464
  return cost;
@@ -1963,15 +2490,46 @@ var SheetRun = class {
1963
2490
  visit.need = void 0;
1964
2491
  this.#top = visit;
1965
2492
  this.#used += cost;
1966
- const result = evaluate(program, {
1967
- ...this.#opts,
1968
- space: visit.table.space,
1969
- origin: visit.key
1970
- });
2493
+ const result = this.#run(visit.table, visit.column, visit.key, program);
1971
2494
  this.#used -= cost;
1972
2495
  this.#top = caller;
1973
2496
  if (!visit.paused) visit.result = result;
1974
2497
  }
2498
+ /** This method evaluates the formula `program` of a cell, with its compiled program or with the interpreter. */
2499
+ #run(t, column, key, program) {
2500
+ const options = {
2501
+ ...this.#opts,
2502
+ space: t.space,
2503
+ origin: key
2504
+ };
2505
+ const compiled = this.#compiled(t, column, program);
2506
+ if (compiled === void 0) return evaluate(program, options);
2507
+ const active = SheetRun.#active;
2508
+ SheetRun.#active = this;
2509
+ const result = compiled.run(options);
2510
+ SheetRun.#active = active;
2511
+ return result;
2512
+ }
2513
+ /**
2514
+ * This method gives the compiled program of the formula of a column, or `undefined` for the interpreter. A formula
2515
+ * compiles once for each compiler and options, also across runs.
2516
+ */
2517
+ #compiled(t, column, program) {
2518
+ const compile = this.#compile;
2519
+ if (compile === void 0 || t.columns.get(column) !== program) return void 0;
2520
+ const { domains, fns, extensions } = this.#compileOptions;
2521
+ const hit = PROGRAMS.get(program);
2522
+ if (hit !== void 0 && hit.compile === compile && hit.domains === domains && hit.fns === fns && hit.extensions === extensions) return hit.program;
2523
+ const compiled = compile(program, this.#compileOptions);
2524
+ PROGRAMS.set(program, {
2525
+ compile,
2526
+ domains,
2527
+ fns,
2528
+ extensions,
2529
+ program: compiled
2530
+ });
2531
+ return compiled;
2532
+ }
1975
2533
  /** This method ends a cell whose evaluation did not pause: it finishes its component, or it gives its low to the caller. */
1976
2534
  #end(visit, caller) {
1977
2535
  if (visit.low === visit.index) this.#finish(visit);
@@ -1979,11 +2537,15 @@ var SheetRun = class {
1979
2537
  }
1980
2538
  /** This method reads a cell from the formula of the cell at the top. */
1981
2539
  #read(t, column, key) {
1982
- const id = idOf(t, column, key);
1983
- const done = this.#done.get(id);
2540
+ const done = doneOf(t, column, key);
1984
2541
  if (done !== void 0) return done;
1985
2542
  const caller = this.#top;
1986
2543
  if (caller.paused) return cycleError(column, key);
2544
+ if (caller === this.#filling) {
2545
+ this.#missed = true;
2546
+ return cycleError(column, key);
2547
+ }
2548
+ const id = idOf(t, column, key);
1987
2549
  const seen = this.#visits.get(id);
1988
2550
  if (seen !== void 0) {
1989
2551
  caller.low = Math.min(caller.low, seen.index);
@@ -2005,12 +2567,11 @@ var SheetRun = class {
2005
2567
  return cycleError(column, key);
2006
2568
  }
2007
2569
  this.#end(visit, caller);
2008
- return this.#done.get(id) ?? cycleError(column, key);
2570
+ return doneOf(t, column, key) ?? cycleError(column, key);
2009
2571
  }
2010
2572
  /** This method evaluates a cell from the top level. The cells that pause go on a list, not on the call stack. */
2011
2573
  #drive(t, column, key) {
2012
- const id = idOf(t, column, key);
2013
- const done = this.#done.get(id);
2574
+ const done = doneOf(t, column, key);
2014
2575
  if (done !== void 0) return done;
2015
2576
  if (this.#programOf(t, column, key) === void 0) return this.#unbound(t, column, key);
2016
2577
  const work = [this.#start(t, column, key)];
@@ -2026,7 +2587,7 @@ var SheetRun = class {
2026
2587
  work.pop();
2027
2588
  this.#end(visit, work.at(-1));
2028
2589
  }
2029
- return this.#done.get(id) ?? cycleError(column, key);
2590
+ return doneOf(t, column, key) ?? cycleError(column, key);
2030
2591
  }
2031
2592
  /** This method takes the component of `root` from the stack, and sets the final result of each of its cells. */
2032
2593
  #finish(root) {
@@ -2034,7 +2595,7 @@ var SheetRun = class {
2034
2595
  const cyclic = members.length > 1 || root.reread;
2035
2596
  for (const m of members) {
2036
2597
  this.#visits.delete(m.id);
2037
- this.#done.set(m.id, cyclic ? cycleError(m.column, m.key) : m.result);
2598
+ setDone(m.table, m.column, m.key, cyclic ? cycleError(m.column, m.key) : m.result);
2038
2599
  }
2039
2600
  }
2040
2601
  /** This method evaluates one cell with a trace of the nodes of its program. The result is the result of the cell. */
@@ -2056,6 +2617,27 @@ var SheetRun = class {
2056
2617
  };
2057
2618
  }
2058
2619
  /**
2620
+ * This method evaluates each cell of the table `table`, or of the main table (SHEET.FILL). Each column comes after
2621
+ * the columns that it reads, and the keys of a column come in the order of its reads from itself. Thus most reads
2622
+ * find a finished cell. An evaluation that reads a cell that is not finished has no effect, and the search then
2623
+ * evaluates its cell. A read of a cell gives the same result after a fill.
2624
+ */
2625
+ fill(table) {
2626
+ const t = table === void 0 ? this.#main : this.#byName.get(table);
2627
+ if (t === void 0 || this.#top.index >= 0) return;
2628
+ const host = this.#top;
2629
+ for (const column of columnOrder(t)) for (const key of keyOrder(t.space, readsOf(t, column).directions)) {
2630
+ const program = this.#programOf(t, column, key);
2631
+ if (program === void 0 || doneOf(t, column, key) !== void 0) continue;
2632
+ this.#top = this.#filling;
2633
+ this.#missed = false;
2634
+ const result = this.#run(t, column, key, program);
2635
+ this.#top = host;
2636
+ if (this.#missed) this.#drive(t, column, key);
2637
+ else setDone(t, column, key, result);
2638
+ }
2639
+ }
2640
+ /**
2059
2641
  * This method evaluates the column `column` at each key before `key`, in key order. A recurrence over the keys,
2060
2642
  * for example a running total, then reads finished cells.
2061
2643
  */
@@ -2085,6 +2667,16 @@ function toExpr(a, addr) {
2085
2667
  if (isChainLike(a)) return a.program;
2086
2668
  return lit(a);
2087
2669
  }
2670
+ /** This function gives the expressions of a step of a loop, with the unique names of the loop. */
2671
+ function stepExprs(step, unique, addr) {
2672
+ const out = {};
2673
+ for (const [n, a] of Object.entries(step)) {
2674
+ const name = unique.get(n);
2675
+ if (name === void 0) throw new TypeError(`the name "${n}" of the step is not a name of init`);
2676
+ out[name] = toExpr(a, addr);
2677
+ }
2678
+ return out;
2679
+ }
2088
2680
  const PROXY_RESERVED = /* @__PURE__ */ new Set([
2089
2681
  "then",
2090
2682
  "catch",
@@ -2152,10 +2744,10 @@ var ChainImpl = class ChainImpl {
2152
2744
  });
2153
2745
  }
2154
2746
  to(k) {
2155
- return this.#move(key(k));
2747
+ return this.#move(key(typeof k === "string" ? k : k.program));
2156
2748
  }
2157
2749
  index(i) {
2158
- return this.#move(index(i));
2750
+ return this.#move(index(typeof i === "number" ? i : i.program));
2159
2751
  }
2160
2752
  offset(...d) {
2161
2753
  return this.#move(offset(...d));
@@ -2226,6 +2818,41 @@ var ChainImpl = class ChainImpl {
2226
2818
  expr: let_(bindExprs, inner.program)
2227
2819
  });
2228
2820
  }
2821
+ /**
2822
+ * This method gives the names of a loop. Each name of `init` gets a name that is unique at the depth of the chain.
2823
+ * It also gets its first value at the address of the chain, and a chain of its value.
2824
+ */
2825
+ loopNames(init) {
2826
+ const depth = this.#s.depth;
2827
+ const unique = /* @__PURE__ */ new Map();
2828
+ const first = {};
2829
+ const vars = {};
2830
+ for (const [n, a] of Object.entries(init)) {
2831
+ const name = `${n}$${depth}`;
2832
+ unique.set(n, name);
2833
+ first[name] = toExpr(a, this.#s.addr);
2834
+ vars[n] = new ChainImpl({
2835
+ ...this.#s,
2836
+ expr: v(name),
2837
+ addr: [],
2838
+ depth: depth + 1
2839
+ });
2840
+ }
2841
+ return {
2842
+ unique,
2843
+ first,
2844
+ vars
2845
+ };
2846
+ }
2847
+ iterate(limit, init, step, result, opts) {
2848
+ const { unique, first, vars } = this.loopNames(init);
2849
+ const next = stepExprs(step(vars), unique, this.#s.addr);
2850
+ const until = opts?.until === void 0 ? void 0 : toExpr(opts.until(vars), this.#s.addr);
2851
+ return new ChainImpl({
2852
+ ...this.#s,
2853
+ expr: iterate(limit, first, next, toExpr(result(vars), this.#s.addr), until)
2854
+ });
2855
+ }
2229
2856
  #axis(a, body, opts) {
2230
2857
  const { name, start } = this.#bound();
2231
2858
  const inTarget = new ChainImpl({
@@ -2310,6 +2937,23 @@ var ListChainImpl = class {
2310
2937
  get program() {
2311
2938
  return this.#s.expr;
2312
2939
  }
2940
+ fold(init, step, result) {
2941
+ const { bind, body: loop } = this.#s.expr;
2942
+ const names = new ChainImpl({
2943
+ ...this.#s,
2944
+ expr: lit(null)
2945
+ }).loopNames(init);
2946
+ const item = new ChainImpl({
2947
+ ...this.#s,
2948
+ expr: loop.body,
2949
+ addr: []
2950
+ });
2951
+ const next = stepExprs(step(names.vars, item), names.unique, []);
2952
+ return new ChainImpl({
2953
+ ...this.#s,
2954
+ expr: let_(bind, fold(loop.axis, names.first, next, toExpr(result(names.vars), this.#s.addr), loop.at))
2955
+ });
2956
+ }
2313
2957
  #op(op, extra, opts) {
2314
2958
  const options = {
2315
2959
  ...opts?.strict === true ? { strict: true } : {},
@@ -2473,6 +3117,7 @@ var SheetImpl = class SheetImpl {
2473
3117
  }
2474
3118
  table() {
2475
3119
  const run = this.#run();
3120
+ run.fill();
2476
3121
  const names = [...this.#columns.keys()];
2477
3122
  return this.#env.space.keys.map((key) => ({
2478
3123
  key,
@@ -2499,6 +3144,6 @@ function vex(...domains) {
2499
3144
  };
2500
3145
  }
2501
3146
  //#endregion
2502
- export { CELL_KIND, LIST_OPS, MAX_NESTING, SPECIAL_FORMS, SheetRun, app, applyMove, axes, axisTargets, cell, chainResult, children, codeOf, compile, defineDomain, deps, describeType, domainOf, each, evaluate, explain, ext, fail, findMethod, formatError, formatTrace, getOr, index, isAxis, isDepthError, isExpr, isListOp, isMove, isNone, isOpName, isSome, isStackOverflow, isVexList, key, labelOf, let_, liftsAt, lit, mapResult, monoids, nestingOf, none, offset, ok, origin, other, parent, parse, previewValue, rec, ref, resolveAddr, resolveOp, serialize, sizeOf, some, space, toOptional, toPath, traversal, v, vex, vexError, vexList };
3147
+ export { CELL_KIND, LIST_OPS, MAX_ITERATIONS, MAX_NESTING, SPECIAL_FORMS, SheetRun, addrExprs, app, applyMove, axes, axisTargets, cell, chainResult, children, codeOf, compile, defineDomain, deps, describeType, domainOf, each, evaluate, explain, ext, fail, findMethod, fixAddr, fold, formatError, formatTrace, getOr, index, isAxis, isDepthError, isExpr, isFieldName, isFixedAddr, isListOp, isMove, isNone, isOpName, isSome, isStackOverflow, isVexList, iterate, key, labelOf, let_, liftsAt, lit, mapResult, matchesKind, monoids, moveExpr, nestingOf, none, offset, ok, origin, other, parent, parse, previewValue, rec, ref, resolveAddr, resolveOp, safeIs, serialize, shapeError, sizeOf, some, space, toOptional, toPath, traversal, v, vex, vexError, vexList };
2503
3148
 
2504
3149
  //# sourceMappingURL=index.js.map