@mark1russell7/vex 0.7.0 → 0.8.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.7.0",
4
+ "version": "0.8.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
@@ -2,10 +2,10 @@
2
2
  * The typed builder. Method calls make an expression of the IR. The builder has no other job: it does not
3
3
  * evaluate anything until a caller asks for a value.
4
4
  */
5
- import type { AnyDomain, Domain, OpSpec } from "./domain.ts";
5
+ import type { AnyDomain, Domain, OpSpec, PrimitiveKind } 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, 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";
8
+ import { app, call as callExpr, each, ext, fn as fnExpr, 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 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";
@@ -17,6 +17,7 @@ import { traversal, type Traversal } from "./traversal.ts";
17
17
 
18
18
  declare const ARG_TYPE: unique symbol;
19
19
  declare const CHAIN_VALUE: unique symbol;
20
+ declare const FN_RESULT: unique symbol;
20
21
 
21
22
  /** An argument token: an expression with the static type `T` of its value. */
22
23
  export interface Arg<T> {
@@ -224,6 +225,11 @@ export interface ChainBase<Ctx extends ChainContext, T> {
224
225
  binds: B,
225
226
  body: (c: ChainOf<Ctx, T>, vars: { readonly [N in keyof B]: Arg<ArgValue<Ctx, B[N]>> }) => ChainBase<Ctx, U>,
226
227
  ): ChainOf<Ctx, U>;
228
+ /**
229
+ * This method binds functions of `root.fn` (BUILD.FN) and gives the value of `body`. `call` gives a chain of a call of
230
+ * each function. A function cannot call another function of the same `functions`, so it uses an outer one (FN.TOTAL).
231
+ */
232
+ functions<const F extends Readonly<Record<string, FnDef<readonly FnParamKind[], unknown>>>, U>(fns: F, body: (c: ChainOf<Ctx, T>, call: FnCalls<Ctx, F>) => ChainBase<Ctx, U>): ChainOf<Ctx, U>;
227
233
  /** The others axis: the body evaluates at each key except the focus. Its start value is the current value. */
228
234
  others<U>(body: (c: ChainOf<Ctx, T>) => ChainBase<Ctx, U>, opts?: AxisOpts<Ctx, T>): ListChain<Ctx, U>;
229
235
  /** The neighbors axis of a grid. */
@@ -260,8 +266,20 @@ export interface ChainBase<Ctx extends ChainContext, T> {
260
266
  export interface AxisOpts<Ctx extends ChainContext, T> {
261
267
  /** A test at each target. The body evaluates only at the targets where the test gives `true`. */
262
268
  readonly where?: (c: ChainOf<Ctx, T>) => ChainBase<Ctx, boolean>;
269
+ /** With `true`, the targets come in the reverse order (AXIS.REVERSE). The axis table has no reverse order. */
270
+ readonly reverse?: boolean;
271
+ }
272
+
273
+ /** A function of the builder in its implementation: the kinds of its parameters, and the function that gives its body. */
274
+ interface FnDefImpl {
275
+ readonly kind: "vex.fn";
276
+ readonly params: readonly string[];
277
+ readonly build: (...params: ChainImpl[]) => { readonly program: Expr };
263
278
  }
264
279
 
280
+ /** The options of an axis in the implementation of the builder. */
281
+ type AxisOptsImpl = { readonly where?: (c: ChainImpl) => { readonly program: Expr }; readonly reverse?: boolean };
282
+
265
283
  /** The members of a chain whose value has a domain. */
266
284
  export interface DomainMembers<Ctx extends ChainContext, Dm> {
267
285
  /** The ops of the domain of the current value. */
@@ -301,6 +319,28 @@ export type LoopVars<Ctx extends ChainContext, I> = { readonly [N in keyof I]: C
301
319
  /** The next values of a step of a loop: a value for some of the names of `init`. */
302
320
  export type LoopStep<Ctx extends ChainContext, I> = { readonly [N in keyof I]?: ArgInput<LoopValue<Ctx, I[N]>, Ctx, false> };
303
321
 
322
+ /** The kind of a parameter of a function of the builder (BUILD.FN): a primitive type, or `any`. */
323
+ export type FnParamKind = PrimitiveKind | "any";
324
+
325
+ /** The type of a value of a kind of a parameter. */
326
+ export type KindValue<K> = K extends "number" ? number : K extends "string" ? string : K extends "boolean" ? boolean : unknown;
327
+
328
+ /** A chain of each parameter of a function of the builder. */
329
+ export type ParamChains<Ctx extends ChainContext, P extends readonly FnParamKind[]> = { readonly [I in keyof P]: ChainOf<Ctx, KindValue<P[I]>> };
330
+
331
+ /** A function of the builder (BUILD.FN): the kinds of its parameters and its body. `functions` binds it. */
332
+ export interface FnDef<P extends readonly FnParamKind[], R> {
333
+ readonly kind: "vex.fn";
334
+ readonly params: P;
335
+ /** This phantom member carries the type of the result. It is not present at run time. */
336
+ readonly [FN_RESULT]?: R;
337
+ }
338
+
339
+ /** The calls of the functions of `functions`: each gives a chain of a call (FN.CALL). */
340
+ export type FnCalls<Ctx extends ChainContext, F> = {
341
+ readonly [N in keyof F]: F[N] extends FnDef<infer P, infer R> ? (...args: { readonly [I in keyof P]: ArgInput<KindValue<P[I]>, Ctx, false> }) => ChainOf<Ctx, R> : never;
342
+ };
343
+
304
344
  export interface ListChain<Ctx extends ChainContext, U> {
305
345
  readonly kind: "vex.list-chain";
306
346
  /** The expression of the chain, as plain data. */
@@ -329,6 +369,17 @@ export interface ListChain<Ctx extends ChainContext, U> {
329
369
  errors(): ChainOf<Ctx, readonly VexError[]>;
330
370
  first(opts?: ListOpts): ChainOf<Ctx, U>;
331
371
  reduce(op: OpNames<DomainFor<Ctx["domains"], U>>, opts?: ReduceOpts<Ctx>): ChainOf<Ctx, U>;
372
+ /** The items in the order of their values, from the smallest (LIST.SORT). The values are numbers or texts of one kind. */
373
+ sortBy(opts?: ListOpts): ListChain<Ctx, U>;
374
+ /** The first `n` items (LIST.TAKE). */
375
+ take(n: number, opts?: ListOpts): ListChain<Ctx, U>;
376
+ /** The value of the item at the position `i`, from 0 (LIST.NTH). */
377
+ nth(i: number, opts?: ListOpts): ChainOf<Ctx, U>;
378
+ /**
379
+ * The axis list (AXIS.LIST): the body evaluates at the key of each item, in the order of the list. The body reads the
380
+ * fields of the record of the item. The chain of the body has no value of its own.
381
+ */
382
+ each<V>(body: (c: ChainOf<Ctx, null>) => ChainBase<Ctx, V>, opts?: AxisOpts<Ctx, null>): ListChain<Ctx, V>;
332
383
  /** The list at the origin `k`: one item for each target of the axis, with its key and its result. */
333
384
  result(k: Ctx["keys"]): Result<VexList<U>>;
334
385
  /** The list at the origin `k`, as an `Optional`. */
@@ -371,6 +422,11 @@ export interface Root<Ctx extends ChainContext> {
371
422
  ext<T>(kind: string, data?: unknown): Arg<T>;
372
423
  /** This method starts a sheet over the space: named columns of formulas. Refer to `Sheet`. */
373
424
  sheet(): Sheet<Ctx, object>;
425
+ /**
426
+ * This method makes a function (BUILD.FN) with the kinds of its parameters. The body gets a chain of each parameter,
427
+ * and it evaluates at the focus of each call. The method `functions` of a chain binds the function.
428
+ */
429
+ fn<const P extends readonly FnParamKind[], R>(params: P, body: (...params: ParamChains<Ctx, P>) => ChainBase<Ctx, R>): FnDef<P, R>;
374
430
  /** The space of the root. */
375
431
  readonly space: Space<Ctx["keys"], Ctx["record"]>;
376
432
  }
@@ -617,6 +673,23 @@ class ChainImpl {
617
673
  return new ChainImpl({ ...this.#s, expr: let_(bindExprs, inner.program) });
618
674
  }
619
675
 
676
+ functions(fns: Readonly<Record<string, FnDefImpl>>, body: (c: ChainImpl, call: Readonly<Record<string, (...args: readonly unknown[]) => ChainImpl>>) => { readonly program: Expr }): ChainImpl {
677
+ const depth = this.#s.depth;
678
+ const binds: Record<string, Expr> = {};
679
+ const calls: Record<string, (...args: readonly unknown[]) => ChainImpl> = {};
680
+ for (const [n, def] of Object.entries(fns)) {
681
+ if ((def as { readonly kind?: unknown }).kind !== "vex.fn") throw new TypeError(`the function "${n}" is not a function of root.fn`);
682
+ const unique = `${n}$${depth}`;
683
+ const params = def.params.map((_k, i) => `${unique}$${i}`);
684
+ // A parameter is a chain at the focus of the call, so a field of the body reads at the call.
685
+ const chains = params.map((p) => new ChainImpl({ ...this.#s, expr: v(p), addr: [], depth: depth + 1 }));
686
+ binds[unique] = fnExpr(params, def.build(...chains).program);
687
+ calls[n] = (...args) => new ChainImpl({ ...this.#s, expr: callExpr(unique, ...args.map((a) => toExpr(a, []))), addr: [], depth: depth + 1 });
688
+ }
689
+ const inner = body(new ChainImpl({ ...this.#s, depth: depth + 1 }), calls);
690
+ return new ChainImpl({ ...this.#s, expr: let_(binds, inner.program) });
691
+ }
692
+
620
693
  /**
621
694
  * 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
695
  * It also gets its first value at the address of the chain, and a chain of its value.
@@ -648,49 +721,50 @@ class ChainImpl {
648
721
  return new ChainImpl({ ...this.#s, expr: iterateExpr(limit, first, next, toExpr(result(vars), this.#s.addr), until) });
649
722
  }
650
723
 
651
- #axis(a: Axis, body: (c: ChainImpl) => { readonly program: Expr }, opts?: { readonly where?: (c: ChainImpl) => { readonly program: Expr } }): ListChainImpl {
724
+ #axis(a: Axis, body: (c: ChainImpl) => { readonly program: Expr }, opts?: AxisOptsImpl): ListChainImpl {
652
725
  const { name, start } = this.#bound();
653
726
  // Inside the axis, the focus is the target, so the address of the body starts empty.
654
727
  const inTarget = new ChainImpl({ ...start.#s, addr: [] });
655
728
  const inner = body(inTarget);
656
- const axis: Axis = opts?.where === undefined ? a : { t: "where", axis: a, test: opts.where(inTarget).program };
729
+ const ordered: Axis = opts?.reverse === true ? { t: "reverse", axis: a } : a;
730
+ const axis: Axis = opts?.where === undefined ? ordered : { t: "where", axis: ordered, test: opts.where(inTarget).program };
657
731
  // The moves before the axis are its address: parent().children(f) gives f at each child of the parent.
658
732
  return new ListChainImpl({ ...this.#s, expr: let_({ [name]: this.#s.expr }, each(axis, inner.program, this.#s.addr)) });
659
733
  }
660
- others(body: (c: ChainImpl) => { readonly program: Expr }, opts?: { readonly where?: (c: ChainImpl) => { readonly program: Expr } }): ListChainImpl {
734
+ others(body: (c: ChainImpl) => { readonly program: Expr }, opts?: AxisOptsImpl): ListChainImpl {
661
735
  return this.#axis({ t: "others" }, body, opts);
662
736
  }
663
- neighbors(n: 4 | 8, body: (c: ChainImpl) => { readonly program: Expr }, opts?: { readonly where?: (c: ChainImpl) => { readonly program: Expr } }): ListChainImpl {
737
+ neighbors(n: 4 | 8, body: (c: ChainImpl) => { readonly program: Expr }, opts?: AxisOptsImpl): ListChainImpl {
664
738
  return this.#axis({ t: "neighbors", n }, body, opts);
665
739
  }
666
- each(body: (c: ChainImpl) => { readonly program: Expr }, opts?: { readonly where?: (c: ChainImpl) => { readonly program: Expr } }): ListChainImpl {
740
+ each(body: (c: ChainImpl) => { readonly program: Expr }, opts?: AxisOptsImpl): ListChainImpl {
667
741
  return this.#axis({ t: "all" }, body, opts);
668
742
  }
669
- children(body: (c: ChainImpl) => { readonly program: Expr }, opts?: { readonly where?: (c: ChainImpl) => { readonly program: Expr } }): ListChainImpl {
743
+ children(body: (c: ChainImpl) => { readonly program: Expr }, opts?: AxisOptsImpl): ListChainImpl {
670
744
  return this.#axis({ t: "children" }, body, opts);
671
745
  }
672
- ancestors(body: (c: ChainImpl) => { readonly program: Expr }, opts?: { readonly where?: (c: ChainImpl) => { readonly program: Expr } }): ListChainImpl {
746
+ ancestors(body: (c: ChainImpl) => { readonly program: Expr }, opts?: AxisOptsImpl): ListChainImpl {
673
747
  return this.#axis({ t: "ancestors" }, body, opts);
674
748
  }
675
- descendants(body: (c: ChainImpl) => { readonly program: Expr }, opts?: { readonly where?: (c: ChainImpl) => { readonly program: Expr } }): ListChainImpl {
749
+ descendants(body: (c: ChainImpl) => { readonly program: Expr }, opts?: AxisOptsImpl): ListChainImpl {
676
750
  return this.#axis({ t: "descendants" }, body, opts);
677
751
  }
678
- siblings(body: (c: ChainImpl) => { readonly program: Expr }, opts?: { readonly where?: (c: ChainImpl) => { readonly program: Expr } }): ListChainImpl {
752
+ siblings(body: (c: ChainImpl) => { readonly program: Expr }, opts?: AxisOptsImpl): ListChainImpl {
679
753
  return this.#axis({ t: "siblings" }, body, opts);
680
754
  }
681
- window(from: number, to: number, body: (c: ChainImpl) => { readonly program: Expr }, opts?: { readonly where?: (c: ChainImpl) => { readonly program: Expr } }): ListChainImpl {
755
+ window(from: number, to: number, body: (c: ChainImpl) => { readonly program: Expr }, opts?: AxisOptsImpl): ListChainImpl {
682
756
  return this.#axis({ t: "window", from, to }, body, opts);
683
757
  }
684
- table(name: string, body: (c: ChainImpl) => { readonly program: Expr }, opts?: { readonly where?: (c: ChainImpl) => { readonly program: Expr } }): ListChainImpl {
758
+ table(name: string, body: (c: ChainImpl) => { readonly program: Expr }, opts?: AxisOptsImpl): ListChainImpl {
685
759
  return this.#axis({ t: "table", name }, body, opts);
686
760
  }
687
- successors(body: (c: ChainImpl) => { readonly program: Expr }, opts?: { readonly where?: (c: ChainImpl) => { readonly program: Expr } }): ListChainImpl {
761
+ successors(body: (c: ChainImpl) => { readonly program: Expr }, opts?: AxisOptsImpl): ListChainImpl {
688
762
  return this.#axis({ t: "successors" }, body, opts);
689
763
  }
690
- predecessors(body: (c: ChainImpl) => { readonly program: Expr }, opts?: { readonly where?: (c: ChainImpl) => { readonly program: Expr } }): ListChainImpl {
764
+ predecessors(body: (c: ChainImpl) => { readonly program: Expr }, opts?: AxisOptsImpl): ListChainImpl {
691
765
  return this.#axis({ t: "predecessors" }, body, opts);
692
766
  }
693
- reachable(body: (c: ChainImpl) => { readonly program: Expr }, opts?: { readonly where?: (c: ChainImpl) => { readonly program: Expr } }): ListChainImpl {
767
+ reachable(body: (c: ChainImpl) => { readonly program: Expr }, opts?: AxisOptsImpl): ListChainImpl {
694
768
  return this.#axis({ t: "reachable" }, body, opts);
695
769
  }
696
770
  }
@@ -723,13 +797,16 @@ class ListChainImpl {
723
797
  step: (vars: Readonly<Record<string, ChainImpl>>, item: ChainImpl) => Readonly<Record<string, unknown>>,
724
798
  result: (vars: Readonly<Record<string, ChainImpl>>) => unknown,
725
799
  ): 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"> };
800
+ // The list of an axis is a let of the start value around the axis, and the list of `each` of a list is the axis
801
+ // alone. The fold keeps the let, and the body of the axis is the item of each step.
802
+ const e = this.#s.expr;
803
+ const loop = e.tag === "let" ? e.body : e;
804
+ if (loop.tag !== "each") throw new TypeError("fold needs the list of an axis: go over the items of the list with each first");
729
805
  const names = new ChainImpl({ ...this.#s, expr: lit(null) }).loopNames(init);
730
806
  const item = new ChainImpl({ ...this.#s, expr: loop.body, addr: [] });
731
807
  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)) });
808
+ const folded = foldExpr(loop.axis, names.first, next, toExpr(result(names.vars), this.#s.addr), loop.at);
809
+ return new ChainImpl({ ...this.#s, expr: e.tag === "let" ? let_(e.bind, folded) : folded });
733
810
  }
734
811
 
735
812
  #op(op: string, extra: readonly Expr[], opts?: ListOpts & { readonly domain?: string }): ChainImpl {
@@ -776,6 +853,26 @@ class ListChainImpl {
776
853
  reduce(op: string, opts?: ListOpts & { readonly domain?: string }): ChainImpl {
777
854
  return this.#op("reduce", [lit(op)], opts);
778
855
  }
856
+ #list(op: string, extra: readonly Expr[], opts?: ListOpts): ListChainImpl {
857
+ return new ListChainImpl({ ...this.#s, expr: this.#op(op, extra, opts).program });
858
+ }
859
+ sortBy(opts?: ListOpts): ListChainImpl {
860
+ return this.#list("sortBy", [], opts);
861
+ }
862
+ take(n: number, opts?: ListOpts): ListChainImpl {
863
+ return this.#list("take", [lit(n)], opts);
864
+ }
865
+ nth(i: number, opts?: ListOpts): ChainImpl {
866
+ return this.#op("nth", [lit(i)], opts);
867
+ }
868
+ each(body: (c: ChainImpl) => { readonly program: Expr }, opts?: AxisOptsImpl): ListChainImpl {
869
+ // The chain of the body is at the key of the item, and it has no value of its own.
870
+ const start = new ChainImpl({ ...this.#s, expr: lit(null), addr: [], depth: this.#s.depth + 1 });
871
+ const list: Axis = { t: "list", list: this.#s.expr };
872
+ const ordered: Axis = opts?.reverse === true ? { t: "reverse", axis: list } : list;
873
+ const axis: Axis = opts?.where === undefined ? ordered : { t: "where", axis: ordered, test: opts.where(start).program };
874
+ return new ListChainImpl({ ...this.#s, expr: each(axis, body(start).program) });
875
+ }
779
876
  result(k: string): Result<unknown> {
780
877
  return evaluate(this.#s.expr, evalOptions(this.#s, k));
781
878
  }
@@ -822,6 +919,9 @@ class RootImpl {
822
919
  sheet(): SheetImpl {
823
920
  return new SheetImpl(this.#env, new Map());
824
921
  }
922
+ fn(params: readonly string[], build: (...params: ChainImpl[]) => { readonly program: Expr }): FnDefImpl {
923
+ return { kind: "vex.fn", params, build };
924
+ }
825
925
  rec(fields: Readonly<Record<string, unknown>>): Arg<unknown> {
826
926
  const out: Record<string, Expr> = {};
827
927
  for (const [n, a] of Object.entries(fields)) out[n] = toExpr(a, []);
package/src/deps.ts CHANGED
@@ -1,4 +1,27 @@
1
- import { addrExprs, children, type Addr, type Axis, type Expr } from "./ir.ts";
1
+ import { addrExprs, children, listOf, type Addr, type Axis, type Expr, type ExprOf } from "./ir.ts";
2
+
3
+ /** A bound function: its node, and the functions of the place of its binding. */
4
+ interface Bound {
5
+ readonly fn: ExprOf<"fn">;
6
+ readonly fns: ReadonlyMap<string, Bound>;
7
+ }
8
+
9
+ /** This function gives the functions of a scope without some names: a parameter or a binding hides a function. */
10
+ const without = (fns: ReadonlyMap<string, Bound>, names: readonly string[]): ReadonlyMap<string, Bound> => new Map([...fns].filter(([n]) => !names.includes(n)));
11
+
12
+ /**
13
+ * This function gives the functions that each child of a node sees. The names of a loop hide the functions with those
14
+ * names in its steps, its test of until and its result. The values of init, the tests of where and an address see the
15
+ * functions outside.
16
+ */
17
+ function childFns(x: Expr, fns: ReadonlyMap<string, Bound>, count: number): (i: number) => ReadonlyMap<string, Bound> {
18
+ if (x.tag !== "fold" && x.tag !== "iterate") return () => fns;
19
+ const hidden = without(fns, Object.keys(x.init));
20
+ const first = Object.keys(x.init).length;
21
+ const steps = first + Object.keys(x.step).length;
22
+ // The children of a fold have the tests of where and the address between the steps and the result.
23
+ return (i) => (i >= first && (i < steps || i === count - 1 || x.tag === "iterate") ? hidden : fns);
24
+ }
2
25
 
3
26
  /** One static read of a program: a field path at an address, inside zero or more axes. */
4
27
  export interface Dependency {
@@ -21,19 +44,41 @@ export function deps(e: Expr): readonly Dependency[] {
21
44
  const out: Dependency[] = [];
22
45
  // A stack, not recursion, so a deep expression needs no deep call stack. The children go on the stack in reverse
23
46
  // order, so the reads come out in the order of a depth-first walk.
24
- const todo: { readonly x: Expr; readonly axes: readonly Axis["t"][]; readonly axisAt: readonly Addr[] }[] = [{ x: e, axes: [], axisAt: [] }];
47
+ type Item = { readonly x: Expr; readonly axes: readonly Axis["t"][]; readonly axisAt: readonly Addr[]; readonly fns: ReadonlyMap<string, Bound> };
48
+ const todo: Item[] = [{ x: e, axes: [], axisAt: [], fns: new Map() }];
25
49
  for (let item = todo.pop(); item !== undefined; item = todo.pop()) {
26
50
  const { x } = item;
27
51
  if (x.tag === "ref") out.push({ at: x.at ?? [], path: x.path, axes: item.axes, axisAt: item.axisAt });
52
+ // A function reads at each call, inside the axes of the call (FN.CALL). Its body does not read where it is bound.
53
+ if (x.tag === "let") {
54
+ const names = Object.keys(x.bind);
55
+ const inner = new Map(without(item.fns, names));
56
+ for (const [name, b] of Object.entries(x.bind)) if (b.tag === "fn") inner.set(name, { fn: b, fns: item.fns });
57
+ todo.push({ ...item, x: x.body, fns: inner });
58
+ for (const b of Object.values(x.bind).toReversed()) if (b.tag !== "fn") todo.push({ ...item, x: b });
59
+ continue;
60
+ }
61
+ if (x.tag === "call") {
62
+ const bound = item.fns.get(x.fn);
63
+ if (bound !== undefined) todo.push({ ...item, x: bound.fn.body, fns: without(bound.fns, bound.fn.params) });
64
+ for (const a of x.args.toReversed()) todo.push({ ...item, x: a });
65
+ continue;
66
+ }
28
67
  const all = children(x);
68
+ const fnsOf = childFns(x, item.fns, all.length);
29
69
  const axial = x.tag === "each" || x.tag === "fold";
30
70
  // 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.
71
+ // fold, the list of the axis list and the expressions of an address evaluate at the node, outside the axis.
32
72
  const first = x.tag === "fold" ? Object.keys(x.init).length : 0;
33
73
  const last = axial ? all.length - addrExprs(x.at).length - (x.tag === "fold" ? 1 : 0) : 0;
74
+ // The list of the axis list comes after the body or the values of the step, before the tests of where.
75
+ const listAt = axial && listOf(x.axis) !== undefined ? (x.tag === "fold" ? first + Object.keys(x.step).length : 1) : -1;
34
76
  const axes = axial ? [...item.axes, x.axis.t] : item.axes;
35
77
  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 });
78
+ for (let i = all.length - 1; i >= 0; i--) {
79
+ const inside = i >= first && i < last && i !== listAt;
80
+ todo.push({ x: all[i] as Expr, axes: inside ? axes : item.axes, axisAt: inside ? axisAt : item.axisAt, fns: fnsOf(i) });
81
+ }
37
82
  }
38
83
  return out;
39
84
  }
package/src/evaluate.ts CHANGED
@@ -77,6 +77,19 @@ export interface Program {
77
77
  * This function compiles an expression. The result gives the same results and the same traces as `evaluate`,
78
78
  * because `evaluate` uses it too.
79
79
  */
80
+ /** A bound function (FN.BIND): its parameters, its compiled body and the names of the place of its binding. */
81
+ class Closure {
82
+ readonly params: readonly string[];
83
+ readonly body: Node;
84
+ readonly env: ReadonlyMap<string, Result<unknown>>;
85
+
86
+ constructor(params: readonly string[], body: Node, env: ReadonlyMap<string, Result<unknown>>) {
87
+ this.params = params;
88
+ this.body = body;
89
+ this.env = env;
90
+ }
91
+ }
92
+
80
93
  /** The deepest nesting of an expression that `compile` accepts (EVAL.NESTING). */
81
94
  export const MAX_NESTING = 500;
82
95
 
@@ -212,8 +225,17 @@ class Compiler {
212
225
  return this.#ref(e, info);
213
226
  case "var": {
214
227
  const name = e.name;
215
- return (f, c) => this.#emit(c, info, f, f.env.get(name) ?? this.#err("unbound", `the name "${name}" has no binding`, f, path));
228
+ return (f, c) => {
229
+ const bound = f.env.get(name);
230
+ // A function is not a value (FN.VALUE).
231
+ if (bound?.ok === true && bound.value instanceof Closure) return this.#emit(c, info, f, this.#err("kind-mismatch", `the name "${name}" is a function, not a value`, f, path));
232
+ return this.#emit(c, info, f, bound ?? this.#err("unbound", `the name "${name}" has no binding`, f, path));
233
+ };
216
234
  }
235
+ case "fn":
236
+ return this.#fn(e, path);
237
+ case "call":
238
+ return this.#callFn(e, info);
217
239
  case "let": {
218
240
  const binds = Object.entries(e.bind).map(([name, be], i): readonly [string, Node] => [name, this.node(be, [...path, i])]);
219
241
  const body = this.node(e.body, [...path, binds.length]);
@@ -259,6 +281,35 @@ class Compiler {
259
281
  return es.map((x, i) => this.node(x, [...path, i]));
260
282
  }
261
283
 
284
+ /**
285
+ * This method compiles a function (FN.BIND). Its value is a closure: the parameters, the body, and the names of the
286
+ * place of its binding. A binding of `let` does not see the other bindings, so a function cannot call itself.
287
+ */
288
+ #fn(e: ExprOf<"fn">, path: readonly number[]): Node {
289
+ const body = this.node(e.body, [...path, 0]);
290
+ return (f) => ok(new Closure(e.params, body, f.env));
291
+ }
292
+
293
+ /**
294
+ * This method compiles a call (FN.CALL, FN.ARGS). Each parameter gets the result of its argument at the call, so an
295
+ * argument that fails has an effect only where the body reads it. The body evaluates at the position of the call.
296
+ */
297
+ #callFn(e: ExprOf<"call">, info: Info): Node {
298
+ const { path } = info;
299
+ const args = this.#nodes(e.args, path);
300
+ return (f, c) => {
301
+ const bound = f.env.get(e.fn);
302
+ if (bound === undefined) return this.#emit(c, info, f, this.#err("unbound", `the function "${e.fn}" has no binding`, f, path));
303
+ if (!bound.ok) return this.#emit(c, info, f, bound);
304
+ const callee = bound.value;
305
+ if (!(callee instanceof Closure)) return this.#emit(c, info, f, this.#err("kind-mismatch", `the name "${e.fn}" is a value, not a function`, f, path));
306
+ if (callee.params.length !== args.length) return this.#emit(c, info, f, this.#err("bad-expression", `the function "${e.fn}" takes ${String(callee.params.length)} arguments, not ${String(args.length)}`, f, path));
307
+ const env = new Map(callee.env);
308
+ callee.params.forEach((p, i) => env.set(p, (args[i] as Node)(f, c)));
309
+ return this.#emit(c, info, f, callee.body({ pos: f.pos, env }, c));
310
+ };
311
+ }
312
+
262
313
  /** This method gives an error of a handler the path, the origin and the focus of its node, if it has no origin. */
263
314
  #locate(r: Result<unknown>, f: Frame, path: readonly number[]): Result<unknown> {
264
315
  if (r.ok || r.error.origin !== undefined) return r;
@@ -501,6 +552,8 @@ class Compiler {
501
552
  /** This method compiles the targets of an axis. For `where`, a failed test keeps the target with its error. */
502
553
  #targets(a: Axis, path: readonly number[], counter: { next: number }): (f: Frame, c: Ctx) => Result<readonly { readonly key: string; readonly test?: Result<unknown> }[]> {
503
554
  if (a.t === "table") return (_f, c) => ok(c.space.keys.map((key) => ({ key })));
555
+ const base = a.t === "reverse" ? a.axis : a;
556
+ if (base.t === "list") return this.#listTargets(base.list, a.t === "reverse", path, counter);
504
557
  if (a.t !== "where") {
505
558
  return (f, c) => {
506
559
  const keys = axisTargets(c.space, f.pos, a);
@@ -533,6 +586,21 @@ class Compiler {
533
586
  };
534
587
  }
535
588
 
589
+ /**
590
+ * This method compiles the targets of the axis list (AXIS.LIST): the keys of the items of a list, in its order. The
591
+ * expression evaluates at the key of the address. An error item keeps its target with its error.
592
+ */
593
+ #listTargets(list: Expr, reverse: boolean, path: readonly number[], counter: { next: number }): (f: Frame, c: Ctx) => Result<readonly { readonly key: string; readonly test?: Result<unknown> }[]> {
594
+ const node = this.node(list, [...path, counter.next++]);
595
+ return (f, c) => {
596
+ const r = node(f, c);
597
+ if (!r.ok) return r;
598
+ if (!isVexList(r.value)) return this.#err("kind-mismatch", `the axis "list" needs a list, not a ${describeType(r.value)}`, f, path);
599
+ const items = r.value.items.map(({ key, result }) => (result.ok ? { key } : { key, test: result }));
600
+ return ok(reverse ? items.toReversed() : items);
601
+ };
602
+ }
603
+
536
604
  #app(op: string, args: readonly Node[], info: Info): Node {
537
605
  const { path } = info;
538
606
  const listOp = isListOp(op) ? op : undefined;
@@ -651,7 +719,8 @@ class Compiler {
651
719
  }
652
720
 
653
721
  #listOp(op: ListOp, list: VexList, rest: readonly unknown[], f: Frame, path: readonly number[]): Result<unknown> {
654
- const optsArg = op === "reduce" ? rest[1] : rest[0];
722
+ // The options come after the first argument of reduce, take and nth.
723
+ const optsArg = op === "reduce" || op === "take" || op === "nth" ? rest[1] : rest[0];
655
724
  // A reduction that skips error items does not skip #DEPTH! (EVAL.DEPTH).
656
725
  const depth = list.items.find((it) => !it.result.ok && isDepthError(it.result.error))?.result;
657
726
  if (depth !== undefined && !depth.ok) return fail(depth.error);
@@ -668,7 +737,24 @@ class Compiler {
668
737
  return bad === undefined ? ok(okValues as readonly boolean[]) : this.#err("kind-mismatch", `"${op}" needs booleans, but an item is a ${describeType(bad)}`, f, path, { op });
669
738
  };
670
739
  const empty = (): Result<never> => this.#err("empty", `"${op}" has no values to work with`, f, path, { op });
740
+ // A count or a position of take and nth is a whole number from 0.
741
+ const whole = (): Result<number> => {
742
+ const n = rest[0] as number;
743
+ return Number.isSafeInteger(n) && n >= 0 ? ok(n) : this.#err("kind-mismatch", `"${op}" needs a whole number from 0, not ${describeType(n)}`, f, path, { op });
744
+ };
745
+ const okItems = list.items.filter((it) => it.result.ok);
671
746
  switch (op) {
747
+ case "sortBy":
748
+ return this.#sortBy(okItems, okValues, f, path);
749
+ case "take": {
750
+ const n = whole();
751
+ return n.ok ? ok(vexList(okItems.slice(0, n.value))) : n;
752
+ }
753
+ case "nth": {
754
+ const i = whole();
755
+ if (!i.ok) return i;
756
+ return i.value < okValues.length ? ok(okValues[i.value]) : this.#err("empty", `"nth" has no item at the position ${String(i.value)}, and the list has ${String(okValues.length)} items`, f, path, { op });
757
+ }
672
758
  case "count":
673
759
  return ok(okValues.length);
674
760
  case "values":
@@ -709,6 +795,24 @@ class Compiler {
709
795
  }
710
796
  }
711
797
 
798
+ /**
799
+ * This method sorts the items of a list by their values, from the smallest (LIST.SORT). The sort is stable. The values
800
+ * are all numbers without NaN, or all texts. Texts compare by their UTF-16 code units.
801
+ */
802
+ #sortBy(items: readonly ListItem[], values: readonly unknown[], f: Frame, path: readonly number[]): Result<VexList> {
803
+ const kind = typeof values[0];
804
+ const bad = values.findIndex((x) => typeof x !== kind || (kind !== "number" && kind !== "string") || Number.isNaN(x));
805
+ if (bad >= 0) return this.#err("kind-mismatch", `"sortBy" needs numbers without NaN or texts, all of one kind, but an item is ${Number.isNaN(values[bad]) ? "NaN" : `a ${describeType(values[bad])}`}`, f, path, { op: "sortBy" });
806
+ const order = values.map((_x, i) => i).toSorted((i, j) => {
807
+ const a = values[i] as number | string;
808
+ const b = values[j] as number | string;
809
+ // The sort of Node reads only a negative result, and the sort of another engine needs the whole comparison.
810
+ // Stryker disable next-line ConditionalExpression,EqualityOperator: see the comment above
811
+ return a < b ? -1 : a > b ? 1 : 0;
812
+ });
813
+ return ok(vexList(order.map((i) => items[i] as ListItem)));
814
+ }
815
+
712
816
  /**
713
817
  * This method folds the values with a domain op, from the left. An empty list gives the identity of the op, if one
714
818
  * domain has an identity for the op (LIST.EMPTY). The option `domain` names that domain when more domains have one.
@@ -797,6 +901,11 @@ export function labelOf(e: Expr): string {
797
901
  return e.op;
798
902
  case "let":
799
903
  return `let ${Object.keys(e.bind).join(", ")}`;
904
+ // A function makes no event of the trace, so its label only completes the switch.
905
+ // Stryker disable next-line all: see the comment above
906
+ case "fn": return `fn (${e.params.join(", ")})`;
907
+ case "call":
908
+ return `call ${e.fn}`;
800
909
  case "var":
801
910
  return e.name;
802
911
  case "rec":