@mark1russell7/vex 0.6.0 → 0.8.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,88 @@ 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
+ }
188
+ /**
189
+ * This function makes a function (FN.BIND): the names of its parameters and its body. A function is only the value of
190
+ * a binding of `let`. The body sees the names of the place of that `let`, so a function cannot call itself.
191
+ */
192
+ const fn = (params, body) => ({
193
+ tag: "fn",
194
+ params,
195
+ body
196
+ });
197
+ /** This function makes a call of a bound function (FN.CALL). The body evaluates at the position of the call. */
198
+ const call = (name, ...args) => ({
199
+ tag: "call",
200
+ fn: name,
201
+ args
202
+ });
145
203
  /** This function makes an expression of an extension kind. */
146
204
  const ext = (kind, data) => ({
147
205
  tag: "ext",
148
206
  kind,
149
207
  data
150
208
  });
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
- });
209
+ function key(k) {
210
+ return {
211
+ t: "key",
212
+ key: k
213
+ };
214
+ }
215
+ function index(i) {
216
+ return {
217
+ t: "index",
218
+ i
219
+ };
220
+ }
221
+ /** This function gives the expression of a move with a computed key or position, or `undefined`. */
222
+ function moveExpr(m) {
223
+ if (m.t === "key") return typeof m.key === "string" ? void 0 : m.key;
224
+ return m.t === "index" && typeof m.i !== "number" ? m.i : void 0;
225
+ }
226
+ /** This function gives the expressions of the computed moves of an address, in the order of the moves. */
227
+ const addrExprs = (at) => (at ?? []).flatMap((m) => moveExpr(m) ?? []);
228
+ /** This function tells if each move of an address is fixed. */
229
+ const isFixedAddr = (at) => addrExprs(at).length === 0;
161
230
  /** The move to the other key of a space with two keys. */
162
231
  const other = Object.freeze({ t: "other" });
163
232
  /** The relative move in an array (one number) or a grid (two numbers). */
@@ -213,6 +282,22 @@ const axes = {
213
282
  predecessors: Object.freeze({ t: "predecessors" }),
214
283
  /** Each key that a path of edges reaches from the focus, in breadth-first order, without the focus. */
215
284
  reachable: Object.freeze({ t: "reachable" }),
285
+ /**
286
+ * The targets of `axis` in the reverse order (AXIS.REVERSE). The inner axis is a base axis: not `where`, `reverse` or
287
+ * `table`. A test goes outside: `where(reverse(axis), test)`.
288
+ */
289
+ reverse: (axis) => ({
290
+ t: "reverse",
291
+ axis
292
+ }),
293
+ /**
294
+ * The keys of the items of the list that `list` gives, in the order of the list (AXIS.LIST). The expression evaluates
295
+ * before the targets. An error item gives an error item for its target.
296
+ */
297
+ list: (list) => ({
298
+ t: "list",
299
+ list
300
+ }),
216
301
  /** The targets of `axis` where `test` gives `true`. */
217
302
  where: (axis, test) => ({
218
303
  t: "where",
@@ -222,39 +307,105 @@ const axes = {
222
307
  };
223
308
  const isObject = (u) => typeof u === "object" && u !== null;
224
309
  const isStringArray = (u) => Array.isArray(u) && u.every((s) => typeof s === "string");
225
- /** This function tells if a value is a valid move. */
310
+ /** This function tells if a value is a valid move. The expression of a computed move must be valid too. */
226
311
  function isMove(u) {
227
- if (!isObject(u)) return false;
312
+ const exprs = moveParts(u);
313
+ return exprs !== void 0 && exprs.every(isExpr);
314
+ }
315
+ const anyNumber = (x) => typeof x === "number";
316
+ /** This function checks the fixed parts of a move. It gives the expressions of the move, or `undefined` for a bad move. */
317
+ function moveParts(u, isNumber = Number.isInteger) {
318
+ if (!isObject(u)) return void 0;
228
319
  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));
320
+ case "key": return typeof u["key"] === "string" ? [] : isObject(u["key"]) ? [u["key"]] : void 0;
321
+ case "index": return isNumber(u["i"]) ? [] : isObject(u["i"]) ? [u["i"]] : void 0;
322
+ case "offset": return Array.isArray(u["d"]) && u["d"].every((n) => isNumber(n)) ? [] : void 0;
232
323
  case "other":
233
324
  case "origin":
234
- case "parent": return true;
235
- default: return false;
325
+ case "parent": return [];
326
+ default: return;
236
327
  }
237
328
  }
238
329
  /** This function tells if a value is a valid axis. It checks the tests of `where` too. */
239
330
  function isAxis(u) {
240
- return validTree([{
331
+ return badPart([{
241
332
  axis: true,
242
333
  u
243
- }]);
334
+ }], true) === void 0;
244
335
  }
245
336
  /** This function tells if a value is a valid expression. It checks the whole tree. */
