@mark1russell7/vex 0.4.0 → 0.5.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
@@ -50,8 +50,19 @@ const CODE_OF = {
50
50
  threw: "#CALC!",
51
51
  "undefined-result": "#CALC!",
52
52
  args: "#ARGS",
53
- cycle: "#CYCLE!"
53
+ cycle: "#CYCLE!",
54
+ depth: "#DEPTH!"
54
55
  };
56
+ /**
57
+ * This function tells if an exception is the report of the engine that the call stack is full. V8 and JavaScriptCore
58
+ * throw a `RangeError`. SpiderMonkey throws an `InternalError` ("too much recursion").
59
+ */
60
+ function isStackOverflow(thrown) {
61
+ if (!(thrown instanceof Error)) return false;
62
+ return thrown instanceof RangeError && /call stack/i.test(thrown.message) || thrown.name === "InternalError" && /recursion/i.test(thrown.message);
63
+ }
64
+ /** This function tells if an error is `#DEPTH!`. `ifError` and the reductions that skip errors do not hide it (EVAL.DEPTH). */
65
+ const isDepthError = (e) => e.kind === "depth";
55
66
  /** This function gives the code of an error kind. */
56
67
  const codeOf = (kind) => CODE_OF[kind];
57
68
  /** This function makes a `VexError`. */
@@ -199,37 +210,87 @@ function isMove(u) {
199
210
  default: return false;
200
211
  }
201
212
  }
202
- /** This function tells if a value is a valid axis. */
213
+ /** This function tells if a value is a valid axis. It checks the tests of `where` too. */
203
214
  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
- }
215
+ return validTree([{
216
+ axis: true,
217
+ u
218
+ }]);
217
219
  }
218
- const isExprRecord = (u) => isObject(u) && !Array.isArray(u) && Object.values(u).every((e) => isExpr(e));
219
220
  /** This function tells if a value is a valid expression. It checks the whole tree. */
220
221
  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;
222
+ return validTree([{
223
+ axis: false,
224
+ u
225
+ }]);
226
+ }
227
+ const isAddr = (u) => u === void 0 || Array.isArray(u) && u.every(isMove);
228
+ /**
229
+ * This function checks a tree of expressions and axes. It uses a stack, not recursion, so the input can be deep. For
230
+ * example, a deep JSON file from a stranger does not need a deep call stack (EVAL.NESTING).
231
+ */
232
+ function validTree(todo) {
233
+ const push = (axis, values) => {
234
+ for (const u of values) todo.push({
235
+ axis,
236
+ u
237
+ });
238
+ };
239
+ for (let item = todo.pop(); item !== void 0; item = todo.pop()) {
240
+ const { u } = item;
241
+ if (!isObject(u)) return false;
242
+ if (item.axis) {
243
+ const t = u["t"];
244
+ if (t === "neighbors") {
245
+ if (u["n"] !== 4 && u["n"] !== 8) return false;
246
+ } else if (t === "where") {
247
+ push(true, [u["axis"]]);
248
+ push(false, [u["test"]]);
249
+ } else if (![
250
+ "all",
251
+ "others",
252
+ "other",
253
+ "children",
254
+ "ancestors",
255
+ "descendants",
256
+ "siblings"
257
+ ].includes(t)) return false;
258
+ continue;
259
+ }
260
+ switch (u["tag"]) {
261
+ case "lit":
262
+ if (!("value" in u)) return false;
263
+ break;
264
+ case "ref":
265
+ if (!isStringArray(u["path"]) || !isAddr(u["at"])) return false;
266
+ break;
267
+ case "app":
268
+ if (typeof u["op"] !== "string" || !Array.isArray(u["args"])) return false;
269
+ push(false, u["args"]);
270
+ break;
271
+ case "let":
272
+ if (!isObject(u["bind"]) || Array.isArray(u["bind"])) return false;
273
+ push(false, [...Object.values(u["bind"]), u["body"]]);
274
+ break;
275
+ case "var":
276
+ if (typeof u["name"] !== "string") return false;
277
+ break;
278
+ case "rec":
279
+ if (!isObject(u["fields"]) || Array.isArray(u["fields"])) return false;
280
+ push(false, Object.values(u["fields"]));
281
+ break;
282
+ case "each":
283
+ if (!isAddr(u["at"])) return false;
284
+ push(true, [u["axis"]]);
285
+ push(false, [u["body"]]);
286
+ break;
287
+ case "ext":
288
+ if (typeof u["kind"] !== "string" || !("data" in u)) return false;
289
+ break;
290
+ default: return false;
291
+ }
232
292
  }
293
+ return true;
233
294
  }
