@mark1russell7/vex 0.9.1 → 0.11.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.9.1",
4
+ "version": "0.11.0",
5
5
  "description": "Vex: typed spreadsheet formulas over domain objects. The kernel and the typed builder.",
6
6
  "keywords": [
7
7
  "typescript",
@@ -27,6 +27,7 @@
27
27
  "directory": "packages/core"
28
28
  },
29
29
  "type": "module",
30
+ "sideEffects": false,
30
31
  "main": "./build/index.js",
31
32
  "types": "./build/index.d.ts",
32
33
  "exports": {
@@ -47,8 +48,10 @@
47
48
  "publishConfig": {
48
49
  "access": "public"
49
50
  },
51
+ "dependencies": {
52
+ "@mark1russell7/coeval": "^0.6.3"
53
+ },
50
54
  "devDependencies": {
51
- "@mark1russell7/coeval": "^0.1.0",
52
55
  "@mark1russell7/cue": "github:mark1russell7/cue",
53
56
  "@mark1russell7/optional": "github:mark1russell7/optional",
54
57
  "@types/node": "^26.6.4",
package/src/builder.ts CHANGED
@@ -7,10 +7,10 @@ import type { VexError } from "./errors.ts";
7
7
  import { evaluate, explain, type EvalOptions, type ExtHandler, type FreeFn } from "./evaluate.ts";
8
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
- import { toOptional, type Optional, type Result } from "./result.ts";
10
+ import { ok, toOptional, type Optional, type Result } from "./result.ts";
11
11
  import type { Space } from "./space.ts";
12
12
  import type { Trace } from "./trace.ts";
13
- import type { VexList } from "./list.ts";
13
+ import { vexList, type VexList } from "./list.ts";
14
14
  import { traversal, type Traversal } from "./traversal.ts";
15
15
 
16
16
  // ---------------------------------------------------------------- argument tokens
@@ -211,8 +211,16 @@ export interface ChainBase<Ctx extends ChainContext, T> {
211
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
212
  /**
213
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.
214
+ * gives the next values. A true `until` stops the steps (ITERATE.UNTIL). `result` gives the value of the chain. A
215
+ * name with a list chain as its first value is a list chain (BUILD.LIST.LOOP), and a list result gives a list chain.
215
216
  */
217
+ iterate<const I extends Readonly<Record<string, unknown>>, U>(
218
+ limit: number,
219
+ init: I,
220
+ step: (vars: LoopVars<Ctx, I>) => NoInfer<LoopStep<Ctx, I>>,
221
+ result: (vars: LoopVars<Ctx, I>) => ListChain<Ctx, U>,
222
+ opts?: { readonly until?: (vars: LoopVars<Ctx, I>) => ArgInput<boolean, Ctx, false> },
223
+ ): ListChain<Ctx, U>;
216
224
  iterate<const I extends Readonly<Record<string, unknown>>, R>(
217
225
  limit: number,
218
226
  init: I,
@@ -231,35 +239,35 @@ export interface ChainBase<Ctx extends ChainContext, T> {
231
239
  */
232
240
  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>;
233
241
  /** The others axis: the body evaluates at each key except the focus. Its start value is the current value. */
234
- others<U>(body: (c: ChainOf<Ctx, T>) => ChainBase<Ctx, U>, opts?: AxisOpts<Ctx, T>): ListChain<Ctx, U>;
242
+ others<U>(body: (c: ChainOf<Ctx, T>) => AxisBody<Ctx, U>, opts?: AxisOpts<Ctx, T>): ListChain<Ctx, U>;
235
243
  /** The neighbors axis of a grid. */
236
- neighbors<U>(n: 4 | 8, body: (c: ChainOf<Ctx, T>) => ChainBase<Ctx, U>, opts?: AxisOpts<Ctx, T>): ListChain<Ctx, U>;
244
+ neighbors<U>(n: 4 | 8, body: (c: ChainOf<Ctx, T>) => AxisBody<Ctx, U>, opts?: AxisOpts<Ctx, T>): ListChain<Ctx, U>;
237
245
  /** The all axis inside the expression: the body evaluates at each key, with the current value as start value. */
238
- each<U>(body: (c: ChainOf<Ctx, T>) => ChainBase<Ctx, U>, opts?: AxisOpts<Ctx, T>): ListChain<Ctx, U>;
246
+ each<U>(body: (c: ChainOf<Ctx, T>) => AxisBody<Ctx, U>, opts?: AxisOpts<Ctx, T>): ListChain<Ctx, U>;
239
247
  /** The children axis of a tree space: the body evaluates at each child of the focus. */
240
- children<U>(body: (c: ChainOf<Ctx, T>) => ChainBase<Ctx, U>, opts?: AxisOpts<Ctx, T>): ListChain<Ctx, U>;
248
+ children<U>(body: (c: ChainOf<Ctx, T>) => AxisBody<Ctx, U>, opts?: AxisOpts<Ctx, T>): ListChain<Ctx, U>;
241
249
  /** The ancestors axis of a tree space: the parent first, the root last. */
242
- ancestors<U>(body: (c: ChainOf<Ctx, T>) => ChainBase<Ctx, U>, opts?: AxisOpts<Ctx, T>): ListChain<Ctx, U>;
250
+ ancestors<U>(body: (c: ChainOf<Ctx, T>) => AxisBody<Ctx, U>, opts?: AxisOpts<Ctx, T>): ListChain<Ctx, U>;
243
251
  /** The descendants axis of a tree space: depth first, each parent before its children. */
244
- descendants<U>(body: (c: ChainOf<Ctx, T>) => ChainBase<Ctx, U>, opts?: AxisOpts<Ctx, T>): ListChain<Ctx, U>;
252
+ descendants<U>(body: (c: ChainOf<Ctx, T>) => AxisBody<Ctx, U>, opts?: AxisOpts<Ctx, T>): ListChain<Ctx, U>;
245
253
  /** The siblings axis of a tree space: the other children of the parent, or the other roots for a root. */
246
- siblings<U>(body: (c: ChainOf<Ctx, T>) => ChainBase<Ctx, U>, opts?: AxisOpts<Ctx, T>): ListChain<Ctx, U>;
254
+ siblings<U>(body: (c: ChainOf<Ctx, T>) => AxisBody<Ctx, U>, opts?: AxisOpts<Ctx, T>): ListChain<Ctx, U>;
247
255
  /**
248
256
  * The window axis of an array space or a tree space: the keys at the offsets from `from` to `to` of the focus, in
249
257
  * order. The offset 0 is the focus. An offset outside the space has no target.
250
258
  */
251
- window<U>(from: number, to: number, body: (c: ChainOf<Ctx, T>) => ChainBase<Ctx, U>, opts?: AxisOpts<Ctx, T>): ListChain<Ctx, U>;
259
+ window<U>(from: number, to: number, body: (c: ChainOf<Ctx, T>) => AxisBody<Ctx, U>, opts?: AxisOpts<Ctx, T>): ListChain<Ctx, U>;
252
260
  /**
253
261
  * The table axis: the body evaluates at each key of the table `name` of the evaluation, in the space of that table.
254
262
  * The body reads the fields of that table, but the types of the chain are the types of this space.
255
263
  */
256
- table<U>(name: string, body: (c: ChainOf<Ctx, T>) => ChainBase<Ctx, U>, opts?: AxisOpts<Ctx, T>): ListChain<Ctx, U>;
264
+ table<U>(name: string, body: (c: ChainOf<Ctx, T>) => AxisBody<Ctx, U>, opts?: AxisOpts<Ctx, T>): ListChain<Ctx, U>;
257
265
  /** The successors axis of a graph space: the ends of the edges from the focus. In a tree space, the children. */
258
- successors<U>(body: (c: ChainOf<Ctx, T>) => ChainBase<Ctx, U>, opts?: AxisOpts<Ctx, T>): ListChain<Ctx, U>;
266
+ successors<U>(body: (c: ChainOf<Ctx, T>) => AxisBody<Ctx, U>, opts?: AxisOpts<Ctx, T>): ListChain<Ctx, U>;
259
267
  /** The predecessors axis of a graph space: the keys with an edge to the focus. In a tree space, the parent. */
260
- predecessors<U>(body: (c: ChainOf<Ctx, T>) => ChainBase<Ctx, U>, opts?: AxisOpts<Ctx, T>): ListChain<Ctx, U>;
268
+ predecessors<U>(body: (c: ChainOf<Ctx, T>) => AxisBody<Ctx, U>, opts?: AxisOpts<Ctx, T>): ListChain<Ctx, U>;
261
269
  /** The reachable axis of a graph space: each key that a path of edges reaches, in breadth-first order. */
262
- reachable<U>(body: (c: ChainOf<Ctx, T>) => ChainBase<Ctx, U>, opts?: AxisOpts<Ctx, T>): ListChain<Ctx, U>;
270
+ reachable<U>(body: (c: ChainOf<Ctx, T>) => AxisBody<Ctx, U>, opts?: AxisOpts<Ctx, T>): ListChain<Ctx, U>;
263
271
  }
264
272
 
265
273
  /** The options of an axis. */
@@ -309,15 +317,29 @@ export type ArgValue<Ctx extends ChainContext, A> = A extends Arg<infer T>
309
317
  ? NonNullable<Ctx["record"][A]>
310
318
  : A;
311
319
 
312
- /** A chain whose value is a list: the result of an axis. */
313
320
  /** The type of a value of a name of a loop: a literal of `init` gives its primitive type. */
314
321
  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
322
 
323
+ /** The type of the items of a list chain, or `never` for another value. */
324
+ type ItemsOf<A> = A extends { readonly kind: "vex.list-chain"; readonly [CHAIN_VALUE]?: VexList<infer U> } ? U : never;
325
+
326
+ /** A value of `init` that is a list chain: then the name of the loop holds a list (LOOP.LIST). */
327
+ type IsList<A> = A extends { readonly kind: "vex.list-chain" } ? true : false;
328
+
329
+ /**
330
+ * The chain of a name of a loop: a list chain for a list chain of `init` (BUILD.LIST.LOOP), and else a chain of its
331
+ * value.
332
+ */
333
+ export type LoopVar<Ctx extends ChainContext, A> = IsList<A> extends true ? ListChain<Ctx, ItemsOf<A>> : ChainOf<Ctx, LoopValue<Ctx, A>>;
334
+
316
335
  /** 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]>> };
336
+ export type LoopVars<Ctx extends ChainContext, I> = { readonly [N in keyof I]: LoopVar<Ctx, I[N]> };
337
+
338
+ /** The next value of a name of a loop. A name of a list takes a list chain with items of the same type. */
339
+ export type LoopNext<Ctx extends ChainContext, A> = IsList<A> extends true ? ListChain<Ctx, ItemsOf<A>> : ArgInput<LoopValue<Ctx, A>, Ctx, false>;
318
340
 
319
341
  /** 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> };
342
+ export type LoopStep<Ctx extends ChainContext, I> = { readonly [N in keyof I]?: LoopNext<Ctx, I[N]> };
321
343
 
322
344
  /** The kind of a parameter of a function of the builder (BUILD.FN): a primitive type, or `any`. */
323
345
  export type FnParamKind = PrimitiveKind | "any";
@@ -341,14 +363,35 @@ export type FnCalls<Ctx extends ChainContext, F> = {
341
363
  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
364
  };
343
365
 
366
+ /**
367
+ * The value of the body of an axis: a chain, or a list chain (BUILD.LIST.BUILD). For a list chain, the value of each
368
+ * item of the axis is a list, so `flat` joins the lists.
369
+ */
370
+ export type AxisBody<Ctx extends ChainContext, U> = ChainBase<Ctx, U> | ListBody<U>;
371
+
372
+ /** A list chain as the body of an axis. Its phantom member carries the list. */
373
+ export interface ListBody<U> {
374
+ readonly kind: "vex.list-chain";
375
+ readonly [CHAIN_VALUE]?: U;
376
+ readonly program: Expr;
377
+ }
378
+
379
+ /** A chain whose value is a list: the result of an axis, of a list op or of a list literal. */
344
380
  export interface ListChain<Ctx extends ChainContext, U> {
345
381
  readonly kind: "vex.list-chain";
382
+ /** This phantom member carries the type of the list. It is not present at run time. */
383
+ readonly [CHAIN_VALUE]?: VexList<U>;
346
384
  /** The expression of the chain, as plain data. */
347
385
  readonly program: Expr;
348
386
  /**
349
387
  * This method folds the items in the order of the axis (FOLD.ORDER). `init` gives the names and their first values.
350
388
  * `step` gives the next values from the names and the item, a chain at the target. `result` gives the value.
351
389
  */
390
+ fold<const I extends Readonly<Record<string, unknown>>, V>(
391
+ init: I,
392
+ step: (vars: LoopVars<Ctx, I>, item: ChainOf<Ctx, U>) => NoInfer<LoopStep<Ctx, I>>,
393
+ result: (vars: LoopVars<Ctx, I>) => ListChain<Ctx, V>,
394
+ ): ListChain<Ctx, V>;
352
395
  fold<const I extends Readonly<Record<string, unknown>>, R>(
353
396
  init: I,
354
397
  step: (vars: LoopVars<Ctx, I>, item: ChainOf<Ctx, U>) => NoInfer<LoopStep<Ctx, I>>,
@@ -375,11 +418,24 @@ export interface ListChain<Ctx extends ChainContext, U> {
375
418
  take(n: number, opts?: ListOpts): ListChain<Ctx, U>;
376
419
  /** The value of the item at the position `i`, from 0 (LIST.NTH). */
377
420
  nth(i: number, opts?: ListOpts): ChainOf<Ctx, U>;
421
+ /**
422
+ * The value of the first item with the key `k` (LIST.GET). A chain of a text gives the key, and it evaluates at the
423
+ * focus. A key that no item has gives `#N/A`. Thus a step reads the old value of each key.
424
+ */
425
+ get(k: Ctx["keys"] | ChainBase<Ctx, string>, opts?: ListOpts): ChainOf<Ctx, U>;
426
+ /** The items after the first `n` items (LIST.DROP). Thus `drop(1)` removes the first item of a stack. */
427
+ drop(n: number, opts?: ListOpts): ListChain<Ctx, U>;
428
+ /** The items of this list, and then the items of `other` (LIST.APPEND). Two items can have the same key. */
429
+ append<V>(other: ListChain<Ctx, V>, opts?: ListOpts): ListChain<Ctx, U | V>;
430
+ /** The items of this list whose key is not the key of an item of `other` (LIST.WITHOUT). */
431
+ without<V>(other: ListChain<Ctx, V>, opts?: ListOpts): ListChain<Ctx, U>;
432
+ /** The items of the lists that are the values of the items, in order (LIST.FLAT). The values must be lists. */
433
+ flat<V>(this: ListChain<Ctx, VexList<V>>, opts?: ListOpts): ListChain<Ctx, V>;
378
434
  /**
379
435
  * 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
436
  * fields of the record of the item. The chain of the body has no value of its own.
381
437
  */
382
- each<V>(body: (c: ChainOf<Ctx, null>) => ChainBase<Ctx, V>, opts?: AxisOpts<Ctx, null>): ListChain<Ctx, V>;
438
+ each<V>(body: (c: ChainOf<Ctx, null>) => AxisBody<Ctx, V>, opts?: AxisOpts<Ctx, null>): ListChain<Ctx, V>;
383
439
  /** The list at the origin `k`: one item for each target of the axis, with its key and its result. */
384
440
  result(k: Ctx["keys"]): Result<VexList<U>>;
385
441
  /** The list at the origin `k`, as an `Optional`. */
@@ -415,6 +471,11 @@ export interface Root<Ctx extends ChainContext> {
415
471
  ofPath<T>(k: Ctx["keys"], path: string): Arg<T>;
416
472
  /** This method makes a record argument from field arguments. */
417
473
  rec<const F extends Readonly<Record<string, unknown>>>(fields: F): Arg<{ readonly [N in keyof F]: ArgValue<Ctx, F[N]> }>;
474
+ /**
475
+ * This method makes a list literal (LIST.LITERAL, BUILD.LIST.LOOP): an item for each pair of a key and a value, in
476
+ * order. Without pairs, it gives the empty list. Thus a loop can start a stack or a seen set.
477
+ */
478
+ list<U = unknown>(items?: readonly (readonly [Ctx["keys"], U])[]): ListChain<Ctx, U>;
418
479
  /**
419
480
  * This method makes an extension argument: the node `ext(kind, data)`. The handler of `kind` in the options of
420
481
  * `withOptions` gives its value. The caller gives the type `T` of that value.
@@ -546,6 +607,12 @@ const kindOf = (u: unknown): unknown => (u as { kind?: unknown } | null | undefi
546
607
  const isArg = (u: unknown): u is Arg<unknown> => kindOf(u) === "vex.arg";
547
608
  const isChainLike = (u: unknown): u is { readonly program: Expr } => kindOf(u) === "vex.chain" || kindOf(u) === "vex.list-chain";
548
609
 
610
+ /** This function gives the expression of the list of `append` and `without`. The list is a chain, not a literal. */
611
+ function listProgram(op: string, other: unknown): Expr {
612
+ if (!isChainLike(other)) throw new TypeError(`${op} needs a list chain`);
613
+ return other.program;
614
+ }
615
+
549
616
  /** This function turns a builder argument into an expression. A bare string is a field reference at `addr`. */
550
617
  function toExpr(a: unknown, addr: readonly Move[]): Expr {
551
618
  if (typeof a === "string") return ref(toPath(a), addr);
@@ -694,16 +761,18 @@ class ChainImpl {
694
761
  * 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
762
  * It also gets its first value at the address of the chain, and a chain of its value.
696
763
  */
697
- loopNames(init: Readonly<Record<string, unknown>>): { readonly unique: ReadonlyMap<string, string>; readonly first: Readonly<Record<string, Expr>>; readonly vars: Readonly<Record<string, ChainImpl>> } {
764
+ loopNames(init: Readonly<Record<string, unknown>>): { readonly unique: ReadonlyMap<string, string>; readonly first: Readonly<Record<string, Expr>>; readonly vars: Readonly<Record<string, ChainImpl | ListChainImpl>> } {
698
765
  const depth = this.#s.depth;
699
766
  const unique = new Map<string, string>();
700
767
  const first: Record<string, Expr> = {};
701
- const vars: Record<string, ChainImpl> = {};
768
+ const vars: Record<string, ChainImpl | ListChainImpl> = {};
702
769
  for (const [n, a] of Object.entries(init)) {
703
770
  const name = `${n}$${depth}`;
704
771
  unique.set(n, name);
705
772
  first[name] = toExpr(a, this.#s.addr);
706
- vars[n] = new ChainImpl({ ...this.#s, expr: v(name), addr: [], depth: depth + 1 });
773
+ // A name of a list is a list chain, so a step can use the list ops on it (BUILD.LIST.LOOP).
774
+ const s: State = { ...this.#s, expr: v(name), addr: [], depth: depth + 1 };
775
+ vars[n] = kindOf(a) === "vex.list-chain" ? new ListChainImpl(s) : new ChainImpl(s);
707
776
  }
708
777
  return { unique, first, vars };
709
778
  }
@@ -711,14 +780,15 @@ class ChainImpl {
711
780
  iterate(
712
781
  limit: number,
713
782
  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 {
783
+ step: (vars: Readonly<Record<string, ChainImpl | ListChainImpl>>) => Readonly<Record<string, unknown>>,
784
+ result: (vars: Readonly<Record<string, ChainImpl | ListChainImpl>>) => unknown,
785
+ opts?: { readonly until?: (vars: Readonly<Record<string, ChainImpl | ListChainImpl>>) => unknown },
786
+ ): ChainImpl | ListChainImpl {
718
787
  const { unique, first, vars } = this.loopNames(init);
719
788
  const next = stepExprs(step(vars), unique, this.#s.addr);
720
789
  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) });
790
+ const r = result(vars);
791
+ return chainOf({ ...this.#s, expr: iterateExpr(limit, first, next, toExpr(r, this.#s.addr), until) }, r);
722
792
  }
723
793
 
724
794
  #axis(a: Axis, body: (c: ChainImpl) => { readonly program: Expr }, opts?: AxisOptsImpl): ListChainImpl {
@@ -769,6 +839,9 @@ class ChainImpl {
769
839
  }
770
840
  }
771
841
 
842
+ /** This function gives the chain of a loop: a list chain when its result is a list chain (BUILD.LIST.LOOP). */
843
+ const chainOf = (s: State, result: unknown): ChainImpl | ListChainImpl => (kindOf(result) === "vex.list-chain" ? new ListChainImpl(s) : new ChainImpl(s));
844
+
772
845
  /** This function gives the options of an evaluation of a chain or a list chain at the origin `k`. */
773
846
  function evalOptions(s: State, k: string): EvalOptions {
774
847
  const { env } = s;
@@ -794,9 +867,9 @@ class ListChainImpl {
794
867
  }
795
868
  fold(
796
869
  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 {
870
+ step: (vars: Readonly<Record<string, ChainImpl | ListChainImpl>>, item: ChainImpl) => Readonly<Record<string, unknown>>,
871
+ result: (vars: Readonly<Record<string, ChainImpl | ListChainImpl>>) => unknown,
872
+ ): ChainImpl | ListChainImpl {
800
873
  // 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
874
  // alone. The fold keeps the let, and the body of the axis is the item of each step.
802
875
  const e = this.#s.expr;
@@ -805,8 +878,9 @@ class ListChainImpl {
805
878
  const names = new ChainImpl({ ...this.#s, expr: lit(null) }).loopNames(init);
806
879
  const item = new ChainImpl({ ...this.#s, expr: loop.body, addr: [] });
807
880
  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 });
881
+ const r = result(names.vars);
882
+ const folded = foldExpr(loop.axis, names.first, next, toExpr(r, this.#s.addr), loop.at);
883
+ return chainOf({ ...this.#s, expr: e.tag === "let" ? let_(e.bind, folded) : folded }, r);
810
884
  }
811
885
 
812
886
  #op(op: string, extra: readonly Expr[], opts?: ListOpts & { readonly domain?: string }): ChainImpl {
@@ -865,6 +939,22 @@ class ListChainImpl {
865
939
  nth(i: number, opts?: ListOpts): ChainImpl {
866
940
  return this.#op("nth", [lit(i)], opts);
867
941
  }
942
+ get(k: string | { readonly program: Expr }, opts?: ListOpts): ChainImpl {
943
+ // A text is a key, not a field reference, as for the move to(k).
944
+ return this.#op("get", [typeof k === "string" ? lit(k) : k.program], opts);
945
+ }
946
+ drop(n: number, opts?: ListOpts): ListChainImpl {
947
+ return this.#list("drop", [lit(n)], opts);
948
+ }
949
+ append(other: unknown, opts?: ListOpts): ListChainImpl {
950
+ return this.#list("append", [listProgram("append", other)], opts);
951
+ }
952
+ without(other: unknown, opts?: ListOpts): ListChainImpl {
953
+ return this.#list("without", [listProgram("without", other)], opts);
954
+ }
955
+ flat(opts?: ListOpts): ListChainImpl {
956
+ return this.#list("flat", [], opts);
957
+ }
868
958
  each(body: (c: ChainImpl) => { readonly program: Expr }, opts?: AxisOptsImpl): ListChainImpl {
869
959
  // The chain of the body is at the key of the item, and it has no value of its own.
870
960
  const start = new ChainImpl({ ...this.#s, expr: lit(null), addr: [], depth: this.#s.depth + 1 });
@@ -927,6 +1017,10 @@ class RootImpl {
927
1017
  for (const [n, a] of Object.entries(fields)) out[n] = toExpr(a, []);
928
1018
  return argToken(rec(out));
929
1019
  }
1020
+ list(items: readonly (readonly [string, unknown])[] = []): ListChainImpl {
1021
+ // LIST.LITERAL: a literal of the list, with a value for each item.
1022
+ return new ListChainImpl({ env: this.#env, expr: lit(vexList(items.map(([key, value]) => ({ key, result: ok(value) })))), addr: [], depth: 0 });
1023
+ }
930
1024
  }
931
1025
 
932
1026
  class SheetRootImpl extends RootImpl {
package/src/deps.ts CHANGED
@@ -1,27 +1,12 @@
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
1
  /**
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.
2
+ * The static reads of a program (DEPS.READS). The static kit of coeval finds the references of the document of the
3
+ * program, by the contracts of Vex (`refsOf`). Vex adds only what is its own: the axes around a read, and the reads of
4
+ * a function at each of its calls (FN.CALL).
16
5
  */
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
- }
6
+ import { pathMatches, refsOf, type DocVisit, type Key, type RefUse } from "@mark1russell7/coeval";
7
+ import type { Addr, Axis, Expr, ExprOf } from "./ir.ts";
8
+ import { VEX_WORLD } from "./kernel.ts";
9
+ import { writeDocument } from "./write.ts";
25
10
 
26
11
  /** One static read of a program: a field path at an address, inside zero or more axes. */
27
12
  export interface Dependency {
@@ -35,50 +20,179 @@ export interface Dependency {
35
20
  readonly axisAt: readonly Addr[];
36
21
  }
37
22
 
23
+ /** An axis around a read: the kind of the axis of a loop, and the address of the loop. */
24
+ interface Around {
25
+ readonly t: Axis["t"];
26
+ readonly at: Addr;
27
+ }
28
+
29
+ /** A chain of items, the innermost first. The chains of two documents share the items of the documents around both. */
30
+ interface Chain<T> {
31
+ readonly item: T;
32
+ readonly up: Chain<T> | undefined;
33
+ }
34
+
35
+ /** The context of a document for its reads. */
36
+ interface Context {
37
+ /** The axes around the document, the innermost first. */
38
+ readonly axes: Chain<Around> | undefined;
39
+ /** Inside the axis document of a loop: the axis of that loop. A test of `where` there is inside the axis. */
40
+ readonly axis: Around | undefined;
41
+ /** The nearest function around the document: a binding of a let. Its reads happen at its calls, not here. */
42
+ readonly fn: DocVisit | undefined;
43
+ /** The calls around the document whose function is a binding of a let, the innermost first. */
44
+ readonly calls: Chain<DocVisit> | undefined;
45
+ }
46
+
47
+ const ROOT: Context = { axes: undefined, axis: undefined, fn: undefined, calls: undefined };
48
+
49
+ /** This function gives the items of a chain until the chain `end`, from the outside to the inside. */
50
+ function itemsUntil<T>(chain: Chain<T> | undefined, end: Chain<T> | undefined): T[] {
51
+ const out: T[] = [];
52
+ for (let c = chain; c !== undefined && c !== end; c = c.up) out.push(c.item);
53
+ return out.toReversed();
54
+ }
55
+
56
+ /** This function gives the kind of a visit, as its keys joined with dots, for example `each` or `axes.where`. */
57
+ // Stryker disable next-line ArrayDeclaration: each document of the writer has a type of the world, so each visit has a type path
58
+ const kindOf = (v: DocVisit): string => (v.typePath ?? []).join(".");
59
+
38
60
  /**
39
- * This function gives the static reads of an expression. A host can use them to recompute a program only
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).
61
+ * This function gives the static reads of an expression. A host can use them to recompute a program only when a field
62
+ * that it reads changes. A computed move reads a key that only a run knows. Its address keeps the expression, and the
63
+ * reads of that expression are in the list too (DEPS.COMPUTED). The kernel walks the document with a stack, so an
64
+ * expression of any depth works (EVAL.NESTING).
42
65
  */
43
66
  export function deps(e: Expr): readonly Dependency[] {
44
- const out: Dependency[] = [];
45
- // A stack, not recursion, so a deep expression needs no deep call stack. The children go on the stack in reverse
46
- // order, so the reads come out in the order of a depth-first walk.
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() }];
49
- for (let item = todo.pop(); item !== undefined; item = todo.pop()) {
50
- const { x } = item;
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;
67
+ const nodes = new Map<object, Expr>();
68
+ // The order "reads" puts the body or the steps of a loop before its axis, as the reads of an evaluation come.
69
+ const doc = writeDocument(e, {
70
+ // Stryker disable next-line ArrayDeclaration: the reads come from the references, not from the form of a literal
71
+ domains: [],
72
+ // Stryker disable next-line StringLiteral: the writer tests only the mode "json", and each other mode keeps the value
73
+ literals: "host",
74
+ order: "reads",
75
+ nodes,
76
+ });
77
+ const uses = refsOf(VEX_WORLD, doc);
78
+ const memo = new WeakMap<DocVisit, Context>();
79
+ const functions = new WeakMap<DocVisit, DocVisit | null>();
80
+ const fnVisits = new Map<unknown, DocVisit>();
81
+
82
+ /** This function gives the function of a call: the visit of the binding of a let, or `undefined` (FN.CALL). */
83
+ const functionOf = (call: DocVisit): DocVisit | undefined => {
84
+ const known = functions.get(call);
85
+ if (known !== undefined) return known ?? undefined;
86
+ const name = (call.doc.value as { readonly fn: { readonly value: readonly [string, string] } }).fn.value[1];
87
+ let found: DocVisit | undefined;
88
+ // The innermost kind that binds the name decides. A parameter, a binding or a name of a loop hides a function.
89
+ search: for (let child: DocVisit = call, around = call.parent; around !== undefined; child = around, around = around.parent) {
90
+ // Stryker disable next-line OptionalChaining: each document around a call is a term or a function, so it has a kind
91
+ for (const rule of around.kind?.scope ?? []) {
92
+ if (!rule.in.some((pattern) => pathMatches(child.slot, pattern))) continue;
93
+ const source = rule.names as { readonly keysAt?: readonly Key[]; readonly listAt?: readonly Key[] };
94
+ // Stryker disable next-line ArrayDeclaration: each rule of the scopes of Vex gives its names with keysAt or listAt
95
+ const at = (source.keysAt ?? source.listAt ?? []).reduce<unknown>((x, k) => (x as Readonly<Record<string, unknown>>)[String(k)], around.doc.value);
96
+ const names = source.keysAt !== undefined ? Object.keys(at as object) : (at as readonly string[]);
97
+ if (!names.includes(name)) continue;
98
+ // Only a binding of a let is a function (FN.BIND), and the map has only the documents of the functions.
99
+ found = fnVisits.get((at as Readonly<Record<string, unknown>>)[name]);
100
+ break search;
101
+ }
60
102
  }
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;
103
+ functions.set(call, found ?? null);
104
+ return found;
105
+ };
106
+
107
+ /** This function gives the context of a child from the context of its parent. */
108
+ const step = (outer: Context, parent: DocVisit, child: DocVisit): Context => {
109
+ const kind = kindOf(parent);
110
+ const head = child.slot[0];
111
+ let { axes, fn, calls } = outer;
112
+ let axis: Around | undefined;
113
+ if (outer.axis !== undefined) {
114
+ // In the axis document of a loop: a test of where is inside the axis, and the list of the axis list is outside.
115
+ // Only the axis where has a test.
116
+ if (head === "test") axes = { item: outer.axis, up: axes };
117
+ else if (head === "axis") axis = outer.axis;
118
+ } else if (kind === "each" || kind === "fold") {
119
+ const node = nodes.get(parent.doc) as ExprOf<"each" | "fold">;
120
+ const around: Around = { t: node.axis.t, at: node.at ?? [] };
121
+ if (head === "body" || head === "step") axes = { item: around, up: axes };
122
+ else if (head === "axis") axis = around;
66
123
  }
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) });
124
+ if (kind === "fn") {
125
+ fn = parent;
126
+ fnVisits.set(parent.doc, parent);
81
127
  }
128
+ // Each call goes in the chain, also a call of a name that is not a function: inCall looks for one call of a function.
129
+ if (kind === "call") calls = { item: parent, up: calls };
130
+ return { axes, axis, fn, calls };
131
+ };
132
+
133
+ /**
134
+ * This function gives the context of a visit. It walks up to a known context with a loop, not with recursion. The
135
+ * context of no visit is the context of the root.
136
+ */
137
+ const contextOf = (v: DocVisit | undefined): Context => {
138
+ const todo: DocVisit[] = [];
139
+ let x: DocVisit | undefined = v;
140
+ while (x !== undefined && !memo.has(x)) {
141
+ todo.push(x);
142
+ x = x.parent;
143
+ }
144
+ let ctx = x === undefined ? ROOT : (memo.get(x) as Context);
145
+ for (let i = todo.length - 1; i >= 0; i--) {
146
+ const child = todo[i] as DocVisit;
147
+ ctx = child.parent === undefined ? ROOT : step(ctx, child.parent, child);
148
+ memo.set(child, ctx);
149
+ }
150
+ return ctx;
151
+ };
152
+
153
+ // The references of each function, apart from the others: they read at each call of the function.
154
+ const groups = new Map<DocVisit | undefined, RefUse[]>();
155
+ for (const use of uses) {
156
+ const fn = contextOf(use.visit).fn;
157
+ const group = groups.get(fn) ?? [];
158
+ group.push(use);
159
+ groups.set(fn, group);
82
160
  }
161
+
162
+ const out: Dependency[] = [];
163
+ /** This function gives the reads of the references of a function at a call, inside the axes of the call. */
164
+ const emit = (group: readonly RefUse[], base: DocVisit | undefined, outside: readonly Around[]): void => {
165
+ const baseAxes = contextOf(base).axes;
166
+ const inside = (v: DocVisit): readonly Around[] => [...outside, ...itemsUntil(contextOf(v).axes, baseAxes)];
167
+ // The reads of a call come after the reads of its arguments, so a call waits until the walk leaves it.
168
+ const pending: { readonly call: DocVisit; readonly fn: DocVisit; readonly axes: readonly Around[] }[] = [];
169
+ const inCall = (v: DocVisit | undefined, call: DocVisit): boolean => {
170
+ for (let c = contextOf(v).calls; c !== undefined && c.item.depth >= call.depth; c = c.up) if (c.item === call) return true;
171
+ return false;
172
+ };
173
+ const flush = (until?: DocVisit): void => {
174
+ for (;;) {
175
+ const top = pending.at(-1);
176
+ if (top === undefined || inCall(until, top.call)) return;
177
+ pending.pop();
178
+ emit(groups.get(top.fn) ?? [], top.fn, top.axes);
179
+ }
180
+ };
181
+ for (const use of group) {
182
+ flush(use.visit);
183
+ if (use.root === "self" && !use.address) {
184
+ const node = nodes.get(use.visit.doc) as ExprOf<"ref">;
185
+ const axes = inside(use.visit);
186
+ out.push({ at: node.at ?? [], path: node.path, axes: axes.map((a) => a.t), axisAt: axes.map((a) => a.at) });
187
+ }
188
+ const call = use.visit.parent;
189
+ if (call !== undefined && kindOf(call) === "call" && use.visit.slot[0] === "fn") {
190
+ const fn = functionOf(call);
191
+ if (fn !== undefined) pending.push({ call, fn, axes: inside(call) });
192
+ }
193
+ }
194
+ flush();
195
+ };
196
+ emit(groups.get(undefined) ?? [], undefined, []);
83
197
  return out;
84
198
  }