@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/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.6.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/builder.ts CHANGED
@@ -6,7 +6,7 @@ import type { AnyDomain, Domain, OpSpec } from "./domain.ts";
6
6
  import type { VexError } from "./errors.ts";
7
7
  import { evaluate, explain, type EvalOptions, type ExtHandler, type FreeFn } from "./evaluate.ts";
8
8
  import { app, each, ext, index as indexMove, key as keyMove, let_, lit, offset as offsetMove, other as otherMove, origin as originMove, parent as parentMove, rec, ref, toPath, v, type Addr, type Axis, type Expr, type Move } from "./ir.ts";
9
- import { cell as cellRef, SheetRun } from "./sheet.ts";
9
+ import { cell as cellRef, SheetRun, type CellFormulas } from "./sheet.ts";
10
10
  import { toOptional, type Optional, type Result } from "./result.ts";
11
11
  import type { Space } from "./space.ts";
12
12
  import type { Trace } from "./trace.ts";
@@ -221,6 +221,22 @@ export interface ChainBase<Ctx extends ChainContext, T> {
221
221
  descendants<U>(body: (c: ChainOf<Ctx, T>) => ChainBase<Ctx, U>, opts?: AxisOpts<Ctx, T>): ListChain<Ctx, U>;
222
222
  /** The siblings axis of a tree space: the other children of the parent, or the other roots for a root. */
223
223
  siblings<U>(body: (c: ChainOf<Ctx, T>) => ChainBase<Ctx, U>, opts?: AxisOpts<Ctx, T>): ListChain<Ctx, U>;
224
+ /**
225
+ * The window axis of an array space or a tree space: the keys at the offsets from `from` to `to` of the focus, in
226
+ * order. The offset 0 is the focus. An offset outside the space has no target.
227
+ */
228
+ window<U>(from: number, to: number, body: (c: ChainOf<Ctx, T>) => ChainBase<Ctx, U>, opts?: AxisOpts<Ctx, T>): ListChain<Ctx, U>;
229
+ /**
230
+ * The table axis: the body evaluates at each key of the table `name` of the evaluation, in the space of that table.
231
+ * The body reads the fields of that table, but the types of the chain are the types of this space.
232
+ */
233
+ table<U>(name: string, body: (c: ChainOf<Ctx, T>) => ChainBase<Ctx, U>, opts?: AxisOpts<Ctx, T>): ListChain<Ctx, U>;
234
+ /** The successors axis of a graph space: the ends of the edges from the focus. In a tree space, the children. */
235
+ successors<U>(body: (c: ChainOf<Ctx, T>) => ChainBase<Ctx, U>, opts?: AxisOpts<Ctx, T>): ListChain<Ctx, U>;
236
+ /** The predecessors axis of a graph space: the keys with an edge to the focus. In a tree space, the parent. */
237
+ predecessors<U>(body: (c: ChainOf<Ctx, T>) => ChainBase<Ctx, U>, opts?: AxisOpts<Ctx, T>): ListChain<Ctx, U>;
238
+ /** The reachable axis of a graph space: each key that a path of edges reaches, in breadth-first order. */
239
+ reachable<U>(body: (c: ChainOf<Ctx, T>) => ChainBase<Ctx, U>, opts?: AxisOpts<Ctx, T>): ListChain<Ctx, U>;
224
240
  }
225
241
 
226
242
  /** The options of an axis. */
