@mark1russell7/vex 0.4.0 → 0.6.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
@@ -38,6 +38,8 @@ const CODE_OF = {
38
38
  "no-offset": "#REF!",
39
39
  "no-grid": "#REF!",
40
40
  "no-tree": "#REF!",
41
+ "no-table": "#REF!",
42
+ "no-graph": "#REF!",
41
43
  "missing-field": "#N/A",
42
44
  empty: "#N/A",
43
45
  "not-instance": "#VALUE!",
@@ -50,8 +52,19 @@ const CODE_OF = {
50
52
  threw: "#CALC!",
51
53
  "undefined-result": "#CALC!",
52
54
  args: "#ARGS",
53
- cycle: "#CYCLE!"
55
+ cycle: "#CYCLE!",
56
+ depth: "#DEPTH!"
54
57
  };
58
+ /**
59
+ * This function tells if an exception is the report of the engine that the call stack is full. V8 and JavaScriptCore
60
+ * throw a `RangeError`. SpiderMonkey throws an `InternalError` ("too much recursion").
61
+ */
62
+ function isStackOverflow(thrown) {
63
+ if (!(thrown instanceof Error)) return false;
64
+ return thrown instanceof RangeError && /call stack/i.test(thrown.message) || thrown.name === "InternalError" && /recursion/i.test(thrown.message);
65
+ }
66
+ /** This function tells if an error is `#DEPTH!`. `ifError` and the reductions that skip errors do not hide it (EVAL.DEPTH). */
67
+ const isDepthError = (e) => e.kind === "depth";
55
68
  /** This function gives the code of an error kind. */
56
69
  const codeOf = (kind) => CODE_OF[kind];
57
70
  /** This function makes a `VexError`. */
@@ -177,6 +190,29 @@ const axes = {
177
190
  descendants: Object.freeze({ t: "descendants" }),
178
191
  /** The other children of the parent of the focus. For a root, the other roots. */
179
192
  siblings: Object.freeze({ t: "siblings" }),
193
+ /**
194
+ * The keys at the offsets from `from` to `to` of the focus, in order: a window of rows. The offset 0 is the focus. In
195
+ * a tree space, the offsets go among the siblings. An offset outside the space has no target.
196
+ */
197
+ window: (from, to) => ({
198
+ t: "window",
199
+ from,
200
+ to
201
+ }),
202
+ /**
203
+ * Each key of the table `name` of the evaluation, in key order. The body evaluates in the space of that table, and
204
+ * there the origin is the target.
205
+ */
206
+ table: (name) => ({
207
+ t: "table",
208
+ name
209
+ }),
210
+ /** The keys at the ends of the edges from the focus, in a graph space. In a tree space, the children. */
211
+ successors: Object.freeze({ t: "successors" }),
212
+ /** The keys with an edge to the focus, in key order. In a tree space, the parent. */
213
+ predecessors: Object.freeze({ t: "predecessors" }),
214
+ /** Each key that a path of edges reaches from the focus, in breadth-first order, without the focus. */
215
+ reachable: Object.freeze({ t: "reachable" }),
180
216
  /** The targets of `axis` where `test` gives `true`. */
181
217
  where: (axis, test) => ({
182
218
  t: "where",
@@ -199,37 +235,94 @@ function isMove(u) {
199
235
  default: return false;
200
236
  }
201
237
  }
202
- /** This function tells if a value is a valid axis. */
238
+ /** This function tells if a value is a valid axis. It checks the tests of `where` too. */
203
239
  function isAxis(u) {
204
- if (!isObject(u)) return false;
205
- switch (u["t"]) {
206
- case "all":
207
- case "others":
208
- case "other":
209
- case "children":
210
- case "ancestors":
211
- case "descendants":
212
- case "siblings": return true;
213
- case "neighbors": return u["n"] === 4 || u["n"] === 8;
214
- case "where": return isAxis(u["axis"]) && isExpr(u["test"]);
215
- default: return false;
216
- }
240
+ return validTree([{
241
+ axis: true,
242
+ u
243
+ }]);
217
244
  }
218
- const isExprRecord = (u) => isObject(u) && !Array.isArray(u) && Object.values(u).every((e) => isExpr(e));
219
245
  /** This function tells if a value is a valid expression. It checks the whole tree. */
220
246
  function isExpr(u) {
221
- if (!isObject(u)) return false;
222
- switch (u["tag"]) {
223
- case "lit": return "value" in u;
224
- case "ref": return isStringArray(u["path"]) && (u["at"] === void 0 || Array.isArray(u["at"]) && u["at"].every(isMove));
225
- case "app": return typeof u["op"] === "string" && Array.isArray(u["args"]) && u["args"].every((a) => isExpr(a));
226
- case "let": return isExprRecord(u["bind"]) && isExpr(u["body"]);
227
- case "var": return typeof u["name"] === "string";
228
- case "rec": return isExprRecord(u["fields"]);
229
- case "each": return isAxis(u["axis"]) && isExpr(u["body"]) && (u["at"] === void 0 || Array.isArray(u["at"]) && u["at"].every(isMove));
230
- case "ext": return typeof u["kind"] === "string" && "data" in u;
231
- default: return false;
247
+ return validTree([{
248
+ axis: false,
249
+ u
250
+ }]);
251
+ }
252
+ const isAddr = (u) => u === void 0 || Array.isArray(u) && u.every(isMove);
253
+ /**
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).
256
+ */
257
+ function validTree(todo) {
258
+ const push = (axis, values) => {
259
+ for (const u of values) todo.push({
260
+ axis,
261
+ u
262
+ });
263
+ };
264
+ for (let item = todo.pop(); item !== void 0; item = todo.pop()) {
265
+ const { u } = item;
266
+ if (!isObject(u)) return false;
267
+ if (item.axis) {
268
+ const t = u["t"];
269
+ if (t === "neighbors") {
270
+ if (u["n"] !== 4 && u["n"] !== 8) return false;
271
+ } else if (t === "window") {
272
+ if (!Number.isSafeInteger(u["from"]) || !Number.isSafeInteger(u["to"])) return false;
273
+ } else if (t === "table") {
274
+ if (typeof u["name"] !== "string") return false;
275
+ } else if (t === "where") {
276
+ push(true, [u["axis"]]);
277
+ push(false, [u["test"]]);
278
+ } else if (![
279
+ "all",
280
+ "others",
281
+ "other",
282
+ "children",
283
+ "ancestors",
284
+ "descendants",
285
+ "siblings",
286
+ "successors",
287
+ "predecessors",
288
+ "reachable"
289
+ ].includes(t)) return false;
290
+ continue;
291
+ }
292
+ switch (u["tag"]) {
293
+ case "lit":
294
+ if (!("value" in u)) return false;
295
+ break;
296
+ case "ref":
297
+ if (!isStringArray(u["path"]) || !isAddr(u["at"])) return false;
298
+ break;
299
+ case "app":
300
+ if (typeof u["op"] !== "string" || !Array.isArray(u["args"])) return false;
301
+ push(false, u["args"]);
302
+ break;
303
+ case "let":
304
+ if (!isObject(u["bind"]) || Array.isArray(u["bind"])) return false;
305
+ push(false, [...Object.values(u["bind"]), u["body"]]);
306
+ break;
307
+ case "var":
308
+ if (typeof u["name"] !== "string") return false;
309
+ break;
310
+ case "rec":
311
+ if (!isObject(u["fields"]) || Array.isArray(u["fields"])) return false;
312
+ push(false, Object.values(u["fields"]));
313
+ break;
314
+ case "each":
315
+ if (!isAddr(u["at"])) return false;
316
+ push(true, [u["axis"]]);
317
+ push(false, [u["body"]]);
318
+ break;
319
+ case "ext":
320
+ if (typeof u["kind"] !== "string" || !("data" in u)) return false;
321
+ break;
322
+ default: return false;
323
+ }
232
324
  }
325
+ return true;
233
326
  }
234
327
  /** This function gives the child expressions of an expression, in the order of their child index. */
235
328
  function children(e) {
@@ -244,8 +337,11 @@ function children(e) {
244
337
  case "ext": return [];
245
338
  }
246
339
  }
340
+ /** This function gives the tests of the `where` axes of an axis, from the inside out. It uses a loop, not recursion. */
247
341
  function whereTests(a) {
248
- return a.t === "where" ? [...whereTests(a.axis), a.test] : [];
342
+ const out = [];
343
+ for (let x = a; x.t === "where"; x = x.axis) out.unshift(x.test);
344
+ return out;
249
345
  }
250
346
  //#endregion
251
347
  //#region src/space.ts
@@ -361,6 +457,13 @@ var TreeSpace = class {
361
457
  }
362
458
  coords() {}
363
459
  keyAt() {}
460
+ successorsOf(k) {
461
+ return this.childrenOf(k);
462
+ }
463
+ predecessorsOf(k) {
464
+ const p = this.#parents.get(k);
465
+ return p === void 0 ? [] : [p];
466
+ }
364
467
  parentOf(k) {
365
468
  return this.#parents.get(k);
366
469
  }
@@ -369,6 +472,49 @@ var TreeSpace = class {
369
472
  }
370
473
  };
371
474
  /** The constructors of spaces. */
475
+ /** The empty list of keys. */
476
+ const NO_KEYS = Object.freeze([]);
477
+ var GraphSpace = class {
478
+ kind = "graph";
479
+ keys;
480
+ #records;
481
+ #out;
482
+ #in;
483
+ constructor(records, edges) {
484
+ const entries = Object.entries(records);
485
+ this.keys = Object.freeze(entries.map(([k]) => k));
486
+ this.#records = new Map(entries);
487
+ const out = /* @__PURE__ */ new Map();
488
+ for (const [k, to] of Object.entries(edges)) {
489
+ if (!this.#records.has(k)) throw new TypeError(`the graph has no key "${k}", but the edges name it`);
490
+ const ends = [...new Set(to ?? NO_KEYS)];
491
+ for (const t of ends) if (!this.#records.has(t)) throw new TypeError(`the edge from "${k}" goes to "${t}", which is not a key of the graph`);
492
+ out.set(k, Object.freeze(ends));
493
+ }
494
+ this.#out = out;
495
+ const into = /* @__PURE__ */ new Map();
496
+ for (const k of this.keys) for (const t of out.get(k) ?? NO_KEYS) {
497
+ const from = into.get(t);
498
+ if (from === void 0) into.set(t, [k]);
499
+ else from.push(k);
500
+ }
501
+ this.#in = new Map([...into].map(([k, from]) => [k, Object.freeze(from)]));
502
+ }
503
+ has(k) {
504
+ return this.#records.has(k);
505
+ }
506
+ get(k) {
507
+ return this.#records.get(k);
508
+ }
509
+ coords() {}
510
+ keyAt() {}
511
+ successorsOf(k) {
512
+ return this.#out.get(k) ?? NO_KEYS;
513
+ }
514
+ predecessorsOf(k) {
515
+ return this.#in.get(k) ?? NO_KEYS;
516
+ }
517
+ };
372
518
  const space = {
373
519
  /** This function makes a space from the entries of an object. The keys are the property names. */
374
520
  record(records) {
@@ -388,6 +534,13 @@ const space = {
388
534
  */
389
535
  tree(records, parents) {
390
536
  return new TreeSpace(records, parents);
537
+ },
538
+ /**
539
+ * This function makes a graph space: the records by key, and the edges from each key, in order. An edge to a key
540
+ * that is not in the graph throws a `TypeError`. A graph can have cycles, and an edge can go from a key to itself.
541
+ */
542
+ graph(records, edges) {
543
+ return new GraphSpace(records, edges);
391
544
  }
392
545
  };
393
546
  /** This function applies one move to the focus. It gives the new focus, or a `#REF!` error. */
@@ -516,8 +669,49 @@ function axisTargets(s, at, a) {
516
669
  case "ancestors":
517
670
  case "descendants":
518
671
  case "siblings": return treeTargets(s, at, a.t);
672
+ case "window": return windowTargets(s, at, a.from, a.to);
673
+ case "successors":
674
+ case "predecessors":
675
+ case "reachable": return graphTargets(s, at, a.t);
676
+ 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));
519
677
  }
520
678
  }
679
+ /**
680
+ * This function gives the targets of an axis of a graph. `reachable` has each key that a path of one or more edges
681
+ * reaches from the focus, once, in the order of a breadth-first search. The focus is not a target of `reachable`.
682
+ */
683
+ function graphTargets(s, at, t) {
684
+ const successorsOf = s.successorsOf?.bind(s);
685
+ const predecessorsOf = s.predecessorsOf?.bind(s);
686
+ if (successorsOf === void 0 || predecessorsOf === void 0) return fail(vexError("no-graph", `"${t}" needs a graph space or a tree space, but this space is a ${s.kind}`, at));
687
+ if (t === "successors") return ok(successorsOf(at.focus));
688
+ if (t === "predecessors") return ok(predecessorsOf(at.focus));
689
+ const seen = /* @__PURE__ */ new Set([at.focus]);
690
+ const queue = [at.focus];
691
+ for (const k of queue) for (const next of successorsOf(k)) {
692
+ if (seen.has(next)) continue;
693
+ seen.add(next);
694
+ queue.push(next);
695
+ }
696
+ return ok(queue.slice(1));
697
+ }
698
+ /**
699
+ * This function gives the targets of the axis `window(from, to)`: the keys of the moves `offset(d)` for each `d`
700
+ * from `from` to `to`, in order. An offset outside the space has no target. The axis needs an array space or a tree
701
+ * space, where an offset has one number.
702
+ */
703
+ function windowTargets(s, at, from, to) {
704
+ if (!(s.parentOf !== void 0 && s.childrenOf !== void 0) && s.coords(at.focus)?.length !== 1) return fail(vexError("no-offset", `"window" needs an array space or a tree space, but this space is a ${s.kind}`, at));
705
+ const out = [];
706
+ for (let d = Math.max(from, -s.keys.length); d <= Math.min(to, s.keys.length); d++) {
707
+ const r = applyMove(s, at, {
708
+ t: "offset",
709
+ d: [d]
710
+ });
711
+ if (r.ok) out.push(r.value);
712
+ }
713
+ return ok(out);
714
+ }
521
715
  //#endregion
522
716
  //#region src/domain.ts
523
717
  /** This function makes a domain. The result is frozen. */
@@ -621,8 +815,27 @@ const isSpecialForm = (op) => SPECIAL_FORMS.has(op);
621
815
  * This function compiles an expression. The result gives the same results and the same traces as `evaluate`,
622
816
  * because `evaluate` uses it too.
623
817
  */
818
+ /** The deepest nesting of an expression that `compile` accepts (EVAL.NESTING). */
819
+ const MAX_NESTING = 500;
820
+ const DEPTH_MESSAGE = "the evaluation is too deep for the call stack of the engine";
821
+ /** This function gives the number of nodes on the longest path from the root of `e`. It uses a stack, not recursion. */
822
+ function nestingOf(e) {
823
+ let deepest = 0;
824
+ const todo = [[e, 1]];
825
+ for (let item = todo.pop(); item !== void 0; item = todo.pop()) {
826
+ const [x, d] = item;
827
+ if (d > deepest) deepest = d;
828
+ for (const child of children(x)) todo.push([child, d + 1]);
829
+ }
830
+ return deepest;
831
+ }
624
832
  function compile(expr, opts = {}) {
625
- const root = new Compiler(opts).node(expr, []);
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`, {
835
+ path: [],
836
+ origin: f.pos.origin,
837
+ focus: f.pos.focus
838
+ })) : new Compiler(opts).node(expr, []);
626
839
  const run = (r) => {
627
840
  const { space, origin } = r;
628
841
  if (!space.has(origin)) return fail(vexError("unknown-key", `the space has no key "${origin}"`, {
@@ -639,9 +852,15 @@ function compile(expr, opts = {}) {
639
852
  env
640
853
  }, {
641
854
  space,
642
- trace: r.trace
855
+ trace: r.trace,
856
+ tables: r.tables
643
857
  });
644
858
  } catch (thrown) {
859
+ if (isStackOverflow(thrown)) return fail(vexError("depth", DEPTH_MESSAGE, {
860
+ origin,
861
+ focus: origin,
862
+ thrown
863
+ }));
645
864
  return fail(vexError("threw", "the evaluation threw an exception", {
646
865
  origin,
647
866
  focus: origin,
@@ -686,6 +905,8 @@ function evaluate(expr, opts) {
686
905
  function explain(expr, opts) {
687
906
  return compiled(expr, opts).explain(opts);
688
907
  }
908
+ /** This function gives the axis inside the `where` axes of an axis. */
909
+ const baseAxis = (a) => a.t === "where" ? baseAxis(a.axis) : a;
689
910
  var Compiler = class {
690
911
  #domains;
691
912
  #fns;
@@ -792,12 +1013,19 @@ var Compiler = class {
792
1013
  try {
793
1014
  return run();
794
1015
  } catch (thrown) {
795
- return this.#err("threw", `"${op}" threw an exception`, f, path, {
796
- op,
797
- thrown
798
- });
1016
+ return this.#threw(thrown, `"${op}" threw an exception`, f, path, { op });
799
1017
  }
800
1018
  }
1019
+ /** This method gives the error of an exception: `#DEPTH!` for a full call stack, and `#CALC!` for each other exception. */
1020
+ #threw(thrown, message, f, path, extra = {}) {
1021
+ return isStackOverflow(thrown) ? this.#err("depth", DEPTH_MESSAGE, f, path, {
1022
+ ...extra,
1023
+ thrown
1024
+ }) : this.#err("threw", message, f, path, {
1025
+ ...extra,
1026
+ thrown
1027
+ });
1028
+ }
801
1029
  #ref(e, info) {