234
295
  /** This function gives the child expressions of an expression, in the order of their child index. */
235
296
  function children(e) {
@@ -244,8 +305,11 @@ function children(e) {
244
305
  case "ext": return [];
245
306
  }
246
307
  }
308
+ /** This function gives the tests of the `where` axes of an axis, from the inside out. It uses a loop, not recursion. */
247
309
  function whereTests(a) {
248
- return a.t === "where" ? [...whereTests(a.axis), a.test] : [];
310
+ const out = [];
311
+ for (let x = a; x.t === "where"; x = x.axis) out.unshift(x.test);
312
+ return out;
249
313
  }
250
314
  //#endregion
251
315
  //#region src/space.ts
@@ -621,8 +685,27 @@ const isSpecialForm = (op) => SPECIAL_FORMS.has(op);
621
685
  * This function compiles an expression. The result gives the same results and the same traces as `evaluate`,
622
686
  * because `evaluate` uses it too.
623
687
  */
688
+ /** The deepest nesting of an expression that `compile` accepts (EVAL.NESTING). */
689
+ const MAX_NESTING = 500;
690
+ const DEPTH_MESSAGE = "the evaluation is too deep for the call stack of the engine";
691
+ /** This function gives the number of nodes on the longest path from the root of `e`. It uses a stack, not recursion. */
692
+ function nestingOf(e) {
693
+ let deepest = 0;
694
+ const todo = [[e, 1]];
695
+ for (let item = todo.pop(); item !== void 0; item = todo.pop()) {
696
+ const [x, d] = item;
697
+ if (d > deepest) deepest = d;
698
+ for (const child of children(x)) todo.push([child, d + 1]);
699
+ }
700
+ return deepest;
701
+ }
624
702
  function compile(expr, opts = {}) {
625
- const root = new Compiler(opts).node(expr, []);
703
+ const nesting = nestingOf(expr);
704
+ const root = nesting > 500 ? (f) => fail(vexError("bad-expression", `the expression is nested ${nesting} levels deep, and the limit is 500`, {
705
+ path: [],
706
+ origin: f.pos.origin,
707
+ focus: f.pos.focus
708
+ })) : new Compiler(opts).node(expr, []);
626
709
  const run = (r) => {
627
710
  const { space, origin } = r;
628
711
  if (!space.has(origin)) return fail(vexError("unknown-key", `the space has no key "${origin}"`, {
@@ -642,6 +725,11 @@ function compile(expr, opts = {}) {
642
725
  trace: r.trace
643
726
  });
644
727
  } catch (thrown) {
728
+ if (isStackOverflow(thrown)) return fail(vexError("depth", DEPTH_MESSAGE, {
729
+ origin,
730
+ focus: origin,
731
+ thrown
732
+ }));
645
733
  return fail(vexError("threw", "the evaluation threw an exception", {
646
734
  origin,
647
735
  focus: origin,
@@ -792,12 +880,19 @@ var Compiler = class {
792
880
  try {
793
881
  return run();
794
882
  } catch (thrown) {
795
- return this.#err("threw", `"${op}" threw an exception`, f, path, {
796
- op,
797
- thrown
798
- });
883
+ return this.#threw(thrown, `"${op}" threw an exception`, f, path, { op });
799
884
  }
800
885
  }
886
+ /** This method gives the error of an exception: `#DEPTH!` for a full call stack, and `#CALC!` for each other exception. */
887
+ #threw(thrown, message, f, path, extra = {}) {
888
+ return isStackOverflow(thrown) ? this.#err("depth", DEPTH_MESSAGE, f, path, {
889
+ ...extra,
890
+ thrown
891
+ }) : this.#err("threw", message, f, path, {
892
+ ...extra,
893
+ thrown
894
+ });
895
+ }
801
896
  #ref(e, info) {
