@mark1russell7/vex-compiler 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/lower.ts CHANGED
@@ -4,10 +4,38 @@
4
4
  *
5
5
  * Each value that the interpreter can give as an error has a check. The block of the check tells what a failure does
6
6
  * (`Fail`). A list op skips an error item, and an error in the first argument of `ifError` gives the second argument.
7
- * Each other error stops the program with `FALLBACK`.
7
+ * These contexts drop the error, so the check has no error site. In each other context, the check has the site of its
8
+ * error, and the program ends with that error or a binding keeps it (`keeps`). Where the error has a use, a check without
9
+ * a site stops the program with `FALLBACK`. `#DEPTH!` of an extension stops the program too (COMPILE.EXT).
10
+ *
11
+ * A check for a result that only tier 1 can give is no error, so no context drops it (`#decide`, V-071).
12
+ *
13
+ * After a failure, the interpreter still evaluates the later arguments of a node, and two errors give `#ARGS`. The value
14
+ * path of generated code has no flags for this. A failure jumps to a copy of the later arguments (`#chain`), which only
15
+ * the failure path reads. A copy uses flags, so the size of the code stays near the size of the program times its depth.
8
16
  */
9
- import { addrExprs, isFieldName, isListOp, MAX_NESTING, nestingOf, shapeError, type Addr, type Axis, type Expr, type ExprOf, type ListOp, type Names, type PrimitiveKind } from "@mark1russell7/vex";
10
- import { factsOf, listReason, MAX_CALLS, primitiveOf, type Facts, type Schema } from "./facts.ts";
17
+ import {
18
+ addrExprs,
19
+ axisExprs,
20
+ children,
21
+ errorText,
22
+ isFieldName,
23
+ joinKind,
24
+ limitAxis,
25
+ listOf,
26
+ MAX_ITERATIONS,
27
+ nestingError,
28
+ shapeError,
29
+ type Addr,
30
+ type Axis,
31
+ type ErrorText,
32
+ type Expr,
33
+ type ExprOf,
34
+ type FixJoin,
35
+ type Names,
36
+ type PrimitiveKind,
37
+ } from "@mark1russell7/vex";
38
+ import { factsOf, isFusedOp, MAX_CALLS, primitiveOf, type Facts, type FusedOp, type Schema } from "./facts.ts";
11
39
  import { memoNodes } from "./memo.ts";