802
1030
  const { path } = info;
803
1031
  const segs = e.path;
@@ -831,7 +1059,7 @@ var Compiler = class {
831
1059
  try {
832
1060
  value = Reflect.get(value, seg);
833
1061
  } catch (thrown) {
834
- return failed(this.#err("threw", `reading "${where}" at "${key}" threw an exception`, f, path, { thrown }));
1062
+ return failed(this.#threw(thrown, `reading "${where}" at "${key}" threw an exception`, f, path));
835
1063
  }
836
1064
  if (value === void 0 || value === null) return missing(where);
837
1065
  }
@@ -854,6 +1082,8 @@ var Compiler = class {
854
1082
  else (errors ??= [first]).push(r.error);
855
1083
  }
856
1084
  if (first === void 0) return ok(values);
1085
+ const depth = [first, ...errors ?? []].find(isDepthError);
1086
+ if (depth !== void 0) return fail(depth);
857
1087
  return errors === void 0 ? fail(first) : this.#err("args", `${errors.length} ${what} failed`, f, path, { causes: errors });
858
1088
  }
859
1089
  #each(e, info) {
@@ -877,7 +1107,17 @@ var Compiler = class {
877
1107
  env: f.env
878
1108
  };
879
1109
  }
880
- const ts = targets(from, c);
1110
+ const base = baseAxis(e.axis);
1111
+ let inner = c;
1112
+ if (base.t === "table") {
1113
+ const space = c.tables !== void 0 && Object.hasOwn(c.tables, base.name) ? c.tables[base.name] : void 0;
1114
+ if (space === void 0) return this.#emit(c, info, f, this.#err("no-table", `the evaluation has no table "${base.name}"`, f, path));
1115
+ inner = {
1116
+ ...c,
1117
+ space
1118
+ };
1119
+ }
1120
+ const ts = targets(from, inner);
881
1121
  if (!ts.ok) return this.#emit(c, info, f, ts);