802
897
  const { path } = info;
803
898
  const segs = e.path;
@@ -831,7 +926,7 @@ var Compiler = class {
831
926
  try {
832
927
  value = Reflect.get(value, seg);
833
928
  } catch (thrown) {
834
- return failed(this.#err("threw", `reading "${where}" at "${key}" threw an exception`, f, path, { thrown }));
929
+ return failed(this.#threw(thrown, `reading "${where}" at "${key}" threw an exception`, f, path));
835
930
  }
836
931
  if (value === void 0 || value === null) return missing(where);
837
932
  }
@@ -854,6 +949,8 @@ var Compiler = class {
854
949
  else (errors ??= [first]).push(r.error);
855
950
  }
856
951
  if (first === void 0) return ok(values);
952
+ const depth = [first, ...errors ?? []].find(isDepthError);
953
+ if (depth !== void 0) return fail(depth);
857
954
  return errors === void 0 ? fail(first) : this.#err("args", `${errors.length} ${what} failed`, f, path, { causes: errors });
858
955
  }
859
956
  #each(e, info) {
@@ -994,7 +1091,7 @@ var Compiler = class {
994
1091
  }
995
1092
  case "ifError": return (f, c) => {
996
1093
  const first = arg(0, f, c);
997
- return this.#emit(c, info, f, first.ok ? first : arg(1, f, c));
1094
+ return this.#emit(c, info, f, first.ok || isDepthError(first.error) ? first : arg(1, f, c));
998
1095
  };
999
1096
  }
1000
1097
  }
@@ -1021,10 +1118,7 @@ var Compiler = class {
1021
1118
  try {
1022
1119
  return ok(run());
1023
1120
  } catch (thrown) {
1024
- return this.#err("threw", `"${op}" threw an exception`, f, path, {
1025
- op,
1026
- thrown
1027
- });
1121
+ return this.#threw(thrown, `"${op}" threw an exception`, f, path, { op });
1028
1122
  }
1029
1123
  }
1030
1124
  /** This method checks the value that an op gave: no `undefined`, finite numbers, and valid domain values. */
@@ -1040,10 +1134,7 @@ var Compiler = class {
1040
1134
  try {
1041
1135
  valid = d.valid(value);
1042
1136
  } catch (thrown) {
1043
- return this.#err("threw", `the "valid" check of "${d.name}" threw an exception`, f, path, {
1044
- ...extra,
1045
- thrown
1046
- });
1137
+ return this.#threw(thrown, `the "valid" check of "${d.name}" threw an exception`, f, path, extra);
1047
1138
  }
1048
1139
  if (!valid) return this.#err("invalid-value", `"${op}" gave a value that is not a valid ${d.name}`, f, path, extra);
1049
1140
  }
@@ -1051,6 +1142,8 @@ var Compiler = class {
1051
1142
  }
1052
1143
  #listOp(op, list, rest, f, path) {
1053
1144
  const optsArg = op === "reduce" ? rest[1] : rest[0];
1145
+ const depth = list.items.find((it) => !it.result.ok && isDepthError(it.result.error))?.result;
1146
+ if (depth !== void 0 && !depth.ok) return fail(depth.error);
1054
1147
  const strict = optsArg?.strict === true;
1055
1148
  const firstError = list.items.find((it) => !it.result.ok)?.result;
1056
1149
  if (strict && firstError !== void 0 && !firstError.ok) return fail(firstError.error);
@@ -1231,25 +1324,30 @@ const sizeOf = (e) => 1 + children(e).reduce((s, c) => s + sizeOf(c), 0);
1231
1324
  */
