@mark1russell7/vex 0.17.2 → 0.19.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,16 +1,28 @@
1
1
  import { CHECKED } from "./checked.ts";
2
2
  import { fromDocument, isDocument, type Envelope } from "./document.ts";
3
- import { findMethod, isOpName, liftsAt, resolveOp, type AnyDomain, type OpSpec, type ParamKind, type PrimitiveKind, type ResolvedOp } from "./domain.ts";
3
+ import { fixRounds, fixValueError, joinValues, worstRow } from "./fix.ts";
4
+ import { findMethod, isOpName, liftsAt, resolveOp, type AnyDomain, type Monotone, type OpSpec, type ParamKind, type PrimitiveKind, type ResolvedOp, type ReturnKind, type SizeRule } from "./domain.ts";
5
+ import { describeType, errorAt, errorText, type ErrorExtra, type ErrorText } from "./error-text.ts";
4
6
  import { formatError, isDepthError, isStackOverflow, vexError, type ErrorKind, type VexError } from "./errors.ts";
5
- import { addrExprs, children, shapeError, type Addr, type Axis, type Expr, type ExprOf, type FixedMove, type ItemNames, type Move } from "./ir.ts";
7
+ import { limitError, overLimitMessage, worstError } from "./limit-error.ts";
8
+ import { addrExprs, children, limitAxis, MAX_ITERATIONS, shapeError, type Addr, type Axis, type Expr, type ExprOf, type FixedMove, type ItemNames, type Move } from "./ir.ts";
6
9
  import { asList, fillList, isFillCount, isIndexValue, listOfArray } from "./array-list.ts";
10
+ import { monotoneError } from "./monotone.ts";
11
+ import { sizeError } from "./size.ts";
12
+ import { stepError, type VexStep } from "./steps.ts";
7
13
  import { isListOp, isVexList, vexList, type ListItem, type ListOp, type ListOptions, type VexList } from "./list.ts";
8
14
  import { fail, ok, type Result } from "./result.ts";
9
15
  import { axisTargets, fixAddr, resolveAddr, type Position, type Space } from "./space.ts";
10
16
  import type { Read, Trace, TraceEvent, TraceSink } from "./trace.ts";
11
17
 
12
- /** A free function op. The interpreter gives it the values of all arguments. */
13
- export type FreeFn = (...args: readonly unknown[]) => unknown;
18
+ export { describeType };
19
+
20
+ /**
21
+ * A free function op. The interpreter gives it the values of all arguments. The property `size` is its size rule
22
+ * (LOOP.SIZE.OPS). Without it, a step of a loop cannot use its result in the size of a list name. The property
23
+ * `returns` is the kind of its result, as in `OpSpec`. The interpreter does not examine it.
24
+ */
25
+ export type FreeFn = ((...args: readonly unknown[]) => unknown) & { readonly size?: SizeRule; readonly returns?: ReturnKind; readonly monotone?: readonly Monotone[] };
14
26
 
15
27
  /** The context of an extension handler. */