882
1122
  const items = ts.value.map(({ key, test }) => {
883
1123
  if (test !== void 0 && !test.ok) return {
@@ -888,11 +1128,11 @@ var Compiler = class {
888
1128
  key,
889
1129
  result: body({
890
1130
  pos: {
891
- origin: f.pos.origin,
1131
+ origin: base.t === "table" ? key : f.pos.origin,
892
1132
  focus: key
893
1133
  },
894
1134
  env: f.env
895
- }, c)
1135
+ }, inner)
896
1136
  };
897
1137
  });
898
1138
  return this.#emit(c, info, f, ok(vexList(items)));
@@ -900,6 +1140,7 @@ var Compiler = class {
900
1140
  }
901
1141
  /** This method compiles the targets of an axis. For `where`, a failed test keeps the target with its error. */
902
1142
  #targets(a, path, counter) {
1143
+ if (a.t === "table") return (_f, c) => ok(c.space.keys.map((key) => ({ key })));
903
1144
  if (a.t !== "where") return (f, c) => {
904
1145
  const keys = axisTargets(c.space, f.pos, a);
905
1146
  return keys.ok ? ok(keys.value.map((key) => ({ key }))) : fail({
@@ -910,6 +1151,7 @@ var Compiler = class {
910
1151
  const inner = this.#targets(a.axis, path, counter);
911
1152
  const testPath = [...path, counter.next++];
912
1153
  const test = this.node(a.test, testPath);
1154
+ const sameOrigin = baseAxis(a).t === "table";
913
1155
  return (f, c) => {
914
1156
  const ts = inner(f, c);
915
1157
  if (!ts.ok) return ts;
@@ -921,7 +1163,7 @@ var Compiler = class {
921
1163
  }
922
1164
  const at = {
923
1165
  pos: {
924
- origin: f.pos.origin,
1166
+ origin: sameOrigin ? t.key : f.pos.origin,
925
1167
  focus: t.key
926
1168
  },
927
1169
  env: f.env
@@ -994,7 +1236,7 @@ var Compiler = class {
994
1236
  }
995
1237
  case "ifError": return (f, c) => {
996
1238
  const first = arg(0, f, c);
997
- return this.#emit(c, info, f, first.ok ? first : arg(1, f, c));
1239
+ return this.#emit(c, info, f, first.ok || isDepthError(first.error) ? first : arg(1, f, c));
998
1240
  };
999
1241
  }
1000
1242
  }
@@ -1021,10 +1263,7 @@ var Compiler = class {
1021
1263
  try {
1022
1264
  return ok(run());
1023
1265
  } catch (thrown) {
1024
- return this.#err("threw", `"${op}" threw an exception`, f, path, {
1025
- op,
1026
- thrown
1027
- });
1266
+ return this.#threw(thrown, `"${op}" threw an exception`, f, path, { op });
1028
1267
  }
1029
1268
  }
1030
1269
  /** This method checks the value that an op gave: no `undefined`, finite numbers, and valid domain values. */
@@ -1040,10 +1279,7 @@ var Compiler = class {
1040
1279
  try {
1041
1280
  valid = d.valid(value);
1042
1281
  } catch (thrown) {
1043
- return this.#err("threw", `the "valid" check of "${d.name}" threw an exception`, f, path, {
1044
- ...extra,
1045
- thrown
1046
- });
1282
+ return this.#threw(thrown, `the "valid" check of "${d.name}" threw an exception`, f, path, extra);
1047
1283
  }
1048
1284
  if (!valid) return this.#err("invalid-value", `"${op}" gave a value that is not a valid ${d.name}`, f, path, extra);
1049
1285
  }