1232
1325
  function deps(e) {
1233
1326
  const out = [];
1234
- const walk = (x, axes, axisAt) => {
1327
+ const todo = [{
1328
+ x: e,
1329
+ axes: [],
1330
+ axisAt: []
1331
+ }];
1332
+ for (let item = todo.pop(); item !== void 0; item = todo.pop()) {
1333
+ const { x } = item;
1235
1334
  if (x.tag === "ref") {
1236
1335
  out.push({
1237
1336
  at: x.at ?? [],
1238
1337
  path: x.path,
1239
- axes,
1240
- axisAt
1338
+ axes: item.axes,
1339
+ axisAt: item.axisAt
1241
1340
  });
1242
- return;
1243
- }
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;
1341
+ continue;
1249
1342
  }
1250
- children(x).forEach((c) => walk(c, axes, axisAt));
1251
- };
1252
- walk(e, [], []);
1343
+ const axes = x.tag === "each" ? [...item.axes, x.axis.t] : item.axes;
1344
+ const axisAt = x.tag === "each" ? [...item.axisAt, x.at ?? []] : item.axisAt;
1345
+ for (const child of children(x).toReversed()) todo.push({
1346
+ x: child,
1347
+ axes,
1348
+ axisAt
1349
+ });
1350
+ }
1253
1351
  return out;
1254
1352
  }
1255
1353
  //#endregion
@@ -1409,6 +1507,7 @@ function serialize(e, domains = []) {
1409
1507
  const tree = mapValues(e, (v) => encodeValue(v, domains));
1410
1508
  return tree.ok ? ok(JSON.stringify(tree.value)) : fail(tree.error);
1411
1509
  } catch (thrown) {
1510
+ if (isStackOverflow(thrown)) return fail(vexError("depth", "the expression is too deep for the call stack of the engine", { thrown }));
1412
1511
  return fail(vexError("threw", "the expression has no JSON form", { thrown }));
1413
1512
  }
1414
1513
  }
@@ -1420,9 +1519,14 @@ function parse(text, domains = []) {
1420
1519
  } catch (thrown) {
1421
1520
  return fail(vexError("bad-expression", "the text is not JSON", { thrown }));
1422
1521
  }
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"));
1522
+ try {
1523
+ const tree = mapValues(raw, (v) => decodeValue(v, domains));
1524
+ if (!tree.ok) return fail(tree.error);
1525
+ return isExpr(tree.value) ? ok(tree.value) : fail(vexError("bad-expression", "the JSON is not a valid Vex expression"));
1526
+ } catch (thrown) {
1527
+ if (isStackOverflow(thrown)) return fail(vexError("depth", "the JSON is too deep for the call stack of the engine", { thrown }));
1528
+ return fail(vexError("threw", "a decoder of a domain threw an exception", { thrown }));
1529
+ }
1426
1530
  }
1427
1531
  //#endregion
1428
1532
  //#region src/traversal.ts