16
28
  export interface ExtContext {
@@ -40,11 +52,16 @@ export interface EvalOptions {
40
52
  readonly tables?: Readonly<Record<string, Space>>;
41
53
  /** A receiver of trace events. */
42
54
  readonly trace?: TraceSink;
55
+ /**
56
+ * The highest step of the language that the host accepts (STEP.MAX). The default is B. A program that needs a higher
57
+ * step gives `#VALUE!` before the evaluation, and the reason names its step.
58
+ */
59
+ readonly maxStep?: VexStep;
43
60
  }
44
61
 
45
62
  /** The names of a frame: a map of the variables of the caller, or a scope inside it. */
46
63
  interface Env {
47
- get(name: string): Result<unknown> | undefined;
64
+ get(name: string | symbol): Result<unknown> | undefined;
48
65
  }
49
66
 
50
67
  /**
@@ -54,16 +71,16 @@ interface Env {
54
71
  */
55
72
  class Scope implements Env {
56
73
  readonly #outer: Env;
57
- readonly #names: readonly string[];
74
+ readonly #names: readonly (string | symbol)[];
58
75
  readonly #values: readonly Result<unknown>[];
59
76
 
60
- constructor(outer: Env, names: readonly string[], values: readonly Result<unknown>[]) {
77
+ constructor(outer: Env, names: readonly (string | symbol)[], values: readonly Result<unknown>[]) {
61
78
  this.#outer = outer;
62
79
  this.#names = names;
63
80
  this.#values = values;
64
81
  }
65
82
 
66
- get(name: string): Result<unknown> | undefined {
83
+ get(name: string | symbol): Result<unknown> | undefined {
67
84
  const at = this.#names.indexOf(name);
68
85
  return at >= 0 ? this.#values[at] : this.#outer.get(name);
69
86
  }
@@ -92,7 +109,7 @@ export const SPECIAL_FORMS: ReadonlySet<string> = new Set<SpecialForm>(["if", "a
92
109
  const isSpecialForm = (op: string): op is SpecialForm => SPECIAL_FORMS.has(op);
93
110
 
94
111
  /** The options that a compiled program keeps: the domains, the free functions and the extension handlers. */
95
- export type CompileOptions = Pick<EvalOptions, "domains" | "fns" | "extensions">;
112
+ export type CompileOptions = Pick<EvalOptions, "domains" | "fns" | "extensions" | "maxStep">;
96
113
 
97
114
  /** The options of one run of a compiled program. */
98
115
  export type RunOptions = Pick<EvalOptions, "space" | "origin" | "vars" | "trace" | "tables">;
@@ -126,6 +143,9 @@ class Closure {
126
143
  }
127
144
  }
128
145
 
146
+ /** This function gives the error of an origin that is not a key of the space (EVAL.ORIGIN). */
147
+ export const noKeyError = (origin: string): VexError => vexError("unknown-key", `the space has no key "${origin}"`, { origin, focus: origin });
148
+
129
149
  /** The deepest nesting of an expression that `compile` accepts (EVAL.NESTING). */
130
150
  export const MAX_NESTING = 500;
131
151
 
@@ -143,10 +163,40 @@ export function nestingOf(e: Expr): number {
143
163
  return deepest;
144
164
  }
145
165
 
166
+ /** This function gives the reason of the refusal of an expression that is nested too deep (EVAL.NESTING), or undefined. */
167
+ export function nestingError(e: Expr): string | undefined {
168
+ const nesting = nestingOf(e);
169
+ return nesting > MAX_NESTING ? `the expression is nested ${String(nesting)} levels deep, and the limit is ${String(MAX_NESTING)}` : undefined;
170
+ }
171
+
146
172
  /**
147
173
  * This function compiles an expression or a document (DOC.ENTRY). The result gives the same results and the same traces
148
174
  * as `evaluate`, because `evaluate` uses it too.
149
175
  */
176
+ /**
177
+ * The list ops of `compile` for the values of a host (LIST.OPS). A result has the rules of the interpreter. An error of
178
+ * the op has the position and the path of the call, and an error of an item keeps its own.
179
+ */
180
+ export interface ListOps {
181
+ /** This function gives the result of a list op on a list. The list is the receiver, and `rest` has the other arguments. */
182
+ readonly list: (op: ListOp, list: VexList, rest: readonly unknown[], position: Position, path: readonly number[]) => Result<unknown>;
183
+ /** This function gives the result of a list op on an array (LIST.ARRAY). A missing item is an error item with the position and the path. */
184
+ readonly array: (op: ListOp, array: readonly unknown[], rest: readonly unknown[], position: Position, path: readonly number[]) => Result<unknown>;
185
+ /** This function gives the result of `fill` (LIST.FILL). */
186
+ readonly fill: (values: readonly unknown[], position: Position, path: readonly number[]) => Result<VexList>;
187
+ }
188
+
189
+ /** This function gives the list ops of `compile` for the options. It keeps the index of each list that `get` read. */
190
+ export function listOps(opts: CompileOptions = {}): ListOps {
191
+ const compiler = new Compiler(opts);
192
+ const names = new Map<string, Result<unknown>>();
193
+ return {
194
+ list: (op, list, rest, pos, path) => compiler.listOp(op, list, rest, { pos, env: names }, path),
195
+ array: (op, array, rest, pos, path) => compiler.arrayOp(op, array, rest, { pos, env: names }, path),
196
+ fill: (values, pos, path) => compiler.fill(values, { pos, env: names }, path),
197
+ };
198
+ }
199
+
150
200
  export function compile(source: Expr | Envelope, opts: CompileOptions = {}): Program {
151
201
  // DOC.ENTRY: a document gives its expression first. A document that is not valid gives the error of fromDocument.
152
202
  const read = isDocument(source) ? fromDocument(source, opts.domains) : ok(source);
@@ -154,13 +204,16 @@ export function compile(source: Expr | Envelope, opts: CompileOptions = {}): Pro
154
204
  // EVAL.SHAPE: an expression that is not valid, for example from a newer version of Vex, gives an error before a walk.
155
205
  // EVAL.NESTING: a program nested too deep gives an error before the compiler walks it with recursion.
156
206
  const shape = read.ok ? shapeError(expr) : read.error.message;
157
- const nesting = shape === undefined ? nestingOf(expr) : 0;
158
- const bad = shape ?? (nesting > MAX_NESTING ? `the expression is nested ${nesting} levels deep, and the limit is ${MAX_NESTING}` : undefined);
207
+ const deep = shape ?? nestingError(expr);
208
+ // LOOP.SIZE: a step of a loop that can double the size of a list at each step gives an error before a run.
209
+ // STEP.MAX: a program above the highest step of the host gives an error before a run.
210
+ // FIX.MONOTONE: a step of a fixed point without a proof that it moves one way gives an error before a run.
211
+ const bad = deep ?? sizeError(expr, opts) ?? stepError(expr, opts) ?? monotoneError(expr, opts);
159
212
  const kind = read.ok ? "bad-expression" : read.error.kind;
160
213
  const root: Node = bad === undefined ? new Compiler(opts).node(expr, []) : (f) => fail(vexError(kind, bad, { path: [], origin: f.pos.origin, focus: f.pos.focus }));
161
214
  const run = (r: RunOptions): Result<unknown> => {
162
215
  const { space, origin } = r;
163
- if (!space.has(origin)) return fail(vexError("unknown-key", `the space has no key "${origin}"`, { origin, focus: origin }));
216
+ if (!space.has(origin)) return fail(noKeyError(origin));
164
217
  const env = new Map<string, Result<unknown>>(Object.entries(r.vars ?? {}).map(([k, val]) => [k, ok(val)]));
165
218
  try {
166
219
  return root({ pos: { origin, focus: origin }, env }, { space, trace: r.trace, tables: r.tables });
@@ -182,7 +235,7 @@ export function compile(source: Expr | Envelope, opts: CompileOptions = {}): Pro
182
235
  }
183
236
 
184
237
  // The cache of compiled programs: one entry for each expression object or document, for the last options.
185
- const CACHE = new WeakMap<Expr | Envelope, { readonly domains: unknown; readonly fns: unknown; readonly extensions: unknown; readonly program: Program }>();
238
+ const CACHE = new WeakMap<Expr | Envelope, { readonly domains: unknown; readonly fns: unknown; readonly extensions: unknown; readonly maxStep: unknown; readonly program: Program }>();
186
239
 
187
240
  function compiled(expr: Expr | Envelope, opts: CompileOptions): Program {
188
241
  // V-056: a program that is not an object cannot be a key of the cache. Its compilation gives #VALUE! (EVAL.SHAPE).
@@ -191,9 +244,9 @@ function compiled(expr: Expr | Envelope, opts: CompileOptions): Program {
191
244
  // Without the cache, each evaluation compiles again: the result is the same, so a mutant that removes a hit is
192
245
  // equivalent. A false hit changes results, and the tests find it.
193
246
  // Stryker disable next-line ConditionalExpression: a missed hit only compiles again
194
- if (hit !== undefined && hit.domains === opts.domains && hit.fns === opts.fns && hit.extensions === opts.extensions) return hit.program;
247
+ if (hit !== undefined && hit.domains === opts.domains && hit.fns === opts.fns && hit.extensions === opts.extensions && hit.maxStep === opts.maxStep) return hit.program;
195
248
  const program = compile(expr, opts);
196
- CACHE.set(expr, { domains: opts.domains, fns: opts.fns, extensions: opts.extensions, program });
249
+ CACHE.set(expr, { domains: opts.domains, fns: opts.fns, extensions: opts.extensions, maxStep: opts.maxStep, program });
197
250
  return program;
198
251
  }
199
252
 
@@ -283,6 +336,8 @@ class Compiler {
283
336
  readonly #ofType = new Map<string, readonly AnyDomain[]>();
284
337
  /** The domains without a primitive type. Only they can accept a value of another type, for example an object. */
285
338
  readonly #open: readonly AnyDomain[];
339
+ /** The slot of the column of each `fix` around the node that the compiler reads (FIX.LAST). A symbol is no name of the program. */
340
+ #columns: ReadonlyMap<string, symbol> = new Map();
286
341
 
287
342
  constructor(opts: CompileOptions) {
288
343
  // Stryker disable next-line ArrayDeclaration: a list with a value that is not a domain matches no value
@@ -297,13 +352,18 @@ class Compiler {
297
352
  return fail(vexError(kind, message, { path, origin: f.pos.origin, focus: f.pos.focus, ...extra }));
298
353
  }
299
354
 
355
+ /** This method gives the error of a text at a node (`errorAt`). */
356
+ #at(text: ErrorText, f: Frame, path: readonly number[], extra?: ErrorExtra): Result<never> {
357
+ return fail(errorAt(text, f.pos, path, extra));
358
+ }
359
+
300
360
  /** This method gives the error of a position of an array without a value (LIST.ARRAY), at a node. */
301
361
  #missing(f: Frame, path: readonly number[]): (message: string) => VexError {
302
362
  return (message) => vexError("missing-field", message, { path, origin: f.pos.origin, focus: f.pos.focus });
303
363
  }
304
364
 
305
365
  /** This method gives the list of `fill(n, value)` (LIST.FILL). A count that is not a whole number from 0 to 100000 gives `#VALUE!`. */
306
- #fill(values: readonly unknown[], f: Frame, path: readonly number[]): Result<VexList> {
366
+ fill(values: readonly unknown[], f: Frame, path: readonly number[]): Result<VexList> {
307
367
  const [n, value] = values;
308
368
  if (!isFillCount(n)) return this.#err("kind-mismatch", `"fill" needs a whole number from 0 to 100000, not ${describeType(n)}`, f, path, { op: "fill" });
309
369
  if (value === undefined) return this.#err("bad-expression", '"fill" needs argument 2', f, path, { op: "fill" });
@@ -344,8 +404,8 @@ class Compiler {
344
404
  return (f, c) => {
345
405
  const bound = f.env.get(name);
346
406
  // A function is not a value (FN.VALUE).
347
- if (bound?.ok === true && bound.value instanceof Closure) return this.#emit(c, info, f, this.#err("kind-mismatch", `the name "${name}" is a function, not a value`, f, path));
348
- return this.#emit(c, info, f, bound ?? this.#err("unbound", `the name "${name}" has no binding`, f, path));
407
+ if (bound?.ok === true && bound.value instanceof Closure) return this.#emit(c, info, f, this.#at(errorText.functionValue(name), f, path));
408
+ return this.#emit(c, info, f, bound ?? this.#at(errorText.unbound(name), f, path));
349
409
  };
350
410
  }
351
411
  case "fn":
@@ -382,11 +442,15 @@ class Compiler {
382
442
  return this.#fold(e, info);
383
443
  case "iterate":
384
444
  return this.#iterate(e, info);
445
+ case "fix":
446
+ return this.#fix(e, info);
447
+ case "last":
448
+ return this.#last(e, info);
385
449
  case "ext": {
386
450
  const extensions = this.#extensions ?? {};
387
451
  const handler = Object.hasOwn(extensions, e.kind) ? extensions[e.kind] : undefined;
388
452
  const { kind, data } = e;
389
- if (handler === undefined) return (f, c) => this.#emit(c, info, f, this.#err("unknown-op", `no handler for the extension kind "${kind}"`, f, path));
453
+ if (handler === undefined) return (f, c) => this.#emit(c, info, f, this.#at(errorText.noHandler(kind), f, path));
390
454
  return (f, c) =>
391
455
  this.#emit(c, info, f, this.#locate(this.#guard(() => handler(data, { space: c.space, position: f.pos, path }), f, path, kind), f, path));
392
456
  }
@@ -415,11 +479,11 @@ class Compiler {
415
479
  const args = this.#nodes(e.args, path);
416
480
  return (f, c) => {
417
481
  const bound = f.env.get(e.fn);
418
- if (bound === undefined) return this.#emit(c, info, f, this.#err("unbound", `the function "${e.fn}" has no binding`, f, path));
482
+ if (bound === undefined) return this.#emit(c, info, f, this.#at(errorText.noFunction(e.fn), f, path));
419
483
  if (!bound.ok) return this.#emit(c, info, f, bound);
420
484
  const callee = bound.value;
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));
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));
485
+ if (!(callee instanceof Closure)) return this.#emit(c, info, f, this.#at(errorText.notFunction(e.fn), f, path));
486
+ if (callee.params.length !== args.length) return this.#emit(c, info, f, this.#at(errorText.arity(e.fn, callee.params.length, args.length), f, path));
423
487
  const values: Result<unknown>[] = [];
424
488
  for (const n of args) values.push(n(f, c));
425
489
  return this.#emit(c, info, f, callee.body({ pos: f.pos, env: new Scope(callee.env, callee.params, values) }, c));
@@ -436,13 +500,13 @@ class Compiler {
436
500
  try {
437
501
  return run();
438
502
  } catch (thrown) {
439
- return this.#threw(thrown, `"${op}" threw an exception`, f, path, { op });
503
+ return this.#threw(thrown, errorText.threw(op), f, path);
440
504
  }
441
505
  }
442
506
 
443
507
  /** This method gives the error of an exception: `#DEPTH!` for a full call stack, and `#CALC!` for each other exception. */
444
- #threw(thrown: unknown, message: string, f: Frame, path: readonly number[], extra: Partial<VexError> = {}): Result<never> {
445
- return isStackOverflow(thrown) ? this.#err("depth", DEPTH_MESSAGE, f, path, { ...extra, thrown }) : this.#err("threw", message, f, path, { ...extra, thrown });
508
+ #threw(thrown: unknown, text: ErrorText, f: Frame, path: readonly number[]): Result<never> {
509
+ return this.#at(isStackOverflow(thrown) ? { ...text, kind: "depth", message: DEPTH_MESSAGE } : text, f, path, { thrown });
446
510
  }
447
511
 
448
512
  /**
@@ -483,7 +547,7 @@ class Compiler {
483
547
  key = where.value;
484
548
  }
485
549
  const failed = (r: Result<unknown>): Result<unknown> => this.#emit(c, info, f, r, [{ key, path: segs, ok: false }]);
486
- const missing = (where: string): Result<unknown> => failed(this.#err("missing-field", `the record at "${key}" has no value at "${where}"`, f, path));
550
+ const missing = (where: string): Result<unknown> => failed(this.#at(errorText.missing(key, where), f, path));
487
551
  let value: unknown = c.space.get(key);
488
552
  if (value === undefined || value === null) return missing(label === "" ? "(record)" : label);
489
553
  for (const { seg, where, valid } of steps) {
@@ -491,7 +555,7 @@ class Compiler {
491
555
  try {
492
556
  value = Reflect.get(value, seg);
493
557
  } catch (thrown) {
494
- return failed(this.#threw(thrown, `reading "${where}" at "${key}" threw an exception`, f, path));
558
+ return failed(this.#threw(thrown, errorText.readThrew(key, where), f, path));
495
559
  }
496
560
  if (value === undefined || value === null) return missing(where);
497
561
  }
@@ -514,7 +578,7 @@ class Compiler {
514
578
  // A #DEPTH! argument is the result, so #ARGS does not wrap it, and ifError cannot hide it.
515
579
  const depth = [first, ...(errors ?? [])].find(isDepthError);
516
580
  if (depth !== undefined) return fail(depth);
517
- return errors === undefined ? fail(first) : this.#err("args", `${errors.length} ${what} failed`, f, path, { causes: errors });
581
+ return errors === undefined ? fail(first) : this.#at(errorText.args(errors.length, what), f, path, { causes: errors });
518
582
  }
519
583
 
520
584
  #each(e: ExprOf<"each">, info: Info): Node {
@@ -536,12 +600,9 @@ class Compiler {
536
600
  // The axis table moves the evaluation to the space of its table, where the origin of this space is not a key.
537
601
  // Thus there the origin is the target, and a value of this space goes in through a variable.
538
602
  const base = baseAxis(e.axis);
539
- let inner = c;
540
- if (base.t === "table") {
541
- const space = c.tables !== undefined && Object.hasOwn(c.tables, base.name) ? c.tables[base.name] : undefined;
542
- if (space === undefined) return this.#emit(c, info, f, this.#err("no-table", `the evaluation has no table "${base.name}"`, f, path));
543
- inner = { ...c, space };
544
- }
603
+ const axisCtx = this.#axisCtx(base, f, c, path);
604
+ if (!axisCtx.ok) return this.#emit(c, info, f, axisCtx);
605
+ const inner = axisCtx.value;
545
606
  const ts = targets(from, inner);
546
607
  if (!ts.ok) return this.#emit(c, info, f, ts);
547
608
  const items: ListItem[] = ts.value.map((t) => {
@@ -605,12 +666,9 @@ class Compiler {
605
666
  if (!where.ok) return this.#emit(c, info, f, where);
606
667
  from = { pos: { origin: f.pos.origin, focus: where.value }, env: f.env };
607
668
  }
608
- let inner = c;
609
- if (base.t === "table") {
610
- const space = c.tables !== undefined && Object.hasOwn(c.tables, base.name) ? c.tables[base.name] : undefined;
611
- if (space === undefined) return this.#emit(c, info, f, this.#err("no-table", `the evaluation has no table "${base.name}"`, f, path));
612
- inner = { ...c, space };
613
- }
669
+ const axisCtx = this.#axisCtx(base, f, c, path);
670
+ if (!axisCtx.ok) return this.#emit(c, info, f, axisCtx);
671
+ const inner = axisCtx.value;
614
672
  const ts = targets(from, inner);
615
673
  if (!ts.ok) return this.#emit(c, info, f, ts);
616
674
  for (const t of ts.value) {
@@ -628,28 +686,125 @@ class Compiler {
628
686
  * This method compiles an iteration (ITERATE.LIMIT, ITERATE.UNTIL, ITERATE.ERROR). The test `until` evaluates before
629
687
  * each step and after the last step. `result` evaluates with the last values.
630
688
  */
689
+ /**
690
+ * This method compiles a fixed-point column (FIX.ROUNDS). Each round evaluates each row from the column of the last
691
+ * round, so the order of the rows has no effect. The first round without a change ends the rounds.
692
+ */
693
+ #fix(e: ExprOf<"fix">, info: Info): Node {
694
+ const { path } = info;
695
+ const { name, join } = e;
696
+ const init = this.node(e.init, [...path, 0]);
697
+ const slot = Symbol(name);
698
+ const outer = this.#columns;
699
+ this.#columns = new Map(outer).set(name, slot);
700
+ const step = this.node(e.step, [...path, 1]);
701
+ this.#columns = outer;
702
+ return (f, c) => {
703
+ const { keys } = c.space;
704
+ const first = this.#rows(e, init, f, f.env, c, path);
705
+ if (!first.ok) return this.#emit(c, info, f, first);
706
+ let column = first.value;
707
+ this.#round(c, info, f, 0, keys, column);
708
+ const limit = fixRounds(keys.length);
709
+ for (let round = 1; round <= limit; round++) {
710
+ const stepped = this.#rows(e, step, f, new Scope(f.env, [slot], [ok(column)]), c, path);
711
+ if (!stepped.ok) return this.#emit(c, info, f, stepped);
712
+ const next = new Map<string, unknown>();
713
+ const changed: string[] = [];
714
+ for (const key of keys) {
715
+ const old = column.get(key);
716
+ const value = joinValues(join, old, stepped.value.get(key));
717
+ if (value !== old) changed.push(key);
718
+ next.set(key, value);
719
+ }
720
+ this.#round(c, info, f, round, changed, next);
721
+ if (changed.length === 0) return this.#emit(c, info, f, this.#rowOf(name, column, f, path));
722
+ column = next;
723
+ }
724
+ return this.#emit(c, info, f, this.#at(errorText.fixLimit(name, limit), f, path));
725
+ };
726
+ }
727
+
728
+ /** This method evaluates a node at each row (FIX.ERROR). Each row runs, also after an error, so the rule of the errors has all of them. */
729
+ #rows(e: ExprOf<"fix">, node: Node, f: Frame, env: Env, c: Ctx, path: readonly number[]): Result<ReadonlyMap<string, unknown>> {
730
+ const out = new Map<string, unknown>();
731
+ const errors: VexError[] = [];
732
+ for (const key of c.space.keys) {
733
+ const frame: Frame = { pos: { origin: f.pos.origin, focus: key }, env };
734
+ const r = node(frame, c);
735
+ const wrong = r.ok ? fixValueError(e.name, e.join, r.value) : undefined;
736
+ if (!r.ok) errors.push(r.error);
737
+ else if (wrong !== undefined) errors.push(errorAt(wrong, frame.pos, path));
738
+ else out.set(key, r.value);
739
+ }
740
+ if (errors.length === 0) return ok(out);
741
+ const worst = worstRow(errors);
742
+ return worst === undefined ? this.#at(errorText.args(errors.length, "rows"), f, path, { causes: errors }) : fail(worst);
743
+ }
744
+
745
+ /** This method adds a round to the trace: the count of the round, the rows that it changed and the column (FIX.TRACE). */
746
+ #round(c: Ctx, info: Info, f: Frame, round: number, changed: readonly string[], column: ReadonlyMap<string, unknown>): void {
747
+ if (c.trace === undefined) return;
748
+ const items = [...column].map(([key, value]): ListItem => ({ key, result: ok(value) }));
749
+ c.trace.events.push({
750
+ path: info.path,
751
+ tag: info.tag,
752
+ label: `${info.label}: round ${String(round)}, ${String(changed.length)} rows changed`,
753
+ origin: f.pos.origin,
754
+ focus: f.pos.focus,
755
+ round: { index: round, changed },
756
+ result: ok(vexList(items)),
757
+ });
758
+ }
759
+
760
+ /** This method gives the value of the row of the focus. The focus of an item of the axis `list` can be no row (FIX.LAST). */
761
+ #rowOf(name: string, column: ReadonlyMap<string, unknown>, f: Frame, path: readonly number[]): Result<unknown> {
762
+ const value = column.get(f.pos.focus);
763
+ return value === undefined ? this.#at(errorText.lastKey(name, f.pos.focus), f, path) : ok(value);
764
+ }
765
+
766
+ /** This method compiles a read of the last round at the focus (FIX.LAST). The check gives each read a `fix`. */
767
+ #last(e: ExprOf<"last">, info: Info): Node {
768
+ const { path } = info;
769
+ const slot = this.#columns.get(e.name) as symbol;
770
+ return (f, c) => {
771
+ const column = f.env.get(slot) as { readonly value: ReadonlyMap<string, unknown> };
772
+ return this.#emit(c, info, f, this.#rowOf(e.name, column.value, f, path));
773
+ };
774
+ }
775
+
631
776
  #iterate(e: ExprOf<"iterate">, info: Info): Node {
632
777
  const { path } = info;
633
778
  const names = this.#names(e, path);
634
- const untilAt = Object.keys(e.init).length + Object.keys(e.step).length;
779
+ const counter = { next: Object.keys(e.init).length + Object.keys(e.step).length };
780
+ const axis = limitAxis(e);
781
+ const size = axis === undefined ? undefined : this.#size(axis, path, counter);
782
+ const untilAt = counter.next;
635
783
  const untilPath = [...path, untilAt];
636
784
  const until = e.until === undefined ? undefined : this.node(e.until, untilPath);
637
785
  const result = this.node(e.result, [...path, untilAt + (until === undefined ? 0 : 1)]);
638
- const { limit } = e;
786
+ const fixed = e.limit as number;
639
787
  return (f, c) => {
640
788
  const first = names.first(f, c);
641
789
  if (!first.ok) return this.#emit(c, info, f, first);
642
790
  let env = first.value;
791
+ let limit = fixed;
792
+ // The data limit evaluates at the node, after the first values and before the steps (ITERATE.LIMIT.DATA).
793
+ if (size !== undefined) {
794
+ const counted = size(f, c);
795
+ if (!counted.ok) return this.#emit(c, info, f, counted);
796
+ limit = counted.value;
797
+ }
643
798
  for (let k = 0; ; k++) {
644
799
  const frame: Frame = { pos: f.pos, env };
645
800
  if (until !== undefined) {
646
801
  const t = until(frame, c);
647
802
  if (!t.ok) return this.#emit(c, info, f, t);
648
803
  if (t.value === true) break;
649
- if (t.value !== false) return this.#emit(c, info, f, this.#err("kind-mismatch", `the test "until" of "iterate" gave a ${typeof t.value}, not a boolean`, f, untilPath));
804
+ if (t.value !== false) return this.#emit(c, info, f, this.#at(errorText.untilKind(t.value), f, untilPath));
650
805
  }
651
806
  if (k === limit) {
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));
807
+ if (until !== undefined) return this.#emit(c, info, f, this.#at(errorText.limit(limit), f, path));
653
808
  break;
654
809
  }
655
810
  const after = names.next(frame, c, env);
@@ -660,6 +815,33 @@ class Compiler {
660
815
  };
661
816
  }
662
817
 
818
+ /**
819
+ * This method compiles a data limit: the number of targets of an axis (ITERATE.LIMIT.DATA). Each failure of the axis, of
820
+ * a test or of an item, and a count above the cap, is one error (ITERATE.LIMIT.ERROR).
821
+ */
822
+ #size(axis: Axis, path: readonly number[], counter: { next: number }): (f: Frame, c: Ctx) => Result<number> {
823
+ const targets = this.#targets(axis, path, counter);
824
+ const base = baseAxis(axis);
825
+ const invalid = (f: Frame, cause: VexError): Result<never> => fail(limitError(cause, { path, origin: f.pos.origin, focus: f.pos.focus }));
826
+ return (f, c) => {
827
+ const inner = this.#axisCtx(base, f, c, path);
828
+ if (!inner.ok) return invalid(f, inner.error);
829
+ const ts = targets(f, inner.value);
830
+ if (!ts.ok) return invalid(f, ts.error);
831
+ const cause = worstError(ts.value.flatMap(({ test }) => (test === undefined || test.ok ? [] : test.error)));
832
+ if (cause !== undefined) return invalid(f, cause);
833
+ const count = ts.value.length;
834
+ return count > MAX_ITERATIONS ? this.#err("limit", overLimitMessage(count), f, path) : ok(count);
835
+ };
836
+ }
837
+
838
+ /** This method gives the context of an axis: the space of its table for the axis `table`, or `c` (AXIS.TABLE). */
839
+ #axisCtx(base: Axis, f: Frame, c: Ctx, path: readonly number[]): Result<Ctx> {
840
+ if (base.t !== "table") return ok(c);
841
+ const space = c.tables !== undefined && Object.hasOwn(c.tables, base.name) ? c.tables[base.name] : undefined;
842
+ return space === undefined ? this.#at(errorText.noTable(base.name), f, path) : ok({ ...c, space });
843
+ }
844
+
663
845
  /** This method compiles the targets of an axis. For `where`, a failed test keeps the target with its error. */