@@ -1051,6 +1287,8 @@ var Compiler = class {
1051
1287
  }
1052
1288
  #listOp(op, list, rest, f, path) {
1053
1289
  const optsArg = op === "reduce" ? rest[1] : rest[0];
1290
+ const depth = list.items.find((it) => !it.result.ok && isDepthError(it.result.error))?.result;
1291
+ if (depth !== void 0 && !depth.ok) return fail(depth.error);
1054
1292
  const strict = optsArg?.strict === true;
1055
1293
  const firstError = list.items.find((it) => !it.result.ok)?.result;
1056
1294
  if (strict && firstError !== void 0 && !firstError.ok) return fail(firstError.error);
@@ -1231,25 +1469,30 @@ const sizeOf = (e) => 1 + children(e).reduce((s, c) => s + sizeOf(c), 0);
1231
1469
  */
1232
1470
  function deps(e) {
1233
1471
  const out = [];
1234
- const walk = (x, axes, axisAt) => {
1472
+ const todo = [{
1473
+ x: e,
1474
+ axes: [],
1475
+ axisAt: []
1476
+ }];
1477
+ for (let item = todo.pop(); item !== void 0; item = todo.pop()) {
1478
+ const { x } = item;
1235
1479
  if (x.tag === "ref") {
1236
1480
  out.push({
1237
1481
  at: x.at ?? [],
1238
1482
  path: x.path,
1239
- axes,
1240
- axisAt
1483
+ axes: item.axes,
1484
+ axisAt: item.axisAt
1241
1485
  });
1242
- return;
1486
+ continue;
1243
1487
  }
1244
- if (x.tag === "each") {
1245
- const inner = [...axes, x.axis.t];
1246
- const innerAt = [...axisAt, x.at ?? []];
1247
- children(x).forEach((c) => walk(c, inner, innerAt));
1248
- return;
1249
- }
1250
- children(x).forEach((c) => walk(c, axes, axisAt));
1251
- };
1252
- walk(e, [], []);
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
+ });
1495
+ }
1253
1496
  return out;