@@ -1529,6 +1633,28 @@ const cycleError = (column, key) => fail(vexError("cycle", `the cell "${column}"
1529
1633
  origin: key,
1530
1634
  focus: key
1531
1635
  }));
1636
+ /** The id of a cell. */
1637
+ const idOf = (column, key) => `${column}\u0000${key}`;
1638
+ /**
1639
+ * The budget of the stack for the recursion of a run, in estimated frames. Each engine has more stack than this, so
1640
+ * the recursion of a run cannot fill the stack (SHEET.DEEP).
1641
+ */
1642
+ const STACK_BUDGET = 3e3;
1643
+ /**
1644
+ * One run of a sheet. It keeps the result of each cell that it evaluated. The space does not change, so a cell has
1645
+ * one result in a run.
1646
+ *
1647
+ * The run is a depth-first search with the algorithm of Tarjan for strongly connected components. A cell finishes
1648
+ * when its component finishes. Each cell of a component with two or more cells, or with a reference to itself,
1649
+ * gives `#CYCLE!`. A read of a cell that is not finished gives `#CYCLE!` too. Thus the order of the evaluations
1650
+ * does not change a result, also when `ifError` catches the error of a cycle.
1651
+ *
1652
+ * The search does not depend on the call stack of the engine (SHEET.DEEP). A read of a cell evaluates that cell
1653
+ * with recursion while the stack of the run stays in a budget. When a read is over the budget, the run starts the
1654
+ * cell, and the cell that reads it pauses. A paused evaluation reads no other cell and changes no state of the
1655
+ * search. The run then evaluates the started cell from its own list, and it evaluates the paused cell again after
1656
+ * that cell. A formula is pure (EVAL.PURE), so the second evaluation gives the result of one evaluation.
1657
+ */
1532
1658
  var SheetRun = class {
1533
1659
  #columns;
1534
1660
  #opts;
@@ -1544,11 +1670,18 @@ var SheetRun = class {
1544
1670
  index: -1,
1545
1671
  low: -1,
1546
1672
  reread: false,
1547
- result: cycleError("", "")
1673
+ result: cycleError("", ""),
1674
+ paused: false,
1675
+ need: void 0
1548
1676
  };
1549
1677
  #next = 0;
1550
- constructor(columns, opts) {
1678
+ #used = 0;
1679
+ #cost = /* @__PURE__ */ new Map();
1680
+ #budget;
1681
+ /** `budget` is the budget of the stack in estimated frames. A test can make it small, so the run pauses often. */
1682
+ constructor(columns, opts, budget = STACK_BUDGET) {
1551
1683
  this.#columns = columns;
1684
+ this.#budget = budget;
1552
1685
  this.#opts = {
1553
1686
  ...opts,
1554
1687
  extensions: {
@@ -1564,16 +1697,16 @@ var SheetRun = class {
1564
1697
  ...where.error,
1565
1698
  path: ctx.path
1566
1699
  });
1567
- return this.cell(data.column, where.value);
1700
+ return this.#read(data.column, where.value);
1568
1701
  };
1569
1702
  /**
1570
1703
  * 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.
1704
+ * the column at the keys before `key`, in key order. Thus a recurrence over the keys reads finished cells.
1573
1705
  */
1574
1706
  cell(column, key) {
1575
- if (this.#top.index < 0) this.#warmTo(column, key);
1576
- return this.#cell(column, key);
1707
+ if (this.#top.index >= 0) return this.#read(column, key);
1708
+ this.#warmTo(column, key);
1709
+ return this.#drive(column, key);
1577
1710
  }
1578
1711
  /** This method evaluates the column `column` at each key before `key` that it did not evaluate before, in key order. */
1579
1712
  #warmTo(column, key) {
@@ -1582,51 +1715,117 @@ var SheetRun = class {
1582
1715
  this.#index ??= new Map(keys.map((k, i) => [k, i]));
1583
1716
  const end = this.#index.get(key) ?? 0;
1584
1717
  const start = this.#warmed.get(column) ?? 0;
1585
- for (let i = start; i < end; i++) this.#cell(column, keys[i] ?? key);
1718
+ for (let i = start; i < end; i++) this.#drive(column, keys[i] ?? key);
1586
1719
  if (end > start) this.#warmed.set(column, end);
1587
1720
  }
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);
1721
+ /** This method gives the estimated frames of the stack that one evaluation of a cell of `column` uses. */
1722
+ #costOf(column, program) {
1723
+ let cost = this.#cost.get(column);
1724
+ if (cost === void 0) {
1725
+ cost = 3 * nestingOf(program) + 16;
1726
+ this.#cost.set(column, cost);
1599
1727
  }
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
- }));
1728
+ return cost;
1729
+ }
1730
+ /** This method puts a new cell on the stack of the search. */
1731
+ #start(column, key) {
1605
1732
  const n = this.#next++;
1606
1733
  const visit = {
1607
- id,
1734
+ id: idOf(column, key),
1608
1735
  column,
1609
1736
  key,
1610
1737
  index: n,
1611
1738
  low: n,
1612
1739
  reread: false,
1613
- result: cycleError(column, key)
1740
+ result: cycleError(column, key),
1741
+ paused: false,
1742
+ need: void 0
1614
1743
  };
1615
- this.#visits.set(id, visit);
1744
+ this.#visits.set(visit.id, visit);
1616
1745
  this.#stack.push(visit);
1746
+ return visit;
1747
+ }
1748
+ /** This method evaluates the formula of a cell once. When the evaluation pauses, the result of the cell does not change. */
1749
+ #evaluate(visit, program) {
1750
+ const caller = this.#top;
1751
+ const cost = this.#costOf(visit.column, program);
1752
+ visit.paused = false;
1753
+ visit.need = void 0;
1617
1754
  this.#top = visit;
