@mark1russell7/vex 0.13.4 → 0.15.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.13.4",
4
+ "version": "0.15.0",
5
5
  "description": "Vex: typed spreadsheet formulas over domain objects. The kernel and the typed builder.",
6
6
  "keywords": [
7
7
  "typescript",
@@ -49,7 +49,7 @@
49
49
  "access": "public"
50
50
  },
51
51
  "dependencies": {
52
- "@mark1russell7/coeval": "^0.8.0"
52
+ "@mark1russell7/coeval": "^0.9.0"
53
53
  },
54
54
  "devDependencies": {
55
55
  "@mark1russell7/cue": "github:mark1russell7/cue",
package/src/builder.ts CHANGED
@@ -5,7 +5,7 @@
5
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, 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";
8
+ import { app, call as callExpr, children, each, ext, fn as fnExpr, fold as foldExpr, index as indexMove, iterate as iterateExpr, key as keyMove, let_, lit, listOf, offset as offsetMove, other as otherMove, origin as originMove, parent as parentMove, rec, ref, toPath, v, type Axis, type Expr, type FixedMove, type ItemNames, type Move } from "./ir.ts";
9
9
  import { cell as cellRef, SheetRun, type CellFormulas } from "./sheet.ts";
10
10
  import { ok, toOptional, type Optional, type Result } from "./result.ts";
11
11
  import type { Space } from "./space.ts";
@@ -385,16 +385,17 @@ export interface ListChain<Ctx extends ChainContext, U> {
385
385
  readonly program: Expr;
386
386
  /**
387
387
  * This method folds the items in the order of the axis (FOLD.ORDER). `init` gives the names and their first values.
388
- * `step` gives the next values from the names and the item, a chain at the target. `result` gives the value.
388
+ * `step` gives the next values from the names and the item, a chain at the target. `result` gives the value. In a
389
+ * fold over the axis `list`, `step` also gets the index of the item (BUILD.LIST.ITEM).
389
390
  */
390
391
  fold<const I extends Readonly<Record<string, unknown>>, V>(
391
392
  init: I,
392
- step: (vars: LoopVars<Ctx, I>, item: ChainOf<Ctx, U>) => NoInfer<LoopStep<Ctx, I>>,
393
+ step: (vars: LoopVars<Ctx, I>, item: ChainOf<Ctx, U>, index: ChainOf<Ctx, number>) => NoInfer<LoopStep<Ctx, I>>,
393
394
  result: (vars: LoopVars<Ctx, I>) => ListChain<Ctx, V>,
394
395
  ): ListChain<Ctx, V>;
395
396
  fold<const I extends Readonly<Record<string, unknown>>, R>(
396
397
  init: I,
397
- step: (vars: LoopVars<Ctx, I>, item: ChainOf<Ctx, U>) => NoInfer<LoopStep<Ctx, I>>,
398
+ step: (vars: LoopVars<Ctx, I>, item: ChainOf<Ctx, U>, index: ChainOf<Ctx, number>) => NoInfer<LoopStep<Ctx, I>>,
398
399
  result: (vars: LoopVars<Ctx, I>) => ArgInput<R, Ctx, false>,
399
400
  ): ChainOf<Ctx, R>;
400
401
  count(opts?: ListOpts): ChainOf<Ctx, number>;
@@ -431,11 +432,21 @@ export interface ListChain<Ctx extends ChainContext, U> {
431
432
  without<V>(other: ListChain<Ctx, V>, opts?: ListOpts): ListChain<Ctx, U>;
432
433
  /** The items of the lists that are the values of the items, in order (LIST.FLAT). The values must be lists. */
433
434
  flat<V>(this: ListChain<Ctx, VexList<V>>, opts?: ListOpts): ListChain<Ctx, V>;
435
+ /** The first item of each value, in the order of the list (LIST.DISTINCT). The values are numbers, texts or booleans. */
436
+ distinct(opts?: ListOpts): ListChain<Ctx, U>;
437
+ /**
438
+ * The groups of the items by the text keys of `keys` (LIST.GROUP). The key at a position is the key of the item at
439
+ * the same position. Each key gives one item, and its value is the list of its items (BUILD.LIST.GROUP).
440
+ */
441
+ group(keys: ListChain<Ctx, string>, opts?: ListOpts): ListChain<Ctx, VexList<U>>;
442
+ /** The texts of the items with the text `sep` between them (LIST.JOIN). A chain of a text gives the separator. */
443
+ join(this: ListChain<Ctx, string>, sep: string | ChainBase<Ctx, string>, opts?: ListOpts): ChainOf<Ctx, string>;
434
444
  /**
435
445
  * The axis list (AXIS.LIST): the body evaluates at the key of each item, in the order of the list. The body reads the
436
- * fields of the record of the item. The chain of the body has no value of its own.
446
+ * fields of the record of the item. The chain of the body has no value of its own. The body also gets a chain of the
447
+ * value of the item and a chain of its index, from 0 (BUILD.LIST.ITEM).
437
448
  */
438
- each<V>(body: (c: ChainOf<Ctx, null>) => AxisBody<Ctx, V>, opts?: AxisOpts<Ctx, null>): ListChain<Ctx, V>;
449
+ each<V>(body: (c: ChainOf<Ctx, null>, item: ChainOf<Ctx, U>, index: ChainOf<Ctx, number>) => AxisBody<Ctx, V>, opts?: AxisOpts<Ctx, null>): ListChain<Ctx, V>;
439
450
  /** The list at the origin `k`: one item for each target of the axis, with its key and its result. */
440
451
  result(k: Ctx["keys"]): Result<VexList<U>>;
441
452
  /** The list at the origin `k`, as an `Optional`. */
@@ -632,6 +643,41 @@ function stepExprs(step: Readonly<Record<string, unknown>>, unique: ReadonlyMap<
632
643
  return out;
633
644
  }
634
645
 
646
+ /**
647
+ * The number of the open bodies of `each` and steps of `fold` of a list chain. The names `as` of a loop end with this
648
+ * number, so a loop inside a body has other names than the loop around it (BUILD.LIST.ITEM).
649
+ */
650
+ let itemDepth = 0;
651
+
652
+ /** This function gives the value of `build`, with the next number for the names `as` inside it. */
653
+ function inItemLoop<T>(build: () => T): T {
654
+ itemDepth += 1;
655
+ try {
656
+ return build();
657
+ } finally {
658
+ itemDepth -= 1;
659
+ }
660
+ }
661
+
662
+ /** This function tells if the expression reads the name, in one of its parts. It uses a stack, not recursion. */
663
+ function reads(e: Expr, name: string): boolean {
664
+ const todo: Expr[] = [e];
665
+ for (let x = todo.pop(); x !== undefined; x = todo.pop()) {
666
+ if (x.tag === "var" && x.name === name) return true;
667
+ todo.push(...children(x));
668
+ }
669
+ return false;
670
+ }
671
+
672
+ /**
673
+ * This function gives the names `as` of a fold whose step reads the index. The axis must be `list`. The name of the item
674
+ * of the loop of `each` stays, so the item of the step keeps its value (BUILD.LIST.ITEM).
675
+ */
676
+ function foldItemNames(loop: { readonly axis: Axis; readonly as?: ItemNames }, index: string): ItemNames {
677
+ if (listOf(loop.axis) === undefined) throw new TypeError("the index of a fold needs the axis list: go over the items of a list with each first");
678
+ return [loop.as?.[0] ?? `$item${itemDepth}`, index];
679
+ }
680
+
635
681
  const PROXY_RESERVED = new Set(["then", "catch", "finally", "toJSON", "valueOf", "toString", "constructor", "inspect", "asymmetricMatch", "$$typeof", "nodeType"]);
636
682
 
637
683
  class ChainImpl {
@@ -867,7 +913,7 @@ class ListChainImpl {
867
913
  }
868
914
  fold(
869
915
  init: Readonly<Record<string, unknown>>,
870
- step: (vars: Readonly<Record<string, ChainImpl | ListChainImpl>>, item: ChainImpl) => Readonly<Record<string, unknown>>,
916
+ step: (vars: Readonly<Record<string, ChainImpl | ListChainImpl>>, item: ChainImpl, index: ChainImpl) => Readonly<Record<string, unknown>>,
871
917
  result: (vars: Readonly<Record<string, ChainImpl | ListChainImpl>>) => unknown,
872
918
  ): ChainImpl | ListChainImpl {
873
919
  // 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
@@ -877,9 +923,12 @@ class ListChainImpl {
877
923
  if (loop.tag !== "each") throw new TypeError("fold needs the list of an axis: go over the items of the list with each first");
878
924
  const names = new ChainImpl({ ...this.#s, expr: lit(null) }).loopNames(init);
879
925
  const item = new ChainImpl({ ...this.#s, expr: loop.body, addr: [] });
880
- const next = stepExprs(step(names.vars, item), names.unique, []);
926
+ // The names as of the loop of each stay. A step that reads the index adds a name for it (BUILD.LIST.ITEM).
927
+ const index = loop.as?.[1] ?? `$index${itemDepth}`;
928
+ const next = stepExprs(inItemLoop(() => step(names.vars, item, new ChainImpl({ ...this.#s, expr: v(index), addr: [] }))), names.unique, []);
929
+ const as = Object.values(next).some((x) => reads(x, index)) ? foldItemNames(loop, index) : loop.as;
881
930
  const r = result(names.vars);
882
- const folded = foldExpr(loop.axis, names.first, next, toExpr(r, this.#s.addr), loop.at);
931
+ const folded = foldExpr(loop.axis, names.first, next, toExpr(r, this.#s.addr), loop.at, as);
883
932
  return chainOf({ ...this.#s, expr: e.tag === "let" ? let_(e.bind, folded) : folded }, r);
884
933
  }
885
934
 
@@ -955,13 +1004,27 @@ class ListChainImpl {
955
1004
  flat(opts?: ListOpts): ListChainImpl {
956
1005
  return this.#list("flat", [], opts);
957
1006
  }
958
- each(body: (c: ChainImpl) => { readonly program: Expr }, opts?: AxisOptsImpl): ListChainImpl {
959
- // The chain of the body is at the key of the item, and it has no value of its own.
960
- const start = new ChainImpl({ ...this.#s, expr: lit(null), addr: [], depth: this.#s.depth + 1 });
1007
+ distinct(opts?: ListOpts): ListChainImpl {
1008
+ return this.#list("distinct", [], opts);
1009
+ }
1010
+ group(keys: unknown, opts?: ListOpts): ListChainImpl {
1011
+ return this.#list("group", [listProgram("group", keys)], opts);
1012
+ }
1013
+ join(sep: string | { readonly program: Expr }, opts?: ListOpts): ChainImpl {
1014
+ return this.#op("join", [typeof sep === "string" ? lit(sep) : sep.program], opts);
1015
+ }
1016
+ each(body: (c: ChainImpl, item: ChainImpl, index: ChainImpl) => { readonly program: Expr }, opts?: AxisOptsImpl): ListChainImpl {
1017
+ // The chains of the body are at the key of the item. The chain of the body has no value of its own.
1018
+ const inner: State = { ...this.#s, addr: [], depth: this.#s.depth + 1 };
1019
+ const start = new ChainImpl({ ...inner, expr: lit(null) });
961
1020
  const list: Axis = { t: "list", list: this.#s.expr };
962
1021
  const ordered: Axis = opts?.reverse === true ? { t: "reverse", axis: list } : list;
963
1022
  const axis: Axis = opts?.where === undefined ? ordered : { t: "where", axis: ordered, test: opts.where(start).program };
964
- return new ListChainImpl({ ...this.#s, expr: each(axis, body(start).program) });
1023
+ const names = [`$item${itemDepth}`, `$index${itemDepth}`] as const;
1024
+ const program = inItemLoop(() => body(start, new ChainImpl({ ...inner, expr: v(names[0]) }), new ChainImpl({ ...inner, expr: v(names[1]) })).program);
1025
+ // BUILD.LIST.ITEM: the field as has only the names that the body reads.
1026
+ const as: ItemNames | undefined = reads(program, names[1]) ? names : reads(program, names[0]) ? [names[0]] : undefined;
1027
+ return new ListChainImpl({ ...this.#s, expr: each(axis, program, undefined, as) });
965
1028
  }
966
1029
  result(k: string): Result<unknown> {
967
1030
  return evaluate(this.#s.expr, evalOptions(this.#s, k));
package/src/checked.ts ADDED
@@ -0,0 +1,6 @@
1
+ /**
2
+ * The cache of the lists that passed the check of LIST.SHAPE. `isVexList` adds each frozen list that passes its check.
3
+ * The interpreter adds each list that it makes from the items of such lists, because these items passed the check.
4
+ * The package index does not export this module.
5
+ */
6
+ export const CHECKED: WeakSet<object> = new WeakSet<object>();
package/src/deps.ts CHANGED
@@ -93,7 +93,9 @@ export function deps(e: Expr): readonly Dependency[] {
93
93
  const source = rule.names as { readonly keysAt?: readonly Key[]; readonly listAt?: readonly Key[] };
94
94
  // Stryker disable next-line ArrayDeclaration: each rule of the scopes of Vex gives its names with keysAt or listAt
95
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[]);
96
+ // A loop without the names `as` of its items has no list there (AXIS.LIST.SCOPE).
97
+ // Stryker disable next-line ArrayDeclaration: a name that no program binds does not hide a function
98
+ const names = source.keysAt !== undefined ? Object.keys(at as object) : ((at as readonly string[] | undefined) ?? []);
97
99
  if (!names.includes(name)) continue;
98
100
  // Only a binding of a let is a function (FN.BIND), and the map has only the documents of the functions.
99
101
  found = fnVisits.get((at as Readonly<Record<string, unknown>>)[name]);
package/src/document.ts CHANGED
@@ -13,26 +13,29 @@
13
13
  * | `fn` | `{ "type": "fn", "value": { "params", "body" } }` |
14
14
  * | `call` | `{ "type": "call", "value": { "fn": { "type": "ref", "value": ["names", name] }, "args" } }` |
15
15
  * | `rec` | `{ "type": "record", "value": { ...fields } }` |
16
- * | `each` | `{ "type": "each", "value": { "axis", "body", "at"? } }` |
17
- * | `fold` | `{ "type": "fold", "value": { "axis", "init", "step", "result", "at"? } }` |
16
+ * | `each` | `{ "type": "each", "value": { "axis", "as"?, "body", "at"? } }` |
17
+ * | `fold` | `{ "type": "fold", "value": { "axis", "as"?, "init", "step", "result", "at"? } }` |
18
18
  * | `iterate` | `{ "type": "iterate", "value": { "limit", "init", "step", "until"?, "result" } }` |
19
19
  * | `ext` | `{ "type": ["ext", ...keys], "value": data }` |
20
20
  * | a move | `{ "type": ["moves", kind], "value": v }` |
21
21
  * | an axis | `{ "type": ["axes", name], "value": { ...parameters } }` |
22
22
  *
23
23
  * The address `at` of `each` and `fold` is a reference from `self` with moves only. An empty address is no address.
24
+ * The field `as` of `each` and `fold` names the item of a loop over the axis `list`, and then its index (AXIS.LIST.SCOPE).
24
25
  *
25
26
  * The kernel checks a document by the contracts of `VEX_WORLD` (DOC.CHECK). A contract gives the shape of a kind, the
26
27
  * data of its fields and the kinds of each position. Then `fromDocument` reads the expression. It checks only the grammar
27
- * of Vex: the steps of a reference, the address, the function of a call and the names of a loop.
28
+ * of Vex: the steps of a reference, the address, the function of a call and the names of a loop. It also checks the
29
+ * names of the items.
28
30
  */
29
31
  import { check, isEnvelope, typeName, typePath, type Envelope, type Issue, type Key, type Machine } from "@mark1russell7/coeval";
30
32
  import { decodeValue } from "./codec.ts";
31
33
  import type { AnyDomain } from "./domain.ts";
32
34
  import { isStackOverflow, vexError, type VexError } from "./errors.ts";
33
- import { app, call, each, ext, fn, fold, index, iterate, key, let_, lit, offset, origin, other, parent, rec, ref, shapeError, v, type Addr, type Axis, type Expr, type Move, type Names } from "./ir.ts";
35
+ import { app, call, each, ext, fn, fold, index, iterate, key, let_, lit, offset, origin, other, parent, rec, ref, shapeError, v, type Addr, type Axis, type Expr, type ItemNames, type Move, type Names } from "./ir.ts";
34
36
  import { MAX_DOCUMENT_DEPTH, TERM_KINDS, vexChecker } from "./kernel.ts";
35
37
  import { fail, ok, type Result } from "./result.ts";
38
+ import { itemNamesError } from "./item-names.ts";
36
39
  import { WriteStop, writeDocument, type WriteOptions } from "./write.ts";
37
40
 
38
41
  export type { Envelope, Json } from "@mark1russell7/coeval";
@@ -169,11 +172,16 @@ class Reader {
169
172
  }
170
173
  case "record":
171
174
  return rec(this.#names(u.value, at));
172
- case "each":
173
- return each(this.#axis(f["axis"] as Envelope, into(at, "axis")), this.term(f["body"], into(at, "body")), this.#address(f["at"], into(at, "at")));
175
+ case "each": {
176
+ const axis = this.#axis(f["axis"] as Envelope, into(at, "axis"));
177
+ const as = this.#items(f, axis, at);
178
+ return each(axis, this.term(f["body"], into(at, "body")), this.#address(f["at"], into(at, "at")), as);
179
+ }
174
180
  case "fold": {
175
181
  const [init, step] = this.#loop(f, at);
176
- return fold(this.#axis(f["axis"] as Envelope, into(at, "axis")), init, step, this.term(f["result"], into(at, "result")), this.#address(f["at"], into(at, "at")));
182
+ const axis = this.#axis(f["axis"] as Envelope, into(at, "axis"));
183
+ const as = this.#items(f, axis, at);
184
+ return fold(axis, init, step, this.term(f["result"], into(at, "result")), this.#address(f["at"], into(at, "at")), as);
177
185
  }
178
186
  default: {
179
187
  // iterate: the contract gives a whole number from 0 to MAX_ITERATIONS for the limit (ITERATE.LIMIT).
@@ -228,6 +236,15 @@ class Reader {
228
236
  return extra === undefined ? [init, step] : bad(into(into(at, "step"), extra), `the name "${extra}" of step is not a name of init`);
229
237
  }
230
238
 
239
+ /**
240
+ * This method reads the names `as` of a loop (AXIS.LIST.SCOPE). The contract gives a list of distinct texts. The
241
+ * grammar of Vex needs one or two names, the axis `list` and no name of `init`.
242
+ */
243
+ #items(f: Readonly<Record<string, unknown>>, axis: Axis, at: string): ItemNames | undefined {
244
+ const reason = itemNamesError({ as: f["as"], axis, init: f["init"] });
245
+ return reason === undefined ? (f["as"] as ItemNames | undefined) : bad(into(at, "as"), reason);
246
+ }
247
+
231
248
  /** This method reads a reference: the fields of `self` after its moves, or a name of `names` (DOC.REF). */
232
249
  #ref(path: readonly unknown[], where: string): Expr {
233
250
  const [root, ...steps] = path;