@@ -360,8 +376,19 @@ export interface Sheet<Ctx extends ChainContext, Cols, Decl = object> {
360
376
  * `cell` and its type: the column itself (a recurrence) or a later column. It has no effect at run time.
361
377
  */
362
378
  declare<D extends Readonly<Record<string, unknown>>>(): Sheet<Ctx, Cols, Decl & D>;
379
+ /**
380
+ * This method gives a new sheet in which the cell of the column `column` at the key `k` has its own formula. That
381
+ * formula replaces the formula of the column at the key `k`. It must give a value of the type of the column.
382
+ */
383
+ cellFormula<const N extends keyof (Cols & Decl) & string>(
384
+ k: Ctx["keys"],
385
+ column: N,
386
+ formula: (r: SheetRoot<Ctx, Cols & Decl>) => ChainBase<Ctx, (Cols & Decl)[N]>,
387
+ ): Sheet<Ctx, Cols, Decl>;
363
388
  /** The program of each column. */
364
389
  readonly columns: Readonly<Record<string, Expr>>;
390
+ /** The program of each cell with its own formula, by column and then by key. */
391
+ readonly cellFormulas: Readonly<Record<string, Readonly<Record<string, Expr>>>>;
365
392
  /** This method evaluates one cell, and gives the error if there is one. */
366
393
  result<N extends keyof Cols & string>(k: Ctx["keys"], column: N): Result<Cols[N]>;
367
394
  /** This method evaluates one cell. An error gives `none`. */
@@ -573,6 +600,21 @@ class ChainImpl {
573
600
  siblings(body: (c: ChainImpl) => { readonly program: Expr }, opts?: { readonly where?: (c: ChainImpl) => { readonly program: Expr } }): ListChainImpl {
574
601
  return this.#axis({ t: "siblings" }, body, opts);
575
602
  }
603
+ window(from: number, to: number, body: (c: ChainImpl) => { readonly program: Expr }, opts?: { readonly where?: (c: ChainImpl) => { readonly program: Expr } }): ListChainImpl {
604
+ return this.#axis({ t: "window", from, to }, body, opts);
605
+ }
606
+ table(name: string, body: (c: ChainImpl) => { readonly program: Expr }, opts?: { readonly where?: (c: ChainImpl) => { readonly program: Expr } }): ListChainImpl {
607
+ return this.#axis({ t: "table", name }, body, opts);
608
+ }
609
+ successors(body: (c: ChainImpl) => { readonly program: Expr }, opts?: { readonly where?: (c: ChainImpl) => { readonly program: Expr } }): ListChainImpl {
610
+ return this.#axis({ t: "successors" }, body, opts);
611
+ }
612
+ predecessors(body: (c: ChainImpl) => { readonly program: Expr }, opts?: { readonly where?: (c: ChainImpl) => { readonly program: Expr } }): ListChainImpl {
613
+ return this.#axis({ t: "predecessors" }, body, opts);
614
+ }
615
+ reachable(body: (c: ChainImpl) => { readonly program: Expr }, opts?: { readonly where?: (c: ChainImpl) => { readonly program: Expr } }): ListChainImpl {
616
+ return this.#axis({ t: "reachable" }, body, opts);
617
+ }
576
618
  }
577
619
 
578
620
  /** This function gives the options of an evaluation of a chain or a list chain at the origin `k`. */
@@ -704,25 +746,36 @@ class SheetRootImpl extends RootImpl {
704
746
  class SheetImpl {
705
747
  readonly #env: Env;
706
748
  readonly #columns: ReadonlyMap<string, Expr>;
707
- constructor(env: Env, columns: ReadonlyMap<string, Expr>) {
749
+ readonly #cells: CellFormulas;
750
+ constructor(env: Env, columns: ReadonlyMap<string, Expr>, cells: CellFormulas = new Map()) {
708
751
  this.#env = env;
709
752
  this.#columns = columns;
753
+ this.#cells = cells;
710
754
  }
711
755
  get columns(): Readonly<Record<string, Expr>> {
712
756
  return Object.freeze(Object.fromEntries(this.#columns));
713
757
  }
758
+ get cellFormulas(): Readonly<Record<string, Readonly<Record<string, Expr>>>> {
759
+ return Object.freeze(Object.fromEntries([...this.#cells].map(([c, keys]) => [c, Object.freeze(Object.fromEntries(keys))])));
760
+ }
714
761
  declare(): SheetImpl {
715
762
  return this;
716
763
  }
717
764
  column(name: string, formula: (r: SheetRootImpl) => { readonly program: Expr }): SheetImpl {
718
765
  const program = formula(new SheetRootImpl(this.#env)).program;
719
- return new SheetImpl(this.#env, new Map([...this.#columns, [name, program]]));
766
+ return new SheetImpl(this.#env, new Map([...this.#columns, [name, program]]), this.#cells);
767
+ }
768
+ cellFormula(k: string, column: string, formula: (r: SheetRootImpl) => { readonly program: Expr }): SheetImpl {
769
+ const program = formula(new SheetRootImpl(this.#env)).program;
770
+ const keys = new Map([...(this.#cells.get(column) ?? []), [k, program]]);
771
+ return new SheetImpl(this.#env, this.#columns, new Map([...this.#cells, [column, keys]]));
720
772
  }
721
773
  #run(): SheetRun {
722
774
  const { space: s, domains, options } = this.#env;
723
775
  return new SheetRun(this.#columns, {
724
776
  space: s,
725
777
  domains,
778
+ cells: this.#cells,
726
779
  // Stryker disable next-line ConditionalExpression: an undefined option and an absent option are the same
727
780
  ...(options.fns === undefined ? {} : { fns: options.fns }),
728
781
  // Stryker disable next-line ConditionalExpression: an undefined option and an absent option are the same
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 =
@@ -12,6 +12,8 @@ export type ErrorKind =
12
12
  | "no-offset"
13
13
  | "no-grid"
14
14
  | "no-tree"
15
+ | "no-table"
16
+ | "no-graph"
15
17
  | "missing-field"
16
18
  | "empty"
17
19
  | "not-instance"
@@ -24,6 +26,7 @@ export type ErrorKind =
24
26
  | "undefined-result"
25
27
  | "args"
26
28
  | "cycle"
29
+ | "depth"
27
30
  | "bad-expression";
28
31
 
29
32
  const CODE_OF: Readonly<Record<ErrorKind, ErrorCode>> = {
@@ -33,6 +36,8 @@ const CODE_OF: Readonly<Record<ErrorKind, ErrorCode>> = {
33
36
  "no-offset": "#REF!",
34
37
  "no-grid": "#REF!",
35
38
  "no-tree": "#REF!",
39
+ "no-table": "#REF!",
40
+ "no-graph": "#REF!",
36
41
  "missing-field": "#N/A",
37
42
  empty: "#N/A",
38
43
  "not-instance": "#VALUE!",
@@ -46,9 +51,22 @@ const CODE_OF: Readonly<Record<ErrorKind, ErrorCode>> = {
46
51
  "undefined-result": "#CALC!",
47
52
  args: "#ARGS",
48
53
  cycle: "#CYCLE!",
54
+ depth: "#DEPTH!",
49
55
  };
50
56
 
51
- /** A Vex error. It is a value: a program can catch it with `ifError`. */
57
+ /**
58
+ * This function tells if an exception is the report of the engine that the call stack is full. V8 and JavaScriptCore
59
+ * throw a `RangeError`. SpiderMonkey throws an `InternalError` ("too much recursion").
60
+ */
61
+ export function isStackOverflow(thrown: unknown): boolean {
62
+ if (!(thrown instanceof Error)) return false;
63
+ return (thrown instanceof RangeError && /call stack/i.test(thrown.message)) || (thrown.name === "InternalError" && /recursion/i.test(thrown.message));
64
+ }
65
+
66
+ /** This function tells if an error is `#DEPTH!`. `ifError` and the reductions that skip errors do not hide it (EVAL.DEPTH). */
67
+ export const isDepthError = (e: VexError): boolean => e.kind === "depth";
68
+
69
+ /** A Vex error. It is a value: a program can catch it with `ifError`, except `#DEPTH!`. */
52
70
  export interface VexError {
53
71
  /** The spreadsheet-style code, for example `#REF!`. */
54
72
  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";
@@ -33,6 +33,8 @@ export interface EvalOptions {
33
33
  readonly extensions?: Readonly<Record<string, ExtHandler>>;
34
34
  /** Variables that the program can read with `v(name)`. */
35
35
  readonly vars?: Readonly<Record<string, unknown>>;
36
+ /** The other spaces of the evaluation, by name. The axis `table(name)` reads them. */
37
+ readonly tables?: Readonly<Record<string, Space>>;
36
38
  /** A receiver of trace events. */
37
39
  readonly trace?: TraceSink;
38
40
  }
@@ -56,7 +58,7 @@ const isSpecialForm = (op: string): op is SpecialForm => SPECIAL_FORMS.has(op);
56
58
  export type CompileOptions = Pick<EvalOptions, "domains" | "fns" | "extensions">;
57
59
 
58
60
  /** The options of one run of a compiled program. */
59
- export type RunOptions = Pick<EvalOptions, "space" | "origin" | "vars" | "trace">;
61
+ export type RunOptions = Pick<EvalOptions, "space" | "origin" | "vars" | "trace" | "tables">;
60
62
 
61
63
  /**
62
64
  * A compiled program: the expression as a tree of functions. A program evaluates many times at different origins,
@@ -75,16 +77,39 @@ export interface Program {
75
77
  * This function compiles an expression. The result gives the same results and the same traces as `evaluate`,
76
78
  * because `evaluate` uses it too.
77
79
  */
80
+ /** The deepest nesting of an expression that `compile` accepts (EVAL.NESTING). */
81
+ export const MAX_NESTING = 500;
82
+
83
+ const DEPTH_MESSAGE = "the evaluation is too deep for the call stack of the engine";
84
+
85
+ /** This function gives the number of nodes on the longest path from the root of `e`. It uses a stack, not recursion. */
86
+ export function nestingOf(e: Expr): number {
87
+ let deepest = 0;
88
+ const todo: [Expr, number][] = [[e, 1]];
89
+ for (let item = todo.pop(); item !== undefined; item = todo.pop()) {
90
+ const [x, d] = item;
91
+ if (d > deepest) deepest = d;
92
+ for (const child of children(x)) todo.push([child, d + 1]);
93
+ }
94
+ return deepest;
95
+ }
96
+
78
97
  export function compile(expr: Expr, opts: CompileOptions = {}): Program {
79
- const root = new Compiler(opts).node(expr, []);
98
+ // EVAL.NESTING: a program nested too deep gives an error before the compiler walks it with recursion.
99
+ const nesting = nestingOf(expr);
100
+ const root: Node =
101
+ nesting > MAX_NESTING
102
+ ? (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 }))
103
+ : new Compiler(opts).node(expr, []);
80
104
  const run = (r: RunOptions): Result<unknown> => {
81
105
  const { space, origin } = r;
82
106
  if (!space.has(origin)) return fail(vexError("unknown-key", `the space has no key "${origin}"`, { origin, focus: origin }));
83
107
  const env = new Map<string, Result<unknown>>(Object.entries(r.vars ?? {}).map(([k, val]) => [k, ok(val)]));
84
108
  try {
85
- return root({ pos: { origin, focus: origin }, env }, { space, trace: r.trace });
109
+ return root({ pos: { origin, focus: origin }, env }, { space, trace: r.trace, tables: r.tables });
86
110
  } catch (thrown) {
87
111
  // A defect in an extension handler or in a test of the interpreter itself. Totality still holds.
112
+ if (isStackOverflow(thrown)) return fail(vexError("depth", DEPTH_MESSAGE, { origin, focus: origin, thrown }));
88
113
  return fail(vexError("threw", "the evaluation threw an exception", { origin, focus: origin, thrown }));
89
114
  }
90
115
  };
@@ -123,12 +148,16 @@ export function explain(expr: Expr, opts: Omit<EvalOptions, "trace">): Trace {
123
148
  return compiled(expr, opts).explain(opts);
124
149
  }
125
150
 
126
- /** The state of one run that the nodes read: the space and the trace sink. */
151
+ /** The state of one run that the nodes read: the space, the trace sink and the other spaces. */
127
152
  interface Ctx {
128
153
  readonly space: Space;
129
154
  readonly trace: TraceSink | undefined;
155
+ readonly tables: Readonly<Record<string, Space>> | undefined;
130
156
  }
131
157
 
158
+ /** This function gives the axis inside the `where` axes of an axis. */
159
+ const baseAxis = (a: Axis): Exclude<Axis, { readonly t: "where" }> => (a.t === "where" ? baseAxis(a.axis) : a);
160
+
132
161
  /** A compiled node: it evaluates in a frame of a run. */
133
162
  type Node = (f: Frame, c: Ctx) => Result<unknown>;
134
163
 
@@ -236,10 +265,15 @@ class Compiler {
236
265
  try {
237
266
  return run();
238
267
  } catch (thrown) {
239
- return this.#err("threw", `"${op}" threw an exception`, f, path, { op, thrown });
268
+ return this.#threw(thrown, `"${op}" threw an exception`, f, path, { op });
240
269
  }
241
270
  }
242
271
 
272
+ /** This method gives the error of an exception: `#DEPTH!` for a full call stack, and `#CALC!` for each other exception. */
273
+ #threw(thrown: unknown, message: string, f: Frame, path: readonly number[], extra: Partial<VexError> = {}): Result<never> {
274
+ return isStackOverflow(thrown) ? this.#err("depth", DEPTH_MESSAGE, f, path, { ...extra, thrown }) : this.#err("threw", message, f, path, { ...extra, thrown });
275
+ }
276
+
243
277
  #ref(e: ExprOf<"ref">, info: Info): Node {
244
278
  const { path } = info;
245
279
  const segs = e.path;
@@ -264,7 +298,7 @@ class Compiler {
264
298
  try {
265
299
  value = Reflect.get(value, seg);
266
300
  } catch (thrown) {
267
- return failed(this.#err("threw", `reading "${where}" at "${key}" threw an exception`, f, path, { thrown }));
301
+ return failed(this.#threw(thrown, `reading "${where}" at "${key}" threw an exception`, f, path));
268
302
  }
269
303
  if (value === undefined || value === null) return missing(where);
270
304
  }
@@ -284,6 +318,9 @@ class Compiler {
284
318
  else (errors ??= [first]).push(r.error);
285
319
  }
286
320
  if (first === undefined) return ok(values);
321
+ // A #DEPTH! argument is the result, so #ARGS does not wrap it, and ifError cannot hide it.
322
+ const depth = [first, ...(errors ?? [])].find(isDepthError);
323
+ if (depth !== undefined) return fail(depth);
287
324
  return errors === undefined ? fail(first) : this.#err("args", `${errors.length} ${what} failed`, f, path, { causes: errors });
288
325
  }
289
326
 
@@ -301,11 +338,20 @@ class Compiler {
301
338
  if (!where.ok) return this.#emit(c, info, f, fail({ ...where.error, path }));
302
339
  from = { pos: { origin: f.pos.origin, focus: where.value }, env: f.env };
303
340
  }
304
- const ts = targets(from, c);
341
+ // The axis table moves the evaluation to the space of its table, where the origin of this space is not a key.
342
+ // Thus there the origin is the target, and a value of this space goes in through a variable.
343
+ const base = baseAxis(e.axis);
344
+ let inner = c;
345
+ if (base.t === "table") {
346
+ const space = c.tables !== undefined && Object.hasOwn(c.tables, base.name) ? c.tables[base.name] : undefined;
347
+ if (space === undefined) return this.#emit(c, info, f, this.#err("no-table", `the evaluation has no table "${base.name}"`, f, path));
348
+ inner = { ...c, space };
349
+ }
350
+ const ts = targets(from, inner);
305
351
  if (!ts.ok) return this.#emit(c, info, f, ts);
306
352
  const items: ListItem[] = ts.value.map(({ key, test }) => {
307
353
  if (test !== undefined && !test.ok) return { key, result: test };
308
- return { key, result: body({ pos: { origin: f.pos.origin, focus: key }, env: f.env }, c) };
354
+ return { key, result: body({ pos: { origin: base.t === "table" ? key : f.pos.origin, focus: key }, env: f.env }, inner) };
309
355
  });
310
356
  return this.#emit(c, info, f, ok(vexList(items)));
311
357
  };
@@ -313,6 +359,7 @@ class Compiler {
313
359
 
314
360
  /** This method compiles the targets of an axis. For `where`, a failed test keeps the target with its error. */
315
361
  #targets(a: Axis, path: readonly number[], counter: { next: number }): (f: Frame, c: Ctx) => Result<readonly { readonly key: string; readonly test?: Result<unknown> }[]> {
362
+ if (a.t === "table") return (_f, c) => ok(c.space.keys.map((key) => ({ key })));
316
363
  if (a.t !== "where") {
317
364
  return (f, c) => {
318
365
  const keys = axisTargets(c.space, f.pos, a);
@@ -322,6 +369,8 @@ class Compiler {
322
369
  const inner = this.#targets(a.axis, path, counter);
323
370
  const testPath = [...path, counter.next++];
324
371
  const test = this.node(a.test, testPath);
372
+ // In the space of the axis table, the origin of the test is the target, as for the body.
373
+ const sameOrigin = baseAxis(a).t === "table";
325
374
  return (f, c) => {
326
375
  const ts = inner(f, c);
327
376
  if (!ts.ok) return ts;
@@ -331,7 +380,7 @@ class Compiler {
331
380
  out.push(t);
332
381
  continue;
333
382
  }
334
- const at: Frame = { pos: { origin: f.pos.origin, focus: t.key }, env: f.env };
383
+ const at: Frame = { pos: { origin: sameOrigin ? t.key : f.pos.origin, focus: t.key }, env: f.env };
335
384
  const r = test(at, c);
336
385
  if (!r.ok) out.push({ key: t.key, test: r });
337
386
  else if (r.value === true) out.push({ key: t.key });
@@ -404,7 +453,8 @@ class Compiler {
404
453
  case "ifError":
405
454
  return (f, c) => {
406
455
  const first = arg(0, f, c);
407
- return this.#emit(c, info, f, first.ok ? first : arg(1, f, c));
456
+ // EVAL.DEPTH: ifError does not hide #DEPTH!, because the engine, not the data, failed.
457
+ return this.#emit(c, info, f, first.ok || isDepthError(first.error) ? first : arg(1, f, c));
408
458
  };
409
459
  }
410
460
  }
@@ -435,7 +485,7 @@ class Compiler {
435
485
  try {
436
486
  return ok(run());
437
487
  } catch (thrown) {
438
- return this.#err("threw", `"${op}" threw an exception`, f, path, { op, thrown });
488
+ return this.#threw(thrown, `"${op}" threw an exception`, f, path, { op });
439
489
  }
440
490
  }
441
491
 
@@ -452,7 +502,7 @@ class Compiler {
452
502
  try {
453
503
  valid = d.valid(value);
454
504
  } catch (thrown) {
455
- return this.#err("threw", `the "valid" check of "${d.name}" threw an exception`, f, path, { ...extra, thrown });
505
+ return this.#threw(thrown, `the "valid" check of "${d.name}" threw an exception`, f, path, extra);
456
506
  }
457
507
  if (!valid) return this.#err("invalid-value", `"${op}" gave a value that is not a valid ${d.name}`, f, path, extra);
458
508
  }
@@ -461,6 +511,9 @@ class Compiler {
461
511
 
462
512
  #listOp(op: ListOp, list: VexList, rest: readonly unknown[], f: Frame, path: readonly number[]): Result<unknown> {
463
513
  const optsArg = op === "reduce" ? rest[1] : rest[0];
514
+ // A reduction that skips error items does not skip #DEPTH! (EVAL.DEPTH).
515
+ const depth = list.items.find((it) => !it.result.ok && isDepthError(it.result.error))?.result;
516
+ if (depth !== undefined && !depth.ok) return fail(depth.error);
464
517
  const strict = (optsArg as ListOptions | null | undefined)?.strict === true;
465
518
  const firstError = list.items.find((it) => !it.result.ok)?.result;
466
519
  if (strict && firstError !== undefined && !firstError.ok) return fail(firstError.error);
package/src/ir.ts CHANGED
@@ -25,6 +25,11 @@ export type Axis =
25
25
  | { readonly t: "ancestors" }
26
26
  | { readonly t: "descendants" }
27
27
  | { readonly t: "siblings" }
28
+ | { readonly t: "window"; readonly from: number; readonly to: number }
29
+ | { readonly t: "table"; readonly name: string }
30
+ | { readonly t: "successors" }
31
+ | { readonly t: "predecessors" }
32
+ | { readonly t: "reachable" }
28
33
  | { readonly t: "where"; readonly axis: Axis; readonly test: Expr };
29
34
 
30
35
  /** A Vex expression. */
@@ -115,6 +120,22 @@ export const axes = {
115
120
  descendants: Object.freeze({ t: "descendants" }) as Axis,
116
121
  /** The other children of the parent of the focus. For a root, the other roots. */
117
122
  siblings: Object.freeze({ t: "siblings" }) as Axis,
123
+ /**
124
+ * 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
125
+ * a tree space, the offsets go among the siblings. An offset outside the space has no target.
126
+ */
127
+ window: (from: number, to: number): Axis => ({ t: "window", from, to }),
128
+ /**
129
+ * Each key of the table `name` of the evaluation, in key order. The body evaluates in the space of that table, and
130
+ * there the origin is the target.
131
+ */
132
+ table: (name: string): Axis => ({ t: "table", name }),
133
+ /** The keys at the ends of the edges from the focus, in a graph space. In a tree space, the children. */
134
+ successors: Object.freeze({ t: "successors" }) as Axis,
135
+ /** The keys with an edge to the focus, in key order. In a tree space, the parent. */
136
+ predecessors: Object.freeze({ t: "predecessors" }) as Axis,
137
+ /** Each key that a path of edges reaches from the focus, in breadth-first order, without the focus. */
138
+ reachable: Object.freeze({ t: "reachable" }) as Axis,
118
139
  /** The targets of `axis` where `test` gives `true`. */
119
140
  where: (axis: Axis, test: Expr): Axis => ({ t: "where", axis, test }),
120
141
  } as const;
@@ -144,53 +165,80 @@ export function isMove(u: unknown): u is Move {
144
165
  }
145
166
  }
146
167
 
147
- /** This function tells if a value is a valid axis. */
168
+ /** This function tells if a value is a valid axis. It checks the tests of `where` too. */
148
169
  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
- }
170
+ return validTree([{ axis: true, u }]);
166
171
  }
167
172
 
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
173
  /** This function tells if a value is a valid expression. It checks the whole tree. */
172
174
  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;
175
+ return validTree([{ axis: false, u }]);
176
+ }
177
+
178
+ const isAddr = (u: unknown): boolean => u === undefined || (Array.isArray(u) && u.every(isMove));
179
+
180
+ /**
181
+ * This function checks a tree of expressions and axes. It uses a stack, not recursion, so the input can be deep. For
182
+ * example, a deep JSON file from a stranger does not need a deep call stack (EVAL.NESTING).
183
+ */
184
+ function validTree(todo: { readonly axis: boolean; readonly u: unknown }[]): boolean {
185
+ const push = (axis: boolean, values: readonly unknown[]): void => {
186
+ for (const u of values) todo.push({ axis, u });
187
+ };
188
+ for (let item = todo.pop(); item !== undefined; item = todo.pop()) {
189
+ const { u } = item;
190
+ if (!isObject(u)) return false;
191
+ if (item.axis) {
192
+ const t = u["t"];
193
+ if (t === "neighbors") {
194
+ if (u["n"] !== 4 && u["n"] !== 8) return false;
195
+ } else if (t === "window") {
196
+ if (!Number.isSafeInteger(u["from"]) || !Number.isSafeInteger(u["to"])) return false;
197
+ } else if (t === "table") {
198
+ if (typeof u["name"] !== "string") return false;
199
+ } else if (t === "where") {
200
+ push(true, [u["axis"]]);
201
+ push(false, [u["test"]]);
202
+ } else if (!["all", "others", "other", "children", "ancestors", "descendants", "siblings", "successors", "predecessors", "reachable"].includes(t as string)) {
203
+ return false;
204
+ }
205
+ continue;
206
+ }
207
+ switch (u["tag"]) {
208
+ case "lit":
209
+ if (!("value" in u)) return false;
210
+ break;
211
+ case "ref":
212
+ if (!isStringArray(u["path"]) || !isAddr(u["at"])) return false;
213
+ break;
214
+ case "app":
215
+ if (typeof u["op"] !== "string" || !Array.isArray(u["args"])) return false;
216
+ push(false, u["args"]);
217
+ break;
218
+ case "let":
219
+ if (!isObject(u["bind"]) || Array.isArray(u["bind"])) return false;
220
+ push(false, [...Object.values(u["bind"]), u["body"]]);
221
+ break;
222
+ case "var":
223
+ if (typeof u["name"] !== "string") return false;
224
+ break;
225
+ case "rec":
226
+ if (!isObject(u["fields"]) || Array.isArray(u["fields"])) return false;
227
+ push(false, Object.values(u["fields"]));
228
+ break;
229
+ case "each":
230
+ if (!isAddr(u["at"])) return false;
231
+ push(true, [u["axis"]]);
232
+ push(false, [u["body"]]);
233
+ break;
234
+ case "ext":
235
+ if (typeof u["kind"] !== "string" || !("data" in u)) return false;
236
+ break;
237
+ default:
238
+ return false;
239
+ }
193
240
  }
241
+ return true;
194
242
  }
195
243
 
196
244
  /** This function gives the child expressions of an expression, in the order of their child index. */
@@ -212,6 +260,9 @@ export function children(e: Expr): readonly Expr[] {
212
260
  }
213
261
  }
214
262
 
263
+ /** This function gives the tests of the `where` axes of an axis, from the inside out. It uses a loop, not recursion. */
215
264
  function whereTests(a: Axis): readonly Expr[] {
216
- return a.t === "where" ? [...whereTests(a.axis), a.test] : [];
265
+ const out: Expr[] = [];
266
+ for (let x: Axis = a; x.t === "where"; x = x.axis) out.unshift(x.test);
267
+ return out;
217
268
  }
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
  }