246
337
  function isExpr(u) {
247
- return validTree([{
338
+ return badPart([{
339
+ axis: false,
340
+ u
341
+ }], true) === void 0;
342
+ }
343
+ /** The tags of the expressions of this version of Vex. */
344
+ const TAGS = /* @__PURE__ */ new Set([
345
+ "lit",
346
+ "ref",
347
+ "app",
348
+ "let",
349
+ "var",
350
+ "rec",
351
+ "each",
352
+ "fold",
353
+ "iterate",
354
+ "fn",
355
+ "call",
356
+ "ext"
357
+ ]);
358
+ /**
359
+ * This function gives the reason that a value is not a valid expression, or `undefined` for a valid expression
360
+ * (EVAL.SHAPE). An expression from a newer version of Vex can have a tag that this version does not know. Unlike
361
+ * `isExpr`, it accepts a number that is not whole in a move or in a window, because it has a meaning at run time.
362
+ */
363
+ function shapeError(u) {
364
+ const bad = badPart([{
248
365
  axis: false,
249
366
  u
250
- }]);
367
+ }], false);
368
+ if (bad === void 0) return void 0;
369
+ const tag = isObject(bad.u) ? bad.u["tag"] : void 0;
370
+ if (bad.axis) return "the expression has an axis that is not valid";
371
+ 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`;
372
+ if (tag === "fn") return "the expression has a function outside the bindings of a let, or a function with parameters that are not distinct names";
373
+ 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
374
  }
252
- const isAddr = (u) => u === void 0 || Array.isArray(u) && u.every(isMove);
253
375
  /**
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).
376
+ * This function checks the names of a loop: `init` and `step` are records, and each name of `step` is a name of `init`.
377
+ * It gives the expressions of `init`, of `step` and `result`, or `undefined` (LOOP.NAMES).
256
378
  */
257
- function validTree(todo) {
379
+ function loopParts(u) {
380
+ const { init, step } = u;
381
+ if (!isObject(init) || Array.isArray(init) || !isObject(step) || Array.isArray(step)) return void 0;
382
+ if (!Object.keys(step).every((n) => Object.hasOwn(init, n))) return void 0;
383
+ return [
384
+ ...Object.values(init),
385
+ ...Object.values(step),
386
+ u["result"]
387
+ ];
388
+ }
389
+ /** This function checks the fixed parts of an address. It gives the expressions of its moves, or `undefined`. */
390
+ function addrParts(u, isNumber) {
391
+ if (u === void 0) return [];
392
+ if (!Array.isArray(u)) return void 0;
393
+ const out = [];
394
+ for (const m of u) {
395
+ const parts = moveParts(m, isNumber);
396
+ if (parts === void 0) return void 0;
397
+ out.push(...parts);
398
+ }
399
+ return out;
400
+ }
401
+ /**
402
+ * This function checks a tree of expressions and axes, and it gives the first part that is not valid. It uses a stack,
403
+ * not recursion, so the input can be deep. For example, a deep JSON file from a stranger does not need a deep call
404
+ * stack (EVAL.NESTING). With `whole`, the numbers of the moves and of the windows must be whole, as the JSON form needs.
405
+ */
406
+ function badPart(todo, whole) {
407
+ const moveNumber = whole ? Number.isInteger : anyNumber;
408
+ const windowNumber = whole ? Number.isSafeInteger : anyNumber;
258
409
  const push = (axis, values) => {
259
410
  for (const u of values) todo.push({
260
411
  axis,
@@ -263,18 +414,27 @@ function validTree(todo) {
263
414
  };
264
415
  for (let item = todo.pop(); item !== void 0; item = todo.pop()) {
265
416
  const { u } = item;
266
- if (!isObject(u)) return false;
417
+ if (!isObject(u)) return item;
267
418
  if (item.axis) {
268
419
  const t = u["t"];
269
420
  if (t === "neighbors") {
270
- if (u["n"] !== 4 && u["n"] !== 8) return false;
421
+ if (u["n"] !== 4 && u["n"] !== 8) return item;
271
422
  } else if (t === "window") {
272
- if (!Number.isSafeInteger(u["from"]) || !Number.isSafeInteger(u["to"])) return false;
423
+ if (!windowNumber(u["from"]) || !windowNumber(u["to"])) return item;
273
424
  } else if (t === "table") {
274
- if (typeof u["name"] !== "string") return false;
425
+ if (typeof u["name"] !== "string") return item;
275
426
  } else if (t === "where") {
276
427
  push(true, [u["axis"]]);
277
428
  push(false, [u["test"]]);
429
+ } else if (t === "list") push(false, [u["list"]]);
430
+ else if (t === "reverse") {
431
+ const inner = u["axis"];
432
+ if (!isObject(inner) || [
433
+ "where",
434
+ "reverse",
435
+ "table"
436
+ ].includes(inner["t"])) return item;
437
+ push(true, [inner]);
278
438
  } else if (![
279
439
  "all",
280
440
  "others",
@@ -286,72 +446,130 @@ function validTree(todo) {
286
446
  "successors",
287
447
  "predecessors",
288
448
  "reachable"
289
- ].includes(t)) return false;
449
+ ].includes(t)) return item;
290
450
  continue;
291
451
  }
292
452
  switch (u["tag"]) {
293
453
  case "lit":
294
- if (!("value" in u)) return false;
454
+ if (!("value" in u)) return item;
295
455
  break;
296
- case "ref":
297
- if (!isStringArray(u["path"]) || !isAddr(u["at"])) return false;
456
+ case "ref": {
457
+ const at = addrParts(u["at"], moveNumber);
458
+ if (!isStringArray(u["path"]) || at === void 0) return item;
459
+ push(false, at);
298
460
  break;
461
+ }
299
462
  case "app":
300
- if (typeof u["op"] !== "string" || !Array.isArray(u["args"])) return false;
463
+ if (typeof u["op"] !== "string" || !Array.isArray(u["args"])) return item;
301
464
  push(false, u["args"]);
302
465
  break;
303
466
  case "let":
304
- if (!isObject(u["bind"]) || Array.isArray(u["bind"])) return false;
305
- push(false, [...Object.values(u["bind"]), u["body"]]);
467
+ if (!isObject(u["bind"]) || Array.isArray(u["bind"])) return item;
468
+ push(false, [...Object.values(u["bind"]).map((b) => isObject(b) && b["tag"] === "fn" && isStringArray(b["params"]) && new Set(b["params"]).size === b["params"].length ? b["body"] : b), u["body"]]);
469
+ break;
470
+ case "call":
471
+ if (typeof u["fn"] !== "string" || !Array.isArray(u["args"])) return item;
472
+ push(false, u["args"]);
306
473
  break;
307
474
  case "var":
308
- if (typeof u["name"] !== "string") return false;
475
+ if (typeof u["name"] !== "string") return item;
309
476
  break;
310
477
  case "rec":
311
- if (!isObject(u["fields"]) || Array.isArray(u["fields"])) return false;
478
+ if (!isObject(u["fields"]) || Array.isArray(u["fields"])) return item;
312
479
  push(false, Object.values(u["fields"]));
313
480
  break;
314
- case "each":
315
- if (!isAddr(u["at"])) return false;
481
+ case "each": {
482
+ const at = addrParts(u["at"], moveNumber);
483
+ if (at === void 0) return item;
316
484
  push(true, [u["axis"]]);
317
- push(false, [u["body"]]);
485
+ push(false, [u["body"], ...at]);
486
+ break;
487
+ }
488
+ case "fold": {
489
+ const at = addrParts(u["at"], moveNumber);
490
+ const names = loopParts(u);
491
+ if (at === void 0 || names === void 0) return item;
492
+ push(true, [u["axis"]]);
493
+ push(false, [...names, ...at]);
494
+ break;
495
+ }
496
+ case "iterate": {
497
+ const limit = u["limit"];
498
+ const names = loopParts(u);
499
+ if (typeof limit !== "number" || !Number.isInteger(limit) || limit < 0 || limit > 1e5 || names === void 0) return item;
500
+ push(false, [...names, ...u["until"] === void 0 ? [] : [u["until"]]]);
318
501
  break;
502
+ }
319
503
  case "ext":
320
- if (typeof u["kind"] !== "string" || !("data" in u)) return false;
504
+ if (typeof u["kind"] !== "string" || !("data" in u)) return item;
321
505
  break;
322
- default: return false;
506
+ default: return item;
323
507
  }
324
508
  }
325
- return true;
326
509
  }
327
- /** This function gives the child expressions of an expression, in the order of their child index. */
510
+ /**
511
+ * This function gives the child expressions of an expression, in the order of their child index. The expressions of
512
+ * the computed moves of an address come last. They evaluate at the position of their node, also for an axis.
513
+ */
328
514
  function children(e) {
329
515
  switch (e.tag) {
330
- case "app": return e.args;
516
+ case "app":
517
+ case "call": return e.args;
518
+ case "fn": return [e.body];
331
519
  case "let": return [...Object.values(e.bind), e.body];
332
520
  case "rec": return Object.values(e.fields);
333
- case "each": return [e.body, ...whereTests(e.axis)];
521
+ case "each": return [
522
+ e.body,
523
+ ...axisExprs(e.axis),
524
+ ...addrExprs(e.at)
525
+ ];
526
+ case "fold": return [
527
+ ...Object.values(e.init),
528
+ ...Object.values(e.step),
529
+ ...axisExprs(e.axis),
530
+ ...addrExprs(e.at),
531
+ e.result
532
+ ];
533
+ case "iterate": return [
534
+ ...Object.values(e.init),
535
+ ...Object.values(e.step),
536
+ ...e.until === void 0 ? [] : [e.until],
537
+ e.result
538
+ ];
539
+ case "ref": return addrExprs(e.at);
334
540
  case "lit":
335
- case "ref":
336
541
  case "var":
337
542
  case "ext": return [];
338
543
  }
339
544
  }
340
- /** This function gives the tests of the `where` axes of an axis, from the inside out. It uses a loop, not recursion. */
341
- function whereTests(a) {
545
+ /**
546
+ * This function gives the expressions of an axis, in the order of their child indexes. The expression of the axis
547
+ * `list` comes first, and then the tests of the `where` axes from the inside out. It uses a loop, not recursion.
548
+ */
549
+ function axisExprs(a) {
342
550
  const out = [];
343
551
  for (let x = a; x.t === "where"; x = x.axis) out.unshift(x.test);
344
- return out;
552
+ const list = listOf(a);
553
+ return list === void 0 ? out : [list, ...out];
554
+ }
555
+ /** This function gives the expression of the axis `list` inside an axis, through `where` and `reverse`, if it has one. */
556
+ function listOf(a) {
557
+ let x = a;
558
+ while (x.t === "where") x = x.axis;
559
+ const base = x.t === "reverse" ? x.axis : x;
560
+ return base.t === "list" ? base.list : void 0;
345
561
  }
346
562
  //#endregion
347
563
  //#region src/space.ts
348
564
  var RecordSpace = class {
349
565
  kind = "record";
350
566
  keys;
567
+ records;
351
568
  #records;
352
569
  constructor(records) {
353
570
  const entries = Object.entries(records);
354
571
  this.keys = Object.freeze(entries.map(([k]) => k));
572
+ this.records = Object.freeze(entries.map(([, o]) => o));
355
573
  this.#records = new Map(entries);
356
574
  }
357
575
  has(k) {
@@ -366,29 +584,28 @@ var RecordSpace = class {
366
584
  var ArraySpace = class {
367
585
  kind = "array";
368
586
  keys;
369
- #items;
587
+ records;
370
588
  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);
589
+ this.keys = Object.freeze(Array.from(items, (_item, i) => `${i}`));
590
+ this.records = Object.freeze(Array.from(items));
374
591
  }
375
592
  has(k) {
376
- return this.#items.has(k);
593
+ return this.keys[Number(k)] === k;
377
594
  }
378
595
  get(k) {
379
- return this.#items.get(k);
596
+ return this.has(k) ? this.records[Number(k)] : void 0;
380
597
  }
381
598
  coords(k) {
382
599
  return this.has(k) ? [Number(k)] : void 0;
383
600
  }
384
601
  keyAt(coords) {
385
- const k = String(coords[0]);
386
- return coords.length === 1 && this.has(k) ? k : void 0;
602
+ return coords.length === 1 ? this.keys[Number(coords[0])] : void 0;
387
603
  }
388
604
  };
389
605
  var GridSpace = class {
390
606
  kind = "grid";
391
607
  keys;
608
+ records;
392
609
  #cells;
393
610
  #coords;
394
611
  constructor(rows) {
@@ -398,6 +615,7 @@ var GridSpace = class {
398
615
  Object.freeze([i, j])
399
616
  ]));
400
617
  this.keys = Object.freeze(entries.map(([k]) => k));
618
+ this.records = Object.freeze(entries.map(([, o]) => o));
401
619
  this.#cells = new Map(entries.map(([k, cell]) => [k, cell]));
402
620
  this.#coords = new Map(entries.map(([k, , c]) => [k, c]));
403
621
  }
@@ -418,12 +636,14 @@ var GridSpace = class {
418
636
  var TreeSpace = class {
419
637
  kind = "tree";
420
638
  keys;
639
+ records;
421
640
  #records;
422
641
  #parents;
423
642
  #children;
424
643
  constructor(records, parents) {
425
644
  const entries = Object.entries(records);
426
645
  this.keys = Object.freeze(entries.map(([k]) => k));
646
+ this.records = Object.freeze(entries.map(([, o]) => o));
427
647
  this.#records = new Map(entries);
428
648
  const parentOf = /* @__PURE__ */ new Map();
429
649
  for (const [k, p] of Object.entries(parents)) {
@@ -477,12 +697,14 @@ const NO_KEYS = Object.freeze([]);
477
697
  var GraphSpace = class {
478
698
  kind = "graph";
479
699
  keys;
700
+ records;
480
701
  #records;
481
702
  #out;
482
703
  #in;
483
704
  constructor(records, edges) {
484
705
  const entries = Object.entries(records);
485
706
  this.keys = Object.freeze(entries.map(([k]) => k));
707
+ this.records = Object.freeze(entries.map(([, o]) => o));
486
708
  this.#records = new Map(entries);
487
709
  const out = /* @__PURE__ */ new Map();
488
710
  for (const [k, to] of Object.entries(edges)) {
@@ -586,6 +808,31 @@ function applyMove(s, at, m) {
586
808
  }
587
809
  }
588
810
  }
811
+ /**
812
+ * This function gives the fixed moves of an address. `values` has the value of the expression of each computed move,
813
+ * in order (NAV.COMPUTED). A key that is not a text, or a position that is not a number, gives `#VALUE!`.
814
+ */
815
+ function fixAddr(addr, values, at) {
816
+ const out = [];
817
+ let next = 0;
818
+ for (const m of addr) {
819
+ if (moveExpr(m) === void 0) {
820
+ out.push(m);
821
+ continue;
822
+ }
823
+ const u = values[next++];
824
+ if (m.t === "key" && typeof u === "string") out.push({
825
+ t: "key",
826
+ key: u
827
+ });
828
+ else if (m.t === "index" && typeof u === "number") out.push({
829
+ t: "index",
830
+ i: u
831
+ });
832
+ 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));
833
+ }
834
+ return ok(out);
835
+ }
589
836
  /** This function applies the moves of an address in order. It gives the key where the address points. */