1254
1497
  }
1255
1498
  //#endregion
@@ -1409,6 +1652,7 @@ function serialize(e, domains = []) {
1409
1652
  const tree = mapValues(e, (v) => encodeValue(v, domains));
1410
1653
  return tree.ok ? ok(JSON.stringify(tree.value)) : fail(tree.error);
1411
1654
  } catch (thrown) {
1655
+ if (isStackOverflow(thrown)) return fail(vexError("depth", "the expression is too deep for the call stack of the engine", { thrown }));
1412
1656
  return fail(vexError("threw", "the expression has no JSON form", { thrown }));
1413
1657
  }
1414
1658
  }
@@ -1420,9 +1664,14 @@ function parse(text, domains = []) {
1420
1664
  } catch (thrown) {
1421
1665
  return fail(vexError("bad-expression", "the text is not JSON", { thrown }));
1422
1666
  }
1423
- const tree = mapValues(raw, (v) => decodeValue(v, domains));
1424
- if (!tree.ok) return fail(tree.error);
1425
- return isExpr(tree.value) ? ok(tree.value) : fail(vexError("bad-expression", "the JSON is not a valid Vex expression"));
1667
+ try {
1668
+ const tree = mapValues(raw, (v) => decodeValue(v, domains));
1669
+ if (!tree.ok) return fail(tree.error);
1670
+ return isExpr(tree.value) ? ok(tree.value) : fail(vexError("bad-expression", "the JSON is not a valid Vex expression"));
1671
+ } catch (thrown) {
1672
+ if (isStackOverflow(thrown)) return fail(vexError("depth", "the JSON is too deep for the call stack of the engine", { thrown }));
1673
+ return fail(vexError("threw", "a decoder of a domain threw an exception", { thrown }));
1674
+ }
1426
1675
  }
1427
1676
  //#endregion
1428
1677
  //#region src/traversal.ts