1618
- visit.result = evaluate(program, {
1755
+ this.#used += cost;
1756
+ const result = evaluate(program, {
1619
1757
  ...this.#opts,
1620
- origin: key
1758
+ origin: visit.key
1621
1759
  });
1760
+ this.#used -= cost;
1622
1761
  this.#top = caller;
1762
+ if (!visit.paused) visit.result = result;
1763
+ }
1764
+ /** This method ends a cell whose evaluation did not pause: it finishes its component, or it gives its low to the caller. */
1765
+ #end(visit, caller) {
1623
1766
  if (visit.low === visit.index) this.#finish(visit);
1624
- else caller.low = Math.min(caller.low, visit.low);
1767
+ else if (caller !== void 0) caller.low = Math.min(caller.low, visit.low);
1768
+ }
1769
+ /** This method reads a cell from the formula of the cell at the top. */
1770
+ #read(column, key) {
1771
+ const id = idOf(column, key);
1772
+ const done = this.#done.get(id);
1773
+ if (done !== void 0) return done;
1774
+ const caller = this.#top;
1775
+ if (caller.paused) return cycleError(column, key);
1776
+ const seen = this.#visits.get(id);
1777
+ if (seen !== void 0) {
1778
+ caller.low = Math.min(caller.low, seen.index);
1779
+ seen.reread = true;
1780
+ return cycleError(column, key);
1781
+ }
1782
+ const program = this.#columns.get(column);
1783
+ if (program === void 0) return fail(vexError("unbound", `the sheet has no column "${column}"`, {
1784
+ origin: key,
1785
+ focus: key
1786
+ }));
1787
+ const visit = this.#start(column, key);
1788
+ if (this.#used + this.#costOf(column, program) > this.#budget) {
1789
+ caller.paused = true;
1790
+ caller.need = visit;
1791
+ return cycleError(column, key);
1792
+ }
1793
+ this.#evaluate(visit, program);
1794
+ if (visit.paused) {
1795
+ caller.paused = true;
1796
+ caller.need = visit;
1797
+ return cycleError(column, key);
1798
+ }
1799
+ this.#end(visit, caller);
1800
+ return this.#done.get(id) ?? cycleError(column, key);
1801
+ }
1802
+ /** This method evaluates a cell from the top level. The cells that pause go on a list, not on the call stack. */
1803
+ #drive(column, key) {
1804
+ const id = idOf(column, key);
1805
+ const done = this.#done.get(id);
1806
+ if (done !== void 0) return done;
1807
+ if (!this.#columns.has(column)) return fail(vexError("unbound", `the sheet has no column "${column}"`, {
1808
+ origin: key,
1809
+ focus: key
1810
+ }));
1811
+ const work = [this.#start(column, key)];
1812
+ for (let visit = work.at(-1); visit !== void 0; visit = work.at(-1)) {
1813
+ const program = this.#columns.get(visit.column);
1814
+ /* v8 ignore next -- @preserve: a visit exists only for a column with a program */
1815
+ if (program === void 0) break;
1816
+ this.#evaluate(visit, program);
1817
+ if (visit.paused) {
1818
+ for (let need = visit.need; need !== void 0; need = need.need) work.push(need);
1819
+ continue;
1820
+ }
1821
+ work.pop();
1822
+ this.#end(visit, work.at(-1));
1823
+ }
1625
1824
  return this.#done.get(id) ?? cycleError(column, key);
1626
1825
  }
1627
1826
  /** This method takes the component of `root` from the stack, and sets the final result of each of its cells. */
1628
1827
  #finish(root) {
1629
- const members = this.#stack.splice(this.#stack.indexOf(root));
1828
+ const members = this.#stack.splice(this.#stack.lastIndexOf(root));
1630
1829
  const cyclic = members.length > 1 || root.reread;
1631
1830
  for (const m of members) {
1632
1831
  this.#visits.delete(m.id);
@@ -1651,7 +1850,7 @@ var SheetRun = class {
1651
1850
  }
1652
1851
  /**
1653
1852
  * 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.
1853
+ * for example a running total, then reads finished cells.
1655
1854
  */
1656
1855
  warm(column, key) {
1657
1856
  this.#warmTo(column, key);
@@ -2059,6 +2258,6 @@ function vex(...domains) {
2059
2258
  };
2060
2259
  }
2061
2260
  //#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 };
2261
+ 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
2262
 
2064
2263
  //# sourceMappingURL=index.js.map