590
837
  function resolveAddr(s, at, addr) {
591
838
  let focus = at.focus;
@@ -673,7 +920,12 @@ function axisTargets(s, at, a) {
673
920
  case "successors":
674
921
  case "predecessors":
675
922
  case "reachable": return graphTargets(s, at, a.t);
923
+ case "reverse": {
924
+ const r = axisTargets(s, at, a.axis);
925
+ return r.ok ? ok(r.value.toReversed()) : r;
926
+ }
676
927
  case "table": return fail(vexError("no-table", `the axis "table" needs the tables of the evaluation, and "${a.name}" is not one of them`, at));
928
+ case "list": return fail(vexError("bad-expression", "the axis \"list\" needs the evaluator, which gives the value of its list", at));
677
929
  }
678
930
  }
679
931
  /**
@@ -797,7 +1049,10 @@ const LIST_OPS = /* @__PURE__ */ new Set([
797
1049
  "keys",
798
1050
  "reduce",
799
1051
  "first",
800
- "errors"
1052
+ "errors",
1053
+ "sortBy",
1054
+ "take",
1055
+ "nth"
801
1056
  ]);
802
1057
  /** This function tells if a name is the name of a core list op. */
803
1058
  const isListOp = (op) => LIST_OPS.has(op);
@@ -815,6 +1070,17 @@ const isSpecialForm = (op) => SPECIAL_FORMS.has(op);
815
1070
  * This function compiles an expression. The result gives the same results and the same traces as `evaluate`,
816
1071
  * because `evaluate` uses it too.
817
1072
  */
1073
+ /** A bound function (FN.BIND): its parameters, its compiled body and the names of the place of its binding. */
1074
+ var Closure = class {
1075
+ params;
1076
+ body;
1077
+ env;
1078
+ constructor(params, body, env) {
1079
+ this.params = params;
1080
+ this.body = body;
1081
+ this.env = env;
1082
+ }
1083
+ };
818
1084
  /** The deepest nesting of an expression that `compile` accepts (EVAL.NESTING). */
819
1085
  const MAX_NESTING = 500;
820
1086
  const DEPTH_MESSAGE = "the evaluation is too deep for the call stack of the engine";
@@ -830,12 +1096,14 @@ function nestingOf(e) {
830
1096
  return deepest;
831
1097
  }