@@ -1516,6 +1765,9 @@ function traversal(items, env, isStrict = false) {
1516
1765
  *
1517
1766
  * A cell reference is the extension node `ext("vex.cell", { column, at })`. Thus the IR has no new kind, and the
1518
1767
  * JSON form, `deps` and the traces work without a change.
1768
+ *
1769
+ * A cell can have its own formula. That formula replaces the formula of the column at the key of the cell. A
1770
+ * spreadsheet has the same thing: a cell with a formula that is different from the other formulas of its column.
1519
1771
  */
1520
1772
  /** The extension kind of a cell reference. */
1521
1773
  const CELL_KIND = "vex.cell";
@@ -1529,34 +1781,120 @@ const cycleError = (column, key) => fail(vexError("cycle", `the cell "${column}"
1529
1781
  origin: key,
1530
1782
  focus: key
1531
1783
  }));
1784
+ /** The id of a cell. */
1785
+ const idOf = (t, column, key) => `${t.tag}\u0001${column}\u0000${key}`;
1786
+ /** This function gives the state of a table at the start of a run. */
1787
+ const tableState = (where, i, t) => ({
1788
+ where,
1789
+ tag: String(i),
1790
+ space: t.space,
1791
+ columns: t.columns,
1792
+ cells: t.cells ?? /* @__PURE__ */ new Map(),
1793
+ warmed: /* @__PURE__ */ new Map(),
1794
+ index: void 0
1795
+ });
1796
+ /**
1797
+ * The budget of the stack for the recursion of a run, in estimated frames. Each engine has more stack than this, so
1798
+ * the recursion of a run cannot fill the stack (SHEET.DEEP).
1799
+ */
1800
+ const STACK_BUDGET = 3e3;
1801
+ /**
1802
+ * One run of a sheet. It keeps the result of each cell that it evaluated. The space does not change, so a cell has
1803
+ * one result in a run.
1804
+ *
1805
+ * The run is a depth-first search with the algorithm of Tarjan for strongly connected components. A cell finishes
1806
+ * when its component finishes. Each cell of a component with two or more cells, or with a reference to itself,
1807
+ * gives `#CYCLE!`. A read of a cell that is not finished gives `#CYCLE!` too. Thus the order of the evaluations
1808
+ * does not change a result, also when `ifError` catches the error of a cycle.
1809
+ *
1810
+ * The search does not depend on the call stack of the engine (SHEET.DEEP). A read of a cell evaluates that cell
1811
+ * with recursion while the stack of the run stays in a budget. When a read is over the budget, the run starts the
1812
+ * cell, and the cell that reads it pauses. A paused evaluation reads no other cell and changes no state of the
1813
+ * search. The run then evaluates the started cell from its own list, and it evaluates the paused cell again after
1814
+ * that cell. A formula is pure (EVAL.PURE), so the second evaluation gives the result of one evaluation.
1815
+ *
1816
+ * A run can have more tables (SHEET.TABLES). Each table has its own space, and one search covers the cells of all
1817
+ * the tables. Thus a cycle across tables gives `#CYCLE!` too.
1818
+ */
1532
1819
  var SheetRun = class {
1533
- #columns;
1820
+ #main;
1821
+ #byName = /* @__PURE__ */ new Map();
1822
+ #bySpace = /* @__PURE__ */ new Map();
1534
1823
  #opts;
1535
1824
  #done = /* @__PURE__ */ new Map();
1536
- #warmed = /* @__PURE__ */ new Map();
1537
- #index;
1538
1825
  #visits = /* @__PURE__ */ new Map();
1539
1826
  #stack = [];
1540
- #top = {
1541
- id: "",
1542
- column: "",
1543
- key: "",
1544
- index: -1,
1545
- low: -1,
1546
- reread: false,
1547
- result: cycleError("", "")
1548
- };
1827
+ #top;
1549
1828
  #next = 0;
1550
- constructor(columns, opts) {
1551
- this.#columns = columns;
1829
+ #used = 0;
1830
+ #cost = /* @__PURE__ */ new Map();
1831
+ #budget;
1832
+ /** `budget` is the budget of the stack in estimated frames. A test can make it small, so the run pauses often. */
1833
+ constructor(columns, opts, budget = STACK_BUDGET) {
1834
+ const { cells, name, tables, space, ...rest } = opts;
1835
+ this.#main = {
1836
+ where: "the sheet",
1837
+ tag: "0",
1838
+ space,
1839
+ columns,
1840
+ cells: cells ?? /* @__PURE__ */ new Map(),
1841
+ warmed: /* @__PURE__ */ new Map(),
1842
+ index: void 0
1843
+ };
1844
+ this.#bySpace.set(space, this.#main);
1845
+ if (name !== void 0) this.#byName.set(name, this.#main);
1846
+ if (tables !== void 0) {
1847
+ let i = 0;
1848
+ for (const [n, t] of tables) {
1849
+ if (this.#byName.has(n)) continue;
1850
+ const other = tableState(`the table "${n}"`, ++i, t);
1851
+ this.#byName.set(n, other);
1852
+ if (!this.#bySpace.has(t.space)) this.#bySpace.set(t.space, other);
1853
+ }
1854
+ }
1855
+ this.#top = {
1856
+ id: "",
1857
+ table: this.#main,
1858
+ column: "",
1859
+ key: "",
1860
+ index: -1,
1861
+ low: -1,
1862
+ reread: false,
1863
+ result: cycleError("", ""),
1864
+ paused: false,
1865
+ need: void 0
1866
+ };
1867
+ this.#budget = budget;
1868
+ const spaces = Object.fromEntries([...this.#byName].map(([n, t]) => [n, t.space]));
1552
1869
  this.#opts = {
1553
- ...opts,
1870
+ ...rest,
1871
+ tables: spaces,
1554
1872
  extensions: {
1555
- ...opts.extensions,
1873
+ ...rest.extensions,
1556
1874
  [CELL_KIND]: this.#handler
1557
1875
  }
1558
1876
  };
1559
1877
  }
1878
+ /** This method gives the program of a cell: its own formula, or the formula of its column (SHEET.CELL.FORMULA). */
1879
+ #programOf(t, column, key) {
1880
+ return (t.cells.size === 0 ? void 0 : t.cells.get(column)?.get(key)) ?? t.columns.get(column);
1881
+ }
1882
+ /** This method gives the error of a cell without a program. */
1883
+ #unbound(t, column, key) {
1884
+ const message = t.cells.has(column) ? `the cell "${column}" at "${key}" has no formula` : `${t.where} has no column "${column}"`;
1885
+ return fail(vexError("unbound", message, {
1886
+ origin: key,
1887
+ focus: key
1888
+ }));
1889
+ }
1890
+ /** This method gives the table of a name for a read from a host. Without a name, it is the main table. */
1891
+ #named(table, key) {
1892
+ if (table === void 0) return this.#main;
1893
+ return this.#byName.get(table) ?? fail(vexError("no-table", `the run has no table "${table}"`, {
1894
+ origin: key,
1895
+ focus: key
1896
+ }));
1897
+ }
1560
1898
  #handler = (data, ctx) => {
1561
1899
  if (!isCellRef(data)) return fail(vexError("bad-expression", "a cell reference needs a column name and an address", { path: ctx.path }));
1562
1900
  const where = resolveAddr(ctx.space, ctx.position, data.at);
@@ -1564,86 +1902,154 @@ var SheetRun = class {
1564
1902
  ...where.error,
1565
1903
  path: ctx.path
1566
1904
  });
1567
- return this.cell(data.column, where.value);
1905
+ /* v8 ignore next -- @preserve: each space of an evaluation of the run is the space of a table */
1906
+ return this.#read(this.#bySpace.get(ctx.space) ?? this.#main, data.column, where.value);
1568
1907
  };
1569
1908
  /**
1570
- * This method gives the result of one cell: the column `column` at the key `key`. A read from a host first evaluates
1571
- * the column at the keys before `key`, in key order. Thus a recurrence over the keys reads finished cells, and a
1572
- * first read at the last key does not go deep into the call stack.
1909
+ * This method gives the result of one cell: the column `column` at the key `key` of the main table, or of the table
1910
+ * `table`. A read from a host first evaluates the column at the keys before `key`, in key order. Thus a recurrence
1911
+ * over the keys reads finished cells.
1573
1912
  */
