@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/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package",
3
3
  "name": "@mark1russell7/vex",
4
- "version": "0.4.0",
4
+ "version": "0.5.0",
5
5
  "description": "Vex: typed spreadsheet formulas over domain objects. The kernel and the typed builder.",
6
6
  "keywords": [
7
7
  "typescript",
package/src/deps.ts CHANGED
@@ -18,19 +18,18 @@ export interface Dependency {
18
18
  */
19
19
  export function deps(e: Expr): readonly Dependency[] {
20
20
  const out: Dependency[] = [];
21
- const walk = (x: Expr, axes: readonly Axis["t"][], axisAt: readonly Addr[]): void => {
21
+ // A stack, not recursion, so a deep expression needs no deep call stack. The children go on the stack in reverse
22
+ // order, so the reads come out in the order of a depth-first walk.
23
+ const todo: { readonly x: Expr; readonly axes: readonly Axis["t"][]; readonly axisAt: readonly Addr[] }[] = [{ x: e, axes: [], axisAt: [] }];
24
+ for (let item = todo.pop(); item !== undefined; item = todo.pop()) {
25
+ const { x } = item;
22
26
  if (x.tag === "ref") {
23
- out.push({ at: x.at ?? [], path: x.path, axes, axisAt });
24
- return;
27
+ out.push({ at: x.at ?? [], path: x.path, axes: item.axes, axisAt: item.axisAt });
28
+ continue;
25
29
  }
26
- if (x.tag === "each") {
27
- const inner = [...axes, x.axis.t];
28
- const innerAt = [...axisAt, x.at ?? []];
29
- children(x).forEach((c) => walk(c, inner, innerAt));
30
- return;
31
- }
32
- children(x).forEach((c) => walk(c, axes, axisAt));
33
- };
34
- walk(e, [], []);
30
+ const axes = x.tag === "each" ? [...item.axes, x.axis.t] : item.axes;
31
+ const axisAt = x.tag === "each" ? [...item.axisAt, x.at ?? []] : item.axisAt;
32
+ for (const child of children(x).toReversed()) todo.push({ x: child, axes, axisAt });
33
+ }
35
34
  return out;
36
35
  }
package/src/errors.ts CHANGED
@@ -2,7 +2,7 @@
2
2
  * The error codes of Vex. The names come from the spreadsheet error values, because a Vex program is a
3
3
  * spreadsheet formula over records.
4
4
  */
5
- export type ErrorCode = "#REF!" | "#N/A" | "#VALUE!" | "#NAME?" | "#NUM!" | "#CALC!" | "#ARGS" | "#CYCLE!";
5
+ export type ErrorCode = "#REF!" | "#N/A" | "#VALUE!" | "#NAME?" | "#NUM!" | "#CALC!" | "#ARGS" | "#CYCLE!" | "#DEPTH!";
6
6
 
7
7
  /** The cause of an error, in more detail than the code. */
8
8
  export type ErrorKind =
@@ -24,6 +24,7 @@ export type ErrorKind =
24
24
  | "undefined-result"
25
25
  | "args"
26
26
  | "cycle"
27
+ | "depth"
27
28
  | "bad-expression";
28
29
 
29
30
  const CODE_OF: Readonly<Record<ErrorKind, ErrorCode>> = {
@@ -46,9 +47,22 @@ const CODE_OF: Readonly<Record<ErrorKind, ErrorCode>> = {
46
47
  "undefined-result": "#CALC!",
47
48
  args: "#ARGS",
48
49
  cycle: "#CYCLE!",
50
+ depth: "#DEPTH!",
49
51
  };
50
52
 
51
- /** A Vex error. It is a value: a program can catch it with `ifError`. */
53
+ /**
54
+ * This function tells if an exception is the report of the engine that the call stack is full. V8 and JavaScriptCore
55
+ * throw a `RangeError`. SpiderMonkey throws an `InternalError` ("too much recursion").
56
+ */
57
+ export function isStackOverflow(thrown: unknown): boolean {
58
+ if (!(thrown instanceof Error)) return false;
59
+ return (thrown instanceof RangeError && /call stack/i.test(thrown.message)) || (thrown.name === "InternalError" && /recursion/i.test(thrown.message));
60
+ }
61
+
62
+ /** This function tells if an error is `#DEPTH!`. `ifError` and the reductions that skip errors do not hide it (EVAL.DEPTH). */
63
+ export const isDepthError = (e: VexError): boolean => e.kind === "depth";
64
+
65
+ /** A Vex error. It is a value: a program can catch it with `ifError`, except `#DEPTH!`. */
52
66
  export interface VexError {
53
67
  /** The spreadsheet-style code, for example `#REF!`. */
54
68
  readonly code: ErrorCode;
package/src/evaluate.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { liftsAt, resolveOp, type AnyDomain, type ParamKind, type ResolvedOp } from "./domain.ts";
2
- import { formatError, vexError, type ErrorKind, type VexError } from "./errors.ts";
2
+ import { formatError, isDepthError, isStackOverflow, vexError, type ErrorKind, type VexError } from "./errors.ts";
3
3
  import { children, type Axis, type Expr, type ExprOf, type Move } from "./ir.ts";
4
4
  import { isListOp, isVexList, vexList, type ListItem, type ListOp, type ListOptions, type VexList } from "./list.ts";
5
5
  import { fail, ok, type Result } from "./result.ts";
@@ -75,8 +75,30 @@ export interface Program {
75
75
  * This function compiles an expression. The result gives the same results and the same traces as `evaluate`,
76
76
  * because `evaluate` uses it too.
77
77
  */
78
+ /** The deepest nesting of an expression that `compile` accepts (EVAL.NESTING). */
79
+ export const MAX_NESTING = 500;
80
+
81
+ const DEPTH_MESSAGE = "the evaluation is too deep for the call stack of the engine";
82
+
83
+ /** This function gives the number of nodes on the longest path from the root of `e`. It uses a stack, not recursion. */
84
+ export function nestingOf(e: Expr): number {
85
+ let deepest = 0;
86
+ const todo: [Expr, number][] = [[e, 1]];
87
+ for (let item = todo.pop(); item !== undefined; item = todo.pop()) {
88
+ const [x, d] = item;
89
+ if (d > deepest) deepest = d;
90
+ for (const child of children(x)) todo.push([child, d + 1]);
91
+ }
92
+ return deepest;
93
+ }
94
+
78
95
  export function compile(expr: Expr, opts: CompileOptions = {}): Program {
79
- const root = new Compiler(opts).node(expr, []);
96
+ // EVAL.NESTING: a program nested too deep gives an error before the compiler walks it with recursion.
97
+ const nesting = nestingOf(expr);
98
+ const root: Node =
99
+ nesting > MAX_NESTING
100
+ ? (f) => fail(vexError("bad-expression", `the expression is nested ${nesting} levels deep, and the limit is ${MAX_NESTING}`, { path: [], origin: f.pos.origin, focus: f.pos.focus }))
101
+ : new Compiler(opts).node(expr, []);
80
102
  const run = (r: RunOptions): Result<unknown> => {
81
103
  const { space, origin } = r;
82
104
  if (!space.has(origin)) return fail(vexError("unknown-key", `the space has no key "${origin}"`, { origin, focus: origin }));
@@ -85,6 +107,7 @@ export function compile(expr: Expr, opts: CompileOptions = {}): Program {
85
107
  return root({ pos: { origin, focus: origin }, env }, { space, trace: r.trace });
86
108
  } catch (thrown) {
87
109
  // A defect in an extension handler or in a test of the interpreter itself. Totality still holds.
110
+ if (isStackOverflow(thrown)) return fail(vexError("depth", DEPTH_MESSAGE, { origin, focus: origin, thrown }));
88
111
  return fail(vexError("threw", "the evaluation threw an exception", { origin, focus: origin, thrown }));
89
112
  }
90
113
  };
@@ -236,10 +259,15 @@ class Compiler {
236
259
  try {
237
260
  return run();
238
261
  } catch (thrown) {
239
- return this.#err("threw", `"${op}" threw an exception`, f, path, { op, thrown });
262
+ return this.#threw(thrown, `"${op}" threw an exception`, f, path, { op });
240
263
  }
241
264
  }
242
265
 
266
+ /** This method gives the error of an exception: `#DEPTH!` for a full call stack, and `#CALC!` for each other exception. */
267
+ #threw(thrown: unknown, message: string, f: Frame, path: readonly number[], extra: Partial<VexError> = {}): Result<never> {
268
+ return isStackOverflow(thrown) ? this.#err("depth", DEPTH_MESSAGE, f, path, { ...extra, thrown }) : this.#err("threw", message, f, path, { ...extra, thrown });
269
+ }
270
+
243
271
  #ref(e: ExprOf<"ref">, info: Info): Node {
244
272
  const { path } = info;
245
273
  const segs = e.path;
@@ -264,7 +292,7 @@ class Compiler {
264
292
  try {
265
293
  value = Reflect.get(value, seg);
266
294
  } catch (thrown) {
267
- return failed(this.#err("threw", `reading "${where}" at "${key}" threw an exception`, f, path, { thrown }));
295
+ return failed(this.#threw(thrown, `reading "${where}" at "${key}" threw an exception`, f, path));
268
296
  }
269
297
  if (value === undefined || value === null) return missing(where);
270
298
  }
@@ -284,6 +312,9 @@ class Compiler {
284
312
  else (errors ??= [first]).push(r.error);
285
313
  }
286
314
  if (first === undefined) return ok(values);
315
+ // A #DEPTH! argument is the result, so #ARGS does not wrap it, and ifError cannot hide it.
316
+ const depth = [first, ...(errors ?? [])].find(isDepthError);
317
+ if (depth !== undefined) return fail(depth);
287
318
  return errors === undefined ? fail(first) : this.#err("args", `${errors.length} ${what} failed`, f, path, { causes: errors });
288
319
  }
289
320
 
@@ -404,7 +435,8 @@ class Compiler {
404
435
  case "ifError":
405
436
  return (f, c) => {
406
437
  const first = arg(0, f, c);
407
- return this.#emit(c, info, f, first.ok ? first : arg(1, f, c));
438
+ // EVAL.DEPTH: ifError does not hide #DEPTH!, because the engine, not the data, failed.
439
+ return this.#emit(c, info, f, first.ok || isDepthError(first.error) ? first : arg(1, f, c));
408
440
  };
409
441
  }
410
442
  }
@@ -435,7 +467,7 @@ class Compiler {
435
467
  try {
436
468
  return ok(run());
437
469
  } catch (thrown) {
438
- return this.#err("threw", `"${op}" threw an exception`, f, path, { op, thrown });
470
+ return this.#threw(thrown, `"${op}" threw an exception`, f, path, { op });
439
471
  }
440
472
  }
441
473
 
@@ -452,7 +484,7 @@ class Compiler {
452
484
  try {
453
485
  valid = d.valid(value);
454
486
  } catch (thrown) {
455
- return this.#err("threw", `the "valid" check of "${d.name}" threw an exception`, f, path, { ...extra, thrown });
487
+ return this.#threw(thrown, `the "valid" check of "${d.name}" threw an exception`, f, path, extra);
456
488
  }
457
489
  if (!valid) return this.#err("invalid-value", `"${op}" gave a value that is not a valid ${d.name}`, f, path, extra);
458
490
  }
@@ -461,6 +493,9 @@ class Compiler {
461
493
 
462
494
  #listOp(op: ListOp, list: VexList, rest: readonly unknown[], f: Frame, path: readonly number[]): Result<unknown> {
463
495
  const optsArg = op === "reduce" ? rest[1] : rest[0];
496
+ // A reduction that skips error items does not skip #DEPTH! (EVAL.DEPTH).
497
+ const depth = list.items.find((it) => !it.result.ok && isDepthError(it.result.error))?.result;
498
+ if (depth !== undefined && !depth.ok) return fail(depth.error);
464
499
  const strict = (optsArg as ListOptions | null | undefined)?.strict === true;
465
500
  const firstError = list.items.find((it) => !it.result.ok)?.result;
466
501
  if (strict && firstError !== undefined && !firstError.ok) return fail(firstError.error);
package/src/ir.ts CHANGED
@@ -144,53 +144,76 @@ export function isMove(u: unknown): u is Move {
144
144
  }
145
145
  }
146
146
 
147
- /** This function tells if a value is a valid axis. */
147
+ /** This function tells if a value is a valid axis. It checks the tests of `where` too. */
148
148
  export function isAxis(u: unknown): u is Axis {
149
- if (!isObject(u)) return false;
150
- switch (u["t"]) {
151
- case "all":
152
- case "others":
153
- case "other":
154
- case "children":
155
- case "ancestors":
156
- case "descendants":
157
- case "siblings":
158
- return true;
159
- case "neighbors":
160
- return u["n"] === 4 || u["n"] === 8;
161
- case "where":
162
- return isAxis(u["axis"]) && isExpr(u["test"]);
163
- default:
164
- return false;
165
- }
149
+ return validTree([{ axis: true, u }]);
166
150
  }
167
151
 
168
- const isExprRecord = (u: unknown): u is Readonly<Record<string, Expr>> =>
169
- isObject(u) && !Array.isArray(u) && Object.values(u).every((e) => isExpr(e));
170
-
171
152
  /** This function tells if a value is a valid expression. It checks the whole tree. */
172
153
  export function isExpr(u: unknown): u is Expr {
173
- if (!isObject(u)) return false;
174
- switch (u["tag"]) {
175
- case "lit":
176
- return "value" in u;
177
- case "ref":
178
- return isStringArray(u["path"]) && (u["at"] === undefined || (Array.isArray(u["at"]) && u["at"].every(isMove)));
179
- case "app":
180
- return typeof u["op"] === "string" && Array.isArray(u["args"]) && u["args"].every((a) => isExpr(a));
181
- case "let":
182
- return isExprRecord(u["bind"]) && isExpr(u["body"]);
183
- case "var":
184
- return typeof u["name"] === "string";
185
- case "rec":
186
- return isExprRecord(u["fields"]);
187
- case "each":
188
- return isAxis(u["axis"]) && isExpr(u["body"]) && (u["at"] === undefined || (Array.isArray(u["at"]) && u["at"].every(isMove)));
189
- case "ext":
190
- return typeof u["kind"] === "string" && "data" in u;
191
- default:
192
- return false;
154
+ return validTree([{ axis: false, u }]);
155
+ }
156
+
157
+ const isAddr = (u: unknown): boolean => u === undefined || (Array.isArray(u) && u.every(isMove));
158
+
159
+ /**
160
+ * This function checks a tree of expressions and axes. It uses a stack, not recursion, so the input can be deep. For
161
+ * example, a deep JSON file from a stranger does not need a deep call stack (EVAL.NESTING).
162
+ */
163
+ function validTree(todo: { readonly axis: boolean; readonly u: unknown }[]): boolean {
164
+ const push = (axis: boolean, values: readonly unknown[]): void => {
165
+ for (const u of values) todo.push({ axis, u });
166
+ };
167
+ for (let item = todo.pop(); item !== undefined; item = todo.pop()) {
168
+ const { u } = item;
169
+ if (!isObject(u)) return false;
170
+ if (item.axis) {
171
+ const t = u["t"];
172
+ if (t === "neighbors") {
173
+ if (u["n"] !== 4 && u["n"] !== 8) return false;
174
+ } else if (t === "where") {
175
+ push(true, [u["axis"]]);
176
+ push(false, [u["test"]]);
177
+ } else if (!["all", "others", "other", "children", "ancestors", "descendants", "siblings"].includes(t as string)) {
178
+ return false;
179
+ }
180
+ continue;
181
+ }
182
+ switch (u["tag"]) {
183
+ case "lit":
184
+ if (!("value" in u)) return false;
185
+ break;
186
+ case "ref":
187
+ if (!isStringArray(u["path"]) || !isAddr(u["at"])) return false;
188
+ break;
189
+ case "app":
190
+ if (typeof u["op"] !== "string" || !Array.isArray(u["args"])) return false;
191
+ push(false, u["args"]);
192
+ break;
193
+ case "let":
194
+ if (!isObject(u["bind"]) || Array.isArray(u["bind"])) return false;
195
+ push(false, [...Object.values(u["bind"]), u["body"]]);
196
+ break;
197
+ case "var":
198
+ if (typeof u["name"] !== "string") return false;
199
+ break;
200
+ case "rec":
201
+ if (!isObject(u["fields"]) || Array.isArray(u["fields"])) return false;
202
+ push(false, Object.values(u["fields"]));
203
+ break;
204
+ case "each":
205
+ if (!isAddr(u["at"])) return false;
206
+ push(true, [u["axis"]]);
207
+ push(false, [u["body"]]);
208
+ break;
209
+ case "ext":
210
+ if (typeof u["kind"] !== "string" || !("data" in u)) return false;
211
+ break;
212
+ default:
213
+ return false;
214
+ }
193
215
  }
216
+ return true;
194
217
  }
195
218
 
196
219
  /** This function gives the child expressions of an expression, in the order of their child index. */
@@ -212,6 +235,9 @@ export function children(e: Expr): readonly Expr[] {
212
235
  }
213
236
  }
214
237
 
238
+ /** This function gives the tests of the `where` axes of an axis, from the inside out. It uses a loop, not recursion. */
215
239
  function whereTests(a: Axis): readonly Expr[] {
216
- return a.t === "where" ? [...whereTests(a.axis), a.test] : [];
240
+ const out: Expr[] = [];
241
+ for (let x: Axis = a; x.t === "where"; x = x.axis) out.unshift(x.test);
242
+ return out;
217
243
  }
package/src/json.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { AnyDomain } from "./domain.ts";
2
- import { vexError } from "./errors.ts";
2
+ import { isStackOverflow, vexError } from "./errors.ts";
3
3
  import { isExpr, type Expr } from "./ir.ts";
4
4
  import { fail, ok, type Result } from "./result.ts";
5
5
 
@@ -171,6 +171,7 @@ export function serialize(e: Expr, domains: readonly AnyDomain[] = []): Result<s
171
171
  const tree = mapValues(e, (v) => encodeValue(v, domains));
172
172
  return tree.ok ? ok(JSON.stringify(tree.value)) : fail(tree.error);
173
173
  } catch (thrown) {
174
+ if (isStackOverflow(thrown)) return fail(vexError("depth", "the expression is too deep for the call stack of the engine", { thrown }));
174
175
  return fail(vexError("threw", "the expression has no JSON form", { thrown }));
175
176
  }
176
177
  }
@@ -184,7 +185,13 @@ export function parse(text: string, domains: readonly AnyDomain[] = []): Result<
184
185
  } catch (thrown) {
185
186
  return fail(vexError("bad-expression", "the text is not JSON", { thrown }));
186
187
  }
187
- const tree = mapValues(raw, (v) => decodeValue(v, domains));
188
- if (!tree.ok) return fail(tree.error);
189
- return isExpr(tree.value) ? ok(tree.value) : fail(vexError("bad-expression", "the JSON is not a valid Vex expression"));
188
+ try {
189
+ const tree = mapValues(raw, (v) => decodeValue(v, domains));
190
+ if (!tree.ok) return fail(tree.error);
191
+ return isExpr(tree.value) ? ok(tree.value) : fail(vexError("bad-expression", "the JSON is not a valid Vex expression"));
192
+ } catch (thrown) {
193
+ // A JSON text nested deeper than the call stack, or a decoder of a domain that throws.
194
+ if (isStackOverflow(thrown)) return fail(vexError("depth", "the JSON is too deep for the call stack of the engine", { thrown }));
195
+ return fail(vexError("threw", "a decoder of a domain threw an exception", { thrown }));
196
+ }
190
197
  }
package/src/sheet.ts CHANGED
@@ -7,7 +7,7 @@
7
7
  * JSON form, `deps` and the traces work without a change.
8
8
  */
9
9
  import { vexError } from "./errors.ts";
10
- import { evaluate, explain, type EvalOptions, type ExtHandler } from "./evaluate.ts";
10
+ import { evaluate, explain, nestingOf, type EvalOptions, type ExtHandler } from "./evaluate.ts";
11
11
  import { ext, isMove, type Addr, type Expr } from "./ir.ts";
12
12
  import { fail, type Result } from "./result.ts";
13
13
  import { resolveAddr } from "./space.ts";
@@ -38,15 +38,9 @@ export type SheetOptions = Omit<EvalOptions, "origin" | "trace">;
38
38
  const cycleError = (column: string, key: string): Result<never> =>
39
39
  fail(vexError("cycle", `the cell "${column}" at "${key}" is on a cycle of cell references`, { origin: key, focus: key }));
40
40
 
41
- /**
42
- * One run of a sheet. It keeps the result of each cell that it evaluated. The space does not change, so a cell has
43
- * one result in a run.
44
- *
45
- * The run is a depth-first search with the algorithm of Tarjan for strongly connected components. A cell finishes
46
- * when its component finishes. Each cell of a component with two or more cells, or with a reference to itself,
47
- * gives `#CYCLE!`. A read of a cell that is not finished gives `#CYCLE!` too. Thus the order of the evaluations
48
- * does not change a result, also when `ifError` catches the error of a cycle.
49
- */
41
+ /** The id of a cell. */
42
+ const idOf = (column: string, key: string): string => `${column}\u0000${key}`;
43
+
50
44
  /** The state of one cell in the search. */
51
45
  interface Visit {
52
46
  readonly id: string;
@@ -56,8 +50,33 @@ interface Visit {
56
50
  low: number;
57
51
  reread: boolean;
58
52
  result: Result<unknown>;
53
+ /** True when the last evaluation paused, because a cell that it reads is not finished. */
54
+ paused: boolean;
55
+ /** The cell that the evaluation waits for: a cell that the run started, or a cell that paused too. */
56
+ need: Visit | undefined;
59
57
  }
60
58
 
59
+ /**
60
+ * The budget of the stack for the recursion of a run, in estimated frames. Each engine has more stack than this, so
61
+ * the recursion of a run cannot fill the stack (SHEET.DEEP).
62
+ */
63
+ const STACK_BUDGET = 3000;
64
+
65
+ /**
66
+ * One run of a sheet. It keeps the result of each cell that it evaluated. The space does not change, so a cell has
67
+ * one result in a run.
68
+ *
69
+ * The run is a depth-first search with the algorithm of Tarjan for strongly connected components. A cell finishes
70
+ * when its component finishes. Each cell of a component with two or more cells, or with a reference to itself,
71
+ * gives `#CYCLE!`. A read of a cell that is not finished gives `#CYCLE!` too. Thus the order of the evaluations
72
+ * does not change a result, also when `ifError` catches the error of a cycle.
73
+ *
74
+ * The search does not depend on the call stack of the engine (SHEET.DEEP). A read of a cell evaluates that cell
75
+ * with recursion while the stack of the run stays in a budget. When a read is over the budget, the run starts the
76
+ * cell, and the cell that reads it pauses. A paused evaluation reads no other cell and changes no state of the
77
+ * search. The run then evaluates the started cell from its own list, and it evaluates the paused cell again after
78
+ * that cell. A formula is pure (EVAL.PURE), so the second evaluation gives the result of one evaluation.
79
+ */
61
80
  export class SheetRun {
62
81
  readonly #columns: ReadonlyMap<string, Expr>;
63
82
  readonly #opts: SheetOptions;
@@ -72,11 +91,17 @@ export class SheetRun {
72
91
  readonly #stack: Visit[] = [];
73
92
  // The cell whose formula is in evaluation. At the top level, it is a placeholder that is not a cell.
74
93
  // Stryker disable next-line all: the placeholder is not a cell, so the search reads none of its fields
75
- #top: Visit = { id: "", column: "", key: "", index: -1, low: -1, reread: false, result: cycleError("", "") };
94
+ #top: Visit = { id: "", column: "", key: "", index: -1, low: -1, reread: false, result: cycleError("", ""), paused: false, need: undefined };
76
95
  #next = 0;
96
+ // The estimated frames of the stack that the evaluations in progress use, and the cost of a cell of each column.
97
+ #used = 0;
98
+ readonly #cost = new Map<string, number>();
99
+ readonly #budget: number;
77
100
 
78
- constructor(columns: ReadonlyMap<string, Expr>, opts: SheetOptions) {
101
+ /** `budget` is the budget of the stack in estimated frames. A test can make it small, so the run pauses often. */
102
+ constructor(columns: ReadonlyMap<string, Expr>, opts: SheetOptions, budget: number = STACK_BUDGET) {
79
103
  this.#columns = columns;
104
+ this.#budget = budget;
80
105
  this.#opts = { ...opts, extensions: { ...opts.extensions, [CELL_KIND]: this.#handler } };
81
106
  }
82
107
 
@@ -84,18 +109,18 @@ export class SheetRun {
84
109
  if (!isCellRef(data)) return fail(vexError("bad-expression", "a cell reference needs a column name and an address", { path: ctx.path }));
85
110
  const where = resolveAddr(ctx.space, ctx.position, data.at);
86
111
  if (!where.ok) return fail({ ...where.error, path: ctx.path });
87
- return this.cell(data.column, where.value);
112
+ return this.#read(data.column, where.value);
88
113
  };
89
114
 
90
115
  /**
91
116
  * This method gives the result of one cell: the column `column` at the key `key`. A read from a host first evaluates
92
- * the column at the keys before `key`, in key order. Thus a recurrence over the keys reads finished cells, and a
93
- * first read at the last key does not go deep into the call stack.
117
+ * the column at the keys before `key`, in key order. Thus a recurrence over the keys reads finished cells.
94
118
  */
95
119
  cell(column: string, key: string): Result<unknown> {
96
120
  // The placeholder at the top has the index -1. A read inside a formula has a cell at the top, so it does not warm.
97
- if (this.#top.index < 0) this.#warmTo(column, key);
98
- return this.#cell(column, key);
121
+ if (this.#top.index >= 0) return this.#read(column, key);
122
+ this.#warmTo(column, key);
123
+ return this.#drive(column, key);
99
124
  }
100
125
 
101
126
  /** This method evaluates the column `column` at each key before `key` that it did not evaluate before, in key order. */
@@ -105,16 +130,57 @@ export class SheetRun {
105
130
  this.#index ??= new Map(keys.map((k, i) => [k, i]));
106
131
  const end = this.#index.get(key) ?? 0;
107
132
  const start = this.#warmed.get(column) ?? 0;
108
- for (let i = start; i < end; i++) this.#cell(column, keys[i] ?? key);
133
+ for (let i = start; i < end; i++) this.#drive(column, keys[i] ?? key);
109
134
  if (end > start) this.#warmed.set(column, end);
110
135
  }
111
136
 
112
- /** This method evaluates one cell, without the warm-up of `cell`. */
113
- #cell(column: string, key: string): Result<unknown> {
114
- const id = `${column}\u0000${key}`;
137
+ /** This method gives the estimated frames of the stack that one evaluation of a cell of `column` uses. */
138
+ #costOf(column: string, program: Expr): number {
139
+ let cost = this.#cost.get(column);
140
+ if (cost === undefined) {
141
+ cost = 3 * nestingOf(program) + 16;
142
+ this.#cost.set(column, cost);
143
+ }
144
+ return cost;
145
+ }
146
+
147
+ /** This method puts a new cell on the stack of the search. */
148
+ #start(column: string, key: string): Visit {
149
+ const n = this.#next++;
150
+ const visit: Visit = { id: idOf(column, key), column, key, index: n, low: n, reread: false, result: cycleError(column, key), paused: false, need: undefined };
151
+ this.#visits.set(visit.id, visit);
152
+ this.#stack.push(visit);
153
+ return visit;
154
+ }
155
+
156
+ /** This method evaluates the formula of a cell once. When the evaluation pauses, the result of the cell does not change. */
157
+ #evaluate(visit: Visit, program: Expr): void {
158
+ const caller = this.#top;
159
+ const cost = this.#costOf(visit.column, program);
160
+ visit.paused = false;
161
+ visit.need = undefined;
162
+ this.#top = visit;
163
+ this.#used += cost;
164
+ const result = evaluate(program, { ...this.#opts, origin: visit.key });
165
+ this.#used -= cost;
166
+ this.#top = caller;
167
+ if (!visit.paused) visit.result = result;
168
+ }
169
+
170
+ /** This method ends a cell whose evaluation did not pause: it finishes its component, or it gives its low to the caller. */
171
+ #end(visit: Visit, caller: Visit | undefined): void {
172
+ if (visit.low === visit.index) this.#finish(visit);
173
+ else if (caller !== undefined) caller.low = Math.min(caller.low, visit.low);
174
+ }
175
+
176
+ /** This method reads a cell from the formula of the cell at the top. */
177
+ #read(column: string, key: string): Result<unknown> {
178
+ const id = idOf(column, key);
115
179
  const done = this.#done.get(id);
116
180
  if (done !== undefined) return done;
117
181
  const caller = this.#top;
182
+ // A paused evaluation reads no other cell, so it does not follow a path that its final evaluation does not follow.
183
+ if (caller.paused) return cycleError(column, key);
118
184
  const seen = this.#visits.get(id);
119
185
  if (seen !== undefined) {
120
186
  // A read of a cell that is not finished: the caller and this cell are on one cycle. The cell is on the
@@ -126,23 +192,50 @@ export class SheetRun {
126
192
  }
127
193
  const program = this.#columns.get(column);
128
194
  if (program === undefined) return fail(vexError("unbound", `the sheet has no column "${column}"`, { origin: key, focus: key }));
195
+ const visit = this.#start(column, key);
196
+ if (this.#used + this.#costOf(column, program) > this.#budget) {
197
+ // Over the budget: the caller pauses, and the run evaluates the new cell from its own list.
198
+ caller.paused = true;
199
+ caller.need = visit;
200
+ return cycleError(column, key);
201
+ }
202
+ this.#evaluate(visit, program);
203
+ if (visit.paused) {
204
+ caller.paused = true;
205
+ caller.need = visit;
206
+ return cycleError(column, key);
207
+ }
208
+ this.#end(visit, caller);
209
+ return this.#done.get(id) ?? cycleError(column, key);
210
+ }
129
211
 
130
- const n = this.#next++;
131
- const visit: Visit = { id, column, key, index: n, low: n, reread: false, result: cycleError(column, key) };
132
- this.#visits.set(id, visit);
133
- this.#stack.push(visit);
134
- this.#top = visit;
135
- visit.result = evaluate(program, { ...this.#opts, origin: key });
136
- this.#top = caller;
137
-
138
- if (visit.low === visit.index) this.#finish(visit);
139
- else caller.low = Math.min(caller.low, visit.low);
212
+ /** This method evaluates a cell from the top level. The cells that pause go on a list, not on the call stack. */
213
+ #drive(column: string, key: string): Result<unknown> {
214
+ const id = idOf(column, key);
215
+ const done = this.#done.get(id);
216
+ if (done !== undefined) return done;
217
+ if (!this.#columns.has(column)) return fail(vexError("unbound", `the sheet has no column "${column}"`, { origin: key, focus: key }));
218
+ const work: Visit[] = [this.#start(column, key)];
219
+ for (let visit = work.at(-1); visit !== undefined; visit = work.at(-1)) {
220
+ const program = this.#columns.get(visit.column);
221
+ /* v8 ignore next -- @preserve: a visit exists only for a column with a program */
222
+ if (program === undefined) break;
223
+ this.#evaluate(visit, program);
224
+ if (visit.paused) {
225
+ // The cells that the evaluation waits for go on the list, the last one on the top.
226
+ for (let need = visit.need; need !== undefined; need = need.need) work.push(need);
227
+ continue;
228
+ }
229
+ work.pop();
230
+ this.#end(visit, work.at(-1));
231
+ }
140
232
  return this.#done.get(id) ?? cycleError(column, key);
141
233
  }
142
234
 
143
235
  /** This method takes the component of `root` from the stack, and sets the final result of each of its cells. */
144
236
  #finish(root: Visit): void {
145
- const members = this.#stack.splice(this.#stack.indexOf(root));
237
+ // The root is near the top of the stack, so the search starts at the top: a deep chain needs no long scan.
238
+ const members = this.#stack.splice(this.#stack.lastIndexOf(root));
146
239
  // A component of two or more cells reads its root again, so root.reread alone decides. The length test is a guard.
147
240
  // Stryker disable next-line ConditionalExpression,LogicalOperator: members.length > 1 implies root.reread
148
241
  const cyclic = members.length > 1 || root.reread;
@@ -163,7 +256,7 @@ export class SheetRun {
163
256
 
164
257
  /**
165
258
  * This method evaluates the column `column` at each key before `key`, in key order. A recurrence over the keys,
166
- * for example a running total, then reads finished cells and does not go deep into the call stack.
259
+ * for example a running total, then reads finished cells.
167
260
  */
168
261
  warm(column: string, key: string): void {
169
262
  this.#warmTo(column, key);