@mark1russell7/vex 0.3.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.3.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",
@@ -59,6 +59,7 @@
59
59
  "test": "vitest run",
60
60
  "test:watch": "vitest",
61
61
  "bench": "vitest bench --run -c vitest.bench.config.ts --reporter=verbose",
62
- "typecheck": "tsc -p tsconfig.json && tsc -p tsconfig.test.json"
62
+ "typecheck": "tsc -p tsconfig.json && tsc -p tsconfig.test.json",
63
+ "bench:gate": "node bench/gate.ts"
63
64
  }
64
65
  }
package/src/builder.ts CHANGED
@@ -3,12 +3,14 @@
3
3
  * evaluate anything until a caller asks for a value.
4
4
  */
5
5
  import type { AnyDomain, Domain, OpSpec } from "./domain.ts";
6
+ import type { VexError } from "./errors.ts";
6
7
  import { evaluate, explain, type EvalOptions, type ExtHandler, type FreeFn } from "./evaluate.ts";
7
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";
8
9
  import { cell as cellRef, SheetRun } from "./sheet.ts";
9
10
  import { toOptional, type Optional, type Result } from "./result.ts";
10
11
  import type { Space } from "./space.ts";
11
12
  import type { Trace } from "./trace.ts";
13
+ import type { VexList } from "./list.ts";
12
14
  import { traversal, type Traversal } from "./traversal.ts";
13
15
 
14
16
  // ---------------------------------------------------------------- argument tokens
@@ -108,7 +110,13 @@ export type ArgInput<P, Ctx extends ChainContext, Lift extends boolean> =
108
110
  | KeysOfType<Ctx["record"], P>
109
111
  | Arg<P>
110
112
  | ChainOf<Ctx, P>
111
- | (Lift extends true ? ([P] extends [DomainValue<DomainFor<Ctx["domains"], P>>] ? number : never) : never);
113
+ | (Lift extends true ? ([P] extends [DomainValue<DomainFor<Ctx["domains"], P>>] ? LiftedNumber<Ctx> : never) : never);
114
+
115
+ /**
116
+ * A number argument for a domain parameter of an op with `liftScalar` (TYPE.LIFT): a number, a field with numbers, an
117
+ * argument or a chain. The interpreter lifts each of them with `fromScalar` (CALL.LIFT).
118
+ */
119
+ type LiftedNumber<Ctx extends ChainContext> = number | KeysOfType<Ctx["record"], number> | Arg<number> | ChainOf<Ctx, number>;
112
120
 
113
121
  type MapArgs<P extends readonly unknown[], Ctx extends ChainContext, Lift extends boolean> = { [I in keyof P]: ArgInput<P[I], Ctx, Lift> };
114
122
 
@@ -182,6 +190,11 @@ export interface ChainBase<Ctx extends ChainContext, T> {
182
190
  parent(): ChainOf<Ctx, T>;
183
191
  /** This method uses `fallback` when the chain gives an error. */
184
192
  ifError<U>(fallback: ArgInput<U, Ctx, false> | T): ChainOf<Ctx, T | U>;
193
+ /**
194
+ * This method gives `then` when the boolean value is true, and `otherwise` when it is false (the form `if`). Only
195
+ * the selected branch evaluates.
196
+ */
197
+ if<U, V>(this: ChainBase<Ctx, boolean>, then: ArgInput<U, Ctx, false>, otherwise: ArgInput<V, Ctx, false>): ChainOf<Ctx, U | V>;
185
198
  /**
186
199
  * This method applies the free function `name` of `withOptions`. The function gets the current value as its first
187
200
  * argument, then `args`. The types accept only the functions whose first parameter accepts the current value.
@@ -259,8 +272,18 @@ export interface ListChain<Ctx extends ChainContext, U> {
259
272
  all(this: ListChain<Ctx, boolean>, opts?: ListOpts): ChainOf<Ctx, boolean>;
260
273
  none(this: ListChain<Ctx, boolean>, opts?: ListOpts): ChainOf<Ctx, boolean>;
261
274
  values(opts?: ListOpts): ChainOf<Ctx, readonly U[]>;
275
+ /** The keys of the items with a value, in the order of the axis. */
276
+ keys(opts?: ListOpts): ChainOf<Ctx, readonly Ctx["keys"][]>;
277
+ /** The error of each item that failed, in the order of the axis. */
278
+ errors(): ChainOf<Ctx, readonly VexError[]>;
262
279
  first(opts?: ListOpts): ChainOf<Ctx, U>;
263
- reduce(op: OpNames<DomainFor<Ctx["domains"], U>>, opts?: ListOpts): ChainOf<Ctx, U>;
280
+ reduce(op: OpNames<DomainFor<Ctx["domains"], U>>, opts?: ReduceOpts<Ctx>): ChainOf<Ctx, U>;
281
+ /** The list at the origin `k`: one item for each target of the axis, with its key and its result. */
282
+ result(k: Ctx["keys"]): Result<VexList<U>>;
283
+ /** The list at the origin `k`, as an `Optional`. */
284
+ at(k: Ctx["keys"]): Optional<VexList<U>>;
285
+ /** The trace of the evaluation of the list at the origin `k`. */
286
+ explain(k: Ctx["keys"]): Trace;
264
287
  }