1574
- cell(column, key) {
1575
- if (this.#top.index < 0) this.#warmTo(column, key);
1576
- return this.#cell(column, key);
1913
+ cell(column, key, table) {
1914
+ const t = this.#named(table, key);
1915
+ if (!("space" in t)) return t;
1916
+ if (this.#top.index >= 0) return this.#read(t, column, key);
1917
+ this.#warmTo(t, column, key);
1918
+ return this.#drive(t, column, key);
1577
1919
  }
1578
1920
  /** This method evaluates the column `column` at each key before `key` that it did not evaluate before, in key order. */
1579
- #warmTo(column, key) {
1580
- if (!this.#columns.has(column)) return;
1581
- const keys = this.#opts.space.keys;
1582
- this.#index ??= new Map(keys.map((k, i) => [k, i]));
1583
- const end = this.#index.get(key) ?? 0;
1584
- const start = this.#warmed.get(column) ?? 0;
1585
- for (let i = start; i < end; i++) this.#cell(column, keys[i] ?? key);
1586
- if (end > start) this.#warmed.set(column, end);
1587
- }
1588
- /** This method evaluates one cell, without the warm-up of `cell`. */
1589
- #cell(column, key) {
1590
- const id = `${column}\u0000${key}`;
1591
- const done = this.#done.get(id);
1592
- if (done !== void 0) return done;
1593
- const caller = this.#top;
1594
- const seen = this.#visits.get(id);
1595
- if (seen !== void 0) {
1596
- caller.low = Math.min(caller.low, seen.index);
1597
- seen.reread = true;
1598
- return cycleError(column, key);
1921
+ #warmTo(t, column, key) {
1922
+ if (!t.columns.has(column)) return;
1923
+ const keys = t.space.keys;
1924
+ t.index ??= new Map(keys.map((k, i) => [k, i]));
1925
+ const end = t.index.get(key) ?? 0;
1926
+ const start = t.warmed.get(column) ?? 0;
1927
+ for (let i = start; i < end; i++) this.#drive(t, column, keys[i] ?? key);
1928
+ if (end > start) t.warmed.set(column, end);
1929
+ }
1930
+ /** This method gives the estimated frames of the stack that one evaluation of the program `program` uses. */
1931
+ #costOf(program) {
1932
+ let cost = this.#cost.get(program);
1933
+ if (cost === void 0) {
1934
+ cost = 3 * nestingOf(program) + 16;
1935
+ this.#cost.set(program, cost);
1599
1936
  }
1600
- const program = this.#columns.get(column);
1601
- if (program === void 0) return fail(vexError("unbound", `the sheet has no column "${column}"`, {
1602
- origin: key,
1603
- focus: key
1604
- }));
1937
+ return cost;
1938
+ }
1939
+ /** This method puts a new cell on the stack of the search. */
1940
+ #start(t, column, key) {
1605
1941
  const n = this.#next++;
1606
1942
  const visit = {
1607
- id,
1943
+ id: idOf(t, column, key),
1944
+ table: t,
1608
1945
  column,
1609
1946
  key,
1610
1947
  index: n,
1611
1948
  low: n,
1612
1949
  reread: false,
1613
- result: cycleError(column, key)
1950
+ result: cycleError(column, key),
1951
+ paused: false,
1952
+ need: void 0
1614
1953
  };
1615
- this.#visits.set(id, visit);
1954
+ this.#visits.set(visit.id, visit);
1616
1955
  this.#stack.push(visit);
1956
+ return visit;
1957
+ }
1958
+ /** This method evaluates the formula of a cell once. When the evaluation pauses, the result of the cell does not change. */
1959
+ #evaluate(visit, program) {
1960
+ const caller = this.#top;
1961
+ const cost = this.#costOf(program);
1962
+ visit.paused = false;
1963
+ visit.need = void 0;
1617
1964
  this.#top = visit;
1618
- visit.result = evaluate(program, {
1965
+ this.#used += cost;
1966
+ const result = evaluate(program, {
1619
1967
  ...this.#opts,
1620
- origin: key
1968
+ space: visit.table.space,
1969
+ origin: visit.key
1621
1970
  });
1971
+ this.#used -= cost;
1622
1972
  this.#top = caller;
1973
+ if (!visit.paused) visit.result = result;
1974
+ }
1975
+ /** This method ends a cell whose evaluation did not pause: it finishes its component, or it gives its low to the caller. */
1976
+ #end(visit, caller) {
1623
1977
  if (visit.low === visit.index) this.#finish(visit);
1624
- else caller.low = Math.min(caller.low, visit.low);
1978
+ else if (caller !== void 0) caller.low = Math.min(caller.low, visit.low);
1979
+ }
1980
+ /** This method reads a cell from the formula of the cell at the top. */
1981
+ #read(t, column, key) {
1982
+ const id = idOf(t, column, key);
1983
+ const done = this.#done.get(id);
1984
+ if (done !== void 0) return done;
1985
+ const caller = this.#top;
1986
+ if (caller.paused) return cycleError(column, key);
1987
+ const seen = this.#visits.get(id);
1988
+ if (seen !== void 0) {
1989
+ caller.low = Math.min(caller.low, seen.index);
1990
+ seen.reread = true;
1991
+ return cycleError(column, key);
1992
+ }
1993
+ const program = this.#programOf(t, column, key);
1994
+ if (program === void 0) return this.#unbound(t, column, key);
1995
+ const visit = this.#start(t, column, key);
1996
+ if (this.#used + this.#costOf(program) > this.#budget) {
1997
+ caller.paused = true;
1998
+ caller.need = visit;
1999
+ return cycleError(column, key);
2000
+ }
2001
+ this.#evaluate(visit, program);
2002
+ if (visit.paused) {
2003
+ caller.paused = true;
2004
+ caller.need = visit;
2005
+ return cycleError(column, key);
2006
+ }
2007
+ this.#end(visit, caller);
2008
+ return this.#done.get(id) ?? cycleError(column, key);
2009
+ }
2010
+ /** This method evaluates a cell from the top level. The cells that pause go on a list, not on the call stack. */
2011
+ #drive(t, column, key) {
2012
+ const id = idOf(t, column, key);
2013
+ const done = this.#done.get(id);
2014
+ if (done !== void 0) return done;
2015
+ if (this.#programOf(t, column, key) === void 0) return this.#unbound(t, column, key);
2016
+ const work = [this.#start(t, column, key)];
2017
+ for (let visit = work.at(-1); visit !== void 0; visit = work.at(-1)) {
2018
+ const program = this.#programOf(visit.table, visit.column, visit.key);
2019
+ /* v8 ignore next -- @preserve: a visit exists only for a cell with a program */
2020
+ if (program === void 0) break;
2021
+ this.#evaluate(visit, program);
2022
+ if (visit.paused) {
2023
+ for (let need = visit.need; need !== void 0; need = need.need) work.push(need);
2024
+ continue;
2025
+ }
2026
+ work.pop();
2027
+ this.#end(visit, work.at(-1));
2028
+ }
1625
2029
  return this.#done.get(id) ?? cycleError(column, key);
1626
2030
  }
1627
2031
  /** This method takes the component of `root` from the stack, and sets the final result of each of its cells. */
1628
2032
  #finish(root) {
1629
- const members = this.#stack.splice(this.#stack.indexOf(root));
2033
+ const members = this.#stack.splice(this.#stack.lastIndexOf(root));
1630
2034
  const cyclic = members.length > 1 || root.reread;
1631
2035
  for (const m of members) {
1632
2036
  this.#visits.delete(m.id);
1633
2037
  this.#done.set(m.id, cyclic ? cycleError(m.column, m.key) : m.result);
1634
2038
  }
1635
2039
  }