664
846
  #targets(a: Axis, path: readonly number[], counter: { next: number }): Targets {
665
847
  if (a.t === "table") return (_f, c) => ok(c.space.keys.map((key) => ({ key })));
@@ -691,7 +873,7 @@ class Compiler {
691
873
  // The target keeps the value and the index of its item (AXIS.LIST.ITEM).
692
874
  else if (r.value === true) out.push(t);
693
875
  else if (r.value !== false) {
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) });
876
+ out.push({ key: t.key, test: this.#at(errorText.whereKind(r.value), at, testPath) });
695
877
  }
696
878
  }
697
879
  return ok(out);
@@ -709,7 +891,7 @@ class Compiler {
709
891
  if (!r.ok) return r;
710
892
  // LIST.ARRAY: an array is a list with the positions as keys.
711
893
  const listed = asList(r.value, this.#missing(f, path));
712
- if (listed === undefined) return this.#err("kind-mismatch", `the axis "list" needs a list, not a ${describeType(r.value)}`, f, path);
894
+ if (listed === undefined) return this.#at(errorText.axisList(r.value), f, path);
713
895
  // The index counts the items with a value, as nth does: nth skips the error items (LIST.LENIENT).
714
896
  let index = 0;
715
897
  const items = listed.items.map(({ key, result }): Target => (result.ok ? { key, value: result.value, index: index++ } : { key, test: result }));
@@ -728,7 +910,7 @@ class Compiler {
728
910
  if (!all.ok) return this.#emit(c, info, f, all);
729
911
  const values = all.value;
730
912
  const self = values[0];
731
- if (listOp !== undefined && isVexList(self)) return this.#emit(c, info, f, this.#listOp(listOp, self, values.slice(1), f, path));
913
+ if (listOp !== undefined && isVexList(self)) return this.#emit(c, info, f, this.listOp(listOp, self, values.slice(1), f, path));
732
914
  let accepted: AnyDomain | undefined;
733
915
  // Without arguments, the receiver is undefined, and no domain of a test accepts it.
734
916
  // Stryker disable next-line ConditionalExpression,EqualityOperator: the loop finds no domain for undefined
@@ -746,11 +928,11 @@ class Compiler {
746
928
  }
747
929
  if (fn !== undefined) return this.#emit(c, info, f, this.#checkResult(this.#invoke(() => fn(...values), op, f, path), f, path, op));
748
930
  // LIST.ARRAY and LIST.FILL come after the domains and the functions of the host, so each of their results stays.
749
- if (listOp !== undefined && Array.isArray(self)) return this.#emit(c, info, f, this.#listOp(listOp, listOfArray(self, this.#missing(f, path)), values.slice(1), f, path));
750
- if (op === "fill") return this.#emit(c, info, f, this.#fill(values, f, path));
751
- if (accepted !== undefined) return this.#emit(c, info, f, this.#err("unknown-op", `the domain "${accepted.name}" has no op "${op}"`, f, path, { op }));
752
- if (values.length === 0) return this.#emit(c, info, f, this.#err("unknown-op", `there is no function "${op}"`, f, path, { op }));
753
- return this.#emit(c, info, f, this.#err("not-instance", `no domain accepts the receiver of "${op}" (${describeType(self)})`, f, path, { op }));
931
+ if (listOp !== undefined && Array.isArray(self)) return this.#emit(c, info, f, this.arrayOp(listOp, self, values.slice(1), f, path));
932
+ if (op === "fill") return this.#emit(c, info, f, this.fill(values, f, path));
933
+ if (accepted !== undefined) return this.#emit(c, info, f, this.#at(errorText.domainNoOp(accepted.name, op), f, path));
934
+ if (values.length === 0) return this.#emit(c, info, f, this.#at(errorText.noOp(op), f, path));
935
+ return this.#emit(c, info, f, this.#at(errorText.noDomain(op, self), f, path));
754
936
  };
755
937
  }
756
938
 
@@ -758,12 +940,12 @@ class Compiler {
758
940
  const { path } = info;
759
941
  const arg = (i: number, f: Frame, c: Ctx): Result<unknown> => {
760
942
  const n = args[i];
761
- return n === undefined ? this.#err("bad-expression", `"${op}" needs argument ${i + 1}`, f, path, { op }) : n(f, c);
943
+ return n === undefined ? this.#at(errorText.needsArgument(op, i), f, path) : n(f, c);
762
944
  };
763
945
  const bool = (i: number, f: Frame, c: Ctx): Result<boolean> => {
764
946
  const r = arg(i, f, c);
765
947
  if (!r.ok) return r;
766
- return typeof r.value === "boolean" ? ok(r.value) : this.#err("kind-mismatch", `argument ${i + 1} of "${op}" is a ${describeType(r.value)}, not a boolean`, f, path, { op });
948
+ return typeof r.value === "boolean" ? ok(r.value) : this.#at(errorText.notBoolean(op, i, r.value), f, path);
767
949
  };
768
950
  switch (op) {
769
951
  case "if":
@@ -775,7 +957,7 @@ class Compiler {
775
957
  case "or": {
776
958
  const stop = op === "or";
777
959
  return (f, c) => {
778
- if (args.length === 0) return this.#emit(c, info, f, this.#err("bad-expression", `"${op}" needs at least 1 argument`, f, path, { op }));
960
+ if (args.length === 0) return this.#emit(c, info, f, this.#at(errorText.needsArguments(op), f, path));
779
961
  for (let i = 0; i < args.length; i++) {
780
962
  const b = bool(i, f, c);
781
963
  if (!b.ok) return this.#emit(c, info, f, b);
@@ -814,17 +996,14 @@ class Compiler {
814
996
  if (spec.params !== undefined) {
815
997
  for (let i = 0; i < callArgs.length; i++) {
816
998
  const kind = spec.params[i] ?? "any";
817
- if (!matchesKind(kind, callArgs[i], domain)) {
818
- const k: ErrorKind = kind === "domain" ? "not-instance" : "kind-mismatch";
819
- return this.#err(k, `argument ${i + 1} of "${name}" is a ${describeType(callArgs[i])}, not a ${kind === "domain" ? domain.name : kind}`, f, path, { op: name });
820
- }
999
+ if (!matchesKind(kind, callArgs[i], domain)) return this.#at(errorText.badParam(name, i, callArgs[i], kind, domain.name), f, path);
821
1000
  }
822
1001
  }
823
1002
  let value: unknown;
824
1003
  try {
825
1004
  value = run(self, ...callArgs);
826
1005
  } catch (thrown) {
827
- return this.#threw(thrown, `"${name}" threw an exception`, f, path, { op: name });
1006
+ return this.#threw(thrown, errorText.threw(name), f, path);
828
1007
  }
829
1008
  return this.#checkResult(ok(value), f, path, name);
830
1009
  }
@@ -833,7 +1012,7 @@ class Compiler {
833
1012
  try {
834
1013
  return ok(run());
835
1014
  } catch (thrown) {
836
- return this.#threw(thrown, `"${op}" threw an exception`, f, path, { op });
1015
+ return this.#threw(thrown, errorText.threw(op), f, path);
837
1016
  }
838
1017
  }
839
1018
 
@@ -851,25 +1030,29 @@ class Compiler {
851
1030
  #checkResult(r: Result<unknown>, f: Frame, path: readonly number[], op: string): Result<unknown> {
852
1031
  if (!r.ok) return r;
853
1032
  const value = r.value;
854
- const extra = { op };
855
- if (value === undefined || value === null) return this.#err("undefined-result", `"${op}" gave no value`, f, path, extra);
856
- if (typeof value === "number" && !Number.isFinite(value)) return this.#err("not-finite", `"${op}" gave ${value}`, f, path, extra);
1033
+ if (value === undefined || value === null) return this.#at(errorText.noValue(op), f, path);
1034
+ if (typeof value === "number" && !Number.isFinite(value)) return this.#at(errorText.notFinite(op, value), f, path);
857
1035
  const d = this.#domainOf(value);
858
1036
  if (d?.valid !== undefined) {
859
1037
  let valid: boolean;
860
1038
  try {
861
1039
  valid = d.valid(value);
862
1040
  } catch (thrown) {
863
- return this.#threw(thrown, `the "valid" check of "${d.name}" threw an exception`, f, path, extra);
1041
+ return this.#threw(thrown, errorText.validThrew(op, d.name), f, path);
864
1042
  }
865
- if (!valid) return this.#err("invalid-value", `"${op}" gave a value that is not a valid ${d.name}`, f, path, extra);
1043
+ if (!valid) return this.#at(errorText.invalid(op, d.name), f, path);
866
1044
  }
867
1045
  return r;
868
1046
  }
869
1047
 
870
- #listOp(op: ListOp, list: VexList, rest: readonly unknown[], f: Frame, path: readonly number[]): Result<unknown> {
1048
+ /** This method gives the result of a list op on an array (LIST.ARRAY): the list op on the list of its items. */
1049
+ arrayOp(op: ListOp, array: readonly unknown[], rest: readonly unknown[], f: Frame, path: readonly number[]): Result<unknown> {
1050
+ return this.listOp(op, listOfArray(array, this.#missing(f, path)), rest, f, path);
1051
+ }
1052
+
1053
+ listOp(op: ListOp, list: VexList, rest: readonly unknown[], f: Frame, path: readonly number[]): Result<unknown> {
871
1054
  // The options come after the second argument of an op with one, for example the count of take.
872
- const optsArg = WITH_ARGUMENT.has(op) ? rest[1] : rest[0];
1055
+ const optsArg = op === "setNth" ? rest[2] : WITH_ARGUMENT.has(op) ? rest[1] : rest[0];
873
1056
  const strict = (optsArg as ListOptions | null | undefined)?.strict === true;
874
1057
  if (op === "get") return this.#get(list, rest[0], strict, f, path);
875
1058
  if (op === "group") return this.#group(list, rest[0], strict, f, path);
@@ -880,13 +1063,13 @@ class Compiler {
880
1063
  for (const it of okItems) okValues.push(valueOf(it));
881
1064
  const numbers = (): Result<readonly number[]> => {
882
1065
  const bad = okValues.find((x) => typeof x !== "number");
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 });
1066
+ return bad === undefined ? ok(okValues as readonly number[]) : this.#at(errorText.needsItems(op, "numbers", bad), f, path);
884
1067
  };
885
1068
  const booleans = (): Result<readonly boolean[]> => {
886
1069
  const bad = okValues.find((x) => typeof x !== "boolean");
887
- return bad === undefined ? ok(okValues as readonly boolean[]) : this.#err("kind-mismatch", `"${op}" needs booleans, but an item is a ${describeType(bad)}`, f, path, { op });
1070
+ return bad === undefined ? ok(okValues as readonly boolean[]) : this.#at(errorText.needsItems(op, "booleans", bad), f, path);
888
1071
  };
889
- const empty = (): Result<never> => this.#err("empty", `"${op}" has no values to work with`, f, path, { op });
1072
+ const empty = (): Result<never> => this.#at(errorText.empty(op), f, path);
890
1073
  // A count or a position of take, drop and nth is a whole number from 0.
891
1074
  const whole = (): Result<number> => {
892
1075
  const n = rest[0] as number;
@@ -949,6 +1132,16 @@ class Compiler {
949
1132
  if (!i.ok) return i;
950
1133
  return i.value < okValues.length ? ok(okValues[i.value]) : this.#err("empty", `"nth" has no item at the position ${String(i.value)}, and the list has ${String(okValues.length)} items`, f, path, { op });
951
1134
  }
1135
+ case "setNth": {
1136
+ const i = whole();
1137
+ if (!i.ok) return i;
1138
+ const old = okItems[i.value];
1139
+ if (old === undefined) return this.#err("empty", `"setNth" has no item at the position ${String(i.value)}, and the list has ${String(okItems.length)} items`, f, path, { op });
1140
+ if (rest[1] === undefined) return this.#err("bad-expression", '"setNth" needs argument 3', f, path, { op });
1141
+ const items = [...okItems];
1142
+ items[i.value] = { key: old.key, result: ok(rest[1]) };
1143
+ return ok(checkedList(items));
1144
+ }
952
1145
  case "count":
953
1146
  return ok(okValues.length);
954
1147
  case "values":
@@ -1092,7 +1285,7 @@ class Compiler {
1092
1285
  op = safeIs(d, x) ? resolveOp(d, x, by) : undefined;
1093
1286
  if (op !== undefined) break;
1094
1287
  }
1095
- if (op === undefined) return this.#err("unknown-op", `no domain gives "${by}" for a ${describeType(x)}`, f, path, { op: by });
1288
+ if (op === undefined) return this.#at(errorText.noStep(by, x), f, path);
1096
1289
  const r = this.#callResolved(op, x, by, [], f, path);
1097
1290
  if (!r.ok) return r;
1098
1291
  out.push(r.value);
@@ -1105,7 +1298,7 @@ class Compiler {
1105
1298
  * domain has an identity for the op (LIST.EMPTY). The option `domain` names that domain when more domains have one.
1106
1299
  */
1107
1300
  #reduce(opName: unknown, values: readonly unknown[], f: Frame, path: readonly number[], opts: unknown): Result<unknown> {
1108
- if (typeof opName !== "string") return this.#err("kind-mismatch", `"reduce" needs an op name, but got a ${describeType(opName)}`, f, path, { op: "reduce" });
1301
+ if (typeof opName !== "string") return this.#at(errorText.reduceName(opName), f, path);
1109
1302
  if (values.length === 0) {
1110
1303
  const named = (opts as { domain?: unknown } | null | undefined)?.domain;
1111
1304
  const candidates = this.#domains.filter((d) => Object.hasOwn(d.ops, opName) && (d.ops[opName] as { identity?: () => unknown }).identity !== undefined && (named === undefined || d.name === named));
@@ -1124,7 +1317,7 @@ class Compiler {
1124
1317
  for (let i = 1; i < values.length; i++) {
1125
1318
  const d = this.#domains.find((dom) => safeIs(dom, acc) && resolveOp(dom, acc, opName) !== undefined);
1126
1319
  const op = d === undefined ? undefined : resolveOp(d, acc, opName);
1127
- if (op === undefined) return this.#err("unknown-op", `no domain gives "${opName}" for a ${describeType(acc)}`, f, path, { op: opName });
1320
+ if (op === undefined) return this.#at(errorText.noStep(opName, acc), f, path);
1128
1321
  const r = this.#callResolved(op, acc, opName, [values[i]], f, path);
1129
1322
  if (!r.ok) return r;
1130
1323
  acc = r.value;
@@ -1237,18 +1430,6 @@ export function matchesKind(kind: ParamKind, value: unknown, domain: AnyDomain):
1237
1430
  }
1238
1431
  }
1239
1432
 
1240
- /** This function gives a short name for the type of a value, for error messages. */
1241
- export function describeType(u: unknown): string {
1242
- if (u === null) return "null";
1243
- if (Array.isArray(u)) return "array";
1244
- if (isVexList(u)) return "list";
1245
- if (typeof u === "object") {
1246
- const name = (Object.getPrototypeOf(u) as { constructor?: { name?: unknown } } | null)?.constructor?.name;
1247
- return typeof name === "string" && name !== "Object" ? name : "object";
1248
- }
1249
- return typeof u;
1250
- }
1251
-
1252
1433
  /** This function gives the label of a node, for traces. */
1253
1434
  export function labelOf(e: Expr): string {
1254
1435
  switch (e.tag) {
@@ -1273,7 +1454,11 @@ export function labelOf(e: Expr): string {
1273
1454
  case "fold":
1274
1455
  return e.at === undefined ? `${e.tag} ${e.axis.t}` : `${e.tag} ${e.axis.t} from ${e.at.map(moveText).join(".")}`;
1275
1456
  case "iterate":
1276
- return `iterate ${String(e.limit)}`;
1457
+ return `iterate ${typeof e.limit === "number" ? String(e.limit) : `size of ${e.limit.axis.t}`}`;
1458
+ case "fix":
1459
+ return `fix ${e.name} ${e.join}`;
1460
+ case "last":
1461
+ return `last ${e.name}`;
1277
1462
  case "ext":
1278
1463
  return e.kind;
1279
1464
  }