832
1098
  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`, {
1099
+ const shape = shapeError(expr);
1100
+ const nesting = shape === void 0 ? nestingOf(expr) : 0;
1101
+ const bad = shape ?? (nesting > 500 ? `the expression is nested ${nesting} levels deep, and the limit is 500` : void 0);
1102
+ const root = bad === void 0 ? new Compiler(opts).node(expr, []) : (f) => fail(vexError("bad-expression", bad, {
835
1103
  path: [],
836
1104
  origin: f.pos.origin,
837
1105
  focus: f.pos.focus
838
- })) : new Compiler(opts).node(expr, []);
1106
+ }));
839
1107
  const run = (r) => {
840
1108
  const { space, origin } = r;
841
1109
  if (!space.has(origin)) return fail(vexError("unknown-key", `the space has no key "${origin}"`, {
@@ -954,8 +1222,14 @@ var Compiler = class {
954
1222
  case "ref": return this.#ref(e, info);
955
1223
  case "var": {
956
1224
  const name = e.name;
957
- return (f, c) => this.#emit(c, info, f, f.env.get(name) ?? this.#err("unbound", `the name "${name}" has no binding`, f, path));
1225
+ return (f, c) => {
1226
+ const bound = f.env.get(name);
1227
+ if (bound?.ok === true && bound.value instanceof Closure) return this.#emit(c, info, f, this.#err("kind-mismatch", `the name "${name}" is a function, not a value`, f, path));
1228
+ return this.#emit(c, info, f, bound ?? this.#err("unbound", `the name "${name}" has no binding`, f, path));
1229
+ };
958
1230
  }
1231
+ case "fn": return this.#fn(e, path);
1232
+ case "call": return this.#callFn(e, info);
959
1233
  case "let": {
960
1234
  const binds = Object.entries(e.bind).map(([name, be], i) => [name, this.node(be, [...path, i])]);
961
1235
  const body = this.node(e.body, [...path, binds.length]);
@@ -983,6 +1257,8 @@ var Compiler = class {
983
1257
  }
984
1258
  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
1259
  case "each": return this.#each(e, info);
1260
+ case "fold": return this.#fold(e, info);
1261
+ case "iterate": return this.#iterate(e, info);
986
1262
  case "ext": {
987
1263
  const extensions = this.#extensions ?? {};
988
1264
  const handler = Object.hasOwn(extensions, e.kind) ? extensions[e.kind] : void 0;
@@ -999,6 +1275,36 @@ var Compiler = class {
999
1275
  #nodes(es, path) {
1000
1276
  return es.map((x, i) => this.node(x, [...path, i]));
1001
1277
  }
1278
+ /**
1279
+ * This method compiles a function (FN.BIND). Its value is a closure: the parameters, the body, and the names of the
1280
+ * place of its binding. A binding of `let` does not see the other bindings, so a function cannot call itself.
1281
+ */
1282
+ #fn(e, path) {
1283
+ const body = this.node(e.body, [...path, 0]);
1284
+ return (f) => ok(new Closure(e.params, body, f.env));
1285
+ }
1286
+ /**
1287
+ * This method compiles a call (FN.CALL, FN.ARGS). Each parameter gets the result of its argument at the call, so an
1288
+ * argument that fails has an effect only where the body reads it. The body evaluates at the position of the call.
1289
+ */
1290
+ #callFn(e, info) {
1291
+ const { path } = info;
1292
+ const args = this.#nodes(e.args, path);
1293
+ return (f, c) => {
1294
+ const bound = f.env.get(e.fn);
1295
+ if (bound === void 0) return this.#emit(c, info, f, this.#err("unbound", `the function "${e.fn}" has no binding`, f, path));
1296
+ if (!bound.ok) return this.#emit(c, info, f, bound);
1297
+ const callee = bound.value;
1298
+ if (!(callee instanceof Closure)) return this.#emit(c, info, f, this.#err("kind-mismatch", `the name "${e.fn}" is a value, not a function`, f, path));
1299
+ if (callee.params.length !== args.length) return this.#emit(c, info, f, this.#err("bad-expression", `the function "${e.fn}" takes ${String(callee.params.length)} arguments, not ${String(args.length)}`, f, path));
1300
+ const env = new Map(callee.env);
1301
+ callee.params.forEach((p, i) => env.set(p, args[i](f, c)));
1302
+ return this.#emit(c, info, f, callee.body({
1303
+ pos: f.pos,
1304
+ env
1305
+ }, c));
1306
+ };
1307
+ }
1002
1308
  /** This method gives an error of a handler the path, the origin and the focus of its node, if it has no origin. */
1003
1309
  #locate(r, f, path) {
1004
1310
  if (r.ok || r.error.origin !== void 0) return r;
@@ -1026,10 +1332,34 @@ var Compiler = class {
1026
1332
  thrown
1027
1333
  });
1028
1334
  }
1335
+ /**
1336
+ * This method compiles an address. Its function gives the key where the address points. The expressions of the
1337
+ * computed moves evaluate first, at the position of the node, and their child indexes start at `first`. An error of
1338
+ * an expression keeps its path, and an error of a move gets the path of the node.
1339
+ */
1340
+ #address(at, path, first) {
1341
+ const nodes = addrExprs(at).map((x, i) => this.node(x, [...path, first + i]));
1342
+ const moved = (r) => r.ok ? r : fail({
1343
+ ...r.error,
1344
+ path
1345
+ });
1346
+ if (nodes.length === 0) return (f, c) => moved(resolveAddr(c.space, f.pos, at));
1347
+ return (f, c) => {
1348
+ const values = [];
1349
+ for (const n of nodes) {
1350
+ const r = n(f, c);
1351
+ if (!r.ok) return r;
1352
+ values.push(r.value);
1353
+ }
1354
+ const fixed = fixAddr(at, values, f.pos);
1355
+ return fixed.ok ? moved(resolveAddr(c.space, f.pos, fixed.value)) : moved(fixed);
1356
+ };
1357
+ }
1029
1358
  #ref(e, info) {
1030
1359
  const { path } = info;
1031
1360
  const segs = e.path;
1032
1361
  const at = e.at ?? [];
1362
+ const address = this.#address(at, path, 0);
1033
1363
  const label = segs.join(".");
1034
1364
  const steps = segs.map((seg, i) => ({
1035
1365
  seg,
@@ -1039,11 +1369,8 @@ var Compiler = class {
1039
1369
  return (f, c) => {
1040
1370
  let key = f.pos.focus;
1041
1371
  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
- }));
1372
+ const where = address(f, c);
1373
+ if (!where.ok) return this.#emit(c, info, f, where);
1047
1374
  key = where.value;
1048
1375
  }
1049
1376
  const failed = (r) => this.#emit(c, info, f, r, [{
@@ -1089,16 +1416,15 @@ var Compiler = class {
1089
1416
  #each(e, info) {
1090
1417
  const { path } = info;
1091
1418
  const at = e.at ?? [];
1092
- const targets = this.#targets(e.axis, path, { next: 1 });
1419
+ const counter = { next: 1 };
1420
+ const targets = this.#targets(e.axis, path, counter);
1093
1421
  const body = this.node(e.body, [...path, 0]);
1422
+ const address = this.#address(at, path, counter.next);
1094
1423
  return (f, c) => {
1095
1424
  let from = f;
1096
1425
  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
- }));
1426
+ const where = address(f, c);
1427
+ if (!where.ok) return this.#emit(c, info, f, where);
1102
1428
  from = {
1103
1429
  pos: {
1104
1430
  origin: f.pos.origin,
@@ -1138,9 +1464,140 @@ var Compiler = class {
1138
1464
  return this.#emit(c, info, f, ok(vexList(items)));
1139
1465
  };
1140
1466
  }
1467
+ /**
1468
+ * This method compiles the names of a loop: `init` at the indexes from 0, and `step` after them (LOOP.NAMES). Its
1469
+ * functions give the first values, and the values after one step. The first error stops each of them.
1470
+ */
1471
+ #names(e, path) {
1472
+ const inits = Object.entries(e.init).map(([name, x], i) => [name, this.node(x, [...path, i])]);
1473
+ const steps = Object.entries(e.step).map(([name, x], i) => [name, this.node(x, [...path, inits.length + i])]);
1474
+ return {
1475
+ first: (f, c) => {
1476
+ const env = new Map(f.env);
1477
+ for (const [name, n] of inits) {
1478
+ const r = n(f, c);
1479
+ if (!r.ok) return r;
1480
+ env.set(name, r);
1481
+ }
1482
+ return ok(env);
1483
+ },
1484
+ next: (f, c) => {
1485
+ const values = [];
1486
+ for (const [name, n] of steps) {
1487
+ const r = n(f, c);
1488
+ if (!r.ok) return r;
1489
+ values.push([name, r]);
1490
+ }
1491
+ const env = new Map(f.env);
1492
+ for (const [name, r] of values) env.set(name, r);
1493
+ return ok(env);
1494
+ }
1495
+ };
1496
+ }
1497
+ /**
1498
+ * This method compiles a fold (FOLD.ORDER, FOLD.ERROR). `init` evaluates at the node, then the address and the
1499
+ * targets. A step evaluates at each target in order. `result` evaluates at the node with the last values.
1500
+ */
1501
+ #fold(e, info) {
1502
+ const { path } = info;
1503
+ const at = e.at ?? [];
1504
+ const names = this.#names(e, path);
1505
+ const counter = { next: Object.keys(e.init).length + Object.keys(e.step).length };
1506
+ const targets = this.#targets(e.axis, path, counter);
1507
+ const address = this.#address(at, path, counter.next);
1508
+ const result = this.node(e.result, [...path, counter.next + addrExprs(at).length]);
1509
+ const base = baseAxis(e.axis);
1510
+ return (f, c) => {
1511
+ const first = names.first(f, c);
1512
+ if (!first.ok) return this.#emit(c, info, f, first);
1513
+ let env = first.value;
1514
+ let from = f;
1515
+ if (at.length > 0) {
1516
+ const where = address(f, c);
1517
+ if (!where.ok) return this.#emit(c, info, f, where);
1518
+ from = {
1519
+ pos: {
1520
+ origin: f.pos.origin,
1521
+ focus: where.value
1522
+ },
1523
+ env: f.env
1524
+ };
1525
+ }
1526
+ let inner = c;
1527
+ if (base.t === "table") {
1528
+ const space = c.tables !== void 0 && Object.hasOwn(c.tables, base.name) ? c.tables[base.name] : void 0;
1529
+ if (space === void 0) return this.#emit(c, info, f, this.#err("no-table", `the evaluation has no table "${base.name}"`, f, path));
1530
+ inner = {
1531
+ ...c,
1532
+ space
1533
+ };
1534
+ }
1535
+ const ts = targets(from, inner);
1536
+ if (!ts.ok) return this.#emit(c, info, f, ts);
1537
+ for (const { key, test } of ts.value) {
1538
+ if (test !== void 0 && !test.ok) return this.#emit(c, info, f, test);
1539
+ const after = names.next({
1540
+ pos: {
1541
+ origin: base.t === "table" ? key : f.pos.origin,
1542
+ focus: key
1543
+ },
1544
+ env
1545
+ }, inner);
1546
+ if (!after.ok) return this.#emit(c, info, f, after);
1547
+ env = after.value;
1548
+ }
1549
+ return this.#emit(c, info, f, result({
1550
+ pos: f.pos,
1551
+ env
1552
+ }, c));
1553
+ };
1554
+ }
1555
+ /**
1556
+ * This method compiles an iteration (ITERATE.LIMIT, ITERATE.UNTIL, ITERATE.ERROR). The test `until` evaluates before
1557
+ * each step and after the last step. `result` evaluates with the last values.
1558
+ */
1559
+ #iterate(e, info) {
1560
+ const { path } = info;
1561
+ const names = this.#names(e, path);
1562
+ const untilAt = Object.keys(e.init).length + Object.keys(e.step).length;
1563
+ const untilPath = [...path, untilAt];
1564
+ const until = e.until === void 0 ? void 0 : this.node(e.until, untilPath);
1565
+ const result = this.node(e.result, [...path, untilAt + (until === void 0 ? 0 : 1)]);
1566
+ const { limit } = e;
1567
+ return (f, c) => {
1568
+ const first = names.first(f, c);
1569
+ if (!first.ok) return this.#emit(c, info, f, first);
1570
+ let env = first.value;
1571
+ for (let k = 0;; k++) {
1572
+ const frame = {
1573
+ pos: f.pos,
1574
+ env
1575
+ };
1576
+ if (until !== void 0) {
1577
+ const t = until(frame, c);
1578
+ if (!t.ok) return this.#emit(c, info, f, t);
1579
+ if (t.value === true) break;
1580
+ 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));
1581
+ }
1582
+ if (k === limit) {
1583
+ 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));
1584
+ break;
1585
+ }
1586
+ const after = names.next(frame, c);
1587
+ if (!after.ok) return this.#emit(c, info, f, after);
1588
+ env = after.value;
1589
+ }
1590
+ return this.#emit(c, info, f, result({
1591
+ pos: f.pos,
1592
+ env
1593
+ }, c));
1594
+ };
1595
+ }
1141
1596
  /** This method compiles the targets of an axis. For `where`, a failed test keeps the target with its error. */
1142
1597
  #targets(a, path, counter) {
1143
1598
  if (a.t === "table") return (_f, c) => ok(c.space.keys.map((key) => ({ key })));
1599
+ const base = a.t === "reverse" ? a.axis : a;
1600
+ if (base.t === "list") return this.#listTargets(base.list, a.t === "reverse", path, counter);
1144
1601
  if (a.t !== "where") return (f, c) => {
1145
1602
  const keys = axisTargets(c.space, f.pos, a);
1146
1603
  return keys.ok ? ok(keys.value.map((key) => ({ key }))) : fail({
@@ -1182,6 +1639,23 @@ var Compiler = class {
1182
1639
  return ok(out);
1183
1640
  };
1184
1641
  }
1642
+ /**
1643
+ * This method compiles the targets of the axis list (AXIS.LIST): the keys of the items of a list, in its order. The
1644
+ * expression evaluates at the key of the address. An error item keeps its target with its error.
1645
+ */
1646
+ #listTargets(list, reverse, path, counter) {
1647
+ const node = this.node(list, [...path, counter.next++]);
1648
+ return (f, c) => {
1649
+ const r = node(f, c);
1650
+ if (!r.ok) return r;
1651
+ if (!isVexList(r.value)) return this.#err("kind-mismatch", `the axis "list" needs a list, not a ${describeType(r.value)}`, f, path);
1652
+ const items = r.value.items.map(({ key, result }) => result.ok ? { key } : {
1653
+ key,
1654
+ test: result
1655
+ });
1656
+ return ok(reverse ? items.toReversed() : items);
1657
+ };
1658
+ }
1185
1659
  #app(op, args, info) {
1186
1660
  const { path } = info;
1187
1661
  const listOp = isListOp(op) ? op : void 0;
@@ -1286,7 +1760,7 @@ var Compiler = class {
1286
1760
  return r;
1287
1761
  }
1288
1762
  #listOp(op, list, rest, f, path) {
1289
- const optsArg = op === "reduce" ? rest[1] : rest[0];
1763
+ const optsArg = op === "reduce" || op === "take" || op === "nth" ? rest[1] : rest[0];
1290
1764
  const depth = list.items.find((it) => !it.result.ok && isDepthError(it.result.error))?.result;
1291
1765
  if (depth !== void 0 && !depth.ok) return fail(depth.error);
1292
1766
  const strict = optsArg?.strict === true;
@@ -1302,7 +1776,22 @@ var Compiler = class {
1302
1776
  return bad === void 0 ? ok(okValues) : this.#err("kind-mismatch", `"${op}" needs booleans, but an item is a ${describeType(bad)}`, f, path, { op });
1303
1777
  };
1304
1778
  const empty = () => this.#err("empty", `"${op}" has no values to work with`, f, path, { op });
1779
+ const whole = () => {
1780
+ const n = rest[0];
1781
+ return Number.isSafeInteger(n) && n >= 0 ? ok(n) : this.#err("kind-mismatch", `"${op}" needs a whole number from 0, not ${describeType(n)}`, f, path, { op });
1782
+ };
1783
+ const okItems = list.items.filter((it) => it.result.ok);
1305
1784
  switch (op) {
1785
+ case "sortBy": return this.#sortBy(okItems, okValues, f, path);
1786
+ case "take": {
1787
+ const n = whole();
1788
+ return n.ok ? ok(vexList(okItems.slice(0, n.value))) : n;
1789
+ }
1790
+ case "nth": {
1791
+ const i = whole();
1792
+ if (!i.ok) return i;
1793
+ return i.value < okValues.length ? ok(okValues[i.value]) : this.#err("empty", `"nth" has no item at the position ${String(i.value)}, and the list has ${String(okValues.length)} items`, f, path, { op });
1794
+ }
1306
1795
  case "count": return ok(okValues.length);
1307
1796
  case "values": return ok(Object.freeze([...okValues]));
1308
1797
  case "keys": return ok(Object.freeze(list.items.filter((it) => it.result.ok).map((it) => it.key)));
@@ -1337,6 +1826,21 @@ var Compiler = class {
1337
1826
  }
1338
1827
  }
1339
1828
  /**
1829
+ * This method sorts the items of a list by their values, from the smallest (LIST.SORT). The sort is stable. The values
1830
+ * are all numbers without NaN, or all texts. Texts compare by their UTF-16 code units.
1831
+ */
1832
+ #sortBy(items, values, f, path) {
1833
+ const kind = typeof values[0];
1834
+ const bad = values.findIndex((x) => typeof x !== kind || kind !== "number" && kind !== "string" || Number.isNaN(x));
1835
+ if (bad >= 0) return this.#err("kind-mismatch", `"sortBy" needs numbers without NaN or texts, all of one kind, but an item is ${Number.isNaN(values[bad]) ? "NaN" : `a ${describeType(values[bad])}`}`, f, path, { op: "sortBy" });
1836
+ const order = values.map((_x, i) => i).toSorted((i, j) => {
1837
+ const a = values[i];
1838
+ const b = values[j];
1839
+ return a < b ? -1 : a > b ? 1 : 0;
1840
+ });
1841
+ return ok(vexList(order.map((i) => items[i])));
1842
+ }
1843
+ /**
1340
1844
  * This method folds the values with a domain op, from the left. An empty list gives the identity of the op, if one
1341
1845
  * domain has an identity for the op (LIST.EMPTY). The option `domain` names that domain when more domains have one.
1342
1846
  */
@@ -1371,6 +1875,7 @@ const FORBIDDEN_FIELDS = /* @__PURE__ */ new Set([
1371
1875
  "constructor",
1372
1876
  "prototype"
1373
1877
  ]);
1878
+ /** This function tells if a segment of a path can name a field. A compiler uses the same rule as the interpreter. */
1374
1879
  const isFieldName = (seg) => seg.length > 0 && !FORBIDDEN_FIELDS.has(seg);
1375
1880
  /** This function runs the `is` test of a domain. A test that throws counts as `false`. */
1376
1881
  function safeIs(d, value) {
@@ -1380,6 +1885,7 @@ function safeIs(d, value) {
1380
1885
  return false;
1381
1886
  }
1382
1887
  }
1888
+ /** This function tells if an argument has the kind of a parameter of an op of the domain `domain`. */
1383
1889
  function matchesKind(kind, value, domain) {
1384
1890
  switch (kind) {
1385
1891
  case "domain": return safeIs(domain, value);
@@ -1407,17 +1913,21 @@ function labelOf(e) {
1407
1913
  case "ref": return e.path.length === 0 ? "(record)" : e.path.join(".");
1408
1914
  case "app": return e.op;
1409
1915
  case "let": return `let ${Object.keys(e.bind).join(", ")}`;
1916
+ case "fn": return `fn (${e.params.join(", ")})`;
1917
+ case "call": return `call ${e.fn}`;
1410
1918
  case "var": return e.name;
1411
1919
  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(".")}`;
