@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/src/evaluate.ts CHANGED
@@ -1,7 +1,8 @@
1
+ import { CHECKED } from "./checked.ts";
1
2
  import { fromDocument, isDocument, type Envelope } from "./document.ts";
2
- import { liftsAt, resolveOp, type AnyDomain, type ParamKind, type ResolvedOp } from "./domain.ts";
3
+ import { findMethod, isOpName, liftsAt, resolveOp, type AnyDomain, type OpSpec, type ParamKind, type PrimitiveKind, type ResolvedOp } from "./domain.ts";
3
4
  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";
5
+ import { addrExprs, children, shapeError, type Addr, type Axis, type Expr, type ExprOf, type FixedMove, type ItemNames, type Move } from "./ir.ts";
5
6
  import { asList, fillList, isFillCount, isIndexValue, listOfArray } from "./array-list.ts";
6
7
  import { isListOp, isVexList, vexList, type ListItem, type ListOp, type ListOptions, type VexList } from "./list.ts";
7
8
  import { fail, ok, type Result } from "./result.ts";
@@ -41,7 +42,41 @@ export interface EvalOptions {
41
42
  readonly trace?: TraceSink;
42
43
  }
43
44
 
44
- type Env = ReadonlyMap<string, Result<unknown>>;
45
+ /** The names of a frame: a map of the variables of the caller, or a scope inside it. */
46
+ interface Env {
47
+ get(name: string): Result<unknown> | undefined;
48
+ }
49
+
50
+ /**
51
+ * A scope: the names of one `let`, a function, an item or a loop. It is in front of the outer names, and it does not
52
+ * copy them. A name of a scope hides an outer name of the same name. The names of one
53
+ * scope are distinct (FN.BIND, LOOP.NAMES, AXIS.LIST.SCOPE).
54
+ */
55
+ class Scope implements Env {
56
+ readonly #outer: Env;
57
+ readonly #names: readonly string[];
58
+ readonly #values: readonly Result<unknown>[];
59
+
60
+ constructor(outer: Env, names: readonly string[], values: readonly Result<unknown>[]) {
61
+ this.#outer = outer;
62
+ this.#names = names;
63
+ this.#values = values;
64
+ }
65
+
66
+ get(name: string): Result<unknown> | undefined {
67
+ const at = this.#names.indexOf(name);
68
+ return at >= 0 ? this.#values[at] : this.#outer.get(name);
69
+ }
70
+
71
+ /** This method gives a copy of this scope with the values `values` at the positions `at` (LOOP.NAMES). */
72
+ with(at: readonly number[], values: readonly Result<unknown>[]): Scope {
73
+ const next = [...this.#values];
74
+ at.forEach((position, i) => {
75
+ next[position] = values[i] as Result<unknown>;
76
+ });
77
+ return new Scope(this.#outer, this.#names, next);
78
+ }
79
+ }
45
80
 
46
81
  interface Frame {
47
82
  readonly pos: Position;
@@ -82,9 +117,9 @@ export interface Program {
82
117
  class Closure {
83
118
  readonly params: readonly string[];
84
119
  readonly body: Node;
85
- readonly env: ReadonlyMap<string, Result<unknown>>;
120
+ readonly env: Env;
86
121
 
87
- constructor(params: readonly string[], body: Node, env: ReadonlyMap<string, Result<unknown>>) {
122
+ constructor(params: readonly string[], body: Node, env: Env) {
88
123
  this.params = params;
89
124
  this.body = body;
90
125
  this.env = env;
@@ -185,6 +220,49 @@ const baseAxis = (a: Axis): Exclude<Axis, { readonly t: "where" }> => (a.t === "
185
220
  /** A compiled node: it evaluates in a frame of a run. */
186
221
  type Node = (f: Frame, c: Ctx) => Result<unknown>;
187
222
 
223
+ /** This function evaluates the nodes in order. The first error stops it and is the result. */
224
+ function allValues(ns: readonly Node[], f: Frame, c: Ctx): Result<Result<unknown>[]> {
225
+ const values: Result<unknown>[] = [];
226
+ for (const n of ns) {
227
+ const r = n(f, c);
228
+ if (!r.ok) return r;
229
+ values.push(r);
230
+ }
231
+ return ok(values);
232
+ }
233
+
234
+ /** The primitive types of KIND.PRIMITIVE. */
235
+ const PRIMITIVE_TYPES: readonly PrimitiveKind[] = ["number", "string", "boolean"];
236
+
237
+ /** The spec of an op without an entry in the op table of a domain with `methods: "all"`. */
238
+ const NO_SPEC: OpSpec<unknown> = Object.freeze({});
239
+
240
+ /** The function of an op: the receiver comes first, then the arguments. */
241
+ type OpFn = (self: unknown, ...args: readonly unknown[]) => unknown;
242
+
243
+ /**
244
+ * 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
245
+ * has the value of its item and its position as `nth` counts it (AXIS.LIST.ITEM, AXIS.LIST.INDEX).
246
+ */
247
+ interface Target {
248
+ readonly key: string;
249
+ readonly test?: Result<unknown>;
250
+ readonly value?: unknown;
251
+ readonly index?: number;
252
+ }
253
+
254
+ /** The targets of an axis from a frame, or the error of the axis. */
255
+ type Targets = (f: Frame, c: Ctx) => Result<readonly Target[]>;
256
+
257
+ /**
258
+ * 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
259
+ * the item, and the second its index (AXIS.LIST.ITEM, AXIS.LIST.INDEX). A loop without `as` keeps its names.
260
+ */
261
+ function withItem(env: Env, as: ItemNames | undefined, t: Target): Env {
262
+ // A scope with one name reads only the first value.
263
+ return as === undefined ? env : new Scope(env, as, [ok(t.value), ok(t.index)]);
264
+ }
265
+
188
266
  /** The static facts of a node for its trace events. */
189
267
  interface Info {
190
268
  readonly path: readonly number[];
@@ -198,12 +276,21 @@ class Compiler {
198
276
  readonly #extensions: Readonly<Record<string, ExtHandler>> | undefined;
199
277
  /** The index of the keys of each list that `get` read (LIST.GET). A list does not change, so its index stays right. */
200
278
  readonly #keyIndex = new WeakMap<VexList, KeyIndex>();
279
+ /**
280
+ * The domains that can accept a value of each primitive type, in order (KIND.PRIMITIVE). These are the domains of
281
+ * that type and the domains without a primitive type.
282
+ */
283
+ readonly #ofType = new Map<string, readonly AnyDomain[]>();
284
+ /** The domains without a primitive type. Only they can accept a value of another type, for example an object. */
285
+ readonly #open: readonly AnyDomain[];
201
286
 
202
287
  constructor(opts: CompileOptions) {
203
288
  // Stryker disable next-line ArrayDeclaration: a list with a value that is not a domain matches no value
204
289
  this.#domains = opts.domains ?? [];
205
290
  this.#fns = opts.fns;
206
291
  this.#extensions = opts.extensions;
292
+ this.#open = this.#domains.filter((d) => d.primitive === undefined);
293
+ for (const t of PRIMITIVE_TYPES) this.#ofType.set(t, this.#domains.filter((d) => d.primitive === undefined || d.primitive === t));
207
294
  }
208
295
 
209
296
  #err(kind: ErrorKind, message: string, f: Frame, path: readonly number[], extra: { op?: string; causes?: readonly VexError[]; thrown?: unknown } = {}): Result<never> {
@@ -219,7 +306,11 @@ class Compiler {
219
306
  #fill(values: readonly unknown[], f: Frame, path: readonly number[]): Result<VexList> {
220
307
  const [n, value] = values;
221
308
  if (!isFillCount(n)) return this.#err("kind-mismatch", `"fill" needs a whole number from 0 to 100000, not ${describeType(n)}`, f, path, { op: "fill" });
222
- return value === undefined ? this.#err("bad-expression", '"fill" needs argument 2', f, path, { op: "fill" }) : ok(fillList(n, value));
309
+ if (value === undefined) return this.#err("bad-expression", '"fill" needs argument 2', f, path, { op: "fill" });
310
+ // Each item of the list has the value, so the list has the shape of LIST.SHAPE.
311
+ const list = fillList(n, value);
312
+ CHECKED.add(list);
313
+ return ok(list);
223
314
  }
224
315
 
225
316
  #emit(c: Ctx, info: Info, f: Frame, result: Result<unknown>, reads?: readonly Read[]): Result<unknown> {
@@ -262,12 +353,14 @@ class Compiler {
262
353
  case "call":
263
354
  return this.#callFn(e, info);
264
355
  case "let": {
265
- const binds = Object.entries(e.bind).map(([name, be], i): readonly [string, Node] => [name, this.node(be, [...path, i])]);
356
+ const names = Object.keys(e.bind);
357
+ const binds = this.#nodes(Object.values(e.bind), path);
266
358
  const body = this.node(e.body, [...path, binds.length]);
267
359
  return (f, c) => {
268
- const env = new Map(f.env);
269
- for (const [name, n] of binds) env.set(name, n(f, c));
270
- return this.#emit(c, info, f, body({ pos: f.pos, env }, c));
360
+ // Each binding evaluates with the outer names, so a binding does not see the other bindings.
361
+ const values: Result<unknown>[] = [];
362
+ for (const n of binds) values.push(n(f, c));
363
+ return this.#emit(c, info, f, body({ pos: f.pos, env: new Scope(f.env, names, values) }, c));
271
364
  };
272
365
  }
273
366
  case "rec": {
@@ -327,9 +420,9 @@ class Compiler {
327
420
  const callee = bound.value;
328
421
  if (!(callee instanceof Closure)) return this.#emit(c, info, f, this.#err("kind-mismatch", `the name "${e.fn}" is a value, not a function`, f, path));
329
422
  if (callee.params.length !== args.length) return this.#emit(c, info, f, this.#err("bad-expression", `the function "${e.fn}" takes ${String(callee.params.length)} arguments, not ${String(args.length)}`, f, path));
330
- const env = new Map(callee.env);
331
- callee.params.forEach((p, i) => env.set(p, (args[i] as Node)(f, c)));
332
- return this.#emit(c, info, f, callee.body({ pos: f.pos, env }, c));
423
+ const values: Result<unknown>[] = [];
424
+ for (const n of args) values.push(n(f, c));
425
+ return this.#emit(c, info, f, callee.body({ pos: f.pos, env: new Scope(callee.env, callee.params, values) }, c));
333
426
  };
334
427
  }
335
428
 
@@ -451,9 +544,10 @@ class Compiler {
451
544
  }
452
545
  const ts = targets(from, inner);
453
546
  if (!ts.ok) return this.#emit(c, info, f, ts);
454
- const items: ListItem[] = ts.value.map(({ key, test }) => {
547
+ const items: ListItem[] = ts.value.map((t) => {
548
+ const { key, test } = t;
455
549
  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) };
550
+ return { key, result: body({ pos: { origin: base.t === "table" ? key : f.pos.origin, focus: key }, env: withItem(f.env, e.as, t) }, inner) };
457
551
  });
458
552
  return this.#emit(c, info, f, ok(vexList(items)));
459
553
  };
@@ -464,32 +558,25 @@ class Compiler {
464
558
  * functions give the first values, and the values after one step. The first error stops each of them.
465
559
  */
466
560
  #names(e: ExprOf<"fold"> | ExprOf<"iterate">, path: readonly number[]): {
467
- readonly first: (f: Frame, c: Ctx) => Result<Map<string, Result<unknown>>>;
468
- readonly next: (f: Frame, c: Ctx) => Result<Map<string, Result<unknown>>>;
561
+ readonly first: (f: Frame, c: Ctx) => Result<Scope>;
562
+ readonly next: (f: Frame, c: Ctx, scope: Scope) => Result<Scope>;
469
563
  } {
470
- const inits = Object.entries(e.init).map(([name, x], i) => [name, this.node(x, [...path, i])] as const);
471
- const steps = Object.entries(e.step).map(([name, x], i) => [name, this.node(x, [...path, inits.length + i])] as const);
564
+ const names = Object.keys(e.init);
565
+ const inits = this.#nodes(Object.values(e.init), path);
566
+ const steps = Object.values(e.step).map((x, i) => this.node(x, [...path, inits.length + i]));
567
+ // Each name of a step is a name of init (LOOP.NAMES), so a step changes the value at a position of the scope.
568
+ const at = Object.keys(e.step).map((name) => names.indexOf(name));
472
569
  return {
473
570
  first: (f, c) => {
474
- const env = new Map(f.env);
475
- for (const [name, n] of inits) {
476
- const r = n(f, c);
477
- if (!r.ok) return r;
478
- env.set(name, r);
479
- }
480
- return ok(env);
571
+ const values = allValues(inits, f, c);
572
+ return values.ok ? ok(new Scope(f.env, names, values.value)) : values;
481
573
  },
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) => {
484
- const values: (readonly [string, Result<unknown>])[] = [];
485
- for (const [name, n] of steps) {
486
- const r = n(f, c);
487
- if (!r.ok) return r;
488
- values.push([name, r]);
489
- }
490
- const env = new Map(f.env);
491
- for (const [name, r] of values) env.set(name, r);
492
- return ok(env);
574
+ // Each value of a step reads the values before the step, so the names change only after all the values. The new
575
+ // names come from `scope`, the scope of the loop, because the frame can have more names, for example the names of
576
+ // an item (AXIS.LIST.SCOPE).
577
+ next: (f, c, scope) => {
578
+ const values = allValues(steps, f, c);
579
+ return values.ok ? ok(scope.with(at, values.value)) : values;
493
580
  },
494
581
  };
495
582
  }
@@ -526,9 +613,10 @@ class Compiler {
526
613
  }
527
614
  const ts = targets(from, inner);
528
615
  if (!ts.ok) return this.#emit(c, info, f, ts);
529
- for (const { key, test } of ts.value) {
616
+ for (const t of ts.value) {
617
+ const { key, test } = t;
530
618
  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);
619
+ const after = names.next({ pos: { origin: base.t === "table" ? key : f.pos.origin, focus: key }, env: withItem(env, e.as, t) }, inner, env);
532
620
  if (!after.ok) return this.#emit(c, info, f, after);
533
621
  env = after.value;
534
622
  }
@@ -564,7 +652,7 @@ class Compiler {
564
652
  if (until !== undefined) return this.#emit(c, info, f, this.#err("limit", `"iterate" made its ${String(limit)} steps, and its test "until" is not true`, f, path));
565
653
  break;
566
654
  }
567
- const after = names.next(frame, c);
655
+ const after = names.next(frame, c, env);
568
656
  if (!after.ok) return this.#emit(c, info, f, after);
569
657
  env = after.value;
570
658
  }
@@ -573,7 +661,7 @@ class Compiler {
573
661
  }
574
662
 
575
663
  /** 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> }[]> {
664
+ #targets(a: Axis, path: readonly number[], counter: { next: number }): Targets {
577
665
  if (a.t === "table") return (_f, c) => ok(c.space.keys.map((key) => ({ key })));
578
666
  const base = a.t === "reverse" ? a.axis : a;
579
667
  if (base.t === "list") return this.#listTargets(base.list, a.t === "reverse", path, counter);
@@ -591,7 +679,7 @@ class Compiler {
591
679
  return (f, c) => {
592
680
  const ts = inner(f, c);
593
681
  if (!ts.ok) return ts;
594
- const out: { key: string; test?: Result<unknown> }[] = [];
682
+ const out: Target[] = [];
595
683
  for (const t of ts.value) {
596
684
  if (t.test !== undefined && !t.test.ok) {
597
685
  out.push(t);
@@ -600,7 +688,8 @@ class Compiler {
600
688
  const at: Frame = { pos: { origin: sameOrigin ? t.key : f.pos.origin, focus: t.key }, env: f.env };
601
689
  const r = test(at, c);
602
690
  if (!r.ok) out.push({ key: t.key, test: r });
603
- else if (r.value === true) out.push({ key: t.key });
691
+ // The target keeps the value and the index of its item (AXIS.LIST.ITEM).
692
+ else if (r.value === true) out.push(t);
604
693
  else if (r.value !== false) {
605
694
  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
695
  }
@@ -613,7 +702,7 @@ class Compiler {
613
702
  * This method compiles the targets of the axis list (AXIS.LIST): the keys of the items of a list, in its order. The
614
703
  * expression evaluates at the key of the address. An error item keeps its target with its error.
615
704
  */
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> }[]> {
705
+ #listTargets(list: Expr, reverse: boolean, path: readonly number[], counter: { next: number }): Targets {
617
706
  const node = this.node(list, [...path, counter.next++]);
618
707
  return (f, c) => {
619
708
  const r = node(f, c);
@@ -621,7 +710,9 @@ class Compiler {
621
710
  // LIST.ARRAY: an array is a list with the positions as keys.
622
711
  const listed = asList(r.value, this.#missing(f, path));
623
712
  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 }));
713
+ // The index counts the items with a value, as nth does: nth skips the error items (LIST.LENIENT).
714
+ let index = 0;
715
+ const items = listed.items.map(({ key, result }): Target => (result.ok ? { key, value: result.value, index: index++ } : { key, test: result }));
625
716
  return ok(reverse ? items.toReversed() : items);
626
717
  };
627
718
  }
@@ -630,6 +721,8 @@ class Compiler {
630
721
  const { path } = info;
631
722
  const listOp = isListOp(op) ? op : undefined;
632
723
  const fn = this.#fns !== undefined && Object.hasOwn(this.#fns, op) ? this.#fns[op] : undefined;
724
+ // A name that cannot be an op name has no op, also with an own entry in an op table (resolveOp).
725
+ const named = isOpName(op);
633
726
  return (f, c) => {
634
727
  const all = this.#all(args, f, c, path, "arguments");
635
728
  if (!all.ok) return this.#emit(c, info, f, all);
@@ -643,8 +736,12 @@ class Compiler {
643
736
  for (const d of this.#domains) {
644
737
  if (!safeIs(d, self)) continue;
645
738
  accepted ??= d;
646
- const resolved = resolveOp(d, self, op);
647
- if (resolved !== undefined) return this.#emit(c, info, f, this.#call(resolved, op, values.slice(1), f, path));
739
+ // The rules of resolveOp, without a closure for each call: the function of the spec, or a method of the
740
+ // receiver for a declared op without a function, or for each op of a domain with `methods: "all"`.
741
+ const spec = named && Object.hasOwn(d.ops, op) ? (d.ops[op] as OpSpec<unknown>) : undefined;
742
+ if (spec?.fn !== undefined) return this.#emit(c, info, f, this.#call(d, spec, spec.fn as OpFn, self, op, values.slice(1), f, path));
743
+ const method = spec !== undefined || d.methods === "all" ? findMethod(self, op) : undefined;
744
+ if (method !== undefined) return this.#emit(c, info, f, this.#call(d, spec ?? NO_SPEC, (receiver, ...given) => method.apply(receiver, [...given]), self, op, values.slice(1), f, path));
648
745
  }
649
746
  }
650
747
  if (fn !== undefined) return this.#emit(c, info, f, this.#checkResult(this.#invoke(() => fn(...values), op, f, path), f, path, op));
@@ -696,8 +793,16 @@ class Compiler {
696
793
  }
697
794
  }
698
795
 
699
- #call(op: ResolvedOp, name: string, rest: readonly unknown[], f: Frame, path: readonly number[]): Result<unknown> {
700
- const { domain, spec } = op;
796
+ /** This method starts an op that resolveOp found, for example a method of the receiver. */
797
+ #callResolved(op: ResolvedOp, self: unknown, name: string, rest: readonly unknown[], f: Frame, path: readonly number[]): Result<unknown> {
798
+ return this.#call(op.domain, op.spec, (_self, ...args) => op.call(args), self, name, rest, f, path);
799
+ }
800
+
801
+ /**
802
+ * This method starts the op `name` of the domain `domain` with the receiver `self` and the arguments `rest`. It lifts
803
+ * the numbers, checks the arguments and checks the result.
804
+ */
805
+ #call(domain: AnyDomain, spec: OpSpec<unknown>, run: OpFn, self: unknown, name: string, rest: readonly unknown[], f: Frame, path: readonly number[]): Result<unknown> {
701
806
  const lift = spec.liftScalar;
702
807
  const from = domain.fromScalar;
703
808
  let callArgs: readonly unknown[] = rest;
@@ -715,7 +820,13 @@ class Compiler {
715
820
  }
716
821
  }
717
822
  }
718
- return this.#checkResult(this.#invoke(() => op.call(callArgs), name, f, path), f, path, name);
823
+ let value: unknown;
824
+ try {
825
+ value = run(self, ...callArgs);
826
+ } catch (thrown) {
827
+ return this.#threw(thrown, `"${name}" threw an exception`, f, path, { op: name });
828
+ }
829
+ return this.#checkResult(ok(value), f, path, name);
719
830
  }
720
831
 
721
832
  #invoke(run: () => unknown, op: string, f: Frame, path: readonly number[]): Result<unknown> {
@@ -726,6 +837,16 @@ class Compiler {
726
837
  }
727
838
  }
728
839
 
840
+ /**
841
+ * This method gives the first domain that accepts a value. It starts only the tests of the domains without a primitive
842
+ * type: a domain of the type of the value accepts it (KIND.PRIMITIVE).
843
+ */
844
+ #domainOf(value: unknown): AnyDomain | undefined {
845
+ const candidates = this.#ofType.get(typeof value) ?? this.#open;
846
+ for (const d of candidates) if (d.primitive !== undefined || testIs(d, value)) return d;
847
+ return undefined;
848
+ }
849
+
729
850
  /** This method checks the value that an op gave: no `undefined`, finite numbers, and valid domain values. */
730
851
  #checkResult(r: Result<unknown>, f: Frame, path: readonly number[], op: string): Result<unknown> {
731
852
  if (!r.ok) return r;
@@ -733,7 +854,7 @@ class Compiler {
733
854
  const extra = { op };
734
855
  if (value === undefined || value === null) return this.#err("undefined-result", `"${op}" gave no value`, f, path, extra);
735
856
  if (typeof value === "number" && !Number.isFinite(value)) return this.#err("not-finite", `"${op}" gave ${value}`, f, path, extra);
736
- const d = this.#domains.find((dom) => safeIs(dom, value));
857
+ const d = this.#domainOf(value);
737
858
  if (d?.valid !== undefined) {
738
859
  let valid: boolean;
739
860
  try {
@@ -751,11 +872,12 @@ class Compiler {
751
872
  const optsArg = WITH_ARGUMENT.has(op) ? rest[1] : rest[0];
752
873
  const strict = (optsArg as ListOptions | null | undefined)?.strict === true;
753
874
  if (op === "get") return this.#get(list, rest[0], strict, f, path);
875
+ if (op === "group") return this.#group(list, rest[0], strict, f, path);
754
876
  const good = goodItems(list, strict);
755
877
  if (!good.ok) return good;
756
878
  const okItems = good.value;
757
- // Stryker disable next-line ConditionalExpression,ArrayDeclaration: each item of okItems has a value
758
- const okValues = okItems.flatMap((it) => (it.result.ok ? [it.result.value] : []));
879
+ const okValues: unknown[] = [];
880
+ for (const it of okItems) okValues.push(valueOf(it));
759
881
  const numbers = (): Result<readonly number[]> => {
760
882
  const bad = okValues.find((x) => typeof x !== "number");
761
883
  return bad === undefined ? ok(okValues as readonly number[]) : this.#err("kind-mismatch", `"${op}" needs numbers, but an item is a ${describeType(bad)}`, f, path, { op });
@@ -782,20 +904,40 @@ class Compiler {
782
904
  case "drop": {
783
905
  const n = whole();
784
906
  if (!n.ok) return n;
785
- return ok(vexList(op === "take" ? okItems.slice(0, n.value) : okItems.slice(n.value)));
907
+ return ok(checkedList(op === "take" ? okItems.slice(0, n.value) : okItems.slice(n.value)));
786
908
  }
787
909
  case "append": {
788
910
  const more = other();
789
- return more.ok ? ok(vexList([...okItems, ...more.value])) : more;
911
+ return more.ok ? ok(checkedList([...okItems, ...more.value])) : more;
790
912
  }
791
913
  case "without": {
792
914
  const more = other();
793
915
  if (!more.ok) return more;
794
916
  const gone = new Set(more.value.map((it) => it.key));
795
- return ok(vexList(okItems.filter((it) => !gone.has(it.key))));
917
+ return ok(checkedList(okItems.filter((it) => !gone.has(it.key))));
796
918
  }
797
919
  case "flat":
798
920
  return this.#flat(okValues, strict, f, path);
921
+ case "distinct": {
922
+ // The first item of each value, in the order of the list (LIST.DISTINCT). === compares the values, as for
923
+ // indexOf, so each NaN stays.
924
+ const seen = new Set<unknown>();
925
+ const out: ListItem[] = [];
926
+ for (let i = 0; i < okValues.length; i++) {
927
+ const x = okValues[i];
928
+ if (!isIndexValue(x)) return this.#err("kind-mismatch", `"distinct" needs numbers, texts or booleans, but an item is a ${describeType(x)}`, f, path, { op });
929
+ if (Number.isNaN(x) || !seen.has(x)) out.push(okItems[i] as ListItem);
930
+ seen.add(x);
931
+ }
932
+ return ok(checkedList(out));
933
+ }
934
+ case "join": {
935
+ // The texts of the items with the text sep between them (LIST.JOIN).
936
+ const sep = rest[0];
937
+ if (typeof sep !== "string") return this.#err("kind-mismatch", `"join" needs a text separator, not a ${describeType(sep)}`, f, path, { op });
938
+ const bad = okValues.find((x) => typeof x !== "string");
939
+ return bad === undefined ? ok(okValues.join(sep)) : this.#err("kind-mismatch", `"join" needs texts, but an item is a ${describeType(bad)}`, f, path, { op });
940
+ }
799
941
  case "indexOf": {
800
942
  const x = rest[0];
801
943
  if (!isIndexValue(x)) return this.#err("kind-mismatch", `"indexOf" needs a number, a text or a boolean, not a ${describeType(x)}`, f, path, { op });
@@ -865,6 +1007,36 @@ class Compiler {
865
1007
  return index.values.has(key) ? ok(index.values.get(key)) : this.#err("missing-field", `the list has no item with the key ${JSON.stringify(key)}`, f, path, { op: "get" });
866
1008
  }
867
1009
 
1010
+ /**
1011
+ * This method gives the groups of a list (LIST.GROUP). The item at a position has the key at the same position of
1012
+ * `keys`, so the two lists must have the same number of items. A pair with an error item or an error key is not in a
1013
+ * group (LIST.LENIENT). Each key gives one item, in the order of its first pair, and its value is a list of its items.
1014
+ */
1015
+ #group(list: VexList, keys: unknown, strict: boolean, f: Frame, path: readonly number[]): Result<VexList> {
1016
+ const good = goodItems(list, strict);
1017
+ if (!good.ok) return good;
1018
+ const listed = asList(keys, this.#missing(f, path));
1019
+ if (listed === undefined) return this.#err("kind-mismatch", `"group" needs a list of keys as its second argument, not a ${describeType(keys)}`, f, path, { op: "group" });
1020
+ const goodKeys = goodItems(listed, strict);
1021
+ if (!goodKeys.ok) return goodKeys;
1022
+ const { items } = list;
1023
+ const keyItems = listed.items;
1024
+ if (keyItems.length !== items.length) return this.#err("kind-mismatch", `"group" needs one key for each item, but the list has ${String(items.length)} items and ${String(keyItems.length)} keys`, f, path, { op: "group" });
1025
+ const groups = new Map<string, ListItem[]>();
1026
+ for (let i = 0; i < items.length; i++) {
1027
+ const it = items[i] as ListItem;
1028
+ const k = (keyItems[i] as ListItem).result;
1029
+ if (!it.result.ok || !k.ok) continue;
1030
+ if (typeof k.value !== "string") return this.#err("kind-mismatch", `"group" needs text keys, but a key is a ${describeType(k.value)}`, f, path, { op: "group" });
1031
+ const g = groups.get(k.value);
1032
+ if (g === undefined) groups.set(k.value, [it]);
1033
+ else g.push(it);
1034
+ }
1035
+ const out: ListItem[] = [];
1036
+ for (const [key, g] of groups) out.push({ key, result: ok(checkedList(g)) });
1037
+ return ok(checkedList(out));
1038
+ }
1039
+
868
1040
  /**
869
1041
  * This method joins the lists that are the values of the items of a list, in order (LIST.FLAT). Each list follows the
870
1042
  * rules of LIST.BUILD. A value that is not a list gives `#VALUE!`.
@@ -878,7 +1050,7 @@ class Compiler {
878
1050
  if (!good.ok) return good;
879
1051
  out.push(...good.value);
880
1052
  }
881
- return ok(vexList(out));
1053
+ return ok(checkedList(out));
882
1054
  }
883
1055
 
884
1056
  /**
@@ -904,7 +1076,7 @@ class Compiler {
904
1076
  // Stryker disable next-line ConditionalExpression,EqualityOperator: see the comment above
905
1077
  return a < b ? -1 : a > b ? 1 : 0;
906
1078
  });
907
- return ok(vexList(order.map((i) => items[i] as ListItem)));
1079
+ return ok(checkedList(order.map((i) => items[i] as ListItem)));
908
1080
  }
909
1081
 
910
1082
  /**
@@ -921,7 +1093,7 @@ class Compiler {
921
1093
  if (op !== undefined) break;
922
1094
  }
923
1095
  if (op === undefined) return this.#err("unknown-op", `no domain gives "${by}" for a ${describeType(x)}`, f, path, { op: by });
924
- const r = this.#call(op, by, [], f, path);
1096
+ const r = this.#callResolved(op, x, by, [], f, path);
925
1097
  if (!r.ok) return r;
926
1098
  out.push(r.value);
927
1099
  }
@@ -953,7 +1125,7 @@ class Compiler {
953
1125
  const d = this.#domains.find((dom) => safeIs(dom, acc) && resolveOp(dom, acc, opName) !== undefined);
954
1126
  const op = d === undefined ? undefined : resolveOp(d, acc, opName);
955
1127
  if (op === undefined) return this.#err("unknown-op", `no domain gives "${opName}" for a ${describeType(acc)}`, f, path, { op: opName });
956
- const r = this.#call(op, opName, [values[i]], f, path);
1128
+ const r = this.#callResolved(op, acc, opName, [values[i]], f, path);
957
1129
  if (!r.ok) return r;
958
1130
  acc = r.value;
959
1131
  }
@@ -962,20 +1134,42 @@ class Compiler {
962
1134
  }
963
1135
 
964
1136
  /** The list ops with a second argument before their options: a count, a position, an op name or a list. */
965
- const WITH_ARGUMENT: ReadonlySet<ListOp> = new Set<ListOp>(["reduce", "take", "nth", "drop", "append", "without", "get", "indexOf"]);
1137
+ const WITH_ARGUMENT: ReadonlySet<ListOp> = new Set<ListOp>(["reduce", "take", "nth", "drop", "append", "without", "get", "indexOf", "group", "join"]);
966
1138
 
967
1139
  /**
968
1140
  * This function gives the items of a list that have a value (LIST.LENIENT). A list op does not skip `#DEPTH!`, so that
969
1141
  * error comes first (EVAL.DEPTH). With `strict`, the first error item is the result.
970
1142
  */
971
1143
  function goodItems(list: VexList, strict: boolean): Result<readonly ListItem[]> {
972
- const depth = list.items.find((it) => !it.result.ok && isDepthError(it.result.error))?.result;
973
- if (depth !== undefined && !depth.ok) return fail(depth.error);
974
- const firstError = list.items.find((it) => !it.result.ok)?.result;
975
- if (strict && firstError !== undefined && !firstError.ok) return fail(firstError.error);
976
- return ok(list.items.filter((it) => it.result.ok));
1144
+ const { items } = list;
1145
+ let first: VexError | undefined;
1146
+ for (const it of items) {
1147
+ if (it.result.ok) continue;
1148
+ if (isDepthError(it.result.error)) return fail(it.result.error);
1149
+ first ??= it.result.error;
1150
+ }
1151
+ // A list without error items gives its own items: no copy. Nothing changes them: the items of `vexList` are frozen,
1152
+ // and each list op makes a new array.
1153
+ if (first === undefined) return ok(items);
1154
+ if (strict) return fail(first);
1155
+ const out: ListItem[] = [];
1156
+ for (const it of items) if (it.result.ok) out.push(it);
1157
+ return ok(out);
977
1158
  }
978
1159
 
1160
+ /**
1161
+ * This function makes a list from the items of lists that passed the check of LIST.SHAPE, or from items of the same
1162
+ * shape. Thus the list skips the check of `isVexList`.
1163
+ */
1164
+ function checkedList(items: readonly ListItem[]): VexList {
1165
+ const list = vexList(items);
1166
+ CHECKED.add(list);
1167
+ return list;
1168
+ }
1169
+
1170
+ /** This function gives the value of an item with a value. */
1171
+ const valueOf = (it: ListItem): unknown => (it.result as { readonly value: unknown }).value;
1172
+
979
1173
  /** The index of the keys of a list (LIST.GET): the value of the first item of each key, and the first errors. */
980
1174
  interface KeyIndex {
981
1175
  readonly values: ReadonlyMap<string, unknown>;
@@ -1006,9 +1200,18 @@ const FORBIDDEN_FIELDS = new Set(["__proto__", "constructor", "prototype"]);
1006
1200
  /** This function tells if a segment of a path can name a field. A compiler uses the same rule as the interpreter. */
1007
1201
  export const isFieldName = (seg: string): boolean => seg.length > 0 && !FORBIDDEN_FIELDS.has(seg);
1008
1202
 
1009
- /** This function runs the `is` test of a domain. A test that throws counts as `false`. */
1010
- // Stryker disable BlockStatement: an empty catch gives undefined, which also counts as false
1203
+ /**
1204
+ * This function tells if a domain accepts a value. A domain with a primitive type accepts each value of that type and
1205
+ * no other value (KIND.PRIMITIVE), so its test `is` does not start. For another domain, a test that throws counts as
1206
+ * `false`.
1207
+ */
1011
1208
  export function safeIs(d: AnyDomain, value: unknown): boolean {
1209
+ return d.primitive !== undefined ? typeof value === d.primitive : testIs(d, value);
1210
+ }
1211
+
1212
+ /** This function starts the `is` test of a domain. A test that throws counts as `false`. */
1213
+ // Stryker disable BlockStatement: an empty catch gives undefined, which also counts as false
1214
+ function testIs(d: AnyDomain, value: unknown): boolean {
1012
1215
  try {
1013
1216
  return d.is(value);
1014
1217
  } catch {