1636
- /** This method evaluates one cell with a trace of the nodes of its column. The result is the result of the cell. */
1637
- explain(column, key) {
1638
- const result = this.cell(column, key);
1639
- const program = this.#columns.get(column);
1640
- if (program === void 0) return {
2040
+ /** This method evaluates one cell with a trace of the nodes of its program. The result is the result of the cell. */
2041
+ explain(column, key, table) {
2042
+ const result = this.cell(column, key, table);
2043
+ const t = this.#named(table, key);
2044
+ const program = "space" in t ? this.#programOf(t, column, key) : void 0;
2045
+ if (program === void 0 || !("space" in t)) return {
1641
2046
  events: [],
1642
2047
  result
1643
2048
  };
1644
2049
  return {
1645
2050
  events: explain(program, {
1646
2051
  ...this.#opts,
2052
+ space: t.space,
1647
2053
  origin: key
1648
2054
  }).events,
1649
2055
  result
@@ -1651,10 +2057,11 @@ var SheetRun = class {
1651
2057
  }
1652
2058
  /**
1653
2059
  * This method evaluates the column `column` at each key before `key`, in key order. A recurrence over the keys,
1654
- * for example a running total, then reads finished cells and does not go deep into the call stack.
2060
+ * for example a running total, then reads finished cells.
1655
2061
  */
1656
- warm(column, key) {
1657
- this.#warmTo(column, key);
2062
+ warm(column, key, table) {
2063
+ const t = this.#named(table, key);
2064
+ if ("space" in t) this.#warmTo(t, column, key);
1658
2065
  }
1659
2066
  };
1660
2067
  //#endregion
@@ -1860,6 +2267,28 @@ var ChainImpl = class ChainImpl {
1860
2267
  siblings(body, opts) {
1861
2268
  return this.#axis({ t: "siblings" }, body, opts);
1862
2269
  }
2270
+ window(from, to, body, opts) {
2271
+ return this.#axis({
2272
+ t: "window",
2273
+ from,
2274
+ to
2275
+ }, body, opts);
2276
+ }
2277
+ table(name, body, opts) {
2278
+ return this.#axis({
2279
+ t: "table",
2280
+ name
2281
+ }, body, opts);
2282
+ }
2283
+ successors(body, opts) {
2284
+ return this.#axis({ t: "successors" }, body, opts);
2285
+ }
2286
+ predecessors(body, opts) {
2287
+ return this.#axis({ t: "predecessors" }, body, opts);
2288
+ }
2289
+ reachable(body, opts) {
2290
+ return this.#axis({ t: "reachable" }, body, opts);
2291
+ }
1863
2292
  };
1864
2293
  /** This function gives the options of an evaluation of a chain or a list chain at the origin `k`. */
1865
2294
  function evalOptions(s, k) {
@@ -1995,25 +2424,36 @@ var SheetRootImpl = class extends RootImpl {
1995
2424
  var SheetImpl = class SheetImpl {
1996
2425
  #env;
1997
2426
  #columns;
1998
- constructor(env, columns) {
2427
+ #cells;
2428
+ constructor(env, columns, cells = /* @__PURE__ */ new Map()) {
1999
2429
  this.#env = env;
2000
2430
  this.#columns = columns;
2431
+ this.#cells = cells;
2001
2432
  }
2002
2433
  get columns() {
2003
2434
  return Object.freeze(Object.fromEntries(this.#columns));
2004
2435
  }
2436
+ get cellFormulas() {
2437
+ return Object.freeze(Object.fromEntries([...this.#cells].map(([c, keys]) => [c, Object.freeze(Object.fromEntries(keys))])));
2438
+ }
2005
2439
  declare() {
2006
2440
  return this;
2007
2441
  }
2008
2442
  column(name, formula) {
2009
2443
  const program = formula(new SheetRootImpl(this.#env)).program;
2010
- return new SheetImpl(this.#env, new Map([...this.#columns, [name, program]]));
2444
+ return new SheetImpl(this.#env, new Map([...this.#columns, [name, program]]), this.#cells);
2445
+ }
2446
+ cellFormula(k, column, formula) {
2447
+ const program = formula(new SheetRootImpl(this.#env)).program;
2448
+ const keys = new Map([...this.#cells.get(column) ?? [], [k, program]]);
2449
+ return new SheetImpl(this.#env, this.#columns, new Map([...this.#cells, [column, keys]]));
2011
2450
  }
2012
2451
  #run() {
2013
2452
  const { space: s, domains, options } = this.#env;
2014
2453
  return new SheetRun(this.#columns, {
2015
2454
  space: s,
2016
2455
  domains,
2456
+ cells: this.#cells,
2017
2457
  ...options.fns === void 0 ? {} : { fns: options.fns },
2018
2458
  ...options.extensions === void 0 ? {} : { extensions: options.extensions }
2019
2459
  });
@@ -2059,6 +2499,6 @@ function vex(...domains) {
2059
2499
  };
2060
2500
  }
2061
2501
  //#endregion
2062
- export { CELL_KIND, LIST_OPS, 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, isExpr, isListOp, isMove, isNone, isOpName, isSome, isVexList, key, labelOf, let_, liftsAt, lit, mapResult, monoids, none, offset, ok, origin, other, parent, parse, previewValue, rec, ref, resolveAddr, resolveOp, serialize, sizeOf, some, space, toOptional, toPath, traversal, v, vex, vexError, vexList };
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 };
2063
2503
 
2064
2504
  //# sourceMappingURL=index.js.map