265
288
 
266
289
  /** The options of a list reduction. */
@@ -269,6 +292,11 @@ export interface ListOpts {
269
292
  readonly strict?: boolean;
270
293
  }
271
294
 
295
+ /** The options of `reduce`. `domain` names the domain whose identity an empty list gives (LIST.EMPTY). */
296
+ export interface ReduceOpts<Ctx extends ChainContext> extends ListOpts {
297
+ readonly domain?: Ctx["domains"][number]["name"];
298
+ }
299
+
272
300
  /** The root of the builder for one space. */
273
301
  export interface Root<Ctx extends ChainContext> {
274
302
  /** This method starts a chain with a field of the record at the focus. */
@@ -432,16 +460,7 @@ class ChainImpl {
432
460
  }
433
461
 
434
462
  #opts(k: string): EvalOptions {
435
- const { env } = this.#s;
436
- return {
437
- space: env.space,
438
- origin: k,
439
- domains: env.domains,
440
- // Stryker disable next-line ConditionalExpression: an undefined option and an absent option are the same
441
- ...(env.options.fns === undefined ? {} : { fns: env.options.fns }),
442
- // Stryker disable next-line ConditionalExpression: an undefined option and an absent option are the same
443
- ...(env.options.extensions === undefined ? {} : { extensions: env.options.extensions }),
444
- };
463
+ return evalOptions(this.#s, k);
445
464
  }
446
465
 
447
466
  result(k: string): Result<unknown> {
@@ -491,6 +510,9 @@ class ChainImpl {
491
510
  call(name: string, ...args: readonly unknown[]): ChainImpl {
492
511
  return new ChainImpl({ ...this.#s, expr: app(name, this.#s.expr, ...args.map((a) => toExpr(a, this.#s.addr))) });
493
512
  }
513
+ if(then: unknown, otherwise: unknown): ChainImpl {
514
+ return new ChainImpl({ ...this.#s, expr: app("if", this.#s.expr, toExpr(then, this.#s.addr), toExpr(otherwise, this.#s.addr)) });
515
+ }
494
516
  ifError(fallback: unknown): ChainImpl {
495
517
  return new ChainImpl({ ...this.#s, expr: app("ifError", this.#s.expr, toExpr(fallback, this.#s.addr)) });
496
518
  }
@@ -527,7 +549,8 @@ class ChainImpl {
527
549
  const inTarget = new ChainImpl({ ...start.#s, addr: [] });
528
550
  const inner = body(inTarget);
529
551
  const axis: Axis = opts?.where === undefined ? a : { t: "where", axis: a, test: opts.where(inTarget).program };
530
- return new ListChainImpl({ ...this.#s, expr: let_({ [name]: this.#s.expr }, each(axis, inner.program)) });
552
+ // The moves before the axis are its address: parent().children(f) gives f at each child of the parent.
553
+ return new ListChainImpl({ ...this.#s, expr: let_({ [name]: this.#s.expr }, each(axis, inner.program, this.#s.addr)) });
531
554
  }
532
555
  others(body: (c: ChainImpl) => { readonly program: Expr }, opts?: { readonly where?: (c: ChainImpl) => { readonly program: Expr } }): ListChainImpl {
533
556
  return this.#axis({ t: "others" }, body, opts);
@@ -552,6 +575,20 @@ class ChainImpl {
552
575
  }
553
576
  }
554
577
 
578
+ /** This function gives the options of an evaluation of a chain or a list chain at the origin `k`. */
579
+ function evalOptions(s: State, k: string): EvalOptions {
580
+ const { env } = s;
581
+ return {
582
+ space: env.space,
583
+ origin: k,
584
+ domains: env.domains,
585
+ // Stryker disable next-line ConditionalExpression: an undefined option and an absent option are the same
586
+ ...(env.options.fns === undefined ? {} : { fns: env.options.fns }),
587
+ // Stryker disable next-line ConditionalExpression: an undefined option and an absent option are the same
588
+ ...(env.options.extensions === undefined ? {} : { extensions: env.options.extensions }),
589
+ };
590
+ }
591
+
555
592
  class ListChainImpl {
556
593
  readonly kind = "vex.list-chain" as const;
557
594
  readonly #s: State;
@@ -561,8 +598,9 @@ class ListChainImpl {
561
598
  get program(): Expr {
562
599
  return this.#s.expr;
563
600
  }
564
- #op(op: string, extra: readonly Expr[], opts?: ListOpts): ChainImpl {
565
- const args = opts?.strict === true ? [...extra, lit({ strict: true })] : extra;
601
+ #op(op: string, extra: readonly Expr[], opts?: ListOpts & { readonly domain?: string }): ChainImpl {
602
+ const options = { ...(opts?.strict === true ? { strict: true } : {}), ...(opts?.domain === undefined ? {} : { domain: opts.domain }) };
603
+ const args = Object.keys(options).length > 0 ? [...extra, lit(options)] : extra;
566
604
  return new ChainImpl({ ...this.#s, expr: app(op, this.#s.expr, ...args) });
567
605
  }
568
606
  count(opts?: ListOpts): ChainImpl {
@@ -592,12 +630,27 @@ class ListChainImpl {
592
630
  values(opts?: ListOpts): ChainImpl {
593
631
  return this.#op("values", [], opts);
594
632
  }
633
+ keys(opts?: ListOpts): ChainImpl {
634
+ return this.#op("keys", [], opts);
635
+ }
636
+ errors(): ChainImpl {
637
+ return this.#op("errors", []);
638
+ }
595
639
  first(opts?: ListOpts): ChainImpl {
596
640
  return this.#op("first", [], opts);
597
641
  }
598
- reduce(op: string, opts?: ListOpts): ChainImpl {
642
+ reduce(op: string, opts?: ListOpts & { readonly domain?: string }): ChainImpl {
599
643
  return this.#op("reduce", [lit(op)], opts);
600
644
  }
645
+ result(k: string): Result<unknown> {
646
+ return evaluate(this.#s.expr, evalOptions(this.#s, k));
647
+ }
648
+ at(k: string): Optional<unknown> {
649
+ return toOptional(this.result(k));
650
+ }
651
+ explain(k: string): Trace {
652
+ return explain(this.#s.expr, evalOptions(this.#s, k));
653
+ }
601
654
  }
602
655
 
603
656
  class RootImpl {
package/src/deps.ts CHANGED
@@ -8,6 +8,8 @@ export interface Dependency {
8
8
  readonly path: readonly string[];
9
9
  /** The axes around the read, from the outside to the inside. Inside an axis, the focus is the target. */
10
10
  readonly axes: readonly Axis["t"][];
11
+ /** The address of each axis in `axes`, in the same order. The empty address is the focus. */
12
+ readonly axisAt: readonly Addr[];
11
13
  }
12
14
 
13
15
  /**
@@ -16,18 +18,18 @@ export interface Dependency {
16
18
  */
17
19
  export function deps(e: Expr): readonly Dependency[] {
18
20
  const out: Dependency[] = [];
19
- const walk = (x: Expr, axes: readonly Axis["t"][]): 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;
20
26
  if (x.tag === "ref") {
21
- out.push({ at: x.at ?? [], path: x.path, axes });
22
- return;
27
+ out.push({ at: x.at ?? [], path: x.path, axes: item.axes, axisAt: item.axisAt });
28
+ continue;
23
29
  }
24
- if (x.tag === "each") {
25
- const inner = [...axes, x.axis.t];
26
- children(x).forEach((c) => walk(c, inner));
27
- return;
28
- }
29
- children(x).forEach((c) => walk(c, axes));
30
- };
31
- 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
+ }
32
34
  return out;
33
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,6 +1,6 @@
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";
3
- import { children, type Axis, type Expr, type ExprOf } from "./ir.ts";
2
+ import { formatError, isDepthError, isStackOverflow, vexError, type ErrorKind, type VexError } from "./errors.ts";
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";
6
6
  import { axisTargets, resolveAddr, type Position, type Space } from "./space.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,15 +312,27 @@ 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
 
290
321
  #each(e: ExprOf<"each">, info: Info): Node {
291
322
  const { path } = info;
323
+ const at = e.at ?? [];
292
324
  const targets = this.#targets(e.axis, path, { next: 1 });
293
325
  const body = this.node(e.body, [...path, 0]);
294
326
  return (f, c) => {
295
- const ts = targets(f, c);
327
+ // An axis with an address finds its targets from the key of the address. The origin does not change.
328
+ let from = f;
329
+ // Stryker disable next-line ConditionalExpression,EqualityOperator: resolveAddr of [] gives the focus too
330
+ if (at.length > 0) {
331
+ const where = resolveAddr(c.space, f.pos, at);
332
+ if (!where.ok) return this.#emit(c, info, f, fail({ ...where.error, path }));
333
+ from = { pos: { origin: f.pos.origin, focus: where.value }, env: f.env };
334
+ }
335
+ const ts = targets(from, c);
296
336
  if (!ts.ok) return this.#emit(c, info, f, ts);
297
337
  const items: ListItem[] = ts.value.map(({ key, test }) => {
298
338
  if (test !== undefined && !test.ok) return { key, result: test };
@@ -395,7 +435,8 @@ class Compiler {
395
435
  case "ifError":
396
436
  return (f, c) => {
397
437
  const first = arg(0, f, c);
398
- 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));
399
440
  };
400
441
  }
401
442
  }
@@ -426,7 +467,7 @@ class Compiler {
426
467
  try {
427
468
  return ok(run());
428
469
  } catch (thrown) {
429
- return this.#err("threw", `"${op}" threw an exception`, f, path, { op, thrown });
470
+ return this.#threw(thrown, `"${op}" threw an exception`, f, path, { op });
430
471
  }
431
472
  }
432
473
 
@@ -443,7 +484,7 @@ class Compiler {
443
484
  try {
444
485
  valid = d.valid(value);
445
486
  } catch (thrown) {
446
- 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);
447
488
  }
448
489
  if (!valid) return this.#err("invalid-value", `"${op}" gave a value that is not a valid ${d.name}`, f, path, extra);
449
490
  }
@@ -452,6 +493,9 @@ class Compiler {
452
493
 
453
494
  #listOp(op: ListOp, list: VexList, rest: readonly unknown[], f: Frame, path: readonly number[]): Result<unknown> {
454
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);
455
499
  const strict = (optsArg as ListOptions | null | undefined)?.strict === true;
456
500
  const firstError = list.items.find((it) => !it.result.ok)?.result;
457
501
  if (strict && firstError !== undefined && !firstError.ok) return fail(firstError.error);
@@ -502,19 +546,29 @@ class Compiler {
502
546
  return ok(!b.value.some((x) => x));
503
547
  }
504
548
  case "reduce":
505
- return this.#reduce(rest[0], okValues, f, path);
549
+ return this.#reduce(rest[0], okValues, f, path, optsArg);
506
550
  }
507
551
  }
508
552
 
509
- /** This method folds the values with a domain op, from the left. An empty list gives the identity of the op. */
510
- #reduce(opName: unknown, values: readonly unknown[], f: Frame, path: readonly number[]): Result<unknown> {
553
+ /**
554
+ * This method folds the values with a domain op, from the left. An empty list gives the identity of the op, if one
555
+ * domain has an identity for the op (LIST.EMPTY). The option `domain` names that domain when more domains have one.
556
+ */
557
+ #reduce(opName: unknown, values: readonly unknown[], f: Frame, path: readonly number[], opts: unknown): Result<unknown> {
511
558
  if (typeof opName !== "string") return this.#err("kind-mismatch", `"reduce" needs an op name, but got a ${describeType(opName)}`, f, path, { op: "reduce" });
512
559
  if (values.length === 0) {
513
- for (const d of this.#domains) {
514
- const id = (d.ops[opName] as { identity?: () => unknown } | undefined)?.identity;
515
- if (id !== undefined && Object.hasOwn(d.ops, opName)) return this.#invoke(id, opName, f, path);
560
+ const named = (opts as { domain?: unknown } | null | undefined)?.domain;
561
+ const candidates = this.#domains.filter((d) => Object.hasOwn(d.ops, opName) && (d.ops[opName] as { identity?: () => unknown }).identity !== undefined && (named === undefined || d.name === named));
562
+ if (named !== undefined && !this.#domains.some((d) => d.name === named)) {
563
+ return this.#err("unknown-op", `"reduce" names the domain ${JSON.stringify(named)}, but the program has no such domain`, f, path, { op: opName });
564
+ }
565
+ const [only, second] = candidates;
566
+ if (only === undefined) return this.#err("empty", `"reduce" with "${opName}" has no values and the op has no identity`, f, path, { op: opName });
567
+ if (second !== undefined) {
568
+ const names = candidates.map((d) => d.name).join(", ");
569
+ return this.#err("empty", `"reduce" with "${opName}" has no values, and more domains have an identity for it (${names}). Name one with { domain }`, f, path, { op: opName });
516
570
  }
517
- return this.#err("empty", `"reduce" with "${opName}" has no values and the op has no identity`, f, path, { op: opName });
571
+ return this.#invoke((only.ops[opName] as { identity: () => unknown }).identity, opName, f, path);
518
572
  }
519
573
  let acc: unknown = values[0];
520
574
  for (let i = 1; i < values.length; i++) {
@@ -587,12 +641,28 @@ export function labelOf(e: Expr): string {
587
641
  case "rec":
588
642
  return `{ ${Object.keys(e.fields).join(", ")} }`;
589
643
  case "each":
590
- return `each ${e.axis.t}`;
644
+ return e.at === undefined ? `each ${e.axis.t}` : `each ${e.axis.t} from ${e.at.map(moveText).join(".")}`;
591
645
  case "ext":
592
646
  return e.kind;
593
647
  }
594
648
  }
595
649
 
650
+ /** This function gives a short text for a move, for the label of an axis with an address. */
651
+ function moveText(m: Move): string {
652
+ switch (m.t) {
653
+ case "key":
654
+ return `key(${m.key})`;
655
+ case "index":
656
+ return `index(${m.i})`;
657
+ case "offset":
658
+ return `offset(${m.d.join(", ")})`;
659
+ case "other":
660
+ case "origin":
661
+ case "parent":
662
+ return m.t;
663
+ }
664
+ }
665
+
596
666
  /** This function gives a short text for a value. */
597
667
  export function previewValue(u: unknown): string {
598
668
  // JSON has no NaN and no Infinity, so a number gets its own text. JSON gives the text of the other primitives.
package/src/ir.ts CHANGED
@@ -35,7 +35,7 @@ export type Expr =
35
35
  | { readonly tag: "let"; readonly bind: Readonly<Record<string, Expr>>; readonly body: Expr }
36
36
  | { readonly tag: "var"; readonly name: string }
37
37
  | { readonly tag: "rec"; readonly fields: Readonly<Record<string, Expr>> }
38
- | { readonly tag: "each"; readonly axis: Axis; readonly body: Expr }
38
+ | { readonly tag: "each"; readonly axis: Axis; readonly body: Expr; readonly at?: Addr }
39
39
  | { readonly tag: "ext"; readonly kind: string; readonly data: unknown };
40
40
 
41
41
  /** The tag of an expression kind. */
@@ -71,8 +71,13 @@ export const v = (name: string): ExprOf<"var"> => ({ tag: "var", name });
71
71
  /** This function makes a record from field expressions. */
72
72
  export const rec = (fields: Readonly<Record<string, Expr>>): ExprOf<"rec"> => ({ tag: "rec", fields });
73
73
 
74
- /** This function evaluates `body` once for each target of `axis`. The result is a list. */
75
- export const each = (axis: Axis, body: Expr): ExprOf<"each"> => ({ tag: "each", axis, body });
74
+ /**
75
+ * This function evaluates `body` once for each target of `axis`. The result is a list. With `at`, the axis finds its
76
+ * targets from the key of that address, not from the focus.
77
+ */
78
+ export function each(axis: Axis, body: Expr, at?: Addr): ExprOf<"each"> {
79
+ return at === undefined || at.length === 0 ? { tag: "each", axis, body } : { tag: "each", axis, body, at };
80
+ }
76
81
 
77
82
  /** This function makes an expression of an extension kind. */
78
83
  export const ext = (kind: string, data: unknown): ExprOf<"ext"> => ({ tag: "ext", kind, data });
@@ -139,53 +144,76 @@ export function isMove(u: unknown): u is Move {
139
144
  }
140
145
  }
141
146
 
142
- /** 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. */
143
148
  export function isAxis(u: unknown): u is Axis {
144
- if (!isObject(u)) return false;
145
- switch (u["t"]) {
146
- case "all":
147
- case "others":
148
- case "other":
149
- case "children":
150
- case "ancestors":
151
- case "descendants":
152
- case "siblings":
153
- return true;
154
- case "neighbors":
155
- return u["n"] === 4 || u["n"] === 8;
156
- case "where":
157
- return isAxis(u["axis"]) && isExpr(u["test"]);
158
- default:
159
- return false;
160
- }
149
+ return validTree([{ axis: true, u }]);
161
150
  }
162
151
 
163
- const isExprRecord = (u: unknown): u is Readonly<Record<string, Expr>> =>
164
- isObject(u) && !Array.isArray(u) && Object.values(u).every((e) => isExpr(e));
165
-
166
152
  /** This function tells if a value is a valid expression. It checks the whole tree. */
167
153
  export function isExpr(u: unknown): u is Expr {
168
- if (!isObject(u)) return false;
169
- switch (u["tag"]) {
170
- case "lit":
171
- return "value" in u;
172
- case "ref":
173
- return isStringArray(u["path"]) && (u["at"] === undefined || (Array.isArray(u["at"]) && u["at"].every(isMove)));
174
- case "app":
175
- return typeof u["op"] === "string" && Array.isArray(u["args"]) && u["args"].every((a) => isExpr(a));
176
- case "let":
177
- return isExprRecord(u["bind"]) && isExpr(u["body"]);
178
- case "var":
179
- return typeof u["name"] === "string";
180
- case "rec":
181
- return isExprRecord(u["fields"]);
182
- case "each":
183
- return isAxis(u["axis"]) && isExpr(u["body"]);
184
- case "ext":
185
- return typeof u["kind"] === "string" && "data" in u;
186
- default:
187
- 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
+ }
188
215
  }
216
+ return true;
189
217
  }
190
218
 
191
219
  /** This function gives the child expressions of an expression, in the order of their child index. */
@@ -207,6 +235,9 @@ export function children(e: Expr): readonly Expr[] {
207
235
  }
208
236
  }
209
237
 
238
+ /** This function gives the tests of the `where` axes of an axis, from the inside out. It uses a loop, not recursion. */
210
239
  function whereTests(a: Axis): readonly Expr[] {
211
- 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;
212
243
  }