@mark1russell7/vex 0.13.3 → 0.14.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.3",
4
+ "version": "0.14.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.7.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>;
@@ -433,9 +434,10 @@ export interface ListChain<Ctx extends ChainContext, U> {
433
434
  flat<V>(this: ListChain<Ctx, VexList<V>>, opts?: ListOpts): ListChain<Ctx, V>;
434
435
  /**
435
436
  * 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.
437
+ * 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
438
+ * value of the item and a chain of its index, from 0 (BUILD.LIST.ITEM).
437
439
  */
438
- each<V>(body: (c: ChainOf<Ctx, null>) => AxisBody<Ctx, V>, opts?: AxisOpts<Ctx, null>): ListChain<Ctx, V>;
440
+ 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
441
  /** The list at the origin `k`: one item for each target of the axis, with its key and its result. */
440
442
  result(k: Ctx["keys"]): Result<VexList<U>>;
441
443
  /** The list at the origin `k`, as an `Optional`. */
@@ -632,6 +634,41 @@ function stepExprs(step: Readonly<Record<string, unknown>>, unique: ReadonlyMap<
632
634
  return out;
633
635
  }
634
636
 
637
+ /**
638
+ * 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
639
+ * number, so a loop inside a body has other names than the loop around it (BUILD.LIST.ITEM).
640
+ */
641
+ let itemDepth = 0;
642
+
643
+ /** This function gives the value of `build`, with the next number for the names `as` inside it. */
644
+ function inItemLoop<T>(build: () => T): T {
645
+ itemDepth += 1;
646
+ try {
647
+ return build();
648
+ } finally {
649
+ itemDepth -= 1;
650
+ }
651
+ }
652
+
653
+ /** This function tells if the expression reads the name, in one of its parts. It uses a stack, not recursion. */
654
+ function reads(e: Expr, name: string): boolean {
655
+ const todo: Expr[] = [e];
656
+ for (let x = todo.pop(); x !== undefined; x = todo.pop()) {
657
+ if (x.tag === "var" && x.name === name) return true;
658
+ todo.push(...children(x));
659
+ }
660
+ return false;
661
+ }
662
+
663
+ /**
664
+ * This function gives the names `as` of a fold whose step reads the index. The axis must be `list`. The name of the item
665
+ * of the loop of `each` stays, so the item of the step keeps its value (BUILD.LIST.ITEM).
666
+ */
667
+ function foldItemNames(loop: { readonly axis: Axis; readonly as?: ItemNames }, index: string): ItemNames {
668
+ 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");
669
+ return [loop.as?.[0] ?? `$item${itemDepth}`, index];
670
+ }
671
+
635
672
  const PROXY_RESERVED = new Set(["then", "catch", "finally", "toJSON", "valueOf", "toString", "constructor", "inspect", "asymmetricMatch", "$$typeof", "nodeType"]);
636
673
 
637
674
  class ChainImpl {
@@ -867,7 +904,7 @@ class ListChainImpl {
867
904
  }
868
905
  fold(
869
906
  init: Readonly<Record<string, unknown>>,
870
- step: (vars: Readonly<Record<string, ChainImpl | ListChainImpl>>, item: ChainImpl) => Readonly<Record<string, unknown>>,
907
+ step: (vars: Readonly<Record<string, ChainImpl | ListChainImpl>>, item: ChainImpl, index: ChainImpl) => Readonly<Record<string, unknown>>,
871
908
  result: (vars: Readonly<Record<string, ChainImpl | ListChainImpl>>) => unknown,
872
909
  ): ChainImpl | ListChainImpl {
873
910
  // 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 +914,12 @@ class ListChainImpl {
877
914
  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
915
  const names = new ChainImpl({ ...this.#s, expr: lit(null) }).loopNames(init);
879
916
  const item = new ChainImpl({ ...this.#s, expr: loop.body, addr: [] });
880
- const next = stepExprs(step(names.vars, item), names.unique, []);
917
+ // The names as of the loop of each stay. A step that reads the index adds a name for it (BUILD.LIST.ITEM).
918
+ const index = loop.as?.[1] ?? `$index${itemDepth}`;
919
+ const next = stepExprs(inItemLoop(() => step(names.vars, item, new ChainImpl({ ...this.#s, expr: v(index), addr: [] }))), names.unique, []);
920
+ const as = Object.values(next).some((x) => reads(x, index)) ? foldItemNames(loop, index) : loop.as;
881
921
  const r = result(names.vars);
882
- const folded = foldExpr(loop.axis, names.first, next, toExpr(r, this.#s.addr), loop.at);
922
+ const folded = foldExpr(loop.axis, names.first, next, toExpr(r, this.#s.addr), loop.at, as);
883
923
  return chainOf({ ...this.#s, expr: e.tag === "let" ? let_(e.bind, folded) : folded }, r);
884
924
  }
885
925
 
@@ -955,13 +995,18 @@ class ListChainImpl {
955
995
  flat(opts?: ListOpts): ListChainImpl {
956
996
  return this.#list("flat", [], opts);
957
997
  }
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 });
998
+ each(body: (c: ChainImpl, item: ChainImpl, index: ChainImpl) => { readonly program: Expr }, opts?: AxisOptsImpl): ListChainImpl {
999
+ // The chains of the body are at the key of the item. The chain of the body has no value of its own.
1000
+ const inner: State = { ...this.#s, addr: [], depth: this.#s.depth + 1 };
1001
+ const start = new ChainImpl({ ...inner, expr: lit(null) });
961
1002
  const list: Axis = { t: "list", list: this.#s.expr };
962
1003
  const ordered: Axis = opts?.reverse === true ? { t: "reverse", axis: list } : list;
963
1004
  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) });
1005
+ const names = [`$item${itemDepth}`, `$index${itemDepth}`] as const;
1006
+ const program = inItemLoop(() => body(start, new ChainImpl({ ...inner, expr: v(names[0]) }), new ChainImpl({ ...inner, expr: v(names[1]) })).program);
1007
+ // BUILD.LIST.ITEM: the field as has only the names that the body reads.
1008
+ const as: ItemNames | undefined = reads(program, names[1]) ? names : reads(program, names[0]) ? [names[0]] : undefined;
1009
+ return new ListChainImpl({ ...this.#s, expr: each(axis, program, undefined, as) });
965
1010
  }
966
1011
  result(k: string): Result<unknown> {
967
1012
  return evaluate(this.#s.expr, evalOptions(this.#s, k));
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;
package/src/evaluate.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { fromDocument, isDocument, type Envelope } from "./document.ts";
2
2
  import { liftsAt, resolveOp, type AnyDomain, type ParamKind, type ResolvedOp } from "./domain.ts";
3
3
  import { formatError, isDepthError, isStackOverflow, vexError, type ErrorKind, type VexError } from "./errors.ts";
4
- import { addrExprs, children, shapeError, type Addr, type Axis, type Expr, type ExprOf, type FixedMove, type Move } from "./ir.ts";
4
+ import { addrExprs, children, shapeError, type Addr, type Axis, type Expr, type ExprOf, type FixedMove, type ItemNames, type Move } from "./ir.ts";
5
5
  import { asList, fillList, isFillCount, isIndexValue, listOfArray } from "./array-list.ts";
6
6
  import { isListOp, isVexList, vexList, type ListItem, type ListOp, type ListOptions, type VexList } from "./list.ts";
7
7
  import { fail, ok, type Result } from "./result.ts";
@@ -185,6 +185,33 @@ const baseAxis = (a: Axis): Exclude<Axis, { readonly t: "where" }> => (a.t === "
185
185
  /** A compiled node: it evaluates in a frame of a run. */
186
186
  type Node = (f: Frame, c: Ctx) => Result<unknown>;
187
187
 
188
+ /**
189
+ * A target of an axis: its key, and the error of a test of `where` or of an error item. A target of the axis `list` also
190
+ * has the value of its item and its position as `nth` counts it (AXIS.LIST.ITEM, AXIS.LIST.INDEX).
191
+ */
192
+ interface Target {
193
+ readonly key: string;
194
+ readonly test?: Result<unknown>;
195
+ readonly value?: unknown;
196
+ readonly index?: number;
197
+ }
198
+
199
+ /** The targets of an axis from a frame, or the error of the axis. */
200
+ type Targets = (f: Frame, c: Ctx) => Result<readonly Target[]>;
201
+
202
+ /**
203
+ * This function adds the names `as` of a loop to the names of a body or of a step. The first name holds the value of
204
+ * the item, and the second its index (AXIS.LIST.ITEM, AXIS.LIST.INDEX). A loop without `as` keeps its names.
205
+ */
206
+ function withItem(env: Env, as: ItemNames | undefined, t: Target): Env {
207
+ if (as === undefined) return env;
208
+ const out = new Map(env);
209
+ const [item, index] = as;
210
+ out.set(item, ok(t.value));
211
+ if (index !== undefined) out.set(index, ok(t.index));
212
+ return out;
213
+ }
214
+
188
215
  /** The static facts of a node for its trace events. */
189
216
  interface Info {
190
217
  readonly path: readonly number[];
@@ -451,9 +478,10 @@ class Compiler {
451
478
  }
452
479
  const ts = targets(from, inner);
453
480
  if (!ts.ok) return this.#emit(c, info, f, ts);
454
- const items: ListItem[] = ts.value.map(({ key, test }) => {
481
+ const items: ListItem[] = ts.value.map((t) => {
482
+ const { key, test } = t;
455
483
  if (test !== undefined && !test.ok) return { key, result: test };
456
- return { key, result: body({ pos: { origin: base.t === "table" ? key : f.pos.origin, focus: key }, env: f.env }, inner) };
484
+ return { key, result: body({ pos: { origin: base.t === "table" ? key : f.pos.origin, focus: key }, env: withItem(f.env, e.as, t) }, inner) };
457
485
  });
458
486
  return this.#emit(c, info, f, ok(vexList(items)));
459
487
  };
@@ -465,7 +493,7 @@ class Compiler {
465
493
  */
466
494
  #names(e: ExprOf<"fold"> | ExprOf<"iterate">, path: readonly number[]): {
467
495
  readonly first: (f: Frame, c: Ctx) => Result<Map<string, Result<unknown>>>;
468
- readonly next: (f: Frame, c: Ctx) => Result<Map<string, Result<unknown>>>;
496
+ readonly next: (f: Frame, c: Ctx, names?: Env) => Result<Map<string, Result<unknown>>>;
469
497
  } {
470
498
  const inits = Object.entries(e.init).map(([name, x], i) => [name, this.node(x, [...path, i])] as const);
471
499
  const steps = Object.entries(e.step).map(([name, x], i) => [name, this.node(x, [...path, inits.length + i])] as const);
@@ -479,15 +507,16 @@ class Compiler {
479
507
  }
480
508
  return ok(env);
481
509
  },
482
- // Each value of a step reads the values before the step, so the names change only after all the values.
483
- next: (f, c) => {
510
+ // Each value of a step reads the values before the step, so the names change only after all the values. The new
511
+ // names come from `names` when the frame has more names, for example the names of an item (AXIS.LIST.SCOPE).
512
+ next: (f, c, names = f.env) => {
484
513
  const values: (readonly [string, Result<unknown>])[] = [];
485
514
  for (const [name, n] of steps) {
486
515
  const r = n(f, c);
487
516
  if (!r.ok) return r;
488
517
  values.push([name, r]);
489
518
  }
490
- const env = new Map(f.env);
519
+ const env = new Map(names);
491
520
  for (const [name, r] of values) env.set(name, r);
492
521
  return ok(env);
493
522
  },
@@ -526,9 +555,10 @@ class Compiler {
526
555
  }
527
556
  const ts = targets(from, inner);
528
557
  if (!ts.ok) return this.#emit(c, info, f, ts);
529
- for (const { key, test } of ts.value) {
558
+ for (const t of ts.value) {
559
+ const { key, test } = t;
530
560
  if (test !== undefined && !test.ok) return this.#emit(c, info, f, test);
531
- const after = names.next({ pos: { origin: base.t === "table" ? key : f.pos.origin, focus: key }, env }, inner);
561
+ const after = names.next({ pos: { origin: base.t === "table" ? key : f.pos.origin, focus: key }, env: withItem(env, e.as, t) }, inner, env);
532
562
  if (!after.ok) return this.#emit(c, info, f, after);
533
563
  env = after.value;
534
564
  }
@@ -573,7 +603,7 @@ class Compiler {
573
603
  }
574
604
 
575
605
  /** This method compiles the targets of an axis. For `where`, a failed test keeps the target with its error. */
576
- #targets(a: Axis, path: readonly number[], counter: { next: number }): (f: Frame, c: Ctx) => Result<readonly { readonly key: string; readonly test?: Result<unknown> }[]> {
606
+ #targets(a: Axis, path: readonly number[], counter: { next: number }): Targets {
577
607
  if (a.t === "table") return (_f, c) => ok(c.space.keys.map((key) => ({ key })));
578
608
  const base = a.t === "reverse" ? a.axis : a;
579
609
  if (base.t === "list") return this.#listTargets(base.list, a.t === "reverse", path, counter);
@@ -591,7 +621,7 @@ class Compiler {
591
621
  return (f, c) => {
592
622
  const ts = inner(f, c);
593
623
  if (!ts.ok) return ts;
594
- const out: { key: string; test?: Result<unknown> }[] = [];
624
+ const out: Target[] = [];
595
625
  for (const t of ts.value) {
596
626
  if (t.test !== undefined && !t.test.ok) {
597
627
  out.push(t);
@@ -600,7 +630,8 @@ class Compiler {
600
630
  const at: Frame = { pos: { origin: sameOrigin ? t.key : f.pos.origin, focus: t.key }, env: f.env };
601
631
  const r = test(at, c);
602
632
  if (!r.ok) out.push({ key: t.key, test: r });
603
- else if (r.value === true) out.push({ key: t.key });
633
+ // The target keeps the value and the index of its item (AXIS.LIST.ITEM).
634
+ else if (r.value === true) out.push(t);
604
635
  else if (r.value !== false) {
605
636
  out.push({ key: t.key, test: this.#err("kind-mismatch", `the test of "where" gave a ${typeof r.value}, not a boolean`, at, testPath) });
606
637
  }
@@ -613,7 +644,7 @@ class Compiler {
613
644
  * This method compiles the targets of the axis list (AXIS.LIST): the keys of the items of a list, in its order. The
614
645
  * expression evaluates at the key of the address. An error item keeps its target with its error.
615
646
  */
616
- #listTargets(list: Expr, reverse: boolean, path: readonly number[], counter: { next: number }): (f: Frame, c: Ctx) => Result<readonly { readonly key: string; readonly test?: Result<unknown> }[]> {
647
+ #listTargets(list: Expr, reverse: boolean, path: readonly number[], counter: { next: number }): Targets {
617
648
  const node = this.node(list, [...path, counter.next++]);
618
649
  return (f, c) => {
619
650
  const r = node(f, c);
@@ -621,7 +652,9 @@ class Compiler {
621
652
  // LIST.ARRAY: an array is a list with the positions as keys.
622
653
  const listed = asList(r.value, this.#missing(f, path));
623
654
  if (listed === undefined) return this.#err("kind-mismatch", `the axis "list" needs a list, not a ${describeType(r.value)}`, f, path);
624
- const items = listed.items.map(({ key, result }) => (result.ok ? { key } : { key, test: result }));
655
+ // The index counts the items with a value, as nth does: nth skips the error items (LIST.LENIENT).
656
+ let index = 0;
657
+ const items = listed.items.map(({ key, result }): Target => (result.ok ? { key, value: result.value, index: index++ } : { key, test: result }));
625
658
  return ok(reverse ? items.toReversed() : items);
626
659
  };
627
660
  }
@@ -777,7 +810,7 @@ class Compiler {
777
810
  };
778
811
  switch (op) {
779
812
  case "sortBy":
780
- return this.#sortBy(okItems, okValues, f, path);
813
+ return this.#sortBy(okItems, okValues, optsArg, f, path);
781
814
  case "take":
782
815
  case "drop": {
783
816
  const n = whole();
@@ -882,16 +915,24 @@ class Compiler {
882
915
  }
883
916
 
884
917
  /**
885
- * This method sorts the items of a list by their values, from the smallest (LIST.SORT). The sort is stable. The values
886
- * are all numbers without NaN, or all texts. Texts compare by their UTF-16 code units.
918
+ * This method sorts the items of a list by their sort values, from the smallest (LIST.SORT). The sort is stable. The
919
+ * sort values are all numbers without NaN, or all texts. Texts compare by their UTF-16 code units. Without the option
920
+ * `by`, the sort value of an item is its value (LIST.SORT.BY).
887
921
  */
888
- #sortBy(items: readonly ListItem[], values: readonly unknown[], f: Frame, path: readonly number[]): Result<VexList> {
889
- const kind = typeof values[0];
890
- const bad = values.findIndex((x) => typeof x !== kind || (kind !== "number" && kind !== "string") || Number.isNaN(x));
891
- if (bad >= 0) return this.#err("kind-mismatch", `"sortBy" needs numbers without NaN or texts, all of one kind, but an item is ${Number.isNaN(values[bad]) ? "NaN" : `a ${describeType(values[bad])}`}`, f, path, { op: "sortBy" });
892
- const order = values.map((_x, i) => i).toSorted((i, j) => {
893
- const a = values[i] as number | string;
894
- const b = values[j] as number | string;
922
+ #sortBy(items: readonly ListItem[], values: readonly unknown[], opts: unknown, f: Frame, path: readonly number[]): Result<VexList> {
923
+ const by = (opts as { readonly by?: unknown } | null | undefined)?.by;
924
+ const sorted = by === undefined ? ok(values) : this.#sortValues(by, values, f, path);
925
+ if (!sorted.ok) return sorted;
926
+ const keys = sorted.value;
927
+ const kind = typeof keys[0];
928
+ const bad = keys.findIndex((x) => typeof x !== kind || (kind !== "number" && kind !== "string") || Number.isNaN(x));
929
+ if (bad >= 0) {
930
+ const what = typeof by === "string" ? `"${by}" of an item` : "an item";
931
+ return this.#err("kind-mismatch", `"sortBy" needs numbers without NaN or texts, all of one kind, but ${what} is ${Number.isNaN(keys[bad]) ? "NaN" : `a ${describeType(keys[bad])}`}`, f, path, { op: "sortBy" });
932
+ }
933
+ const order = keys.map((_x, i) => i).toSorted((i, j) => {
934
+ const a = keys[i] as number | string;
935
+ const b = keys[j] as number | string;
895
936
  // The sort of Node reads only a negative result, and the sort of another engine needs the whole comparison.
896
937
  // Stryker disable next-line ConditionalExpression,EqualityOperator: see the comment above
897
938
  return a < b ? -1 : a > b ? 1 : 0;
@@ -899,6 +940,27 @@ class Compiler {
899
940
  return ok(vexList(order.map((i) => items[i] as ListItem)));
900
941
  }
901
942
 
943
+ /**
944
+ * This method gives the sort value of each item for the option `by` of `sortBy` (LIST.SORT.BY). The op of the name
945
+ * `by` applies to the value of each item, in the order of the list. The first error is the result.
946
+ */
947
+ #sortValues(by: unknown, values: readonly unknown[], f: Frame, path: readonly number[]): Result<readonly unknown[]> {
948
+ if (typeof by !== "string") return this.#err("kind-mismatch", `the option "by" of "sortBy" needs an op name, but got a ${describeType(by)}`, f, path, { op: "sortBy" });
949
+ const out: unknown[] = [];
950
+ for (const x of values) {
951
+ let op: ResolvedOp | undefined;
952
+ for (const d of this.#domains) {
953
+ op = safeIs(d, x) ? resolveOp(d, x, by) : undefined;
954
+ if (op !== undefined) break;
955
+ }
956
+ if (op === undefined) return this.#err("unknown-op", `no domain gives "${by}" for a ${describeType(x)}`, f, path, { op: by });
957
+ const r = this.#call(op, by, [], f, path);
958
+ if (!r.ok) return r;
959
+ out.push(r.value);
960
+ }
961
+ return ok(out);
962
+ }
963
+
902
964
  /**
903
965
  * This method folds the values with a domain op, from the left. An empty list gives the identity of the op, if one
904
966
  * domain has an identity for the op (LIST.EMPTY). The option `domain` names that domain when more domains have one.
package/src/ir.ts CHANGED
@@ -3,6 +3,8 @@
3
3
  * shape as the expressions of `render`.
4
4
  */
5
5
 
6
+ import { itemNamesError } from "./item-names.ts";
7
+
6
8
  /**
7
9
  * One move of an address. The moves of an address apply in order, from the focus of the evaluation. The key of `key`
8
10
  * and the position of `index` can be an expression, which evaluates before the moves (NAV.COMPUTED).
@@ -48,8 +50,8 @@ export type Expr =
48
50
  | { readonly tag: "let"; readonly bind: Readonly<Record<string, Expr>>; readonly body: Expr }
49
51
  | { readonly tag: "var"; readonly name: string }
50
52
  | { readonly tag: "rec"; readonly fields: Readonly<Record<string, Expr>> }
51
- | { readonly tag: "each"; readonly axis: Axis; readonly body: Expr; readonly at?: Addr }
52
- | { readonly tag: "fold"; readonly axis: Axis; readonly init: Names; readonly step: Names; readonly result: Expr; readonly at?: Addr }
53
+ | { readonly tag: "each"; readonly axis: Axis; readonly body: Expr; readonly at?: Addr; readonly as?: ItemNames }
54
+ | { readonly tag: "fold"; readonly axis: Axis; readonly init: Names; readonly step: Names; readonly result: Expr; readonly at?: Addr; readonly as?: ItemNames }
53
55
  | { readonly tag: "iterate"; readonly limit: number; readonly init: Names; readonly step: Names; readonly until?: Expr; readonly result: Expr }
54
56
  | { readonly tag: "fn"; readonly params: readonly string[]; readonly body: Expr }
55
57
  | { readonly tag: "call"; readonly fn: string; readonly args: readonly Expr[] }
@@ -58,6 +60,12 @@ export type Expr =
58
60
  /** The names of a loop and an expression for each (LOOP.NAMES). */
59
61
  export type Names = Readonly<Record<string, Expr>>;
60
62
 
63
+ /**
64
+ * The names of the items of a loop over the axis `list`. The first name holds the value of the item, and the second
65
+ * its position (AXIS.LIST.ITEM, AXIS.LIST.INDEX). The body of `each` and the steps of `fold` see them (AXIS.LIST.SCOPE).
66
+ */
67
+ export type ItemNames = readonly [item: string] | readonly [item: string, index: string];
68
+
61
69
  /** The largest number of steps of `iterate` (ITERATE.LIMIT). */
62
70
  export const MAX_ITERATIONS = 100_000;
63
71
 
@@ -96,18 +104,23 @@ export const rec = (fields: Readonly<Record<string, Expr>>): ExprOf<"rec"> => ({
96
104
 
97
105
  /**
98
106
  * This function evaluates `body` once for each target of `axis`. The result is a list. With `at`, the axis finds its
99
- * targets from the key of that address, not from the focus.
107
+ * targets from the key of that address, not from the focus. With `as`, the body of a loop over the axis `list` reads the
108
+ * value of each item and its position by these names (AXIS.LIST.ITEM, AXIS.LIST.INDEX).
100
109
  */
101
- export function each(axis: Axis, body: Expr, at?: Addr): ExprOf<"each"> {
102
- return at === undefined || at.length === 0 ? { tag: "each", axis, body } : { tag: "each", axis, body, at };
110
+ export function each(axis: Axis, body: Expr, at?: Addr, as?: ItemNames): ExprOf<"each"> {
111
+ const named = as === undefined ? {} : { as };
112
+ return at === undefined || at.length === 0 ? { tag: "each", axis, body, ...named } : { tag: "each", axis, body, at, ...named };
103
113
  }
104
114
 
105
115
  /**
106
116
  * This function makes a fold: a step at each target of `axis`, in order. `init` gives the names and their first
107
- * values, and `step` gives the next values. `result` gives the value from the last values (LOOP.NAMES, FOLD.ORDER).
117
+ * values, and `step` gives the next values. `result` gives the value from the last values (LOOP.NAMES, FOLD.ORDER). With
118
+ * `as`, the steps of a fold over the axis `list` read the value of each item and its position by these names
119
+ * (AXIS.LIST.ITEM, AXIS.LIST.INDEX).
108
120
  */
109
- export function fold(axis: Axis, init: Names, step: Names, result: Expr, at?: Addr): ExprOf<"fold"> {
110
- return at === undefined || at.length === 0 ? { tag: "fold", axis, init, step, result } : { tag: "fold", axis, init, step, result, at };
121
+ export function fold(axis: Axis, init: Names, step: Names, result: Expr, at?: Addr, as?: ItemNames): ExprOf<"fold"> {
122
+ const named = as === undefined ? {} : { as };
123
+ return at === undefined || at.length === 0 ? { tag: "fold", axis, init, step, result, ...named } : { tag: "fold", axis, init, step, result, at, ...named };
111
124
  }
112
125
 
113
126
  /**
@@ -277,6 +290,8 @@ export function shapeError(u: unknown): string | undefined {
277
290
  if (bad.axis) return "the expression has an axis that is not valid";
278
291
  if (typeof tag === "string" && !TAGS.has(tag)) return `the expression has a node with the tag "${tag}", and this version of Vex does not know it`;
279
292
  if (tag === "fn") return "the expression has a function outside the bindings of a let, or a function with parameters that are not distinct names";
293
+ const named = tag === "each" || tag === "fold" ? itemNamesError(bad.u as Readonly<Record<string, unknown>>) : undefined;
294
+ if (named !== undefined) return `the expression has a node "${String(tag)}" with names "as" that are not valid: ${named}`;
280
295
  return typeof tag === "string" ? `the expression has a node "${tag}" with parts that are not valid` : "the expression has a part that is not a node";
281
296
  }
282
297
 
@@ -375,7 +390,7 @@ function badPart(todo: { readonly axis: boolean; readonly u: unknown }[], whole:
375
390
  break;
376
391
  case "each": {
377
392
  const at = addrParts(u["at"], moveNumber);
378
- if (at === undefined) return item;
393
+ if (at === undefined || itemNamesError(u) !== undefined) return item;
379
394
  push(true, [u["axis"]]);
380
395
  push(false, [u["body"], ...at]);
381
396
  break;
@@ -383,7 +398,7 @@ function badPart(todo: { readonly axis: boolean; readonly u: unknown }[], whole:
383
398
  case "fold": {
384
399
  const at = addrParts(u["at"], moveNumber);
385
400
  const names = loopParts(u);
386
- if (at === undefined || names === undefined) return item;
401
+ if (at === undefined || names === undefined || itemNamesError(u) !== undefined) return item;
387
402
  push(true, [u["axis"]]);
388
403
  push(false, [...names, ...at]);
389
404
  break;
@@ -0,0 +1,29 @@
1
+ /**
2
+ * The check of the names `as` of a loop over the axis `list` (AXIS.LIST.SCOPE). The package index does not export this
3
+ * module: `isExpr`, `shapeError` and `fromDocument` use it, so an expression and a document follow the same rule.
4
+ */
5
+
6
+ const isObject = (u: unknown): u is Readonly<Record<string, unknown>> => typeof u === "object" && u !== null;
7
+
8
+ /** This function tells if the base axis of an axis is `list`, through `where` and `reverse`. It uses a loop, not recursion. */
9
+ function isListAxis(u: unknown): boolean {
10
+ let x = u;
11
+ while (isObject(x) && x["t"] === "where") x = x["axis"];
12
+ if (isObject(x) && x["t"] === "reverse") x = x["axis"];
13
+ return isObject(x) && x["t"] === "list";
14
+ }
15
+
16
+ /**
17
+ * This function gives the reason that the names `as` of a loop are not valid, or `undefined` for valid names or no
18
+ * names (AXIS.LIST.SCOPE). The names are one or two distinct texts, the axis is `list`, and no name is a name of `init`.
19
+ */
20
+ export function itemNamesError(u: Readonly<Record<string, unknown>>): string | undefined {
21
+ const as = u["as"];
22
+ if (as === undefined) return undefined;
23
+ if (!Array.isArray(as) || as.length === 0 || as.length > 2 || !as.every((n) => typeof n === "string")) return '"as" is a list of one or two names: the item, and then its index';
24
+ if (as[0] === as[1]) return `the two names of "as" are the same name "${String(as[0])}"`;
25
+ if (!isListAxis(u["axis"])) return '"as" needs the axis "list", also inside "reverse" and "where"';
26
+ const init = u["init"];
27
+ const clash = isObject(init) ? (as as readonly string[]).find((n) => Object.hasOwn(init, n)) : undefined;
28
+ return clash === undefined ? undefined : `the name "${clash}" of "as" is a name of "init" too`;
29
+ }