1920
+ case "each":
1921
+ case "fold": return e.at === void 0 ? `${e.tag} ${e.axis.t}` : `${e.tag} ${e.axis.t} from ${e.at.map(moveText).join(".")}`;
1922
+ case "iterate": return `iterate ${String(e.limit)}`;
1413
1923
  case "ext": return e.kind;
1414
1924
  }
1415
1925
  }
1416
1926
  /** This function gives a short text for a move, for the label of an axis with an address. */
1417
1927
  function moveText(m) {
1418
1928
  switch (m.t) {
1419
- case "key": return `key(${m.key})`;
1420
- case "index": return `index(${m.i})`;
1929
+ case "key": return `key(${typeof m.key === "string" ? m.key : labelOf(m.key)})`;
1930
+ case "index": return `index(${typeof m.i === "number" ? String(m.i) : labelOf(m.i)})`;
1421
1931
  case "offset": return `offset(${m.d.join(", ")})`;
1422
1932
  case "other":
1423
1933
  case "origin":
@@ -1463,35 +1973,89 @@ function formatTrace(trace, domains = []) {
1463
1973
  const sizeOf = (e) => 1 + children(e).reduce((s, c) => s + sizeOf(c), 0);
1464
1974
  //#endregion
1465
1975
  //#region src/deps.ts
1976
+ /** This function gives the functions of a scope without some names: a parameter or a binding hides a function. */
1977
+ const without = (fns, names) => new Map([...fns].filter(([n]) => !names.includes(n)));
1978
+ /**
1979
+ * This function gives the functions that each child of a node sees. The names of a loop hide the functions with those
1980
+ * names in its steps, its test of until and its result. The values of init, the tests of where and an address see the
1981
+ * functions outside.
1982
+ */
1983
+ function childFns(x, fns, count) {
1984
+ if (x.tag !== "fold" && x.tag !== "iterate") return () => fns;
1985
+ const hidden = without(fns, Object.keys(x.init));
1986
+ const first = Object.keys(x.init).length;
1987
+ const steps = first + Object.keys(x.step).length;
1988
+ return (i) => i >= first && (i < steps || i === count - 1 || x.tag === "iterate") ? hidden : fns;
1989
+ }
1466
1990
  /**
1467
1991
  * 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.
1992
+ * when a field that it reads changes. A computed move reads a key that only a run knows. Its address keeps the
1993
+ * expression, and the reads of that expression are in the list too (NAV.COMPUTED).
1469
1994
  */
1470
1995
  function deps(e) {
1471
1996
  const out = [];
1472
1997
  const todo = [{
1473
1998
  x: e,
1474
1999
  axes: [],
1475
- axisAt: []
2000
+ axisAt: [],
2001
+ fns: /* @__PURE__ */ new Map()
1476
2002
  }];
1477
2003
  for (let item = todo.pop(); item !== void 0; item = todo.pop()) {
1478
2004
  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
2005
+ if (x.tag === "ref") out.push({
2006
+ at: x.at ?? [],
2007
+ path: x.path,
2008
+ axes: item.axes,
2009
+ axisAt: item.axisAt
2010
+ });
2011
+ if (x.tag === "let") {
2012
+ const names = Object.keys(x.bind);
2013
+ const inner = new Map(without(item.fns, names));
2014
+ for (const [name, b] of Object.entries(x.bind)) if (b.tag === "fn") inner.set(name, {
2015
+ fn: b,
2016
+ fns: item.fns
2017
+ });
2018
+ todo.push({
2019
+ ...item,
2020
+ x: x.body,
2021
+ fns: inner
2022
+ });
2023
+ for (const b of Object.values(x.bind).toReversed()) if (b.tag !== "fn") todo.push({
2024
+ ...item,
2025
+ x: b
1485
2026
  });
1486
2027
  continue;
1487
2028
  }
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,
1492
- axes,
1493
- axisAt
1494
- });
2029
+ if (x.tag === "call") {
2030
+ const bound = item.fns.get(x.fn);
2031
+ if (bound !== void 0) todo.push({
2032
+ ...item,
2033
+ x: bound.fn.body,
2034
+ fns: without(bound.fns, bound.fn.params)
2035
+ });
2036
+ for (const a of x.args.toReversed()) todo.push({
2037
+ ...item,
2038
+ x: a
2039
+ });
2040
+ continue;
2041
+ }
2042
+ const all = children(x);
2043
+ const fnsOf = childFns(x, item.fns, all.length);
2044
+ const axial = x.tag === "each" || x.tag === "fold";
2045
+ const first = x.tag === "fold" ? Object.keys(x.init).length : 0;
2046
+ const last = axial ? all.length - addrExprs(x.at).length - (x.tag === "fold" ? 1 : 0) : 0;
2047
+ const listAt = axial && listOf(x.axis) !== void 0 ? x.tag === "fold" ? first + Object.keys(x.step).length : 1 : -1;
2048
+ const axes = axial ? [...item.axes, x.axis.t] : item.axes;
2049
+ const axisAt = axial ? [...item.axisAt, x.at ?? []] : item.axisAt;
2050
+ for (let i = all.length - 1; i >= 0; i--) {
2051
+ const inside = i >= first && i < last && i !== listAt;
2052
+ todo.push({
2053
+ x: all[i],
2054
+ axes: inside ? axes : item.axes,
2055
+ axisAt: inside ? axisAt : item.axisAt,
2056
+ fns: fnsOf(i)
2057
+ });
2058
+ }
1495
2059
  }
1496
2060
  return out;
1497
2061
  }
@@ -1612,8 +2176,42 @@ function mapValues(u, f) {
1612
2176
  out[key] = rec;
1613
2177
  }
1614
2178
  };
2179
+ const address = () => {
2180
+ const at = u["at"];
2181
+ if (!Array.isArray(at)) return void 0;
2182
+ const moves = [];
2183
+ for (const m of at) {
2184
+ const field = isRecord(m) ? m["t"] === "key" ? "key" : m["t"] === "index" ? "i" : void 0 : void 0;
2185
+ if (field === void 0 || !isRecord(m) || !isRecord(m[field])) {
2186
+ moves.push(m);
2187
+ continue;
2188
+ }
2189
+ const r = mapValues(m[field], f);
2190
+ if (!r.ok) return r;
2191
+ moves.push({
2192
+ ...m,
2193
+ [field]: r.value
2194
+ });
2195
+ }
2196
+ out["at"] = moves;
2197
+ };
1615
2198
  const axis = (a) => {
1616
- if (!isRecord(a) || a["t"] !== "where") return ok(a);
2199
+ if (!isRecord(a)) return ok(a);
2200
+ if (a["t"] === "list") {
2201
+ const list = mapValues(a["list"], f);
2202
+ return list.ok ? ok({
2203
+ ...a,
2204
+ list: list.value
2205
+ }) : list;
2206
+ }
2207
+ if (a["t"] === "reverse") {
2208
+ const inner = axis(a["axis"]);
2209
+ return inner.ok ? ok({
2210
+ ...a,
2211
+ axis: inner.value
2212
+ }) : inner;
2213
+ }
2214
+ if (a["t"] !== "where") return ok(a);
1617
2215
  const inner = axis(a["axis"]);
1618
2216
  if (!inner.ok) return inner;
1619
2217
  const test = mapValues(a["test"], f);
@@ -1638,8 +2236,18 @@ function mapValues(u, f) {
1638
2236
  const a = axis(u["axis"]);
1639
2237
  if (!a.ok) return a;
1640
2238
  out["axis"] = a.value;
1641
- return child("body") ?? ok(out);
2239
+ return child("body") ?? address() ?? ok(out);
1642
2240
  }
2241
+ case "fold": {
2242
+ const a = axis(u["axis"]);
2243
+ if (!a.ok) return a;
2244
+ out["axis"] = a.value;
2245
+ return each("init") ?? each("step") ?? child("result") ?? address() ?? ok(out);
2246
+ }
2247
+ case "iterate": return each("init") ?? each("step") ?? (u["until"] === void 0 ? void 0 : child("until")) ?? child("result") ?? ok(out);
2248
+ case "fn": return child("body") ?? ok(out);
2249
+ case "call": return each("args") ?? ok(out);
2250
+ case "ref": return address() ?? ok(out);
1643
2251
  default: return ok(out);
1644
2252
  }