12
40
  import {
13
41
  array,
@@ -16,27 +44,36 @@ import {
16
44
  constant,
17
45
  FALLBACK_EXPR,
18
46
  FIXED_LOCALS,
47
+ keeps,
19
48
  local,
20
49
  num,
21
50
  ORIGIN,
51
+ plainOf,
22
52
  prim,
23
53
  RETURN,
24
54
  SPACE,
55
+ STOP,
25
56
  TABLES,
26
57
  VARS,
58
+ type ErrorSite,
27
59
  type Fail,
28
60
  type LExpr,
29
61
  type LoopProgram,
30
62
  type LStmt,
31
63
  } from "./loop.ts";
64
+ import { placesRead, unshared } from "./unshared.ts";
32
65
 
33
66
  /** The error of an expression that the compiler cannot lower. Then the program operates in tier 1. */
34
67
  export class Unsupported extends Error {}
35
68
 
36
- /** A bound name: its value, and the flag that tells if its binding gave a value. Without a flag, it always does. */
69
+ /**
70
+ * A bound name: its value, and the flag that tells if its binding gave a value. Without a flag, it always does. After a
71
+ * failure, `error` is the lazy error of the binding, if the context of the binding keeps it.
72
+ */
37
73
  interface Bound {
38
74
  readonly value: LExpr;
39
75
  readonly ok?: LExpr;
76
+ readonly error?: LExpr;
40
77
  }
41
78
 
42
79
  /** A bound function: its node, the path of its node, and the scope of its binding. */
@@ -56,6 +93,16 @@ interface Scope {
56
93
  readonly fns: ReadonlyMap<string, BoundFn>;
57
94
  /** The record at the focus. In a loop, it reads the record by its index (SPACE.RECORDS). */
58
95
  readonly rec: LExpr;
96
+ /** The columns of the steps around the node (COMPILE.FIX): the last round of each name, and its join. */
97
+ readonly columns: ReadonlyMap<string, FixColumn>;
98
+ /** The index of the focus in the keys of the space, if the lowering knows it. A read of a column uses it. */
99
+ readonly slot: LExpr | undefined;
100
+ }
101
+
102
+ /** A column in the step of its `fix`: the local of an array with the value of each row, and the join of the column. */
103
+ interface FixColumn {
104
+ readonly local: LExpr;
105
+ readonly join: FixJoin;
59
106
  }
60
107
 
61
108
  /** A list of statements, and what a failed check in it does. */
@@ -66,6 +113,29 @@ interface Block {
66
113
 
67
114
  const block = (fail: Fail): Block => ({ stmts: [], fail });
68
115
 
116
+ /**
117
+ * A region of the chains of arguments (`#chain`). The value path of each chain of the region is in one block, `value`.
118
+ * A failure of a part ends that block, and the failure paths of the chains come after it, in `paths`. `fails` holds
119
+ * the failures of the parts. A chain whose block has one of these failures is in the region, so its depth adds nothing.
120
+ */
121
+ interface Region {
122
+ readonly value: number;
123
+ readonly fails: Set<Fail>;
124
+ readonly paths: LStmt[];
125
+ }
126
+
127
+ /**
128
+ * The number of nodes that the failure paths of a program can copy. Past it, a node with two or more arguments that can
129
+ * fail keeps no error, so tier 1 gives its result. Thus the size of the code has a limit.
130
+ */
131
+ export const MAX_COPIED = 2000;
132
+
133
+ /**
134
+ * The number of arguments of a node that `#chain` takes. The test of the failure path has a term for each argument that
135
+ * can fail, and the printer recurses over these terms. A node with more arguments keeps no error.
136
+ */
137
+ export const MAX_CHAINED = 64;
138
+
69
139
  /** This function gives the axis inside the `where` axes of an axis. */
70
140
  const baseAxis = (a: Axis): Exclude<Axis, { readonly t: "where" }> => (a.t === "where" ? baseAxis(a.axis) : a);
71
141
 
@@ -76,6 +146,9 @@ function whereTests(a: Axis): readonly Expr[] {
76
146
  return out;
77
147
  }
78
148
 
149
+ /** This function gives the number of children of an axis: its list, then the tests of `where`. */
150
+ const axisChildren = (a: Axis): number => whereTests(a).length + (listOf(a) === undefined ? 0 : 1);
151
+
79
152
  /** This function gives the `each` under the `let` expressions of a list argument, or `undefined`. */
80
153
  function eachUnderLets(e: Expr | undefined): ExprOf<"each"> | undefined {
81
154
  let x = e;
@@ -83,6 +156,12 @@ function eachUnderLets(e: Expr | undefined): ExprOf<"each"> | undefined {
83
156
  return x?.tag === "each" ? x : undefined;
84
157
  }
85
158
 
159
+ /** The targets of a round of a column: each key of the space, with no address. */
160
+ const ROWS: Pick<ExprOf<"each">, "axis"> = { axis: { t: "all" } };
161
+
162
+ /** The primitive operation of each join (FIX.JOIN). The checks of a row give each join a value of its kind. */
163
+ const JOINS = { or: "||", and: "&&", max: "max", min: "min" } as const;
164
+
86
165
  /** The kinds of the values of the primitive operations that always give a boolean. */
87
166
  const BOOLEAN_PRIMS: ReadonlySet<string> = new Set(["!", "===", "!==", "isNumber", "isBoolean", "isString", "isValue", "isObject"]);
88
167
 
@@ -97,30 +176,106 @@ const join = (a: PrimitiveKind | undefined, b: PrimitiveKind | undefined): Primi
97
176
  * lower. The facts of the options decide the op of a site whose values have known kinds (KIND.STATIC).
98
177
  */
99
178
  export function lower(expr: Expr, facts: Facts = factsOf({}), schema: Schema = {}): LoopProgram {
179
+ // COMPILE.PLACES: the walks below take the time of the places, so the count comes first.
180
+ const places = placesRead([expr]);
181
+ if (places.error !== undefined) throw new Unsupported(places.error);
100
182
  // EVAL.SHAPE and EVAL.NESTING: tier 1 gives the error of a program that is not valid or that is nested too deep.
101
183
  const shape = shapeError(expr);
102
184
  if (shape !== undefined) throw new Unsupported(shape);
103
- if (nestingOf(expr) > MAX_NESTING) throw new Unsupported(`the expression is nested deeper than ${MAX_NESTING} levels`);
104
- const lists = listReason(expr);
105
- if (lists !== undefined) throw new Unsupported(lists);
106
- const l = new Lowerer(memoNodes(expr), facts, schema);
185
+ const deep = nestingError(expr);
186
+ if (deep !== undefined) throw new Unsupported(deep);
187
+ const plain = unshared(expr, places.shares);
188
+ const l = new Lowerer(memoNodes(plain, isFusedOp), facts, schema);
107
189
  const b = block(RETURN);
108
- l.check(b, call("has", local(SPACE), local(ORIGIN)), "the origin is a key of the space");
109
- const top: Scope = { space: local(SPACE), origin: local(ORIGIN), focus: local(ORIGIN), env: new Map(), fns: new Map(), rec: prim("get", local(SPACE), local(ORIGIN)) };
110
- const value = l.expr(expr, top, [], b);
190
+ const top: Scope = { space: local(SPACE), origin: local(ORIGIN), focus: local(ORIGIN), env: new Map(), fns: new Map(), rec: prim("get", local(SPACE), local(ORIGIN)), columns: new Map(), slot: undefined };
191
+ l.check(b, call("has", local(SPACE), local(ORIGIN)), "the origin is a key of the space", l.site(b, top, { t: "key" }));
192
+ const value = l.expr(plain, top, [], b);
111
193
  b.stmts.push({ t: "return", value });
112
- return { body: b.stmts, locals: l.locals, constants: l.constants };
194
+ return { body: flat(b.stmts), locals: l.locals, constants: l.constants };
195
+ }
196
+
197
+ /** This function gives the statements that a statement holds, in the order of the source. */
198
+ function bodiesOf(x: LStmt): readonly (readonly LStmt[])[] {
199
+ if (x.t === "if") return [x.yes, x.no];
200
+ return x.t === "loop" || x.t === "block" || x.t === "repeat" ? [x.body] : [];
201
+ }
202
+
203
+ /** This function gives the label that a failure ends or continues, or the labels of a strict failure. */
204
+ function failLabels(f: Fail): readonly number[] {
205
+ if (f.t === "break") return [f.label];
206
+ if (f.t === "continue") return f.strict === undefined ? [f.label] : [f.label, ...failLabels(f.strict.else)];
207
+ return [];
208
+ }
209
+
210
+ /**
211
+ * This function moves the first statements of a block out of the block, while they do not end it (V-089). Such a
212
+ * statement runs first in both places, and its jumps go to the same statements. A block with no jump to it goes away.
213
+ * Thus a node in the first part of a node adds no level of blocks.
214
+ *
215
+ * The first walk gives each statement a number in the order of the source, and the first jump to each label. The
216
+ * second walk counts in the same order. A statement holds a jump to the block only if that jump has a number in the
217
+ * range of the statement. Thus each walk reads each statement once.
218
+ */
219
+ function flat(body: readonly LStmt[]): LStmt[] {
220
+ const first = new Map<number, number>();
221
+ // The number of the last statement inside each statement, at the index of the number of the statement.
222
+ const ends: number[] = [0];
223
+ let at = 0;
224
+ const note = (xs: readonly LStmt[]): void => {
225
+ for (const x of xs) {
226
+ const self = ++at;
227
+ const labels = x.t === "break" ? [x.label] : x.t === "check" || x.t === "fail" ? failLabels(x.fail) : [];
228
+ for (const label of labels) if (!first.has(label)) first.set(label, self);
229
+ bodiesOf(x).forEach(note);
230
+ ends[self] = at;
231
+ }
232
+ };
233
+ note(body);
234
+ at = 0;
235
+ // Each statement goes into its list once: a moved statement goes straight into the list of the block around it.
236
+ const walk = (xs: readonly LStmt[], out: LStmt[] = []): LStmt[] => {
237
+ for (const x of xs) one(x, out);
238
+ return out;
239
+ };
240
+ const one = (x: LStmt, out: LStmt[]): void => {
241
+ at++;
242
+ if (x.t === "if") out.push({ ...x, yes: walk(x.yes), no: walk(x.no) });
243
+ else if (x.t === "loop" || x.t === "repeat") out.push({ ...x, body: walk(x.body) });
244
+ else if (x.t !== "block") out.push(x);
245
+ else {
246
+ const jump = first.get(x.label) ?? Number.POSITIVE_INFINITY;
247
+ let rest: LStmt[] | undefined;
248
+ for (const y of x.body) {
249
+ if (rest === undefined && jump <= (ends[at + 1] ?? 0)) rest = [];
250
+ one(y, rest ?? out);
251
+ }
252
+ if (rest !== undefined) out.push({ ...x, body: rest });
253
+ }
254
+ };
255
+ return walk(body);
113
256
  }
114
257
 
115
258
  class Lowerer {
116
259
  locals = FIXED_LOCALS;
117
260
  labels = 0;
118
261
  memos = 0;
119
- /** The number of bodies of functions that the lowering put at calls (MAX_CALLS). */
262
+ /** The number of bodies of functions that the lowering put at calls (MAX_CALLS). A copy does not count. */
120
263
  #calls = 0;
264
+ /** The depth of the copies of the failure paths around the lowering. Inside a copy, a node has no memo. */
265
+ #copying = 0;
266
+ /** The number of nodes that the copies have so far (MAX_COPIED). */
267
+ #copied = 0;
268
+ /** The answers of `#mayExt`, for each map of functions. */
269
+ readonly #exts = new WeakMap<ReadonlyMap<string, BoundFn>, Map<Expr, boolean>>();
121
270
  readonly #memo: ReadonlyMap<Expr, readonly Expr[]>;
122
271
  /** The keys of the nodes of the memo whose code the lowering makes, with their values. */
123
272
  #keys: ReadonlyMap<Expr, Bound> = new Map();
273
+ /** The region of the chain whose parts the lowering makes at this time (`#chain`). */
274
+ #region: Region | undefined = undefined;
275
+ /** The depth of the loops around the lowering. */
276
+ #loops = 0;
277
+ /** The depth of the loops at the start of the code of a node of the memo with no keys, or `undefined` outside such code. */
278
+ #once: number | undefined = undefined;
124
279
  readonly #facts: Facts;
125
280
  readonly #schema: Schema;
126
281
  /** The kind of each local whose kind the lowering knows. A local gets its kind where it gets its value. */
@@ -155,9 +310,18 @@ class Lowerer {
155
310
  */
156
311
  #declared(b: Block, x: LExpr, kind: PrimitiveKind | undefined, reason: string): LExpr {
157
312
  if (kind === undefined) return x;
158
- b.stmts.push({ t: "check", ok: prim(KIND_CHECKS[kind], x), reason, fail: RETURN });
313
+ this.#decide(b, prim(KIND_CHECKS[kind], x), reason);
159
314
  return this.#typed(x, kind);
160
315
  }
316
+
317
+ /**
318
+ * This method adds a check whose failure is no error of the program. Tier 1 decides the result, so the check stops the
319
+ * program in each block. `check` is for an error, and a context that catches an error drops its failure (V-071).
320
+ */
321
+ #decide(b: Block, ok: LExpr, reason: string): void {
322
+ b.stmts.push({ t: "check", ok, reason, fail: STOP });
323
+ }
324
+
161
325
  readonly constants: unknown[] = [];
162
326
  readonly #pool = new Map<unknown, number>();
163
327
 
@@ -192,20 +356,34 @@ class Lowerer {
192
356
  return local(n);
193
357
  }
194
358
 
195
- check(b: Block, ok: LExpr, reason: string): void {
196
- b.stmts.push({ t: "check", ok, reason, fail: b.fail });
359
+ /**
360
+ * This method gives the lazy error of a site, where the block keeps it. `undefined` tells that the block drops the
361
+ * error, so the site is not a constant of the program.
362
+ */
363
+ site(b: Block, s: Pick<Scope, "origin" | "focus">, site: ErrorSite, ...operands: LExpr[]): LExpr | undefined {
364
+ return keeps(b.fail) ? call("err", { t: "site", i: this.constants.push(site) - 1 }, s.origin, s.focus, ...operands) : undefined;
365
+ }
366
+
367
+ /** This method gives the lazy error of a text. */
368
+ #text(b: Block, s: Scope, path: readonly number[], text: ErrorText): LExpr | undefined {
369
+ return this.site(b, s, { t: "text", text, path });
370
+ }
371
+
372
+ /** This method adds a check. Without a lazy error, the failure is the plain failure of the block. */
373
+ check(b: Block, ok: LExpr, reason: string, error?: LExpr): void {
374
+ b.stmts.push(error === undefined ? { t: "check", ok, reason, fail: plainOf(b.fail) } : { t: "check", ok, reason, fail: b.fail, error });
197
375
  }
198
376
 
199
377
  /** This method gives a new local with the value of a call of the runtime, and a check that the value is not `FALLBACK`. */
200
- checked(b: Block, value: LExpr, reason: string): LExpr {
378
+ checked(b: Block, value: LExpr, reason: string, error?: LExpr): LExpr {
201
379
  const x = this.value(b, value);
202
- this.check(b, prim("!==", x, FALLBACK_EXPR), reason);
380
+ this.check(b, prim("!==", x, FALLBACK_EXPR), reason, error);
203
381
  return x;
204
382
  }
205
383
 
206
384
  /** This method adds a failure: the interpreter always gives an error here. */
207
- fail(b: Block): LExpr {
208
- b.stmts.push({ t: "fail", fail: b.fail });
385
+ fail(b: Block, error?: LExpr): LExpr {
386
+ b.stmts.push(error === undefined ? { t: "fail", fail: plainOf(b.fail) } : { t: "fail", fail: b.fail, error });
209
387
  return FALLBACK_EXPR;
210
388
  }
211
389
 
@@ -216,12 +394,29 @@ class Lowerer {
216
394
  if (key.ok !== undefined) this.check(b, key.ok, "a key with a value");
217
395
  return key.value;
218
396
  }
219
- const keys = this.#memo.get(e);
397
+ // In the code of a node of the memo with no keys, outside a loop of that code, a node evaluates at most once for each space. Its memo thus saves nothing (V-089).
398
+ const keys = this.#copying > 0 || this.#once === this.#loops ? undefined : this.#memo.get(e);
220
399
  return keys === undefined ? this.#node(e, s, path, b) : this.#memoized(e, keys, s, path, b);
221
400
  }
222
401
 
402
+ /** This method lowers a copy of a part of a failure path. */
403
+ #copy(make: () => void): void {
404
+ this.#copying++;
405
+ make();
406
+ this.#copying--;
407
+ }
408
+
409
+ /** This method lowers a loop of names. A node of the memo inside the loop keeps its memo. */
410
+ #inLoop(make: () => LExpr): LExpr {
411
+ this.#loops++;
412
+ const value = make();
413
+ this.#loops--;
414
+ return value;
415
+ }
416
+
223
417
  /** This method lowers a node itself, without the memo. */
224
418
  #node(e: Expr, s: Scope, path: readonly number[], b: Block): LExpr {
419
+ if (this.#copying > 0) this.#copied++;
225
420
  switch (e.tag) {
226
421
  case "lit":
227
422
  return this.constant(e.value);
@@ -230,12 +425,12 @@ class Lowerer {
230
425
  case "var": {
231
426
  const bound = s.env.get(e.name);
232
427
  // A function is not a value (FN.VALUE): tier 1 gives the error. A name of a loop hides a function with its name.
233
- if (bound === undefined && s.fns.has(e.name)) return this.fail(b);
428
+ if (bound === undefined && s.fns.has(e.name)) return this.fail(b, this.#text(b, s, path, errorText.functionValue(e.name)));
234
429
  if (bound === undefined) {
235
- const x = this.checked(b, call("var", local(VARS), this.constant(e.name)), "a variable");
430
+ const x = this.checked(b, call("var", local(VARS), this.constant(e.name)), "a variable", this.#text(b, s, path, errorText.unbound(e.name)));
236
431
  return this.#declared(b, x, primitiveOf(this.#schema.vars?.[e.name]), "a variable of the schema");
237
432
  }
238
- if (bound.ok !== undefined) this.check(b, bound.ok, "a binding with a value");
433
+ this.#read(b, bound, "a binding with a value");
239
434
  return bound.value;
240
435
  }
241
436
  case "let":
@@ -247,30 +442,36 @@ class Lowerer {
247
442
  case "call":
248
443
  return this.#call(e, s, path, b);
249
444
  case "rec": {
250
- const values = Object.values(e.fields).map((x, i) => this.expr(x, s, [...path, i], b));
445
+ const values = this.#all(Object.values(e.fields), s, path, 0, "fields", b);
251
446
  return this.value(b, call("rec", this.constant(Object.keys(e.fields)), array(...values)));
252
447
  }
253
448
  case "app":
254
449
  return this.#app(e, s, path, b);
255
450
  case "fold":
256
- return this.#fold(e, s, path, b);
451
+ return this.#inLoop(() => this.#fold(e, s, path, b));
257
452
  case "iterate":
258
- return this.#iterate(e, s, path, b);
453
+ return this.#inLoop(() => this.#iterate(e, s, path, b));
454
+ case "fix":
455
+ return this.#inLoop(() => this.#fix(e, s, path, b));
456
+ case "last": {
457
+ const column = s.columns.get(e.name);
458
+ // The lowering comes before the checks. A read outside a step fails a check, and that check gives the reason.
459
+ return column === undefined ? this.fail(b) : this.#rowOf(e.name, column, s, path, b);
460
+ }
259
461
  case "each": {
260
- // A list keeps its error items, and generated code makes no error values. Thus an error item stops the program.
462
+ // A list keeps its error items, and generated code makes no error items. Thus an error item stops the program, and
463
+ // tier 1 gives the list.
261
464
  const keys = this.locals++;
262
465
  const values = this.locals++;
263
466
  b.stmts.push({ t: "let", n: keys, value: array() }, { t: "let", n: values, value: array() });
264
- this.#loop(e, s, path, b, () => RETURN, (body, key, v) => {
467
+ this.#loop(e, s, path, b, () => STOP, (body, key, v) => {
265
468
  body.stmts.push({ t: "push", n: keys, value: key }, { t: "push", n: values, value: v });
266
469
  });
267
470
  return this.value(b, call("list", local(keys), local(values)));
268
471
  }
269
472
  case "ext": {
270
- // An extension can give the error #DEPTH!, which a list op does not skip. Thus an error of an extension stops the program.
271
- const x = this.value(b, call("ext", this.constant(e.kind), this.constant(e.data), s.space, s.origin, s.focus, this.constant(path)));
272
- b.stmts.push({ t: "check", ok: prim("!==", x, FALLBACK_EXPR), reason: "an extension", fail: RETURN });
273
- return x;
473
+ // COMPILE.EXT: an error of an extension is an error of the block. The runtime throws for #DEPTH!, which stops the program.
474
+ return this.checked(b, call("ext", this.constant(e.kind), this.constant(e.data), s.space, s.origin, s.focus, this.constant(path)), "an extension", this.site(b, s, { t: "ext", kind: e.kind, path }));
274
475
  }
275
476
  }
276
477
  }
@@ -279,40 +480,188 @@ class Lowerer {
279
480
  * This method gives the value of a node that depends only on the space (§7.2). The memo has an entry for each space.
280
481
  * Without the entry of the space, the node evaluates in a block, and an error of it makes an entry without a value.
281
482
  * An exception stops the program, so the memo gets no entry for it.
483
+ *
484
+ * The entry has no error, because the error of a node depends on its position and on its child nodes. Where the context
485
+ * keeps the error, a copy of the node evaluates after a read of such an entry. The copy gives the error at this position.
486
+ * A node of the memo and its keys use no extension, so this second evaluation has no effect.
487
+ *
488
+ * The code of a node with no keys evaluates once for each space. Outside its loops, a node inside it thus evaluates
489
+ * once too, and it gets no memo of its own (`#once`). So the code of nested nodes has no nested blocks (V-089).
282
490
  */
283
491
  #memoized(e: Expr, keys: readonly Expr[], s: Scope, path: readonly number[], b: Block): LExpr {
284
492
  const memo: LExpr = { t: "memo", id: this.memos++ };
285
493
  // Each key evaluates here, in a block of its own, as a binding does.
286
- const values = keys.map((k): Bound => this.#attempt(b, (inner) => this.expr(k, s, path, inner)));
494
+ const values = keys.map((k): Bound => this.#attempt(b, (inner) => this.expr(k, s, path, inner), false));
287
495
  const tuple = array(...values.flatMap((k) => [k.value, flag(k)]));
288
496
  const h = this.locals++;
289
497
  const outer = this.#keys;
290
498
  this.#keys = new Map([...outer, ...keys.map((k, i): [Expr, Bound] => [k, values[i] as Bound])]);
291
499
  const compute = block(b.fail);
292
- const node = this.#attempt(compute, (inner) => this.#node(e, s, path, inner));
500
+ const once = this.#once;
501
+ this.#once = keys.length === 0 ? this.#loops : undefined;
502
+ const node = this.#attempt(compute, (inner) => this.#node(e, s, path, inner), false);
503
+ this.#once = once;
293
504
  this.#keys = outer;
294
505
  compute.stmts.push({ t: "set", n: h, value: prim("memoPut", memo, s.space, tuple, node.value, flag(node)) });
295
506
  b.stmts.push({ t: "let", n: h, value: prim("memoGet", memo, s.space, tuple) }, { t: "if", cond: prim("!", prim("isValue", local(h))), yes: compute.stmts, no: [] });
296
- this.check(b, prim("entryOk", local(h)), "a value of the memo");
507
+ const entry = prim("entryOk", local(h));
508
+ const stop: LStmt = { t: "check", ok: entry, reason: "a value of the memo", fail: plainOf(b.fail) };
509
+ if (keeps(b.fail) && this.#copied < MAX_COPIED) {
510
+ const copy = block(b.fail);
511
+ this.#copy(() => this.#node(e, s, path, copy));
512
+ b.stmts.push({ t: "if", cond: prim("!", entry), yes: [...copy.stmts, stop], no: [] });
513
+ } else {
514
+ b.stmts.push(stop);
515
+ }
297
516
  // Each entry of the memo comes from the code of the node, so it has the kind of the value of the node.
298
517
  return this.#typed(this.value(b, prim("entryValue", local(h))), this.kindOf(node.value));
299
518
  }
300
519
 
520
+ /**
521
+ * This method lowers the arguments of an op or the fields of a record, with the child indexes from `first`. After an
522
+ * error, the interpreter still evaluates the later arguments, and two errors give `#ARGS` (`#all` of the interpreter).
523
+ * Where the context keeps the error of two or more arguments that can fail, `#chain` or `#collect` lowers them.
524
+ *
525
+ * An extension in a later argument can give `#DEPTH!`. Thus, where the program catches the error, each argument before
526
+ * the last one that can use an extension has its own block (COMPILE.EXT). Then a failure skips no extension.
527
+ */
528
+ #all(xs: readonly Expr[], s: Scope, path: readonly number[], first: number, what: string, b: Block): LExpr[] {
529
+ if (keeps(b.fail) && xs.filter((x) => x.tag !== "lit").length > 1) {
530
+ if (this.#copying > 0) return this.#collect(xs, s, path, first, what, b);
531
+ if (this.#copied < MAX_COPIED && xs.length <= MAX_CHAINED) return this.#chain(xs, s, path, first, what, b);
532
+ return this.#all(xs, s, path, first, what, { stmts: b.stmts, fail: plainOf(b.fail) });
533
+ }
534
+ const last = b.fail.t === "return" || b.fail.t === "stop" ? -1 : xs.findLastIndex((x) => this.#mayExt(x, s.fns));
535
+ const parts = xs.map((x, i): Bound => {
536
+ const at = [...path, first + i];
537
+ return i < last ? this.#attempt(b, (inner) => this.expr(x, s, at, inner)) : { value: this.expr(x, s, at, b) };
538
+ });
539
+ for (const x of parts) if (x.ok !== undefined) this.check(b, x.ok, "an argument with a value");
540
+ return parts.map((x) => x.value);
541
+ }
542
+
543
+ /**
544
+ * This method lowers arguments on the value path, with no new check. A failure of an argument keeps its error in a
545
+ * local of the argument. It then ends the value block of the region, and the failure path of the chain copies the
546
+ * later arguments that can fail. After the last copy, the errors give the error of the node (`args` of the runtime).
547
+ * The failure path clears the locals, for the next turn of a loop.
548
+ *
549
+ * Each argument evaluates once: the value path gives up at the failure, and the copies start after it.
550
+ *
551
+ * The value path of a chain has no block of its own (V-089). A chain in a part of another chain is in the region of
552
+ * that chain. So its parts go into the value block of the region, and its failure path goes before the failure path of
553
+ * the outer chain. The depth of the blocks thus stays the same for each level of a shape. Before, each level added
554
+ * 3 blocks around argument 0, and the time of the parse of `new Function` grew with the lines times that depth.
555
+ */
556
+ #chain(xs: readonly Expr[], s: Scope, path: readonly number[], first: number, what: string, b: Block): LExpr[] {
557
+ const joined = this.#region?.fails.has(b.fail) === true ? this.#region : undefined;
558
+ const region: Region = joined ?? { value: this.labels++, fails: new Set(), paths: [] };
559
+ const outer = this.#region;
560
+ this.#region = region;
561
+ // The parts write into one list: the statements of the block of a joined chain, or the value block of the region.
562
+ // So a statement goes into a list once, and the lowering stays linear in the depth of the chains.
563
+ const sink = joined === undefined ? [] : b.stmts;
564
+ const parts = xs.map((x, i) => {
565
+ const error = this.locals++;
566
+ const fail: Fail = { t: "break", label: region.value, keep: error };
567
+ region.fails.add(fail);
568
+ const at = [...path, first + i];
569
+ const start = sink.length;
570
+ const value = this.expr(x, s, at, { stmts: sink, fail });
571
+ return { x, at, error, value, fails: sink.length > start };
572
+ });
573
+ this.#region = outer;
574
+ const values = parts.map((p) => p.value);
575
+ const failing = parts.filter((p) => p.fails);
576
+ if (failing.length === 0) return values;
577
+ // Only the failed part has an error at the start of the failure path. A part after a part with an error has a copy.
578
+ const failed = (p: (typeof failing)[number]): LExpr => prim("isValue", local(p.error));
579
+ const after = this.locals++;
580
+ const copies: LStmt[] = [];
581
+ failing.forEach((p, i) => {
582
+ const next = failing[i + 1];
583
+ if (next === undefined) return;
584
+ copies.push({ t: "set", n: after, value: i === 0 ? failed(p) : prim("||", local(after), failed(p)) });
585
+ const label = this.labels++;
586
+ const copy = block({ t: "break", label, keep: next.error });
587
+ this.#copy(() => this.expr(next.x, s, next.at, copy));
588
+ copies.push({ t: "if", cond: local(after), yes: [{ t: "block", label, body: copy.stmts }], no: [] });
589
+ });
590
+ const inner = block(b.fail);
591
+ const error = this.value(inner, this.#argsError(s, path, what, failing.map((p) => local(p.error))));
592
+ inner.stmts.push(...failing.map((p): LStmt => ({ t: "set", n: p.error, value: { t: "none" } })));
593
+ // In the region of an outer chain, the failure path keeps the error for the part of the outer chain. The failure path of that chain comes next.
594
+ if (joined !== undefined && b.fail.t === "break" && b.fail.keep !== undefined) inner.stmts.push({ t: "set", n: b.fail.keep, value: error });
595
+ else this.fail(inner, error);
596
+ const chainFailed = failing.slice(1).reduce((x, p) => prim("||", x, failed(p)), failed(failing[0] as (typeof failing)[number]));
597
+ region.paths.push({ t: "if", cond: chainFailed, yes: [...copies, ...inner.stmts], no: [] });
598
+ if (joined !== undefined) return values;
599
+ const end = this.labels++;
600
+ sink.push({ t: "break", label: end });
601
+ b.stmts.push({ t: "block", label: end, body: [{ t: "block", label: region.value, body: sink }, ...region.paths] });
602
+ return values;
603
+ }
604
+
605
+ /**
606
+ * This method lowers arguments in a copy. The value path does not read a copy, so each argument can have its own block
607
+ * and its flag. A node in a copy thus adds no other copy, and the size of the code stays near the size of the node.
608
+ */
609
+ #collect(xs: readonly Expr[], s: Scope, path: readonly number[], first: number, what: string, b: Block): LExpr[] {
610
+ const parts = xs.map((x, i): Bound => this.#attempt(b, (inner) => this.expr(x, s, [...path, first + i], inner)));
611
+ const errors = parts.flatMap((p) => (p.ok === undefined ? [] : [prim("unless", p.ok, p.value)]));
612
+ if (errors.length > 0) {
613
+ const error = this.value(b, this.#argsError(s, path, what, errors));
614
+ this.check(b, prim("!", prim("isValue", error)), "the arguments have values", error);
615
+ }
616
+ return parts.map((p) => p.value);
617
+ }
618
+
619
+ /** This method gives the call of the runtime that makes the error of some arguments. */
620
+ #argsError(s: Scope, path: readonly number[], what: string, errors: readonly LExpr[]): LExpr {
621
+ const site = this.constants.push({ t: "args", what, path } satisfies ErrorSite) - 1;
622
+ return call("args", { t: "site", i: site }, s.origin, s.focus, array(...errors));
623
+ }
624
+
625
+ /**
626
+ * This method tells if an expression can call an extension. A call reads the body of its function, and the bodies of
627
+ * the functions of that body. A function cannot call itself, so the search ends. Each node has one answer for each
628
+ * map of functions, because functions can call each other many times (V-068).
629
+ */
630
+ #mayExt(e: Expr, fns: ReadonlyMap<string, BoundFn>): boolean {
631
+ let answers = this.#exts.get(fns);
632
+ if (answers === undefined) {
633
+ answers = new Map();
634
+ this.#exts.set(fns, answers);
635
+ }
636
+ const known = answers.get(e);
637
+ if (known !== undefined) return known;
638
+ const bound = e.tag === "call" ? fns.get(e.fn) : undefined;
639
+ const answer = e.tag === "ext" || (bound !== undefined && this.#mayExt(bound.fn.body, bound.scope.fns)) || children(e).some((x) => this.#mayExt(x, fns));
640
+ answers.set(e, answer);
641
+ return answer;
642
+ }
643
+
301
644
  /**
302
645
  * This method evaluates an expression in a block whose errors end the block, as a binding does. It gives the value
303
- * and the flag that tells if the value exists. Without statements, the expression always has a value, so it gets no flag.
646
+ * and the flag that tells if the value exists. Without statements, the expression always has a value, so it gets no
647
+ * flag. With `keep`, a failure keeps its lazy error in the local of the value: only the failure path writes it there.
304
648
  */
305
- #attempt(b: Block, make: (inner: Block) => LExpr): Bound {
649
+ #attempt(b: Block, make: (inner: Block) => LExpr, keep = keeps(b.fail)): Bound {
306
650
  const label = this.labels++;
307
- const attempt = block({ t: "break", label });
651
+ const v = this.locals++;
652
+ const attempt = block(keep ? { t: "break", label, keep: v } : { t: "break", label });
308
653
  const value = make(attempt);
309
654
  if (attempt.stmts.length === 0) return { value };
310
- const v = this.locals++;
311
655
  const ok = this.locals++;
312
656
  this.#typed(local(v), this.kindOf(value));
313
657
  attempt.stmts.push({ t: "set", n: v, value }, { t: "set", n: ok, value: bool(true) });
314
658
  b.stmts.push({ t: "let", n: ok, value: bool(false) }, { t: "block", label, body: attempt.stmts });
315
- return { value: local(v), ok: local(ok) };
659
+ return keep ? { value: local(v), ok: local(ok), error: local(v) } : { value: local(v), ok: local(ok) };
660
+ }
661
+
662
+ /** This method adds the check of a read of a bound name. An error of the binding is the error of the read. */
663
+ #read(b: Block, bound: Bound, reason: string): void {
664
+ if (bound.ok !== undefined) this.check(b, bound.ok, reason, bound.error);
316
665
  }
317
666
 
318
667
  /**
@@ -320,16 +669,19 @@ class Lowerer {
320
669
  * A segment that cannot name a field always gives an error.
321
670
  */
322
671
  #ref(e: ExprOf<"ref">, s: Scope, path: readonly number[], b: Block): LExpr {
323
- const record = e.at === undefined || e.at.length === 0 ? s.rec : prim("get", s.space, this.#address(e.at, s, path, 0, b));
324
- if (!e.path.every(isFieldName)) return this.fail(b);
672
+ const moved = e.at === undefined || e.at.length === 0 ? undefined : this.#address(e.at, s, path, 0, b);
673
+ const key = moved ?? s.focus;
674
+ const missing = (where: string): LExpr | undefined => this.site(b, s, { t: "missing", where, path }, key);
325
675
  const n = this.locals++;
326
676
  const x = local(n);
327
- b.stmts.push({ t: "let", n, value: record });
328
- this.check(b, prim("isValue", x), "a record");
329
- for (const seg of e.path) {
330
- this.check(b, prim("isObject", x), "an object");
677
+ b.stmts.push({ t: "let", n, value: moved === undefined ? s.rec : prim("get", s.space, moved) });
678
+ this.check(b, prim("isValue", x), "a record", missing(e.path.length === 0 ? "(record)" : e.path.join(".")));
679
+ for (const [i, seg] of e.path.entries()) {
680
+ const where = e.path.slice(0, i + 1).join(".");
681
+ if (!isFieldName(seg)) return this.fail(b, missing(where));
682
+ this.check(b, prim("isObject", x), "an object", missing(where));
331
683
  b.stmts.push({ t: "set", n, value: prim("member", x, this.constant(seg)) });
332
- this.check(b, prim("isValue", x), "a field");
684
+ this.check(b, prim("isValue", x), "a field", missing(where));
333
685
  }
334
686
  const [field, ...more] = e.path;
335
687
  // Tier 2 knows only the primitive kinds. A value of a domain goes through the dispatch of the runtime.
@@ -343,29 +695,36 @@ class Lowerer {
343
695
  */
344
696
  #bind(e: ExprOf<"let">, s: Scope, path: readonly number[], b: Block): Pick<Scope, "env" | "fns"> {
345
697
  const env = new Map(s.env);
346
- const fns = new Map(s.fns);
698
+ // A let with no function keeps the map of functions, so the answers of `#mayExt` for that map stay (V-089).
699
+ const fns = Object.values(e.bind).some((x) => x.tag === "fn") ? new Map(s.fns) : undefined;
347
700
  Object.entries(e.bind).forEach(([name, x], i) => {
348
701
  // A function evaluates at each call. A binding sees the scope of the let, so a function cannot call itself.
349
702
  // A value hides a function of its name, because a read looks at the values first.
350
703
  if (x.tag === "fn") {
351
- fns.set(name, { fn: x, path: [...path, i], scope: s });
704
+ fns?.set(name, { fn: x, path: [...path, i], scope: s });
352
705
  env.delete(name);
353
706
  } else {
354
707
  env.set(name, this.#attempt(b, (inner) => this.expr(x, s, [...path, i], inner)));
355
708
  }
356
709
  });
357
- return { env, fns };
710
+ return { env, fns: fns ?? s.fns };
358
711
  }
359
712
 
360
713
  /**
361
714
  * This method lowers a call (FN.CALL). The body of the function goes at the place of the call, with the values of the
362
- * arguments for its parameters. The body sees the names of the place of its binding. A call that is not valid goes
363
- * to tier 1.
715
+ * arguments for its parameters. The body sees the names of the place of its binding.
364
716
  */
365
717
  #call(e: ExprOf<"call">, s: Scope, path: readonly number[], b: Block): LExpr {
366
- const bound = s.env.has(e.fn) ? undefined : s.fns.get(e.fn);
367
- if (bound?.fn.params.length !== e.args.length) return this.fail(b);
368
- if (++this.#calls > MAX_CALLS) throw new Unsupported(`the calls put the bodies of functions in more than ${String(MAX_CALLS)} places`);
718
+ const value = s.env.get(e.fn);
719
+ if (value !== undefined) {
720
+ this.#read(b, value, "a binding with a value");
721
+ return this.fail(b, this.#text(b, s, path, errorText.notFunction(e.fn)));
722
+ }
723
+ const bound = s.fns.get(e.fn);
724
+ // The name can be a variable of the run: only the run tells the error.
725
+ if (bound === undefined) return this.fail(b, this.site(b, s, { t: "call", name: e.fn, path }, local(VARS)));
726
+ if (bound.fn.params.length !== e.args.length) return this.fail(b, this.#text(b, s, path, errorText.arity(e.fn, bound.fn.params.length, e.args.length)));
727
+ if (this.#copying === 0 && ++this.#calls > MAX_CALLS) throw new Unsupported(`the calls put the bodies of functions in more than ${String(MAX_CALLS)} places`);
369
728
  const env = new Map(bound.scope.env);
370
729
  bound.fn.params.forEach((p, i) => env.set(p, this.#attempt(b, (inner) => this.expr(e.args[i] as Expr, s, [...path, i], inner))));
371
730
  return this.expr(bound.fn.body, { ...s, env, fns: bound.scope.fns }, [...bound.path, 0], b);
@@ -378,32 +737,32 @@ class Lowerer {
378
737
  return this.#if(args, s, path, b);
379
738
  case "and":
380
739
  case "or":
381
- return args.length === 0 ? this.fail(b) : this.#andOr(op === "or", args, 0, s, path, b);
740
+ return args.length === 0 ? this.fail(b, this.#text(b, s, path, errorText.needsArguments(op))) : this.#andOr(op === "or", args, 0, s, path, b);
382
741
  case "ifError":
383
742
  return this.#ifError(args, s, path, b);
384
743
  }
385
- if (isListOp(op)) {
744
+ if (isFusedOp(op)) {
386
745
  const target = eachUnderLets(args[0]);
387
746
  if (target !== undefined) return this.#fused(op, e, target, s, path, b);
388
747
  }
389
- const values = args.map((x, i) => this.expr(x, s, [...path, i], b));
748
+ const values = this.#all(args, s, path, 0, "arguments", b);
390
749
  const kinds = values.map((x) => this.kindOf(x));
391
750
  // A static site checks the kind of its result, so the result has the kind that the op declares (KIND.RETURNS).
392
751
  const site = this.#facts.staticSite(op, kinds);
393
- const x = this.checked(b, { t: "op", name: this.index(op), args: values, kinds }, "an op");
752
+ const x = this.checked(b, { t: "op", name: this.index(op), args: values, kinds }, "an op", this.site(b, s, { t: "op", op, path }));
394
753
  return this.#typed(x, site?.t === "fn" ? primitiveOf(site.returns) : undefined);
395
754
  }
396
755
 
397
756
  /** The condition must be a boolean. Only the branch that the condition selects is evaluated. */
398
757
  #if(args: readonly Expr[], s: Scope, path: readonly number[], b: Block): LExpr {
399
758
  const [cond, yes, no] = args;
400
- if (cond === undefined) return this.fail(b);
401
- const c = this.#boolean(this.expr(cond, s, [...path, 0], b), b);
759
+ if (cond === undefined) return this.fail(b, this.#text(b, s, path, errorText.needsArgument("if", 0)));
760
+ const c = this.#boolean(this.expr(cond, s, [...path, 0], b), b, s, { t: "boolean", op: "if", i: 0, path });
402
761
  const r = this.locals++;
403
762
  const kinds: (PrimitiveKind | undefined)[] = [];
404
763
  const branch = (x: Expr | undefined, i: number): LStmt[] => {
405
764
  const inner = block(b.fail);
406
- const value = x === undefined ? this.fail(inner) : this.expr(x, s, [...path, i], inner);
765
+ const value = x === undefined ? this.fail(inner, this.#text(inner, s, path, errorText.needsArgument("if", i))) : this.expr(x, s, [...path, i], inner);
407
766
  kinds.push(this.kindOf(value));
408
767
  inner.stmts.push({ t: "set", n: r, value });
409
768
  return inner.stmts;
@@ -414,7 +773,7 @@ class Lowerer {
414
773
 
415
774
  /** `or` stops at the first `true`, and `and` at the first `false`. Each argument before the stop must be a boolean. */
416
775
  #andOr(isOr: boolean, args: readonly Expr[], i: number, s: Scope, path: readonly number[], b: Block, r = this.locals++): LExpr {
417
- const x = this.#boolean(this.expr(args[i] as Expr, s, [...path, i], b), b);
776
+ const x = this.#boolean(this.expr(args[i] as Expr, s, [...path, i], b), b, s, { t: "boolean", op: isOr ? "or" : "and", i, path });
418
777
  this.#typed(local(r), "boolean");
419
778
  if (i === args.length - 1) {
420
779
  b.stmts.push({ t: "set", n: r, value: x });
@@ -433,7 +792,7 @@ class Lowerer {
433
792
  */
434
793
  #ifError(args: readonly Expr[], s: Scope, path: readonly number[], b: Block): LExpr {
435
794
  const [first, second] = args;
436
- if (first === undefined) return this.fail(b);
795
+ if (first === undefined) return this.fail(b, this.#text(b, s, path, errorText.needsArgument("ifError", 1)));
437
796
  const label = this.labels++;
438
797
  const r = this.locals++;
439
798
  const ok = this.locals++;
@@ -441,20 +800,20 @@ class Lowerer {
441
800
  const value = this.expr(first, s, [...path, 0], attempt);
442
801
  attempt.stmts.push({ t: "set", n: r, value }, { t: "set", n: ok, value: bool(true) });
443
802
  const otherwise = block(b.fail);
444
- const fallback = second === undefined ? this.fail(otherwise) : this.expr(second, s, [...path, 1], otherwise);
803
+ const fallback = second === undefined ? this.fail(otherwise, this.#text(otherwise, s, path, errorText.needsArgument("ifError", 1))) : this.expr(second, s, [...path, 1], otherwise);
445
804
  otherwise.stmts.push({ t: "set", n: r, value: fallback });
446
805
  b.stmts.push({ t: "let", n: ok, value: bool(false) }, { t: "block", label, body: attempt.stmts }, { t: "if", cond: prim("!", local(ok)), yes: otherwise.stmts, no: [] });
447
806
  return this.#typed(local(r), join(this.kindOf(value), this.kindOf(fallback)));
448
807
  }
449
808
 
450
809
  /** A value of a known kind needs no check. */
451
- #boolean(x: LExpr, b: Block): LExpr {
452
- if (this.kindOf(x) !== "boolean") this.check(b, prim("isBoolean", x), "a boolean");
810
+ #boolean(x: LExpr, b: Block, s: Pick<Scope, "origin" | "focus">, site: ErrorSite): LExpr {
811
+ if (this.kindOf(x) !== "boolean") this.check(b, prim("isBoolean", x), "a boolean", this.site(b, s, site, x));
453
812
  return x;
454
813
  }
455
814
 
456
- #number(x: LExpr, b: Block): LExpr {
457
- if (this.kindOf(x) !== "number") this.check(b, prim("isNumber", x), "a number");
815
+ #number(x: LExpr, b: Block, s: Scope, site: ErrorSite): LExpr {
816
+ if (this.kindOf(x) !== "number") this.check(b, prim("isNumber", x), "a number", this.site(b, s, site, x));
458
817
  return x;
459
818
  }
460
819
 
@@ -462,8 +821,13 @@ class Lowerer {
462
821
  * This method lowers a list op over an `each` into one loop. Like the interpreter, the loop skips an error item, and
463
822
  * with the option `strict` the list op fails at an error item. `errors` gives the error values, so an error item of
464
823
  * `errors` stops the program.
824
+ *
825
+ * The loop checks the items in the order of the interpreter, so the first bad item is the item of the interpreter. Two
826
+ * cases differ. With `strict`, the first error item of the whole list comes before a check of the op. With an extension
827
+ * in the list, the interpreter evaluates each item before the op. In both cases, a check of the op keeps no error.
828
+ * The later arguments evaluate before the loop, and the interpreter evaluates them after the list, so they keep no error.
465
829
  */
466
- #fused(op: ListOp, e: ExprOf<"app">, target: ExprOf<"each">, s: Scope, path: readonly number[], b: Block): LExpr {
830
+ #fused(op: FusedOp, e: ExprOf<"app">, target: ExprOf<"each">, s: Scope, path: readonly number[], b: Block): LExpr {
467
831
  // The `let` expressions above the `each`, from the outside in.
468
832
  let inner = s;
469
833
  let at = [...path, 0];
@@ -471,18 +835,23 @@ class Lowerer {
471
835
  inner = { ...inner, ...this.#bind(x, inner, at, b) };
472
836
  at = [...at, Object.keys(x.bind).length];
473
837
  }
474
- const rest = e.args.slice(1).map((x, i) => this.expr(x, s, [...path, i + 1], b));
838
+ // COMPILE.EXT: the interpreter evaluates each item of the list before the op, and an extension in an item can give
839
+ // #DEPTH!. Thus a failure that would skip the later items stops the program, if the list can call an extension.
840
+ const skip: Block = this.#mayExt(e.args[0] as Expr, s.fns) ? { stmts: b.stmts, fail: STOP } : b;
841
+ const plain: Block = { stmts: b.stmts, fail: plainOf(skip.fail) };
842
+ const rest = this.#all(e.args.slice(1), s, path, 1, "arguments", plain);
475
843
  const options = op === "reduce" ? rest[1] : rest[0];
476
844
  const strict = options === undefined ? undefined : this.value(b, prim("===", call("opts", options), bool(true)));
477
845
  const name = rest[0];
478
846
  if (op === "reduce") {
479
- if (name === undefined) return this.fail(b);
480
- this.check(b, prim("isString", name), "an op name");
847
+ if (name === undefined) return this.fail(plain);
848
+ this.check(plain, prim("isString", name), "an op name");
481
849
  }
482
850
  const items = (label: number): Fail => {
483
- if (op === "errors") return RETURN;
484
- return strict === undefined ? { t: "continue", label } : { t: "continue", label, strict: { cond: strict, else: b.fail } };
851
+ if (op === "errors") return STOP;
852
+ return strict === undefined ? { t: "continue", label } : { t: "continue", label, strict: { cond: strict, else: skip.fail } };
485
853
  };
854
+ const opFail = strict === undefined ? skip.fail : plain.fail;
486
855
 
487
856
  const acc = this.locals++;
488
857
  const n = this.typedLocal("number");
@@ -494,15 +863,17 @@ class Lowerer {
494
863
  body.stmts.push({ t: "set", n, value: prim("+", local(n), num(1)) });
495
864
  };
496
865
  // A check of the list op itself is in the loop, but its failure is a failure of the list op.
497
- const opCheck = (body: Block): Block => ({ stmts: body.stmts, fail: b.fail });
866
+ const opCheck = (body: Block): Block => ({ stmts: body.stmts, fail: opFail });
498
867
  const firstThen = (body: Block, v: LExpr, then: (later: Block) => LExpr): void => {
499
- const later = block(b.fail);
868
+ const later = block(opFail);
500
869
  later.stmts.push({ t: "set", n: acc, value: then(later) });
501
870
  body.stmts.push({ t: "if", cond: prim("===", local(n), num(0)), yes: [{ t: "set", n: acc, value: v }], no: later.stmts });
502
871
  };
503
872
  const nonEmpty = (): void => {
504
- this.check(b, prim("!==", local(n), num(0)), "a list that is not empty");
873
+ this.check(b, prim("!==", local(n), num(0)), "a list that is not empty", this.#text(b, s, path, errorText.empty(op)));
505
874
  };
875
+ const opError = (): LExpr | undefined => this.site(b, s, { t: "op", op, path });
876
+ const numbers: ErrorSite = { t: "items", op, what: "numbers", path };
506
877
 
507
878
  switch (op) {
508
879
  case "count":
@@ -512,16 +883,16 @@ class Lowerer {
512
883
  case "mean":
513
884
  init(num(0));
514
885
  this.#loop(target, inner, at, b, items, (body, _key, v) => {
515
- body.stmts.push({ t: "set", n: acc, value: prim("+", local(acc), this.#number(v, opCheck(body))) });
886
+ body.stmts.push({ t: "set", n: acc, value: prim("+", local(acc), this.#number(v, opCheck(body), s, numbers)) });
516
887
  count(body);
517
888
  });
518
- if (op === "sum") return this.#typed(this.checked(b, call("result", local(acc)), "a finite sum"), "number");
889
+ if (op === "sum") return this.#typed(this.checked(b, call("result", local(acc)), "a finite sum", opError()), "number");
519
890
  nonEmpty();
520
- return this.#typed(this.checked(b, call("result", prim("/", local(acc), local(n))), "a finite mean"), "number");
891
+ return this.#typed(this.checked(b, call("result", prim("/", local(acc), local(n))), "a finite mean", opError()), "number");
521
892
  case "min":
522
893
  case "max":
523
894
  this.#loop(target, inner, at, b, items, (body, _key, v) => {
524
- this.#number(v, opCheck(body));
895
+ this.#number(v, opCheck(body), s, numbers);
525
896
  firstThen(body, v, () => prim(op, local(acc), v));
526
897
  count(body);
527
898
  });
@@ -532,7 +903,7 @@ class Lowerer {
532
903
  case "none":
533
904
  init(bool(op === "all"));
534
905
  this.#loop(target, inner, at, b, items, (body, _key, v) => {
535
- body.stmts.push({ t: "set", n: acc, value: prim(op === "all" ? "&&" : "||", local(acc), this.#boolean(v, opCheck(body))) });
906
+ body.stmts.push({ t: "set", n: acc, value: prim(op === "all" ? "&&" : "||", local(acc), this.#boolean(v, opCheck(body), s, { t: "items", op, what: "booleans", path })) });
536
907
  });
537
908
  return op === "none" ? prim("!", local(acc)) : this.#typed(local(acc), "boolean");
538
909
  case "first":
@@ -554,30 +925,25 @@ class Lowerer {
554
925
  return this.value(b, call("frozen", array()));
555
926
  case "reduce":
556
927
  this.#loop(target, inner, at, b, items, (body, _key, v) => {
557
- firstThen(body, v, (later) => this.checked(later, call("step", name as LExpr, local(acc), v), "a step of reduce"));
928
+ firstThen(body, v, (later) => this.checked(later, call("step", name as LExpr, local(acc), v), "a step of reduce", this.site(later, s, { t: "step", path }, name as LExpr)));
558
929
  count(body);
559
930
  });
560
- nonEmpty();
931
+ // An empty list can give the identity of the op, so tier 1 gives its result. Without one identity, it is an error.
932
+ if (this.#emptyFails(e)) this.check(plain, prim("!==", local(n), num(0)), "a list that is not empty");
933
+ else this.#decide(b, prim("!==", local(n), num(0)), "a list that is not empty");
561
934
  return local(acc);
562
- // listReason stops a program with these ops before the lowering, so this case is defensive.
563
- case "sortBy":
564
- case "take":
565
- case "nth":
566
- case "drop":
567
- case "append":
568
- case "flat":
569
- case "without":
570
- case "get":
571
- case "indexOf":
572
- case "distinct":
573
- case "group":
574
- case "join":
575
- /* v8 ignore next -- @preserve */
576
- // Stryker disable next-line all: listReason stops these ops before the lowering
577
- throw new Unsupported(`the list op "${op}"`);
578
935
  }
579
936
  }
580
937
 
938
+ /**
939
+ * This method tells if a `reduce` of an empty list always gives an error (LIST.EMPTY). The name of its op is a literal,
940
+ * and the domains do not have exactly one identity of the op. An option can name a domain, so a third argument tells nothing.
941
+ */
942
+ #emptyFails(e: ExprOf<"app">): boolean {
943
+ const name = e.args[1] as Expr;
944
+ return e.args.length === 2 && name.tag === "lit" && this.#facts.identities(name.value as string) !== 1;
945
+ }
946
+
581
947
  /**
582
948
  * This method lowers the loop over the targets of an axis. The tests of `where` and the body evaluate at each target
583
949
  * in a block whose failure is `items(label)`. Then `onItem` adds the statements for the value of the body.
@@ -588,65 +954,86 @@ class Lowerer {
588
954
  */
589
955
  #address(at: Addr, s: Scope, path: readonly number[], first: number, b: Block): LExpr {
590
956
  const values = addrExprs(at).map((x, i) => this.expr(x, s, [...path, first + i], b));
591
- const args = [s.space, s.origin, s.focus, this.constant(at), ...(values.length === 0 ? [] : [array(...values)])];
592
- return this.checked(b, call("addr", ...args), "an address");
957
+ const moves = values.length === 0 ? [] : [array(...values)];
958
+ return this.checked(b, call("addr", s.space, s.origin, s.focus, this.constant(at), ...moves), "an address", this.site(b, s, { t: "addr", at, path }, s.space, ...moves));
593
959
  }
594
960
 
595
961
  #loop(e: ExprOf<"each">, s: Scope, path: readonly number[], b: Block, items: (label: number) => Fail, onItem: (body: Block, key: LExpr, value: LExpr) => void): void {
596
- this.#targetLoop(e.axis, e.at, s, path, 1, b, items, (body, key, at) => {
597
- onItem(body, key, this.expr(e.body, at, [...path, 0], body));
962
+ this.#targetLoop(e, s, path, 1, b, items, (body, key, at, names) => {
963
+ onItem(body, key, this.expr(e.body, { ...at, env: new Map([...at.env, ...names]) }, [...path, 0], body));
598
964
  });
599
965
  }
600
966
 
601
967
  /**
602
- * This method lowers the loop over the targets of an axis with the address `addr`. The tests of `where` have the child
603
- * indexes from `firstTest`, and the expressions of the address come after them. `each` adds the statements of a target.
968
+ * This method lowers the loop over the targets of an axis with an address. The list of the axis `list` has the child
969
+ * index `firstTest`. The tests of `where` come next, and the expressions of the address come after them. `each` adds
970
+ * the statements of a target. The map `names` has the names `as` of the item. Only the body or the step reads them.
604
971
  */
605
972
  #targetLoop(
606
- axis: Axis,
607
- addr: Addr | undefined,
973
+ e: Pick<ExprOf<"each">, "axis" | "at" | "as">,
608
974
  s: Scope,
609
975
  path: readonly number[],
610
976
  firstTest: number,
611
977
  b: Block,
612
978
  items: (label: number) => Fail,
613
- each: (body: Block, key: LExpr, at: Scope) => void,
979
+ each: (body: Block, key: LExpr, at: Scope, names: ReadonlyMap<string, Bound>) => void,
614
980
  ): void {
615
- const from = addr === undefined || addr.length === 0 ? s.focus : this.#address(addr, s, path, firstTest + whereTests(axis).length, b);
981
+ const { axis, at: addr, as } = e;
982
+ this.#loops++;
983
+ const list = listOf(axis);
984
+ const tests = firstTest + axisChildren(axis) - whereTests(axis).length;
985
+ const from = addr === undefined || addr.length === 0 ? s.focus : this.#address(addr, s, path, firstTest + axisChildren(axis), b);
616
986
  const base = baseAxis(axis);
617
987
  let space = s.space;
618
988
  let over: LExpr;
619
989
  let skip: LExpr | undefined;
620
990
  // The index of the record of each target: the index of the loop, or else the index that the axis gives.
621
991
  let idx: LExpr | undefined;
622
- if (base.t === "table") {
992
+ // The value and the position of each item of the axis list.
993
+ let item: { readonly values: LExpr; readonly nth: LExpr } | undefined;
994
+ if (list !== undefined) {
995
+ // The list evaluates at the key of the address (AXIS.LIST).
996
+ const moved: Scope = from === s.focus ? s : { ...s, focus: from, rec: prim("get", s.space, from), slot: undefined };
997
+ const value = this.value(b, this.expr(list, moved, [...path, firstTest], b));
998
+ const targets = this.checked(b, call("items", value, bool(base.t === "reverse")), "a list of the axis list", this.site(b, moved, { t: "listAxis", path }, value));
999
+ over = prim("keysOf", targets);
1000
+ item = { values: prim("valuesOf", targets), nth: prim("idxOf", targets) };
1001
+ } else if (base.t === "table") {
623
1002
  // The axis table moves the evaluation to the space of its table, and there the origin is the target.
624
- space = this.checked(b, call("table", local(TABLES), this.constant(base.name)), "a table");
1003
+ space = this.checked(b, call("table", local(TABLES), this.constant(base.name)), "a table", this.#text(b, s, path, errorText.noTable(base.name)));
625
1004
  over = call("keys", space);
626
1005
  } else if (base.t === "all" || base.t === "others") {
627
1006
  over = call("keys", s.space);
628
1007
  if (base.t === "others") skip = from;
629
1008
  } else {
630
- const targets = this.checked(b, { t: "targets", axis: this.index(base), args: [s.space, s.origin, from] }, "the targets of an axis");
1009
+ const targets = this.checked(b, { t: "targets", axis: this.index(base), args: [s.space, s.origin, from] }, "the targets of an axis", this.site(b, s, { t: "axis", axis: base, path }, s.space, from));
631
1010
  over = prim("keysOf", targets);
632
1011
  idx = this.value(b, prim("idxOf", targets));
633
1012
  }
634
- const records = this.value(b, prim("records", space));
1013
+ // A key of a list can be outside the space, and it has no index of the space, so the record comes from the key.
1014
+ const records = list === undefined ? this.value(b, prim("records", space)) : undefined;
635
1015
  const label = this.labels++;
636
1016
  const array_ = this.locals++;
637
1017
  const index = this.locals++;
638
- const item = this.locals++;
639
- const key = local(item);
1018
+ const target = this.locals++;
1019
+ const key = local(target);
640
1020
  const body = block(items(label));
641
1021
  if (skip !== undefined) body.stmts.push({ t: "if", cond: prim("===", key, skip), yes: [{ t: "next" }], no: [] });
642
1022
  const slot = idx === undefined ? local(index) : prim("member", idx, local(index));
643
- const at: Scope = { space, origin: base.t === "table" ? key : s.origin, focus: key, env: s.env, fns: s.fns, rec: prim("recordAt", records, slot, space, key) };
1023
+ const rec = records === undefined ? prim("get", space, key) : prim("recordAt", records, slot, space, key);
1024
+ const at: Scope = { space, origin: base.t === "table" ? key : s.origin, focus: key, env: s.env, fns: s.fns, rec, columns: s.columns, slot: list === undefined ? slot : undefined };
644
1025
  whereTests(axis).forEach((test, i) => {
645
- const ok = this.#boolean(this.expr(test, at, [...path, firstTest + i], body), body);
1026
+ const testPath = [...path, tests + i];
1027
+ const ok = this.#boolean(this.expr(test, at, testPath, body), body, at, { t: "test", path: testPath });
646
1028
  body.stmts.push({ t: "if", cond: prim("!", ok), yes: [{ t: "next" }], no: [] });
647
1029
  });
648
- each(body, key, at);
649
- b.stmts.push({ t: "loop", label, item, index, array: array_, over, body: body.stmts });
1030
+ const names = new Map<string, Bound>();
1031
+ const [name, position] = as ?? [];
1032
+ if (name !== undefined && item !== undefined) names.set(name, { value: this.value(body, prim("member", item.values, local(index))) });
1033
+ if (position !== undefined && item !== undefined) names.set(position, { value: this.#typed(this.value(body, prim("member", item.nth, local(index))), "number") });
1034
+ each(body, key, at, names);
1035
+ this.#loops--;
1036
+ b.stmts.push({ t: "loop", label, item: target, index, array: array_, over, body: body.stmts });
650
1037
  }
651
1038
 
652
1039
  /** This method gives a local for each name of a loop, with its first value at the node (LOOP.NAMES). */
@@ -683,20 +1070,115 @@ class Lowerer {
683
1070
  const tests = first + Object.keys(e.step).length;
684
1071
  const { env, locals } = this.#loopNames(e.init, s, path, b);
685
1072
  const inner: Scope = { ...s, env };
1073
+ const limit = this.#limit(e, s, path, tests, b);
1074
+ const untilAt = tests + axisChildren(limitAxis(e) ?? { t: "all" });
686
1075
  const label = this.labels++;
687
1076
  const k = this.typedLocal("number");
688
1077
  b.stmts.push({ t: "let", n: k, value: num(0) });
689
1078
  const body = block(b.fail);
690
1079
  if (e.until !== undefined) {
691
- const stop = this.#boolean(this.expr(e.until, inner, [...path, tests], body), body);
1080
+ const stop = this.#boolean(this.expr(e.until, inner, [...path, untilAt], body), body, inner, { t: "until", path: [...path, untilAt] });
692
1081
  body.stmts.push({ t: "check", ok: prim("!", stop), reason: "the test until", fail: { t: "break", label } });
693
1082
  }
694
1083
  // At the limit, an iteration without a test ends, and an iteration with a test fails.
695
- body.stmts.push({ t: "check", ok: prim("!==", local(k), num(e.limit)), reason: "the limit of iterate", fail: e.until === undefined ? { t: "break", label } : b.fail });
1084
+ const more = prim("!==", local(k), limit);
1085
+ if (e.until === undefined) body.stmts.push({ t: "check", ok: more, reason: "the limit of iterate", fail: { t: "break", label } });
1086
+ else this.check(body, more, "the limit of iterate", this.site(body, s, { t: "limit", path }, limit));
696
1087
  this.#loopStep(e.step, inner, path, first, body, locals);
697
1088
  body.stmts.push({ t: "set", n: k, value: prim("+", local(k), num(1)) });
698
1089
  b.stmts.push({ t: "repeat", label, body: body.stmts });
699
- return this.expr(e.result, inner, [...path, tests + (e.until === undefined ? 0 : 1)], b);
1090
+ return this.expr(e.result, inner, [...path, untilAt + (e.until === undefined ? 0 : 1)], b);
1091
+ }
1092
+
1093
+ /**
1094
+ * This method lowers a fixed point (FIX.ROUNDS). The column is an array with the value of each key, in the order of
1095
+ * the keys. The rows of `init` give its first values, and each round makes the array of the next values. A round
1096
+ * without a change ends the loop with the old array, as the interpreter does. After the last round, an error stops
1097
+ * the column (FIX.LIMIT). The value of the node is the row of the focus.
1098
+ */
1099
+ #fix(e: ExprOf<"fix">, s: Scope, path: readonly number[], b: Block): LExpr {
1100
+ const n = this.locals++;
1101
+ const column: FixColumn = { local: local(n), join: e.join };
1102
+ b.stmts.push({ t: "let", n, value: array() });
1103
+ this.#rows(e, e.init, s, path, 0, b, (row, _at, v) => {
1104
+ row.stmts.push({ t: "push", n, value: v });
1105
+ });
1106
+ const limit = this.value(b, call("rounds", s.space));
1107
+ const label = this.labels++;
1108
+ const k = this.typedLocal("number");
1109
+ b.stmts.push({ t: "let", n: k, value: num(0) });
1110
+ const body = block(b.fail);
1111
+ this.check(body, prim("!==", local(k), limit), "the limit of the rounds", this.site(body, s, { t: "fixLimit", name: e.name, path }, limit));
1112
+ const next = this.locals++;
1113
+ const changed = this.locals++;
1114
+ body.stmts.push({ t: "let", n: next, value: array() }, { t: "let", n: changed, value: bool(false) });
1115
+ // The step has the column in its scope, so an inner `fix` with the same name hides the column.
1116
+ this.#rows(e, e.step, { ...s, columns: new Map([...s.columns, [e.name, column]]) }, path, 1, body, (row, at, v) => {
1117
+ const old = this.value(row, prim("member", column.local, at.slot as LExpr));
1118
+ const value = this.value(row, prim(JOINS[e.join], old, v));
1119
+ row.stmts.push({ t: "if", cond: prim("!==", value, old), yes: [{ t: "set", n: changed, value: bool(true) }], no: [] }, { t: "push", n: next, value });
1120
+ });
1121
+ body.stmts.push(
1122
+ { t: "check", ok: local(changed), reason: "a round that changes a row", fail: { t: "break", label } },
1123
+ { t: "set", n, value: local(next) },
1124
+ { t: "set", n: k, value: prim("+", local(k), num(1)) },
1125
+ );
1126
+ b.stmts.push({ t: "repeat", label, body: body.stmts });
1127
+ return this.#rowOf(e.name, column, s, path, b);
1128
+ }
1129
+
1130
+ /**
1131
+ * This method lowers the evaluation of `x` at each row of a column. An error in a row does not stop the next rows, so
1132
+ * each extension of the round evaluates (FIX.ERROR). After the loop, the errors of the rows give the error of the
1133
+ * node. `each` adds the statements of a row with a good value.
1134
+ */
1135
+ #rows(e: ExprOf<"fix">, x: Expr, s: Scope, path: readonly number[], child: number, b: Block, each: (row: Block, at: Scope, value: LExpr) => void): void {
1136
+ const errors = this.locals++;
1137
+ b.stmts.push({ t: "let", n: errors, value: array() });
1138
+ const kind: ErrorSite = { t: "row", name: e.name, join: e.join, path };
1139
+ // Stryker disable next-line ArrowFunction: each check of a row is in its own block, so the loop reads no failure
1140
+ this.#targetLoop(ROWS, s, path, 0, b, () => b.fail, (body, _key, at) => {
1141
+ const row = this.#attempt(
1142
+ body,
1143
+ (inner) => {
1144
+ const v = this.value(inner, this.expr(x, at, [...path, child], inner));
1145
+ if (joinKind(e.join) === "boolean") this.#boolean(v, inner, at, kind);
1146
+ else this.check(inner, prim("isFinite", v), "a finite number", this.site(inner, at, kind, v));
1147
+ each(inner, at, v);
1148
+ return v;
1149
+ },
1150
+ true,
1151
+ );
1152
+ body.stmts.push({ t: "if", cond: prim("!", row.ok as LExpr), yes: [{ t: "push", n: errors, value: row.value }], no: [] });
1153
+ });
1154
+ const site = this.constants.push({ t: "rows", path } satisfies ErrorSite) - 1;
1155
+ this.check(b, prim("===", prim("member", local(errors), this.constant("length")), num(0)), "the rows have values", call("args", { t: "site", i: site }, s.origin, s.focus, local(errors)));
1156
+ }
1157
+
1158
+ /** This method reads the row of the focus. A focus that is not a key of the space has no row (FIX.LAST). */
1159
+ #rowOf(name: string, column: FixColumn, s: Scope, path: readonly number[], b: Block): LExpr {
1160
+ const x = this.value(b, prim("member", column.local, s.slot ?? call("rowIndex", s.space, s.focus)));
1161
+ this.check(b, prim("isValue", x), "a row of the column", this.site(b, s, { t: "lastKey", name, path }));
1162
+ return this.#typed(x, joinKind(column.join));
1163
+ }
1164
+
1165
+ /**
1166
+ * This method gives the number of steps of an iteration. A data limit counts the targets of its axis. Its failure
1167
+ * stops the program, and tier 1 gives the error (ITERATE.LIMIT.ERROR).
1168
+ */
1169
+ #limit(e: ExprOf<"iterate">, s: Scope, path: readonly number[], firstTest: number, b: Block): LExpr {
1170
+ const axis = limitAxis(e);
1171
+ if (axis === undefined) return num(e.limit as number);
1172
+ const n = this.typedLocal("number");
1173
+ b.stmts.push({ t: "let", n, value: num(0) });
1174
+ // The error of a limit that is not valid keeps its cause, so each failure here is the plain failure of the block.
1175
+ // COMPILE.EXT: the interpreter evaluates each test, and an extension in a test can give #DEPTH!. Thus a failed test stops the program.
1176
+ const plain: Block = { stmts: b.stmts, fail: axisExprs(axis).some((x) => this.#mayExt(x, s.fns)) ? STOP : plainOf(b.fail) };
1177
+ this.#targetLoop({ axis }, s, path, firstTest, plain, () => plain.fail, (body) => {
1178
+ body.stmts.push({ t: "set", n, value: prim("+", local(n), num(1)) });
1179
+ });
1180
+ this.check(b, prim("===", prim("min", local(n), num(MAX_ITERATIONS)), local(n)), "a data limit in the cap");
1181
+ return local(n);
700
1182
  }
701
1183
 
702
1184
  /** This method lowers a fold (FOLD.ORDER): the loop over the targets, with a step at each target. */
@@ -705,10 +1187,10 @@ class Lowerer {
705
1187
  const tests = first + Object.keys(e.step).length;
706
1188
  const { env, locals } = this.#loopNames(e.init, s, path, b);
707
1189
  // An error of a test or of a step is the error of the fold.
708
- this.#targetLoop(e.axis, e.at, s, path, tests, b, () => b.fail, (body, _key, at) => {
709
- this.#loopStep(e.step, { ...at, env }, path, first, body, locals);
1190
+ this.#targetLoop(e, s, path, tests, b, () => b.fail, (body, _key, at, names) => {
1191
+ this.#loopStep(e.step, { ...at, env: new Map([...env, ...names]) }, path, first, body, locals);
710
1192
  });
711
- return this.expr(e.result, { ...s, env }, [...path, tests + whereTests(e.axis).length + addrExprs(e.at).length], b);
1193
+ return this.expr(e.result, { ...s, env }, [...path, tests + axisChildren(e.axis) + addrExprs(e.at).length], b);
712
1194
  }
713
1195
  }
714
1196