@mark1russell7/vex 0.6.0 → 0.7.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.6.0",
4
+ "version": "0.7.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
@@ -5,7 +5,7 @@
5
5
  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
- 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
+ import { app, each, ext, fold as foldExpr, index as indexMove, iterate as iterateExpr, key as keyMove, let_, lit, offset as offsetMove, other as otherMove, origin as originMove, parent as parentMove, rec, ref, toPath, v, type Axis, type Expr, type ExprOf, type FixedMove, type Move } from "./ir.ts";
9
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";
@@ -178,10 +178,16 @@ export interface ChainBase<Ctx extends ChainContext, T> {
178
178
  all(): Traversal<Ctx["keys"], T>;
179
179
  /** This method gives a chain whose value is a field of the record at the current address. */
180
180
  from<P extends keyof Ctx["record"] & string>(field: P): ChainOf<Ctx, NonNullable<Ctx["record"][P]>>;
181
- /** Navigation: later field references read at the key `k`. */
182
- to(k: Ctx["keys"]): ChainOf<Ctx, T>;
183
- /** Navigation: later field references read at the key with this position in the key order. */
184
- index(i: number): ChainOf<Ctx, T>;
181
+ /**
182
+ * Navigation: later field references read at the key `k`. A chain of a text gives the key, and it evaluates at the
183
+ * focus before the moves (NAV.COMPUTED).
184
+ */
185
+ to(k: Ctx["keys"] | ChainBase<Ctx, string>): ChainOf<Ctx, T>;
186
+ /**
187
+ * Navigation: later field references read at the key with this position in the key order. A chain of a number gives
188
+ * the position, and it evaluates at the focus before the moves (NAV.COMPUTED).
189
+ */
190
+ index(i: number | ChainBase<Ctx, number>): ChainOf<Ctx, T>;
185
191
  /** Navigation: later field references read at a relative position in an array or a grid. */
186
192
  offset(...d: readonly number[]): ChainOf<Ctx, T>;
187
193
  /** Navigation: later field references read at the origin again. */
@@ -202,6 +208,17 @@ export interface ChainBase<Ctx extends ChainContext, T> {
202
208
  call<N extends CallableFns<Ctx, T>>(name: N, ...args: CallArgs<Ctx, N>): ChainOf<Ctx, CallReturn<Ctx, N>>;
203
209
  /** This method evaluates each branch with the current value, and gives a record of the results. */
204
210
  fork<const B extends Readonly<Record<string, (c: ChainOf<Ctx, T>) => ChainBase<Ctx, unknown>>>>(branches: B): ChainOf<Ctx, { readonly [N in keyof B]: ValueOf<ReturnType<B[N]>> }>;
211
+ /**
212
+ * This method makes up to `limit` steps (ITERATE.LIMIT). `init` gives the names and their first values, and `step`
213
+ * gives the next values. A true `until` stops the steps (ITERATE.UNTIL). `result` gives the value of the chain.
214
+ */
215
+ iterate<const I extends Readonly<Record<string, unknown>>, R>(
216
+ limit: number,
217
+ init: I,
218
+ step: (vars: LoopVars<Ctx, I>) => NoInfer<LoopStep<Ctx, I>>,
219
+ result: (vars: LoopVars<Ctx, I>) => ArgInput<R, Ctx, false>,
220
+ opts?: { readonly until?: (vars: LoopVars<Ctx, I>) => ArgInput<boolean, Ctx, false> },
221
+ ): ChainOf<Ctx, R>;
205
222
  /** This method binds names for the body. The body gets a variable token for each name. */
206
223
  with<const B extends Readonly<Record<string, unknown>>, U>(
207
224
  binds: B,
@@ -275,10 +292,28 @@ export type ArgValue<Ctx extends ChainContext, A> = A extends Arg<infer T>
275
292
  : A;
276
293
 
277
294
  /** A chain whose value is a list: the result of an axis. */
295
+ /** The type of a value of a name of a loop: a literal of `init` gives its primitive type. */
296
+ type LoopValue<Ctx extends ChainContext, A> = ArgValue<Ctx, A> extends infer T ? (T extends number ? number : T extends string ? string : T extends boolean ? boolean : T) : never;
297
+
298
+ /** The names of a loop of the builder: a chain of the value of each name of `init` (LOOP.NAMES). */
299
+ export type LoopVars<Ctx extends ChainContext, I> = { readonly [N in keyof I]: ChainOf<Ctx, LoopValue<Ctx, I[N]>> };
300
+
301
+ /** The next values of a step of a loop: a value for some of the names of `init`. */
302
+ export type LoopStep<Ctx extends ChainContext, I> = { readonly [N in keyof I]?: ArgInput<LoopValue<Ctx, I[N]>, Ctx, false> };
303
+
278
304
  export interface ListChain<Ctx extends ChainContext, U> {
279
305
  readonly kind: "vex.list-chain";
280
306
  /** The expression of the chain, as plain data. */
281
307
  readonly program: Expr;
308
+ /**
309
+ * This method folds the items in the order of the axis (FOLD.ORDER). `init` gives the names and their first values.
310
+ * `step` gives the next values from the names and the item, a chain at the target. `result` gives the value.
311
+ */
312
+ fold<const I extends Readonly<Record<string, unknown>>, R>(
313
+ init: I,
314
+ step: (vars: LoopVars<Ctx, I>, item: ChainOf<Ctx, U>) => NoInfer<LoopStep<Ctx, I>>,
315
+ result: (vars: LoopVars<Ctx, I>) => ArgInput<R, Ctx, false>,
316
+ ): ChainOf<Ctx, R>;
282
317
  count(opts?: ListOpts): ChainOf<Ctx, number>;
283
318
  sum(this: ListChain<Ctx, number>, opts?: ListOpts): ChainOf<Ctx, number>;
284
319
  mean(this: ListChain<Ctx, number>, opts?: ListOpts): ChainOf<Ctx, number>;
@@ -344,11 +379,12 @@ export interface Root<Ctx extends ChainContext> {
344
379
  export interface SheetRoot<Ctx extends ChainContext, Cols> extends Root<Ctx> {
345
380
  /**
346
381
  * This method makes a cell reference: the column `column` at the key `at`, or at the address `at` from the focus.
347
- * Without `at`, it reads at the focus. The type is the type of a column before this one.
382
+ * The address has only fixed moves. Without `at`, it reads at the focus. The type is the type of a column before
383
+ * this one.
348
384
  */
349
- cell<N extends keyof Cols & string>(column: N, at?: Ctx["keys"] | Addr): Arg<Cols[N]>;
385
+ cell<N extends keyof Cols & string>(column: N, at?: Ctx["keys"] | readonly FixedMove[]): Arg<Cols[N]>;
350
386
  /** This method makes a cell reference to any column, also this column or a later one. The caller gives the type. */
351
- cell<T>(column: string, at?: Ctx["keys"] | Addr): Arg<T>;
387
+ cell<T>(column: string, at?: Ctx["keys"] | readonly FixedMove[]): Arg<T>;
352
388
  }
353
389
 
354
390
  /** One row of a sheet: the key and the result of each column. */
@@ -462,6 +498,17 @@ function toExpr(a: unknown, addr: readonly Move[]): Expr {
462
498
  return lit(a);
463
499
  }
464
500
 
501
+ /** This function gives the expressions of a step of a loop, with the unique names of the loop. */
502
+ function stepExprs(step: Readonly<Record<string, unknown>>, unique: ReadonlyMap<string, string>, addr: readonly Move[]): Readonly<Record<string, Expr>> {
503
+ const out: Record<string, Expr> = {};
504
+ for (const [n, a] of Object.entries(step)) {
505
+ const name = unique.get(n);
506
+ if (name === undefined) throw new TypeError(`the name "${n}" of the step is not a name of init`);
507
+ out[name] = toExpr(a, addr);
508
+ }
509
+ return out;
510
+ }
511
+
465
512
  const PROXY_RESERVED = new Set(["then", "catch", "finally", "toJSON", "valueOf", "toString", "constructor", "inspect", "asymmetricMatch", "$$typeof", "nodeType"]);
466
513
 
467
514
  class ChainImpl {
@@ -515,11 +562,11 @@ class ChainImpl {
515
562
  #move(m: Move): ChainImpl {
516
563
  return new ChainImpl({ ...this.#s, addr: [...this.#s.addr, m] });
517
564
  }
518
- to(k: string): ChainImpl {
519
- return this.#move(keyMove(k));
565
+ to(k: string | { readonly program: Expr }): ChainImpl {
566
+ return this.#move(keyMove(typeof k === "string" ? k : k.program));
520
567
  }
521
- index(i: number): ChainImpl {
522
- return this.#move(indexMove(i));
568
+ index(i: number | { readonly program: Expr }): ChainImpl {
569
+ return this.#move(indexMove(typeof i === "number" ? i : i.program));
523
570
  }
524
571
  offset(...d: readonly number[]): ChainImpl {
525
572
  return this.#move(offsetMove(...d));
@@ -570,6 +617,37 @@ class ChainImpl {
570
617
  return new ChainImpl({ ...this.#s, expr: let_(bindExprs, inner.program) });
571
618
  }
572
619
 
620
+ /**
621
+ * This method gives the names of a loop. Each name of `init` gets a name that is unique at the depth of the chain.
622
+ * It also gets its first value at the address of the chain, and a chain of its value.
623
+ */
624
+ loopNames(init: Readonly<Record<string, unknown>>): { readonly unique: ReadonlyMap<string, string>; readonly first: Readonly<Record<string, Expr>>; readonly vars: Readonly<Record<string, ChainImpl>> } {
625
+ const depth = this.#s.depth;
626
+ const unique = new Map<string, string>();
627
+ const first: Record<string, Expr> = {};
628
+ const vars: Record<string, ChainImpl> = {};
629
+ for (const [n, a] of Object.entries(init)) {
630
+ const name = `${n}$${depth}`;
631
+ unique.set(n, name);
632
+ first[name] = toExpr(a, this.#s.addr);
633
+ vars[n] = new ChainImpl({ ...this.#s, expr: v(name), addr: [], depth: depth + 1 });
634
+ }
635
+ return { unique, first, vars };
636
+ }
637
+
638
+ iterate(
639
+ limit: number,
640
+ init: Readonly<Record<string, unknown>>,
641
+ step: (vars: Readonly<Record<string, ChainImpl>>) => Readonly<Record<string, unknown>>,
642
+ result: (vars: Readonly<Record<string, ChainImpl>>) => unknown,
643
+ opts?: { readonly until?: (vars: Readonly<Record<string, ChainImpl>>) => unknown },
644
+ ): ChainImpl {
645
+ const { unique, first, vars } = this.loopNames(init);
646
+ const next = stepExprs(step(vars), unique, this.#s.addr);
647
+ const until = opts?.until === undefined ? undefined : toExpr(opts.until(vars), this.#s.addr);
648
+ return new ChainImpl({ ...this.#s, expr: iterateExpr(limit, first, next, toExpr(result(vars), this.#s.addr), until) });
649
+ }
650
+
573
651
  #axis(a: Axis, body: (c: ChainImpl) => { readonly program: Expr }, opts?: { readonly where?: (c: ChainImpl) => { readonly program: Expr } }): ListChainImpl {
574
652
  const { name, start } = this.#bound();
575
653
  // Inside the axis, the focus is the target, so the address of the body starts empty.
@@ -640,6 +718,20 @@ class ListChainImpl {
640
718
  get program(): Expr {
641
719
  return this.#s.expr;
642
720
  }
721
+ fold(
722
+ init: Readonly<Record<string, unknown>>,
723
+ step: (vars: Readonly<Record<string, ChainImpl>>, item: ChainImpl) => Readonly<Record<string, unknown>>,
724
+ result: (vars: Readonly<Record<string, ChainImpl>>) => unknown,
725
+ ): ChainImpl {
726
+ // The list of an axis is a let of the start value around the axis. The fold keeps the let, and the body of the
727
+ // axis is the item of each step.
728
+ const { bind, body: loop } = this.#s.expr as ExprOf<"let"> & { readonly body: ExprOf<"each"> };
729
+ const names = new ChainImpl({ ...this.#s, expr: lit(null) }).loopNames(init);
730
+ const item = new ChainImpl({ ...this.#s, expr: loop.body, addr: [] });
731
+ const next = stepExprs(step(names.vars, item), names.unique, []);
732
+ return new ChainImpl({ ...this.#s, expr: let_(bind, foldExpr(loop.axis, names.first, next, toExpr(result(names.vars), this.#s.addr), loop.at)) });
733
+ }
734
+
643
735
  #op(op: string, extra: readonly Expr[], opts?: ListOpts & { readonly domain?: string }): ChainImpl {
644
736
  const options = { ...(opts?.strict === true ? { strict: true } : {}), ...(opts?.domain === undefined ? {} : { domain: opts.domain }) };
645
737
  const args = Object.keys(options).length > 0 ? [...extra, lit(options)] : extra;
@@ -738,7 +830,7 @@ class RootImpl {
738
830
  }
739
831
 
740
832
  class SheetRootImpl extends RootImpl {
741
- cell(column: string, at?: string | Addr): Arg<unknown> {
833
+ cell(column: string, at?: string | readonly FixedMove[]): Arg<unknown> {
742
834
  return argToken(cellRef(column, typeof at === "string" ? [keyMove(at)] : at));
743
835
  }
744
836
  }
@@ -797,6 +889,8 @@ class SheetImpl {
797
889
  }
798
890
  table(): readonly SheetRow<string, Record<string, unknown>>[] {
799
891
  const run = this.#run();
892
+ // The table reads each cell, so a fill evaluates them in the order of their reads first (SHEET.FILL).
893
+ run.fill();
800
894
  const names = [...this.#columns.keys()];
801
895
  return this.#env.space.keys.map((key) => ({ key, cells: Object.fromEntries(names.map((c) => [c, run.cell(c, key)])) }));
802
896
  }
package/src/deps.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { children, type Addr, type Axis, type Expr } from "./ir.ts";
1
+ import { addrExprs, children, type Addr, type Axis, type Expr } from "./ir.ts";
2
2
 
3
3
  /** One static read of a program: a field path at an address, inside zero or more axes. */
4
4
  export interface Dependency {
@@ -14,7 +14,8 @@ export interface Dependency {
14
14
 
15
15
  /**
16
16
  * This function gives the static reads of an expression. A host can use them to recompute a program only
17
- * when a field that it reads changes.
17
+ * when a field that it reads changes. A computed move reads a key that only a run knows. Its address keeps the
18
+ * expression, and the reads of that expression are in the list too (NAV.COMPUTED).
18
19
  */
19
20
  export function deps(e: Expr): readonly Dependency[] {
20
21
  const out: Dependency[] = [];
@@ -23,13 +24,16 @@ export function deps(e: Expr): readonly Dependency[] {
23
24
  const todo: { readonly x: Expr; readonly axes: readonly Axis["t"][]; readonly axisAt: readonly Addr[] }[] = [{ x: e, axes: [], axisAt: [] }];
24
25
  for (let item = todo.pop(); item !== undefined; item = todo.pop()) {
25
26
  const { x } = item;
26
- if (x.tag === "ref") {
27
- out.push({ at: x.at ?? [], path: x.path, axes: item.axes, axisAt: item.axisAt });
28
- continue;
29
- }
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 });
27
+ if (x.tag === "ref") out.push({ at: x.at ?? [], path: x.path, axes: item.axes, axisAt: item.axisAt });
28
+ const all = children(x);
29
+ const axial = x.tag === "each" || x.tag === "fold";
30
+ // Inside the axis: the body or the values of the step, and the tests of where. The values of init, the result of a
31
+ // fold and the expressions of an address evaluate at the node, outside the axis.
32
+ const first = x.tag === "fold" ? Object.keys(x.init).length : 0;
33
+ const last = axial ? all.length - addrExprs(x.at).length - (x.tag === "fold" ? 1 : 0) : 0;
34
+ const axes = axial ? [...item.axes, x.axis.t] : item.axes;
35
+ const axisAt = axial ? [...item.axisAt, x.at ?? []] : item.axisAt;
36
+ for (let i = all.length - 1; i >= 0; i--) todo.push(i >= first && i < last ? { x: all[i] as Expr, axes, axisAt } : { ...item, x: all[i] as Expr });
33
37
  }
34
38
  return out;
35
39
  }
package/src/domain.ts CHANGED
@@ -9,6 +9,9 @@ export type Law = "commutative" | "associative" | "idempotent";
9
9
  /** The kind of a parameter. The interpreter checks the arguments of an op that declares its parameters. */
10
10
  export type ParamKind = "domain" | "number" | "boolean" | "string" | "any";
11
11
 
12
+ /** The kind of the result of an op: a kind of a parameter, or `domain:Name` for a value of the domain `Name`. */
13
+ export type ReturnKind = ParamKind | `domain:${string}`;
14
+
12
15
  /** The description of one op of a domain. */
13
16
  export interface OpSpec<D = never> {
14
17
  /**
@@ -24,8 +27,17 @@ export interface OpSpec<D = never> {
24
27
  readonly liftScalar?: boolean | readonly boolean[];
25
28
  /** The kinds of the parameters after the receiver. When set, the interpreter checks the arguments. */
26
29
  readonly params?: readonly ParamKind[];
30
+ /**
31
+ * The kind of the result: `domain` for a value of this domain, and `domain:Name` for a value of the domain `Name`. A
32
+ * compiler reads it to know the kinds of the values of a program (KIND.RETURNS). The interpreter does not check it,
33
+ * and the law checker of the test kit does.
34
+ */
35
+ readonly returns?: ReturnKind;
27
36
  }
28
37
 
38
+ /** A JavaScript type of primitive values that a domain can accept. */
39
+ export type PrimitiveKind = "number" | "string" | "boolean";
40
+
29
41
  /** The type of an op that lifts number arguments. Use it to type the ops of a domain under `isolatedDeclarations`. */
30
42
  export type LiftedOp<D> = OpSpec<D> & { readonly liftScalar: true };
31
43
 
@@ -46,6 +58,11 @@ export interface DomainSpec<Name extends string, D, Ops extends Readonly<Record<
46
58
  readonly name: Name;
47
59
  /** The runtime test for the values of the domain. It must not give false positives. */
48
60
  readonly is: (u: unknown) => u is D;
61
+ /**
62
+ * The JavaScript type of the values of the domain, if `is` accepts each value of that type and no other value
63
+ * (KIND.PRIMITIVE). A compiler then finds the op of such a value before a run.
64
+ */
65
+ readonly primitive?: PrimitiveKind;
49
66
  /** The ops of the domain, with their metadata. */
50
67
  readonly ops: Ops;
51
68
  /** With `"all"`, each method of a value is an op, also without an entry in `ops`. The default is `"declared"`. */
@@ -60,6 +77,11 @@ export interface DomainSpec<Name extends string, D, Ops extends Readonly<Record<
60
77
  readonly encode?: (d: D) => unknown;
61
78
  /** The value of a JSON form that `encode` made. */
62
79
  readonly decode?: (json: unknown) => D;
80
+ /**
81
+ * Some values of the domain. A compiler gives them to an op and to its copy in a module: the two must give the same
82
+ * results (KIND.DOMAIN).
83
+ */
84
+ readonly samples?: () => readonly D[];
63
85
  }
64
86
 
65
87
  /** A domain. Make one with `defineDomain`. */
package/src/errors.ts CHANGED
@@ -27,7 +27,8 @@ export type ErrorKind =
27
27
  | "args"
28
28
  | "cycle"
29
29
  | "depth"
30
- | "bad-expression";
30
+ | "bad-expression"
31
+ | "limit";
31
32
 
32
33
  const CODE_OF: Readonly<Record<ErrorKind, ErrorCode>> = {
33
34
  "unknown-key": "#REF!",
@@ -47,6 +48,7 @@ const CODE_OF: Readonly<Record<ErrorKind, ErrorCode>> = {
47
48
  unbound: "#NAME?",
48
49
  "not-finite": "#NUM!",
49
50
  "invalid-value": "#NUM!",
51
+ limit: "#NUM!",
50
52
  threw: "#CALC!",
51
53
  "undefined-result": "#CALC!",
52
54
  args: "#ARGS",
package/src/evaluate.ts CHANGED
@@ -1,9 +1,9 @@
1
1
  import { liftsAt, resolveOp, type AnyDomain, type ParamKind, type ResolvedOp } from "./domain.ts";
2
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";
3
+ import { addrExprs, children, shapeError, type Addr, type Axis, type Expr, type ExprOf, type FixedMove, 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
- import { axisTargets, resolveAddr, type Position, type Space } from "./space.ts";
6
+ import { axisTargets, fixAddr, resolveAddr, type Position, type Space } from "./space.ts";
7
7
  import type { Read, Trace, TraceEvent, TraceSink } from "./trace.ts";
8
8
 
9
9
  /** A free function op. The interpreter gives it the values of all arguments. */
@@ -95,12 +95,12 @@ export function nestingOf(e: Expr): number {
95
95
  }
96
96
 
97
97
  export function compile(expr: Expr, opts: CompileOptions = {}): Program {
98
+ // EVAL.SHAPE: an expression that is not valid, for example from a newer version of Vex, gives an error before a walk.
98
99
  // 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, []);
100
+ const shape = shapeError(expr);
101
+ const nesting = shape === undefined ? nestingOf(expr) : 0;
102
+ const bad = shape ?? (nesting > MAX_NESTING ? `the expression is nested ${nesting} levels deep, and the limit is ${MAX_NESTING}` : undefined);
103
+ const root: Node = bad === undefined ? new Compiler(opts).node(expr, []) : (f) => fail(vexError("bad-expression", bad, { path: [], origin: f.pos.origin, focus: f.pos.focus }));
104
104
  const run = (r: RunOptions): Result<unknown> => {
105
105
  const { space, origin } = r;
106
106
  if (!space.has(origin)) return fail(vexError("unknown-key", `the space has no key "${origin}"`, { origin, focus: origin }));
@@ -240,6 +240,10 @@ class Compiler {
240
240
  return isSpecialForm(e.op) ? this.#special(e.op, this.#nodes(e.args, path), info) : this.#app(e.op, this.#nodes(e.args, path), info);
241
241
  case "each":
242
242
  return this.#each(e, info);
243
+ case "fold":
244
+ return this.#fold(e, info);
245
+ case "iterate":
246
+ return this.#iterate(e, info);
243
247
  case "ext": {
244
248
  const extensions = this.#extensions ?? {};
245
249
  const handler = Object.hasOwn(extensions, e.kind) ? extensions[e.kind] : undefined;
@@ -274,10 +278,32 @@ class Compiler {
274
278
  return isStackOverflow(thrown) ? this.#err("depth", DEPTH_MESSAGE, f, path, { ...extra, thrown }) : this.#err("threw", message, f, path, { ...extra, thrown });
275
279
  }
276
280
 
281
+ /**
282
+ * This method compiles an address. Its function gives the key where the address points. The expressions of the
283
+ * computed moves evaluate first, at the position of the node, and their child indexes start at `first`. An error of
284
+ * an expression keeps its path, and an error of a move gets the path of the node.
285
+ */
286
+ #address(at: Addr, path: readonly number[], first: number): (f: Frame, c: Ctx) => Result<string> {
287
+ const nodes = addrExprs(at).map((x, i) => this.node(x, [...path, first + i]));
288
+ const moved = (r: Result<string>): Result<string> => (r.ok ? r : fail({ ...r.error, path }));
289
+ if (nodes.length === 0) return (f, c) => moved(resolveAddr(c.space, f.pos, at as readonly FixedMove[]));
290
+ return (f, c) => {
291
+ const values: unknown[] = [];
292
+ for (const n of nodes) {
293
+ const r = n(f, c);
294
+ if (!r.ok) return r;
295
+ values.push(r.value);
296
+ }
297
+ const fixed = fixAddr(at, values, f.pos);
298
+ return fixed.ok ? moved(resolveAddr(c.space, f.pos, fixed.value)) : moved(fixed);
299
+ };
300
+ }
301
+
277
302
  #ref(e: ExprOf<"ref">, info: Info): Node {
278
303
  const { path } = info;
279
304
  const segs = e.path;
280
305
  const at = e.at ?? [];
306
+ const address = this.#address(at, path, 0);
281
307
  const label = segs.join(".");
282
308
  const steps = segs.map((seg, i) => ({ seg, where: segs.slice(0, i + 1).join("."), valid: isFieldName(seg) }));
283
309
  return (f, c) => {
@@ -285,8 +311,8 @@ class Compiler {
285
311
  // The empty address resolves to the focus, so this fast path changes no result.
286
312
  // Stryker disable next-line ConditionalExpression,EqualityOperator: resolveAddr of [] gives the focus too
287
313
  if (at.length > 0) {
288
- const where = resolveAddr(c.space, f.pos, at);
289
- if (!where.ok) return this.#emit(c, info, f, fail({ ...where.error, path }));
314
+ const where = address(f, c);
315
+ if (!where.ok) return this.#emit(c, info, f, where);
290
316
  key = where.value;
291
317
  }
292
318
  const failed = (r: Result<unknown>): Result<unknown> => this.#emit(c, info, f, r, [{ key, path: segs, ok: false }]);
@@ -327,15 +353,17 @@ class Compiler {
327
353
  #each(e: ExprOf<"each">, info: Info): Node {
328
354
  const { path } = info;
329
355
  const at = e.at ?? [];
330
- const targets = this.#targets(e.axis, path, { next: 1 });
356
+ const counter = { next: 1 };
357
+ const targets = this.#targets(e.axis, path, counter);
331
358
  const body = this.node(e.body, [...path, 0]);
359
+ const address = this.#address(at, path, counter.next);
332
360
  return (f, c) => {
333
361
  // An axis with an address finds its targets from the key of the address. The origin does not change.
334
362
  let from = f;
335
363
  // Stryker disable next-line ConditionalExpression,EqualityOperator: resolveAddr of [] gives the focus too
336
364
  if (at.length > 0) {
337
- const where = resolveAddr(c.space, f.pos, at);
338
- if (!where.ok) return this.#emit(c, info, f, fail({ ...where.error, path }));
365
+ const where = address(f, c);
366
+ if (!where.ok) return this.#emit(c, info, f, where);
339
367
  from = { pos: { origin: f.pos.origin, focus: where.value }, env: f.env };
340
368
  }
341
369
  // The axis table moves the evaluation to the space of its table, where the origin of this space is not a key.
@@ -357,6 +385,119 @@ class Compiler {
357
385
  };
358
386
  }
359
387
 
388
+ /**
389
+ * This method compiles the names of a loop: `init` at the indexes from 0, and `step` after them (LOOP.NAMES). Its
390
+ * functions give the first values, and the values after one step. The first error stops each of them.
391
+ */
392
+ #names(e: ExprOf<"fold"> | ExprOf<"iterate">, path: readonly number[]): {
393
+ readonly first: (f: Frame, c: Ctx) => Result<Map<string, Result<unknown>>>;
394
+ readonly next: (f: Frame, c: Ctx) => Result<Map<string, Result<unknown>>>;
395
+ } {
396
+ const inits = Object.entries(e.init).map(([name, x], i) => [name, this.node(x, [...path, i])] as const);
397
+ const steps = Object.entries(e.step).map(([name, x], i) => [name, this.node(x, [...path, inits.length + i])] as const);
398
+ return {
399
+ first: (f, c) => {
400
+ const env = new Map(f.env);
401
+ for (const [name, n] of inits) {
402
+ const r = n(f, c);
403
+ if (!r.ok) return r;
404
+ env.set(name, r);
405
+ }
406
+ return ok(env);
407
+ },
408
+ // Each value of a step reads the values before the step, so the names change only after all the values.
409
+ next: (f, c) => {
410
+ const values: (readonly [string, Result<unknown>])[] = [];
411
+ for (const [name, n] of steps) {
412
+ const r = n(f, c);
413
+ if (!r.ok) return r;
414
+ values.push([name, r]);
415
+ }
416
+ const env = new Map(f.env);
417
+ for (const [name, r] of values) env.set(name, r);
418
+ return ok(env);
419
+ },
420
+ };
421
+ }
422
+
423
+ /**
424
+ * This method compiles a fold (FOLD.ORDER, FOLD.ERROR). `init` evaluates at the node, then the address and the
425
+ * targets. A step evaluates at each target in order. `result` evaluates at the node with the last values.
426
+ */
427
+ #fold(e: ExprOf<"fold">, info: Info): Node {
428
+ const { path } = info;
429
+ const at = e.at ?? [];
430
+ const names = this.#names(e, path);
431
+ const counter = { next: Object.keys(e.init).length + Object.keys(e.step).length };
432
+ const targets = this.#targets(e.axis, path, counter);
433
+ const address = this.#address(at, path, counter.next);
434
+ const result = this.node(e.result, [...path, counter.next + addrExprs(at).length]);
435
+ const base = baseAxis(e.axis);
436
+ return (f, c) => {
437
+ const first = names.first(f, c);
438
+ if (!first.ok) return this.#emit(c, info, f, first);
439
+ let env = first.value;
440
+ let from = f;
441
+ // Stryker disable next-line ConditionalExpression,EqualityOperator: resolveAddr of [] gives the focus too
442
+ if (at.length > 0) {
443
+ const where = address(f, c);
444
+ if (!where.ok) return this.#emit(c, info, f, where);
445
+ from = { pos: { origin: f.pos.origin, focus: where.value }, env: f.env };
446
+ }
447
+ let inner = c;
448
+ if (base.t === "table") {
449
+ const space = c.tables !== undefined && Object.hasOwn(c.tables, base.name) ? c.tables[base.name] : undefined;
450
+ if (space === undefined) return this.#emit(c, info, f, this.#err("no-table", `the evaluation has no table "${base.name}"`, f, path));
451
+ inner = { ...c, space };
452
+ }
453
+ const ts = targets(from, inner);
454
+ if (!ts.ok) return this.#emit(c, info, f, ts);
455
+ for (const { key, test } of ts.value) {
456
+ if (test !== undefined && !test.ok) return this.#emit(c, info, f, test);
457
+ const after = names.next({ pos: { origin: base.t === "table" ? key : f.pos.origin, focus: key }, env }, inner);
458
+ if (!after.ok) return this.#emit(c, info, f, after);
459
+ env = after.value;
460
+ }
461
+ return this.#emit(c, info, f, result({ pos: f.pos, env }, c));
462
+ };
463
+ }
464
+
465
+ /**
466
+ * This method compiles an iteration (ITERATE.LIMIT, ITERATE.UNTIL, ITERATE.ERROR). The test `until` evaluates before
467
+ * each step and after the last step. `result` evaluates with the last values.
468
+ */
469
+ #iterate(e: ExprOf<"iterate">, info: Info): Node {
470
+ const { path } = info;
471
+ const names = this.#names(e, path);
472
+ const untilAt = Object.keys(e.init).length + Object.keys(e.step).length;
473
+ const untilPath = [...path, untilAt];
474
+ const until = e.until === undefined ? undefined : this.node(e.until, untilPath);
475
+ const result = this.node(e.result, [...path, untilAt + (until === undefined ? 0 : 1)]);
476
+ const { limit } = e;
477
+ return (f, c) => {
478
+ const first = names.first(f, c);
479
+ if (!first.ok) return this.#emit(c, info, f, first);
480
+ let env = first.value;
481
+ for (let k = 0; ; k++) {
482
+ const frame: Frame = { pos: f.pos, env };
483
+ if (until !== undefined) {
484
+ const t = until(frame, c);
485
+ if (!t.ok) return this.#emit(c, info, f, t);
486
+ if (t.value === true) break;
487
+ if (t.value !== false) return this.#emit(c, info, f, this.#err("kind-mismatch", `the test "until" of "iterate" gave a ${typeof t.value}, not a boolean`, f, untilPath));
488
+ }
489
+ if (k === limit) {
490
+ if (until !== undefined) return this.#emit(c, info, f, this.#err("limit", `"iterate" made its ${String(limit)} steps, and its test "until" is not true`, f, path));
491
+ break;
492
+ }
493
+ const after = names.next(frame, c);
494
+ if (!after.ok) return this.#emit(c, info, f, after);
495
+ env = after.value;
496
+ }
497
+ return this.#emit(c, info, f, result({ pos: f.pos, env }, c));
498
+ };
499
+ }
500
+
360
501
  /** This method compiles the targets of an axis. For `where`, a failed test keeps the target with its error. */
361
502
  #targets(a: Axis, path: readonly number[], counter: { next: number }): (f: Frame, c: Ctx) => Result<readonly { readonly key: string; readonly test?: Result<unknown> }[]> {
362
503
  if (a.t === "table") return (_f, c) => ok(c.space.keys.map((key) => ({ key })));
@@ -602,11 +743,12 @@ class Compiler {
602
743
  }
603
744
 
604
745
  const FORBIDDEN_FIELDS = new Set(["__proto__", "constructor", "prototype"]);
605
- const isFieldName = (seg: string): boolean => seg.length > 0 && !FORBIDDEN_FIELDS.has(seg);
746
+ /** This function tells if a segment of a path can name a field. A compiler uses the same rule as the interpreter. */
747
+ export const isFieldName = (seg: string): boolean => seg.length > 0 && !FORBIDDEN_FIELDS.has(seg);
606
748
 
607
749
  /** This function runs the `is` test of a domain. A test that throws counts as `false`. */
608
750
  // Stryker disable BlockStatement: an empty catch gives undefined, which also counts as false
609
- function safeIs(d: AnyDomain, value: unknown): boolean {
751
+ export function safeIs(d: AnyDomain, value: unknown): boolean {
610
752
  try {
611
753
  return d.is(value);
612
754
  } catch {
@@ -616,7 +758,8 @@ function safeIs(d: AnyDomain, value: unknown): boolean {
616
758
  // Stryker restore BlockStatement
617
759
 
618
760
 
619
- function matchesKind(kind: ParamKind, value: unknown, domain: AnyDomain): boolean {
761
+ /** This function tells if an argument has the kind of a parameter of an op of the domain `domain`. */
762
+ export function matchesKind(kind: ParamKind, value: unknown, domain: AnyDomain): boolean {
620
763
  switch (kind) {
621
764
  case "domain":
622
765
  return safeIs(domain, value);
@@ -659,7 +802,10 @@ export function labelOf(e: Expr): string {
659
802
  case "rec":
660
803
  return `{ ${Object.keys(e.fields).join(", ")} }`;
661
804
  case "each":
662
- return e.at === undefined ? `each ${e.axis.t}` : `each ${e.axis.t} from ${e.at.map(moveText).join(".")}`;
805
+ case "fold":
806
+ return e.at === undefined ? `${e.tag} ${e.axis.t}` : `${e.tag} ${e.axis.t} from ${e.at.map(moveText).join(".")}`;
807
+ case "iterate":
808
+ return `iterate ${String(e.limit)}`;
663
809
  case "ext":
664
810
  return e.kind;
665
811
  }
@@ -669,9 +815,9 @@ export function labelOf(e: Expr): string {
669
815
  function moveText(m: Move): string {
670
816
  switch (m.t) {
671
817
  case "key":
672
- return `key(${m.key})`;
818
+ return `key(${typeof m.key === "string" ? m.key : labelOf(m.key)})`;
673
819
  case "index":
674
- return `index(${m.i})`;
820
+ return `index(${typeof m.i === "number" ? String(m.i) : labelOf(m.i)})`;
675
821
  case "offset":
676
822
  return `offset(${m.d.join(", ")})`;
677
823
  case "other":