1645
2253
  }
@@ -1776,7 +2384,14 @@ const cell = (column, at = []) => ext(CELL_KIND, {
1776
2384
  column,
1777
2385
  at
1778
2386
  });
1779
- const isCellRef = (u) => typeof u === "object" && u !== null && typeof u.column === "string" && Array.isArray(u.at) && u.at.every(isMove);
2387
+ 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);
2388
+ /**
2389
+ * The compiled programs of the formulas of the columns: one entry for each formula, for the last compiler and options.
2390
+ * A compiled program reads the cells of the active run, so each run with the same compiler and options can use it.
2391
+ */
2392
+ const PROGRAMS = /* @__PURE__ */ new WeakMap();
2393
+ /** The key of the options without extensions, for the extensions of the compiled programs. */
2394
+ const NO_EXTENSIONS = {};
1780
2395
  const cycleError = (column, key) => fail(vexError("cycle", `the cell "${column}" at "${key}" is on a cycle of cell references`, {
1781
2396
  origin: key,
1782
2397
  focus: key
@@ -1791,8 +2406,122 @@ const tableState = (where, i, t) => ({
1791
2406
  columns: t.columns,
1792
2407
  cells: t.cells ?? /* @__PURE__ */ new Map(),
1793
2408
  warmed: /* @__PURE__ */ new Map(),
1794
- index: void 0
2409
+ index: void 0,
2410
+ done: /* @__PURE__ */ new Map()
1795
2411
  });
2412
+ /** This function gives the result of a finished cell, or `undefined`. */
2413
+ const doneOf = (t, column, key) => t.done.get(column)?.get(key);
2414
+ /** This function keeps the result of a finished cell. */
2415
+ function setDone(t, column, key, result) {
2416
+ let results = t.done.get(column);
2417
+ if (results === void 0) {
2418
+ results = /* @__PURE__ */ new Map();
2419
+ t.done.set(column, results);
2420
+ }
2421
+ results.set(key, result);
2422
+ }
2423
+ /** This function adds the direction of one move or one axis of a read of a column from itself. */
2424
+ function addDirection(d, m) {
2425
+ if (m.t === "reverse") {
2426
+ addDirection(d, m.axis);
2427
+ return;
2428
+ }
2429
+ if (m.t === "offset" || m.t === "window") {
2430
+ const steps = m.t === "offset" ? [m.d.find((x) => x !== 0) ?? 0] : [m.from, m.to];
2431
+ if (steps.some((x) => x < 0)) d.add("before");
2432
+ if (steps.some((x) => x > 0)) d.add("after");
2433
+ } else if (m.t === "children" || m.t === "descendants") d.add("down");
2434
+ }
2435
+ /** This function gives the base axis of an axis, and the tests of its `where` axes. */
2436
+ function partsOf(axis) {
2437
+ const tests = [];
2438
+ let base = axis;
2439
+ while (base.t === "where") {
2440
+ tests.push(base.test);
2441
+ base = base.axis;
2442
+ }
2443
+ return {
2444
+ base,
2445
+ tests
2446
+ };
2447
+ }
2448
+ /**
2449
+ * This function gives the columns that the formulas of the column `self` read with a cell reference: its formula and
2450
+ * the formulas of its cells. It also gives the directions of their reads of the column itself. A read in the body or
2451
+ * in a test of an axis also has the direction of that axis. It walks each expression with a stack, not with recursion.
2452
+ */
2453
+ function readsOf(t, self) {
2454
+ const columns = /* @__PURE__ */ new Set();
2455
+ const directions = /* @__PURE__ */ new Set();
2456
+ const formula = t.columns.get(self);
2457
+ const todo = [...formula === void 0 ? [] : [formula], ...t.cells.get(self)?.values() ?? []].filter((e) => shapeError(e) === void 0).map((e) => [e, void 0]);
2458
+ for (let item = todo.pop(); item !== void 0; item = todo.pop()) {
2459
+ const [e, axis] = item;
2460
+ if (e.tag === "each" || e.tag === "fold") {
2461
+ const { base, tests } = partsOf(e.axis);
2462
+ for (const x of [...e.tag === "each" ? [e.body] : Object.values(e.step), ...tests]) todo.push([x, base]);
2463
+ const list = listOf(e.axis);
2464
+ for (const x of [
2465
+ ...e.tag === "fold" ? [...Object.values(e.init), e.result] : [],
2466
+ ...addrExprs(e.at),
2467
+ ...list === void 0 ? [] : [list]
2468
+ ]) todo.push([x, axis]);
2469
+ } else if (e.tag !== "ext") for (const child of children(e)) todo.push([child, axis]);
2470
+ else if (e.kind === "vex.cell" && isCellRef(e.data)) {
2471
+ columns.add(e.data.column);
2472
+ if (e.data.column === self) for (const m of [...axis === void 0 ? [] : [axis], ...e.data.at]) addDirection(directions, m);
2473
+ }
2474
+ }
2475
+ return {
2476
+ columns,
2477
+ directions
2478
+ };
2479
+ }
2480
+ /**
2481
+ * This function gives the columns of a table in an order where each column comes after the columns that it reads.
2482
+ * The columns of a cycle keep their order. The columns with formulas of cells only come last.
2483
+ */
2484
+ function columnOrder(t) {
2485
+ const names = /* @__PURE__ */ new Set([...t.columns.keys(), ...t.cells.keys()]);
2486
+ let left = [...names].map((c) => ({
2487
+ c,
2488
+ needs: [...readsOf(t, c).columns].filter((x) => x !== c && names.has(x))
2489
+ }));
2490
+ const order = [];
2491
+ const placed = /* @__PURE__ */ new Set();
2492
+ while (left.length > 0) {
2493
+ const ready = left.filter((x) => x.needs.every((n) => placed.has(n)));
2494
+ for (const x of ready.length > 0 ? ready : left.slice(0, 1)) {
2495
+ order.push(x.c);
2496
+ placed.add(x.c);
2497
+ }
2498
+ left = left.filter((x) => !placed.has(x.c));
2499
+ }
2500
+ return order;
2501
+ }
2502
+ /**
2503
+ * 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
2504
+ * reverses the order. In a tree, a read of the children puts the children before their parent.
2505
+ */
2506
+ function keyOrder(s, d) {
2507
+ const reverse = d.has("after") && !d.has("before");
2508
+ const childrenOf = s.childrenOf?.bind(s);
2509
+ if (childrenOf === void 0) return reverse ? s.keys.toReversed() : s.keys;
2510
+ const post = d.has("down");
2511
+ const backwards = post !== reverse;
2512
+ const push = (stack, keys) => {
2513
+ for (const k of backwards ? keys : keys.toReversed()) stack.push(k);
2514
+ };
2515
+ const isChild = new Set(s.keys.flatMap((k) => childrenOf(k)));
2516
+ const stack = [];
2517
+ push(stack, s.keys.filter((k) => !isChild.has(k)));
2518
+ const out = [];
2519
+ for (let k = stack.pop(); k !== void 0; k = stack.pop()) {
2520
+ out.push(k);
2521
+ push(stack, childrenOf(k));
2522
+ }
2523
+ return post ? out.toReversed() : out;
2524
+ }
1796
2525
  /**
1797
2526
  * The budget of the stack for the recursion of a run, in estimated frames. Each engine has more stack than this, so
1798
2527
  * the recursion of a run cannot fill the stack (SHEET.DEEP).
@@ -1816,22 +2545,27 @@ const STACK_BUDGET = 3e3;
1816
2545
  * A run can have more tables (SHEET.TABLES). Each table has its own space, and one search covers the cells of all
1817
2546
  * the tables. Thus a cycle across tables gives `#CYCLE!` too.
1818
2547
  */
1819
- var SheetRun = class {
2548
+ var SheetRun = class SheetRun {
1820
2549
  #main;
1821
2550
  #byName = /* @__PURE__ */ new Map();
1822
2551
  #bySpace = /* @__PURE__ */ new Map();
1823
2552
  #opts;
1824
- #done = /* @__PURE__ */ new Map();
1825
2553
  #visits = /* @__PURE__ */ new Map();
1826
2554
  #stack = [];
1827
2555
  #top;
2556
+ #filling;
2557
+ #missed = false;
1828
2558
  #next = 0;
1829
2559
  #used = 0;
1830
2560
  #cost = /* @__PURE__ */ new Map();
1831
2561
  #budget;
2562
+ #compile;
2563
+ #compileOptions;
2564
+ static #active;
2565
+ static #shared = /* @__PURE__ */ new WeakMap();
1832
2566
  /** `budget` is the budget of the stack in estimated frames. A test can make it small, so the run pauses often. */
1833
2567
  constructor(columns, opts, budget = STACK_BUDGET) {
1834
- const { cells, name, tables, space, ...rest } = opts;
2568
+ const { cells, name, tables, space, compile, ...rest } = opts;
1835
2569
  this.#main = {
1836
2570
  where: "the sheet",
1837
2571
  tag: "0",
@@ -1839,7 +2573,8 @@ var SheetRun = class {
1839
2573
  columns,
1840
2574
  cells: cells ?? /* @__PURE__ */ new Map(),
1841
2575
  warmed: /* @__PURE__ */ new Map(),
1842
- index: void 0
2576
+ index: void 0,
2577
+ done: /* @__PURE__ */ new Map()
1843
2578
  };
1844
2579
  this.#bySpace.set(space, this.#main);
1845
2580
  if (name !== void 0) this.#byName.set(name, this.#main);
@@ -1864,7 +2599,20 @@ var SheetRun = class {
1864
2599
  paused: false,
1865
2600
  need: void 0
1866
2601
  };
2602
+ this.#filling = {
2603
+ id: "",
2604
+ table: this.#main,
2605
+ column: "",
2606
+ key: "",
2607
+ index: 0,
2608
+ low: 0,
2609
+ reread: false,
2610
+ result: cycleError("", ""),
2611
+ paused: false,
2612
+ need: void 0
2613
+ };
1867
2614
  this.#budget = budget;
2615
+ this.#compile = compile;
1868
2616
  const spaces = Object.fromEntries([...this.#byName].map(([n, t]) => [n, t.space]));
1869
2617
  this.#opts = {
1870
2618
  ...rest,
@@ -1874,7 +2622,25 @@ var SheetRun = class {
1874
2622
  [CELL_KIND]: this.#handler
1875
2623
  }
1876
2624
  };
2625
+ const outer = rest.extensions ?? NO_EXTENSIONS;
2626
+ let shared = SheetRun.#shared.get(outer);
2627
+ if (shared === void 0) {
2628
+ shared = {
2629
+ ...rest.extensions,
2630
+ [CELL_KIND]: SheetRun.#cellOfActive
2631
+ };
2632
+ SheetRun.#shared.set(outer, shared);
2633
+ }
2634
+ this.#compileOptions = {
2635
+ ...this.#opts,
2636
+ extensions: shared
2637
+ };
1877
2638
  }
2639
+ /** The cell handler of the compiled programs: it reads the cells of the active run. */
2640
+ static #cellOfActive = (data, ctx) => {
2641
+ const run = SheetRun.#active;
2642
+ return run === void 0 ? fail(vexError("unbound", "a compiled formula reads cells only in the evaluation of a sheet run")) : run.#handler(data, ctx);
2643
+ };
1878
2644
  /** This method gives the program of a cell: its own formula, or the formula of its column (SHEET.CELL.FORMULA). */
1879
2645
  #programOf(t, column, key) {
1880
2646
  return (t.cells.size === 0 ? void 0 : t.cells.get(column)?.get(key)) ?? t.columns.get(column);
@@ -1896,7 +2662,7 @@ var SheetRun = class {
1896
2662
  }));
1897
2663
  }
