@mark1russell7/vex 0.6.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.6.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, 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, 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> {
@@ -178,10 +179,16 @@ export interface ChainBase<Ctx extends ChainContext, T> {
178
179
  all(): Traversal<Ctx["keys"], T>;
179
180
  /** This method gives a chain whose value is a field of the record at the current address. */
180
181
  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>;
182
+ /**
183
+ * Navigation: later field references read at the key `k`. A chain of a text gives the key, and it evaluates at the
184
+ * focus before the moves (NAV.COMPUTED).
185
+ */
186
+ to(k: Ctx["keys"] | ChainBase<Ctx, string>): ChainOf<Ctx, T>;
187
+ /**
188
+ * Navigation: later field references read at the key with this position in the key order. A chain of a number gives
189
+ * the position, and it evaluates at the focus before the moves (NAV.COMPUTED).
190
+ */
191
+ index(i: number | ChainBase<Ctx, number>): ChainOf<Ctx, T>;
185
192
  /** Navigation: later field references read at a relative position in an array or a grid. */
186
193
  offset(...d: readonly number[]): ChainOf<Ctx, T>;
187
194
  /** Navigation: later field references read at the origin again. */
@@ -202,11 +209,27 @@ export interface ChainBase<Ctx extends ChainContext, T> {
202
209
  call<N extends CallableFns<Ctx, T>>(name: N, ...args: CallArgs<Ctx, N>): ChainOf<Ctx, CallReturn<Ctx, N>>;
203
210
  /** This method evaluates each branch with the current value, and gives a record of the results. */
204
211
  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]>> }>;
212
+ /**
213
+ * This method makes up to `limit` steps (ITERATE.LIMIT). `init` gives the names and their first values, and `step`
214
+ * gives the next values. A true `until` stops the steps (ITERATE.UNTIL). `result` gives the value of the chain.
215
+ */
216
+ iterate<const I extends Readonly<Record<string, unknown>>, R>(
217
+ limit: number,
218
+ init: I,
219
+ step: (vars: LoopVars<Ctx, I>) => NoInfer<LoopStep<Ctx, I>>,
220
+ result: (vars: LoopVars<Ctx, I>) => ArgInput<R, Ctx, false>,
221
+ opts?: { readonly until?: (vars: LoopVars<Ctx, I>) => ArgInput<boolean, Ctx, false> },
222
+ ): ChainOf<Ctx, R>;
205
223
  /** This method binds names for the body. The body gets a variable token for each name. */
206
224
  with<const B extends Readonly<Record<string, unknown>>, U>(
207
225
  binds: B,
208
226
  body: (c: ChainOf<Ctx, T>, vars: { readonly [N in keyof B]: Arg<ArgValue<Ctx, B[N]>> }) => ChainBase<Ctx, U>,
209
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>;
210
233
  /** The others axis: the body evaluates at each key except the focus. Its start value is the current value. */
211
234
  others<U>(body: (c: ChainOf<Ctx, T>) => ChainBase<Ctx, U>, opts?: AxisOpts<Ctx, T>): ListChain<Ctx, U>;
212
235
  /** The neighbors axis of a grid. */
@@ -243,8 +266,20 @@ export interface ChainBase<Ctx extends ChainContext, T> {
243
266
  export interface AxisOpts<Ctx extends ChainContext, T> {
244
267
  /** A test at each target. The body evaluates only at the targets where the test gives `true`. */
245
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 };
246
278
  }
247
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
+
248
283
  /** The members of a chain whose value has a domain. */
249
284
  export interface DomainMembers<Ctx extends ChainContext, Dm> {
250
285
  /** The ops of the domain of the current value. */
@@ -275,10 +310,50 @@ export type ArgValue<Ctx extends ChainContext, A> = A extends Arg<infer T>
275
310
  : A;
276
311
 
277
312
  /** A chain whose value is a list: the result of an axis. */
313
+ /** The type of a value of a name of a loop: a literal of `init` gives its primitive type. */
314
+ 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;
315
+
316
+ /** The names of a loop of the builder: a chain of the value of each name of `init` (LOOP.NAMES). */
317
+ export type LoopVars<Ctx extends ChainContext, I> = { readonly [N in keyof I]: ChainOf<Ctx, LoopValue<Ctx, I[N]>> };
318
+
319
+ /** The next values of a step of a loop: a value for some of the names of `init`. */
320
+ export type LoopStep<Ctx extends ChainContext, I> = { readonly [N in keyof I]?: ArgInput<LoopValue<Ctx, I[N]>, Ctx, false> };
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
+
278
344
  export interface ListChain<Ctx extends ChainContext, U> {
279
345
  readonly kind: "vex.list-chain";
280
346
  /** The expression of the chain, as plain data. */
281
347
  readonly program: Expr;
348
+ /**
349
+ * This method folds the items in the order of the axis (FOLD.ORDER). `init` gives the names and their first values.
350
+ * `step` gives the next values from the names and the item, a chain at the target. `result` gives the value.
351
+ */
352
+ fold<const I extends Readonly<Record<string, unknown>>, R>(
353
+ init: I,
354
+ step: (vars: LoopVars<Ctx, I>, item: ChainOf<Ctx, U>) => NoInfer<LoopStep<Ctx, I>>,
355
+ result: (vars: LoopVars<Ctx, I>) => ArgInput<R, Ctx, false>,
356
+ ): ChainOf<Ctx, R>;
282
357
  count(opts?: ListOpts): ChainOf<Ctx, number>;
283
358
  sum(this: ListChain<Ctx, number>, opts?: ListOpts): ChainOf<Ctx, number>;
284
359
  mean(this: ListChain<Ctx, number>, opts?: ListOpts): ChainOf<Ctx, number>;
@@ -294,6 +369,17 @@ export interface ListChain<Ctx extends ChainContext, U> {
294
369
  errors(): ChainOf<Ctx, readonly VexError[]>;
295
370
  first(opts?: ListOpts): ChainOf<Ctx, U>;
296
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>;
297
383
  /** The list at the origin `k`: one item for each target of the axis, with its key and its result. */
298
384
  result(k: Ctx["keys"]): Result<VexList<U>>;
299
385
  /** The list at the origin `k`, as an `Optional`. */
@@ -336,6 +422,11 @@ export interface Root<Ctx extends ChainContext> {
336
422
  ext<T>(kind: string, data?: unknown): Arg<T>;
337
423
  /** This method starts a sheet over the space: named columns of formulas. Refer to `Sheet`. */
338
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>;
339
430
  /** The space of the root. */
340
431
  readonly space: Space<Ctx["keys"], Ctx["record"]>;
341
432
  }
@@ -344,11 +435,12 @@ export interface Root<Ctx extends ChainContext> {
344
435
  export interface SheetRoot<Ctx extends ChainContext, Cols> extends Root<Ctx> {
345
436
  /**
346
437
  * 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.
438
+ * The address has only fixed moves. Without `at`, it reads at the focus. The type is the type of a column before
439
+ * this one.
348
440
  */
349
- cell<N extends keyof Cols & string>(column: N, at?: Ctx["keys"] | Addr): Arg<Cols[N]>;
441
+ cell<N extends keyof Cols & string>(column: N, at?: Ctx["keys"] | readonly FixedMove[]): Arg<Cols[N]>;
350
442
  /** 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>;
443
+ cell<T>(column: string, at?: Ctx["keys"] | readonly FixedMove[]): Arg<T>;
352
444
  }
353
445
 
354
446
  /** One row of a sheet: the key and the result of each column. */
@@ -462,6 +554,17 @@ function toExpr(a: unknown, addr: readonly Move[]): Expr {
462
554
  return lit(a);
463
555
  }
464
556
 
557
+ /** This function gives the expressions of a step of a loop, with the unique names of the loop. */
558
+ function stepExprs(step: Readonly<Record<string, unknown>>, unique: ReadonlyMap<string, string>, addr: readonly Move[]): Readonly<Record<string, Expr>> {
559
+ const out: Record<string, Expr> = {};
560
+ for (const [n, a] of Object.entries(step)) {
561
+ const name = unique.get(n);
562
+ if (name === undefined) throw new TypeError(`the name "${n}" of the step is not a name of init`);
563
+ out[name] = toExpr(a, addr);
564
+ }
565
+ return out;
566
+ }
567
+
465
568
  const PROXY_RESERVED = new Set(["then", "catch", "finally", "toJSON", "valueOf", "toString", "constructor", "inspect", "asymmetricMatch", "$$typeof", "nodeType"]);
466
569
 
467
570
  class ChainImpl {
@@ -515,11 +618,11 @@ class ChainImpl {
515
618
  #move(m: Move): ChainImpl {
516
619
  return new ChainImpl({ ...this.#s, addr: [...this.#s.addr, m] });
517
620
  }
518
- to(k: string): ChainImpl {
519
- return this.#move(keyMove(k));
621
+ to(k: string | { readonly program: Expr }): ChainImpl {
622
+ return this.#move(keyMove(typeof k === "string" ? k : k.program));
520
623
  }
521
- index(i: number): ChainImpl {
522
- return this.#move(indexMove(i));
624
+ index(i: number | { readonly program: Expr }): ChainImpl {
625
+ return this.#move(indexMove(typeof i === "number" ? i : i.program));
523
626
  }
524
627
  offset(...d: readonly number[]): ChainImpl {
525
628
  return this.#move(offsetMove(...d));
@@ -570,49 +673,98 @@ class ChainImpl {
570
673
  return new ChainImpl({ ...this.#s, expr: let_(bindExprs, inner.program) });
571
674
  }
572
675
 
573
- #axis(a: Axis, body: (c: ChainImpl) => { readonly program: Expr }, opts?: { readonly where?: (c: ChainImpl) => { readonly program: Expr } }): ListChainImpl {
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
+
693
+ /**
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.
695
+ * It also gets its first value at the address of the chain, and a chain of its value.
696
+ */
697
+ loopNames(init: Readonly<Record<string, unknown>>): { readonly unique: ReadonlyMap<string, string>; readonly first: Readonly<Record<string, Expr>>; readonly vars: Readonly<Record<string, ChainImpl>> } {
698
+ const depth = this.#s.depth;
699
+ const unique = new Map<string, string>();
700
+ const first: Record<string, Expr> = {};
701
+ const vars: Record<string, ChainImpl> = {};
702
+ for (const [n, a] of Object.entries(init)) {
703
+ const name = `${n}$${depth}`;
704
+ unique.set(n, name);
705
+ first[name] = toExpr(a, this.#s.addr);
706
+ vars[n] = new ChainImpl({ ...this.#s, expr: v(name), addr: [], depth: depth + 1 });
707
+ }
708
+ return { unique, first, vars };
709
+ }
710
+
711
+ iterate(
712
+ limit: number,
713
+ init: Readonly<Record<string, unknown>>,
714
+ step: (vars: Readonly<Record<string, ChainImpl>>) => Readonly<Record<string, unknown>>,
715
+ result: (vars: Readonly<Record<string, ChainImpl>>) => unknown,
716
+ opts?: { readonly until?: (vars: Readonly<Record<string, ChainImpl>>) => unknown },
717
+ ): ChainImpl {
718
+ const { unique, first, vars } = this.loopNames(init);
719
+ const next = stepExprs(step(vars), unique, this.#s.addr);
720
+ const until = opts?.until === undefined ? undefined : toExpr(opts.until(vars), this.#s.addr);
721
+ return new ChainImpl({ ...this.#s, expr: iterateExpr(limit, first, next, toExpr(result(vars), this.#s.addr), until) });
722
+ }
723
+
724
+ #axis(a: Axis, body: (c: ChainImpl) => { readonly program: Expr }, opts?: AxisOptsImpl): ListChainImpl {
574
725
  const { name, start } = this.#bound();
575
726
  // Inside the axis, the focus is the target, so the address of the body starts empty.
576
727
  const inTarget = new ChainImpl({ ...start.#s, addr: [] });
577
728
  const inner = body(inTarget);
578
- 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 };
579
731
  // The moves before the axis are its address: parent().children(f) gives f at each child of the parent.
580
732
  return new ListChainImpl({ ...this.#s, expr: let_({ [name]: this.#s.expr }, each(axis, inner.program, this.#s.addr)) });
581
733
  }
582
- 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 {
583
735
  return this.#axis({ t: "others" }, body, opts);
584
736
  }
585
- 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 {
586
738
  return this.#axis({ t: "neighbors", n }, body, opts);
587
739
  }
588
- 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 {
589
741
  return this.#axis({ t: "all" }, body, opts);
590
742
  }
591
- 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 {
592
744
  return this.#axis({ t: "children" }, body, opts);
593
745
  }
594
- 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 {
595
747
  return this.#axis({ t: "ancestors" }, body, opts);
596
748
  }
597
- 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 {
598
750
  return this.#axis({ t: "descendants" }, body, opts);
599
751
  }
600
- 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 {
601
753
  return this.#axis({ t: "siblings" }, body, opts);
602
754
  }
603
- 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 {
604
756
  return this.#axis({ t: "window", from, to }, body, opts);
605
757
  }
606
- 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 {
607
759
  return this.#axis({ t: "table", name }, body, opts);
608
760
  }
609
- 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 {
610
762
  return this.#axis({ t: "successors" }, body, opts);
611
763
  }
612
- 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 {
613
765
  return this.#axis({ t: "predecessors" }, body, opts);
614
766
  }
615
- 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 {
616
768
  return this.#axis({ t: "reachable" }, body, opts);
617
769
  }
618
770
  }
@@ -640,6 +792,23 @@ class ListChainImpl {
640
792
  get program(): Expr {
641
793
  return this.#s.expr;
642
794
  }
795
+ fold(
796
+ init: Readonly<Record<string, unknown>>,
797
+ step: (vars: Readonly<Record<string, ChainImpl>>, item: ChainImpl) => Readonly<Record<string, unknown>>,
798
+ result: (vars: Readonly<Record<string, ChainImpl>>) => unknown,
799
+ ): ChainImpl {
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");
805
+ const names = new ChainImpl({ ...this.#s, expr: lit(null) }).loopNames(init);
806
+ const item = new ChainImpl({ ...this.#s, expr: loop.body, addr: [] });
807
+ const next = stepExprs(step(names.vars, item), names.unique, []);
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 });
810
+ }
811
+
643
812
  #op(op: string, extra: readonly Expr[], opts?: ListOpts & { readonly domain?: string }): ChainImpl {
644
813
  const options = { ...(opts?.strict === true ? { strict: true } : {}), ...(opts?.domain === undefined ? {} : { domain: opts.domain }) };
645
814
  const args = Object.keys(options).length > 0 ? [...extra, lit(options)] : extra;
@@ -684,6 +853,26 @@ class ListChainImpl {
684
853
  reduce(op: string, opts?: ListOpts & { readonly domain?: string }): ChainImpl {
685
854
  return this.#op("reduce", [lit(op)], opts);
686
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
+ }
687
876
  result(k: string): Result<unknown> {
688
877
  return evaluate(this.#s.expr, evalOptions(this.#s, k));
689
878
  }
@@ -730,6 +919,9 @@ class RootImpl {
730
919
  sheet(): SheetImpl {
731
920
  return new SheetImpl(this.#env, new Map());
732
921
  }
922
+ fn(params: readonly string[], build: (...params: ChainImpl[]) => { readonly program: Expr }): FnDefImpl {
923
+ return { kind: "vex.fn", params, build };
924
+ }
733
925
  rec(fields: Readonly<Record<string, unknown>>): Arg<unknown> {
734
926
  const out: Record<string, Expr> = {};
735
927
  for (const [n, a] of Object.entries(fields)) out[n] = toExpr(a, []);
@@ -738,7 +930,7 @@ class RootImpl {
738
930
  }
739
931
 
740
932
  class SheetRootImpl extends RootImpl {
741
- cell(column: string, at?: string | Addr): Arg<unknown> {
933
+ cell(column: string, at?: string | readonly FixedMove[]): Arg<unknown> {
742
934
  return argToken(cellRef(column, typeof at === "string" ? [keyMove(at)] : at));
743
935
  }
744
936
  }
@@ -797,6 +989,8 @@ class SheetImpl {
797
989
  }
798
990
  table(): readonly SheetRow<string, Record<string, unknown>>[] {
799
991
  const run = this.#run();
992
+ // The table reads each cell, so a fill evaluates them in the order of their reads first (SHEET.FILL).
993
+ run.fill();
800
994
  const names = [...this.#columns.keys()];
801
995
  return this.#env.space.keys.map((key) => ({ key, cells: Object.fromEntries(names.map((c) => [c, run.cell(c, key)])) }));
802
996
  }
package/src/deps.ts CHANGED
@@ -1,4 +1,27 @@
1
- import { 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 {
@@ -14,22 +37,48 @@ export interface Dependency {
14
37
 
15
38
  /**
16
39
  * 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.
40
+ * when a field that it reads changes. A computed move reads a key that only a run knows. Its address keeps the
41
+ * expression, and the reads of that expression are in the list too (NAV.COMPUTED).
18
42
  */
19
43
  export function deps(e: Expr): readonly Dependency[] {
20
44
  const out: Dependency[] = [];
21
45
  // A stack, not recursion, so a deep expression needs no deep call stack. The children go on the stack in reverse
22
46
  // 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: [] }];
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() }];
24
49
  for (let item = todo.pop(); item !== undefined; item = todo.pop()) {
25
50
  const { x } = item;
26
- if (x.tag === "ref") {
27
- out.push({ at: x.at ?? [], path: x.path, axes: item.axes, axisAt: item.axisAt });
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 });
28
59
  continue;
29
60
  }
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 });
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
+ }
67
+ const all = children(x);
68
+ const fnsOf = childFns(x, item.fns, all.length);
69
+ const axial = x.tag === "each" || x.tag === "fold";
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
71
+ // fold, the list of the axis list and the expressions of an address evaluate at the node, outside the axis.
72
+ const first = x.tag === "fold" ? Object.keys(x.init).length : 0;
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;
76
+ const axes = axial ? [...item.axes, x.axis.t] : item.axes;
77
+ const axisAt = axial ? [...item.axisAt, x.at ?? []] : item.axisAt;
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
+ }
33
82
  }
34
83
  return out;
35
84
  }
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",