1898
2664
  #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 }));
2665
+ if (!isCellRef(data)) return fail(vexError("bad-expression", "a cell reference needs a column name and an address of fixed moves"));
1900
2666
  const where = resolveAddr(ctx.space, ctx.position, data.at);
1901
2667
  if (!where.ok) return fail({
1902
2668
  ...where.error,
@@ -1914,6 +2680,8 @@ var SheetRun = class {
1914
2680
  const t = this.#named(table, key);
1915
2681
  if (!("space" in t)) return t;
1916
2682
  if (this.#top.index >= 0) return this.#read(t, column, key);
2683
+ const done = doneOf(t, column, key);
2684
+ if (done !== void 0) return done;
1917
2685
  this.#warmTo(t, column, key);
1918
2686
  return this.#drive(t, column, key);
1919
2687
  }
@@ -1931,7 +2699,7 @@ var SheetRun = class {
1931
2699
  #costOf(program) {
1932
2700
  let cost = this.#cost.get(program);
1933
2701
  if (cost === void 0) {
1934
- cost = 3 * nestingOf(program) + 16;
2702
+ cost = 3 * (shapeError(program) === void 0 ? nestingOf(program) : 1) + 16;
1935
2703
  this.#cost.set(program, cost);
1936
2704
  }
1937
2705
  return cost;
@@ -1963,15 +2731,46 @@ var SheetRun = class {
1963
2731
  visit.need = void 0;
1964
2732
  this.#top = visit;
1965
2733
  this.#used += cost;
1966
- const result = evaluate(program, {
1967
- ...this.#opts,
1968
- space: visit.table.space,
1969
- origin: visit.key
1970
- });
2734
+ const result = this.#run(visit.table, visit.column, visit.key, program);
1971
2735
  this.#used -= cost;
1972
2736
  this.#top = caller;
1973
2737
  if (!visit.paused) visit.result = result;
1974
2738
  }
2739
+ /** This method evaluates the formula `program` of a cell, with its compiled program or with the interpreter. */
2740
+ #run(t, column, key, program) {
2741
+ const options = {
2742
+ ...this.#opts,
2743
+ space: t.space,
2744
+ origin: key
2745
+ };
2746
+ const compiled = this.#compiled(t, column, program);
2747
+ if (compiled === void 0) return evaluate(program, options);
2748
+ const active = SheetRun.#active;
2749
+ SheetRun.#active = this;
2750
+ const result = compiled.run(options);
2751
+ SheetRun.#active = active;
2752
+ return result;
2753
+ }
2754
+ /**
2755
+ * This method gives the compiled program of the formula of a column, or `undefined` for the interpreter. A formula
2756
+ * compiles once for each compiler and options, also across runs.
2757
+ */
2758
+ #compiled(t, column, program) {
2759
+ const compile = this.#compile;
2760
+ if (compile === void 0 || t.columns.get(column) !== program) return void 0;
2761
+ const { domains, fns, extensions } = this.#compileOptions;
2762
+ const hit = PROGRAMS.get(program);
2763
+ if (hit !== void 0 && hit.compile === compile && hit.domains === domains && hit.fns === fns && hit.extensions === extensions) return hit.program;
2764
+ const compiled = compile(program, this.#compileOptions);
2765
+ PROGRAMS.set(program, {
2766
+ compile,
2767
+ domains,
2768
+ fns,
2769
+ extensions,
2770
+ program: compiled
2771
+ });
2772
+ return compiled;
2773
+ }
1975
2774
  /** This method ends a cell whose evaluation did not pause: it finishes its component, or it gives its low to the caller. */
1976
2775
  #end(visit, caller) {
1977
2776
  if (visit.low === visit.index) this.#finish(visit);
@@ -1979,11 +2778,15 @@ var SheetRun = class {
1979
2778
  }
1980
2779
  /** This method reads a cell from the formula of the cell at the top. */
1981
2780
  #read(t, column, key) {
1982
- const id = idOf(t, column, key);
1983
- const done = this.#done.get(id);
2781
+ const done = doneOf(t, column, key);
1984
2782
  if (done !== void 0) return done;
1985
2783
  const caller = this.#top;
1986
2784
  if (caller.paused) return cycleError(column, key);
2785
+ if (caller === this.#filling) {
2786
+ this.#missed = true;
2787
+ return cycleError(column, key);
2788
+ }
2789
+ const id = idOf(t, column, key);
1987
2790
  const seen = this.#visits.get(id);
1988
2791
  if (seen !== void 0) {
1989
2792
  caller.low = Math.min(caller.low, seen.index);
@@ -2005,12 +2808,11 @@ var SheetRun = class {
2005
2808
  return cycleError(column, key);
2006
2809
  }
2007
2810
  this.#end(visit, caller);
2008
- return this.#done.get(id) ?? cycleError(column, key);
2811
+ return doneOf(t, column, key) ?? cycleError(column, key);
2009
2812
  }
2010
2813
  /** This method evaluates a cell from the top level. The cells that pause go on a list, not on the call stack. */
2011
2814
  #drive(t, column, key) {
2012
- const id = idOf(t, column, key);
2013
- const done = this.#done.get(id);
2815
+ const done = doneOf(t, column, key);
2014
2816
  if (done !== void 0) return done;
2015
2817
  if (this.#programOf(t, column, key) === void 0) return this.#unbound(t, column, key);
2016
2818
  const work = [this.#start(t, column, key)];
@@ -2026,7 +2828,7 @@ var SheetRun = class {
2026
2828
  work.pop();
2027
2829
  this.#end(visit, work.at(-1));
2028
2830
  }
2029
- return this.#done.get(id) ?? cycleError(column, key);
2831
+ return doneOf(t, column, key) ?? cycleError(column, key);
2030
2832
  }
2031
2833
  /** This method takes the component of `root` from the stack, and sets the final result of each of its cells. */
2032
2834
  #finish(root) {
@@ -2034,7 +2836,7 @@ var SheetRun = class {
2034
2836
  const cyclic = members.length > 1 || root.reread;
2035
2837
  for (const m of members) {
2036
2838
  this.#visits.delete(m.id);
2037
- this.#done.set(m.id, cyclic ? cycleError(m.column, m.key) : m.result);
2839
+ setDone(m.table, m.column, m.key, cyclic ? cycleError(m.column, m.key) : m.result);
2038
2840
  }
2039
2841
  }
2040
2842
  /** This method evaluates one cell with a trace of the nodes of its program. The result is the result of the cell. */
@@ -2056,6 +2858,27 @@ var SheetRun = class {
2056
2858
  };
2057
2859
  }
2058
2860
  /**
2861
+ * This method evaluates each cell of the table `table`, or of the main table (SHEET.FILL). Each column comes after
2862
+ * the columns that it reads, and the keys of a column come in the order of its reads from itself. Thus most reads
2863
+ * find a finished cell. An evaluation that reads a cell that is not finished has no effect, and the search then
2864
+ * evaluates its cell. A read of a cell gives the same result after a fill.
2865
+ */
2866
+ fill(table) {
2867
+ const t = table === void 0 ? this.#main : this.#byName.get(table);
2868
+ if (t === void 0 || this.#top.index >= 0) return;
2869
+ const host = this.#top;
2870
+ for (const column of columnOrder(t)) for (const key of keyOrder(t.space, readsOf(t, column).directions)) {
2871
+ const program = this.#programOf(t, column, key);
2872
+ if (program === void 0 || doneOf(t, column, key) !== void 0) continue;
2873
+ this.#top = this.#filling;
2874
+ this.#missed = false;
2875
+ const result = this.#run(t, column, key, program);
2876
+ this.#top = host;
2877
+ if (this.#missed) this.#drive(t, column, key);
2878
+ else setDone(t, column, key, result);
2879
+ }
2880
+ }
2881
+ /**
2059
2882
  * This method evaluates the column `column` at each key before `key`, in key order. A recurrence over the keys,
2060
2883
  * for example a running total, then reads finished cells.
2061
2884
  */
@@ -2085,6 +2908,16 @@ function toExpr(a, addr) {
2085
2908
  if (isChainLike(a)) return a.program;
2086
2909
  return lit(a);
2087
2910
  }
2911
+ /** This function gives the expressions of a step of a loop, with the unique names of the loop. */
2912
+ function stepExprs(step, unique, addr) {
2913
+ const out = {};
2914
+ for (const [n, a] of Object.entries(step)) {
2915
+ const name = unique.get(n);
2916
+ if (name === void 0) throw new TypeError(`the name "${n}" of the step is not a name of init`);
2917
+ out[name] = toExpr(a, addr);
2918
+ }
2919
+ return out;
2920
+ }
2088
2921
  const PROXY_RESERVED = /* @__PURE__ */ new Set([
2089
2922
  "then",
2090
2923
  "catch",
@@ -2152,10 +2985,10 @@ var ChainImpl = class ChainImpl {
2152
2985
  });
2153
2986
  }
2154
2987
  to(k) {
2155
- return this.#move(key(k));
2988
+ return this.#move(key(typeof k === "string" ? k : k.program));
2156
2989
  }
2157
2990
  index(i) {
2158
- return this.#move(index(i));
2991
+ return this.#move(index(typeof i === "number" ? i : i.program));
2159
2992
  }
2160
2993
  offset(...d) {
2161
2994
  return this.#move(offset(...d));
@@ -2226,6 +3059,72 @@ var ChainImpl = class ChainImpl {
2226
3059
  expr: let_(bindExprs, inner.program)
2227
3060
  });
2228
3061
  }
3062
+ functions(fns, body) {
3063
+ const depth = this.#s.depth;
3064
+ const binds = {};
3065
+ const calls = {};
3066
+ for (const [n, def] of Object.entries(fns)) {
3067
+ if (def.kind !== "vex.fn") throw new TypeError(`the function "${n}" is not a function of root.fn`);
3068
+ const unique = `${n}$${depth}`;
3069
+ const params = def.params.map((_k, i) => `${unique}$${i}`);
3070
+ const chains = params.map((p) => new ChainImpl({
3071
+ ...this.#s,
3072
+ expr: v(p),
3073
+ addr: [],
3074
+ depth: depth + 1
3075
+ }));
3076
+ binds[unique] = fn(params, def.build(...chains).program);
3077
+ calls[n] = (...args) => new ChainImpl({
3078
+ ...this.#s,
3079
+ expr: call(unique, ...args.map((a) => toExpr(a, []))),
3080
+ addr: [],
3081
+ depth: depth + 1
3082
+ });
3083
+ }
3084
+ const inner = body(new ChainImpl({
3085
+ ...this.#s,
3086
+ depth: depth + 1
3087
+ }), calls);
3088
+ return new ChainImpl({
3089
+ ...this.#s,
3090
+ expr: let_(binds, inner.program)
3091
+ });
3092
+ }
3093
+ /**
3094
+ * This method gives the names of a loop. Each name of `init` gets a name that is unique at the depth of the chain.
3095
+ * It also gets its first value at the address of the chain, and a chain of its value.
3096
+ */
3097
+ loopNames(init) {
3098
+ const depth = this.#s.depth;
3099
+ const unique = /* @__PURE__ */ new Map();
3100
+ const first = {};
3101
+ const vars = {};
3102
+ for (const [n, a] of Object.entries(init)) {
3103
+ const name = `${n}$${depth}`;
3104
+ unique.set(n, name);
3105
+ first[name] = toExpr(a, this.#s.addr);
3106
+ vars[n] = new ChainImpl({
3107
+ ...this.#s,
3108
+ expr: v(name),
3109
+ addr: [],
3110
+ depth: depth + 1
3111
+ });
3112
+ }
3113
+ return {
3114
+ unique,
3115
+ first,
3116
+ vars
3117
+ };
3118
+ }
3119
+ iterate(limit, init, step, result, opts) {
3120
+ const { unique, first, vars } = this.loopNames(init);
3121
+ const next = stepExprs(step(vars), unique, this.#s.addr);
3122
+ const until = opts?.until === void 0 ? void 0 : toExpr(opts.until(vars), this.#s.addr);
3123
+ return new ChainImpl({
3124
+ ...this.#s,
3125
+ expr: iterate(limit, first, next, toExpr(result(vars), this.#s.addr), until)
3126
+ });
3127
+ }
2229
3128
  #axis(a, body, opts) {
2230
3129
  const { name, start } = this.#bound();
2231
3130
  const inTarget = new ChainImpl({
@@ -2233,9 +3132,13 @@ var ChainImpl = class ChainImpl {
2233
3132
  addr: []
2234
3133
  });
2235
3134
  const inner = body(inTarget);
2236
- const axis = opts?.where === void 0 ? a : {
3135
+ const ordered = opts?.reverse === true ? {
3136
+ t: "reverse",
3137
+ axis: a
3138
+ } : a;
3139
+ const axis = opts?.where === void 0 ? ordered : {
2237
3140
  t: "where",
2238
- axis: a,
3141
+ axis: ordered,
2239
3142
  test: opts.where(inTarget).program
2240
3143
  };
2241
3144
  return new ListChainImpl({
@@ -2301,7 +3204,7 @@ function evalOptions(s, k) {
2301
3204
  ...env.options.extensions === void 0 ? {} : { extensions: env.options.extensions }
2302
3205
  };
2303
3206
  }
2304
- var ListChainImpl = class {
3207
+ var ListChainImpl = class ListChainImpl {
2305
3208
  kind = "vex.list-chain";
2306
3209
  #s;
2307
3210
  constructor(s) {
@@ -2310,6 +3213,26 @@ var ListChainImpl = class {
2310
3213
  get program() {
2311
3214
  return this.#s.expr;
2312
3215
  }
3216
+ fold(init, step, result) {
3217
+ const e = this.#s.expr;
3218
+ const loop = e.tag === "let" ? e.body : e;
3219
+ if (loop.tag !== "each") throw new TypeError("fold needs the list of an axis: go over the items of the list with each first");
3220
+ const names = new ChainImpl({
3221
+ ...this.#s,
3222
+ expr: lit(null)
3223
+ }).loopNames(init);
3224
+ const item = new ChainImpl({
3225
+ ...this.#s,
3226
+ expr: loop.body,
3227
+ addr: []
3228
+ });
3229
+ const next = stepExprs(step(names.vars, item), names.unique, []);
3230
+ const folded = fold(loop.axis, names.first, next, toExpr(result(names.vars), this.#s.addr), loop.at);
3231
+ return new ChainImpl({
3232
+ ...this.#s,
3233
+ expr: e.tag === "let" ? let_(e.bind, folded) : folded
3234
+ });
3235
+ }
2313
3236
  #op(op, extra, opts) {
2314
3237
  const options = {
2315
3238
  ...opts?.strict === true ? { strict: true } : {},
@@ -2360,6 +3283,46 @@ var ListChainImpl = class {
2360
3283
  reduce(op, opts) {
2361
3284
  return this.#op("reduce", [lit(op)], opts);
2362
3285
  }
3286
+ #list(op, extra, opts) {
3287
+ return new ListChainImpl({
3288
+ ...this.#s,
3289
+ expr: this.#op(op, extra, opts).program
3290
+ });
3291
+ }
3292
+ sortBy(opts) {
3293
+ return this.#list("sortBy", [], opts);
3294
+ }
3295
+ take(n, opts) {
3296
+ return this.#list("take", [lit(n)], opts);
3297
+ }
3298
+ nth(i, opts) {
3299
+ return this.#op("nth", [lit(i)], opts);
3300
+ }
3301
+ each(body, opts) {
3302
+ const start = new ChainImpl({
3303
+ ...this.#s,
3304
+ expr: lit(null),
3305
+ addr: [],
3306
+ depth: this.#s.depth + 1
3307
+ });
3308
+ const list = {
3309
+ t: "list",
3310
+ list: this.#s.expr
3311
+ };
3312
+ const ordered = opts?.reverse === true ? {
3313
+ t: "reverse",
3314
+ axis: list
3315
+ } : list;
3316
+ const axis = opts?.where === void 0 ? ordered : {
3317
+ t: "where",
3318
+ axis: ordered,
3319
+ test: opts.where(start).program
3320
+ };
3321
+ return new ListChainImpl({
3322
+ ...this.#s,
3323
+ expr: each(axis, body(start).program)
3324
+ });
3325
+ }
2363
3326
  result(k) {
2364
3327
  return evaluate(this.#s.expr, evalOptions(this.#s, k));
2365
3328
  }
@@ -2410,6 +3373,13 @@ var RootImpl = class {
2410
3373
  sheet() {
2411
3374
  return new SheetImpl(this.#env, /* @__PURE__ */ new Map());
2412
3375
  }
3376
+ fn(params, build) {
3377
+ return {
3378
+ kind: "vex.fn",
3379
+ params,
3380
+ build
3381
+ };
3382
+ }
2413
3383
  rec(fields) {
2414
3384
  const out = {};
2415
3385
  for (const [n, a] of Object.entries(fields)) out[n] = toExpr(a, []);
@@ -2473,6 +3443,7 @@ var SheetImpl = class SheetImpl {
2473
3443
  }
2474
3444
  table() {
2475
3445
  const run = this.#run();
3446
+ run.fill();
2476
3447
  const names = [...this.#columns.keys()];
2477
3448
  return this.#env.space.keys.map((key) => ({
2478
3449
  key,
@@ -2499,6 +3470,6 @@ function vex(...domains) {
2499
3470
  };
2500
3471
  }
2501
3472
  //#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 };
3473
+ export { CELL_KIND, LIST_OPS, MAX_ITERATIONS, MAX_NESTING, SPECIAL_FORMS, SheetRun, addrExprs, app, applyMove, axes, axisExprs, axisTargets, call, cell, chainResult, children, codeOf, compile, defineDomain, deps, describeType, domainOf, each, evaluate, explain, ext, fail, findMethod, fixAddr, fn, fold, formatError, formatTrace, getOr, index, isAxis, isDepthError, isExpr, isFieldName, isFixedAddr, isListOp, isMove, isNone, isOpName, isSome, isStackOverflow, isVexList, iterate, key, labelOf, let_, liftsAt, listOf, 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
3474
 
2504
3475
  //# sourceMappingURL=index.js.map