@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/build/index.js CHANGED
@@ -1,13 +1,13 @@
1
- import { Failure, Held, STD_EXT, THING, agree, check, context, formulaDefinitions, formulaEvaluators, isEnvelope, ok as ok$1, pathMatches, prepare, ref as ref$1, reference, refsOf, sameValue, typeName, typePath, typed } from "@mark1russell7/coeval";
1
+ import { Failure, Held, STD_EXT, THING, agree, check, checkStep, context, formulaDefinitions, formulaEvaluators, isEnvelope, isStep, ok as ok$1, pathMatches, prepare, ref as ref$1, reference, refsOf, sameValue, stepLadder, stepOf, stepRank, typeName, typePath, typed } from "@mark1russell7/coeval";
2
2
  // src/result.ts
3
- const NONE$1 = Object.freeze({ tag: "none" });
3
+ const NONE$2 = Object.freeze({ tag: "none" });
4
4
  /** This function makes an `Optional` that holds `value`. */
5
5
  const some = (value) => ({
6
6
  tag: "some",
7
7
  value
8
8
  });
9
9
  /** This function gives the shared empty `Optional`. */
10
- const none = () => NONE$1;
10
+ const none = () => NONE$2;
11
11
  /** This function makes a successful `Result`. */
12
12
  const ok = (value) => ({
13
13
  ok: true,
@@ -84,6 +84,436 @@ function vexError(kind, message, details = {}) {
84
84
  }
85
85
  /** This function gives a short text for an error, for example `#REF! unknown-key: there is no key "Z"`. */
86
86
  const formatError = (e) => `${e.code} ${e.kind}: ${e.message}`;
87
+ // src/checked.ts
88
+ /**
89
+ * The cache of the lists that passed the check of LIST.SHAPE. `isVexList` adds each frozen list that passes its check.
90
+ * The interpreter adds each list that it makes from the items of such lists, because these items passed the check.
91
+ * The package index does not export this module.
92
+ */
93
+ const CHECKED = /* @__PURE__ */ new WeakSet();
94
+ // src/list.ts
95
+ /** This function makes a list. */
96
+ const vexList = (items) => Object.freeze({
97
+ kind: "vex.list",
98
+ items: Object.freeze([...items])
99
+ });
100
+ /** This function tells if a value is an error value: a text `code`, `kind` and `message`, and a `path` (LIST.SHAPE). */
101
+ const isErrorValue = (u) => {
102
+ if (typeof u !== "object" || u === null) return false;
103
+ const e = u;
104
+ return typeof e.code === "string" && typeof e.kind === "string" && typeof e.message === "string" && Array.isArray(e.path);
105
+ };
106
+ /** This function tells if a value is an item of a list: a text key, and a value or an error value (LIST.SHAPE). */
107
+ const isListItem = (u) => {
108
+ if (typeof u !== "object" || u === null) return false;
109
+ const { key, result } = u;
110
+ if (typeof key !== "string" || typeof result !== "object" || result === null) return false;
111
+ const r = result;
112
+ return r.ok === true ? r.value !== void 0 : r.ok === false && isErrorValue(r.error);
113
+ };
114
+ /**
115
+ * This function tells if a value is a Vex list (LIST.SHAPE). A list has the kind `vex.list`, and each item has a text key
116
+ * and a result. Another value with the kind `vex.list` is a record, so no list op applies to it. A frozen
117
+ * list passes the check once.
118
+ */
119
+ const isVexList = (u) => {
120
+ if (typeof u !== "object" || u === null) return false;
121
+ if (CHECKED.has(u)) return true;
122
+ const { kind, items } = u;
123
+ if (kind !== "vex.list" || !Array.isArray(items)) return false;
124
+ for (let i = 0; i < items.length; i++) if (!isListItem(items[i])) return false;
125
+ if (Object.isFrozen(u) && Object.isFrozen(items)) CHECKED.add(u);
126
+ return true;
127
+ };
128
+ /**
129
+ * The names of the core list ops. They apply when the first argument is a list. They apply to an array too, when no
130
+ * domain and no function of the host has the op for it (LIST.ARRAY).
131
+ */
132
+ const LIST_OPS = /* @__PURE__ */ new Set([
133
+ "count",
134
+ "sum",
135
+ "min",
136
+ "max",
137
+ "mean",
138
+ "any",
139
+ "all",
140
+ "none",
141
+ "values",
142
+ "keys",
143
+ "reduce",
144
+ "first",
145
+ "errors",
146
+ "sortBy",
147
+ "take",
148
+ "nth",
149
+ "setNth",
150
+ "drop",
151
+ "append",
152
+ "flat",
153
+ "without",
154
+ "get",
155
+ "indexOf",
156
+ "distinct",
157
+ "group",
158
+ "join"
159
+ ]);
160
+ /**
161
+ * The size rules of the core list ops and of `fill` (LOOP.SIZE.OPS). Each op that gives a list has a rule here. An
162
+ * error item has no size, so `errors` has no bound: the messages of the errors can hold texts.
163
+ */
164
+ const LIST_SIZES = Object.freeze({
165
+ count: "scalar",
166
+ sum: "scalar",
167
+ min: "scalar",
168
+ max: "scalar",
169
+ mean: "scalar",
170
+ any: "scalar",
171
+ all: "scalar",
172
+ none: "scalar",
173
+ indexOf: "scalar",
174
+ values: {
175
+ size: [1],
176
+ count: [1],
177
+ inner: [1],
178
+ item: [1],
179
+ part: [1],
180
+ keys: "position"
181
+ },
182
+ keys: {
183
+ size: [1],
184
+ count: [1],
185
+ keys: "position"
186
+ },
187
+ errors: { size: ["unbounded"] },
188
+ reduce: "reduce",
189
+ first: {
190
+ size: [[1, "item"]],
191
+ count: [[1, "item"]],
192
+ inner: [[1, "item"]],
193
+ item: [[1, "part"]]
194
+ },
195
+ nth: {
196
+ size: [[1, "item"], 0],
197
+ count: [[1, "item"], 0],
198
+ inner: [[1, "item"], 0],
199
+ item: [[1, "part"], 0]
200
+ },
201
+ get: {
202
+ size: [[1, "item"], 0],
203
+ count: [[1, "item"], 0],
204
+ inner: [[1, "item"], 0],
205
+ item: [[1, "part"], 0]
206
+ },
207
+ setNth: {
208
+ size: [
209
+ 1,
210
+ 0,
211
+ 1
212
+ ],
213
+ count: [
214
+ 1,
215
+ 0,
216
+ 0
217
+ ],
218
+ inner: [
219
+ 1,
220
+ 0,
221
+ [1, "count"]
222
+ ],
223
+ item: [
224
+ 1,
225
+ 0,
226
+ [1, "size"]
227
+ ],
228
+ part: [
229
+ 1,
230
+ 0,
231
+ [1, "item"]
232
+ ]
233
+ },
234
+ sortBy: {
235
+ size: [1, 0],
236
+ count: [1, 0],
237
+ inner: [1, 0],
238
+ item: [1, 0],
239
+ part: [1, 0]
240
+ },
241
+ take: {
242
+ size: [1, 0],
243
+ count: [1, 0],
244
+ inner: [1, 0],
245
+ item: [1, 0],
246
+ part: [1, 0],
247
+ limit: 1,
248
+ byParts: {
249
+ size: [["limit", "item"], 0],
250
+ count: [1, 0],
251
+ inner: [["limit", "item"], 0],
252
+ item: [1, 0],
253
+ part: [1, 0]
254
+ }
255
+ },
256
+ drop: {
257
+ size: [1, 0],
258
+ count: [1, 0],
259
+ inner: [1, 0],
260
+ item: [1, 0],
261
+ part: [1, 0]
262
+ },
263
+ without: {
264
+ size: [1, 0],
265
+ count: [1, 0],
266
+ inner: [1, 0],
267
+ item: [1, 0],
268
+ part: [1, 0]
269
+ },
270
+ append: {
271
+ size: [1, 1],
272
+ count: [1, 1],
273
+ inner: [1, 1],
274
+ item: [1, 1],
275
+ part: [1, 1]
276
+ },
277
+ flat: {
278
+ size: [1],
279
+ count: [[1, "inner"]],
280
+ item: [[1, "part"]]
281
+ },
282
+ distinct: {
283
+ size: [1],
284
+ count: [1],
285
+ inner: [1],
286
+ item: [1],
287
+ part: [1]
288
+ },
289
+ group: {
290
+ size: [1, "scaled"],
291
+ count: [0, 1],
292
+ inner: [[1, "count"], 0]
293
+ },
294
+ join: { size: [1, "each"] },
295
+ fill: {
296
+ size: [0, "copies"],
297
+ count: ["number", 0],
298
+ inner: [0, ["copies", "count"]],
299
+ item: [0, [1, "size"]],
300
+ part: [0, [1, "item"]],
301
+ keys: "position"
302
+ }
303
+ });
304
+ /** This function tells if a name is the name of a core list op. */
305
+ const isListOp = (op) => LIST_OPS.has(op);
306
+ // src/error-text.ts
307
+ /** This function gives a short name for the type of a value, for error messages. */
308
+ function describeType(u) {
309
+ if (u === null) return "null";
310
+ if (Array.isArray(u)) return "array";
311
+ if (isVexList(u)) return "list";
312
+ if (typeof u === "object") {
313
+ const name = Object.getPrototypeOf(u)?.constructor?.name;
314
+ return typeof name === "string" && name !== "Object" ? name : "object";
315
+ }
316
+ return typeof u;
317
+ }
318
+ /** The texts of the errors. Each function takes the facts of the error that do not come from the position of its node. */
319
+ const errorText = {
320
+ /** A name without a binding (`var`). */
321
+ unbound: (name) => ({
322
+ kind: "unbound",
323
+ message: `the name "${name}" has no binding`
324
+ }),
325
+ /** A read of a function as a value (FN.VALUE). */
326
+ functionValue: (name) => ({
327
+ kind: "kind-mismatch",
328
+ message: `the name "${name}" is a function, not a value`
329
+ }),
330
+ /** A call of a name without a binding (FN.CALL). */
331
+ noFunction: (name) => ({
332
+ kind: "unbound",
333
+ message: `the function "${name}" has no binding`
334
+ }),
335
+ /** A call of a name that holds a value (FN.CALL). */
336
+ notFunction: (name) => ({
337
+ kind: "kind-mismatch",
338
+ message: `the name "${name}" is a value, not a function`
339
+ }),
340
+ /** A call with the wrong number of arguments (FN.CALL). */
341
+ arity: (name, params, args) => ({
342
+ kind: "bad-expression",
343
+ message: `the function "${name}" takes ${String(params)} arguments, not ${String(args)}`
344
+ }),
345
+ /** An extension kind without a handler. */
346
+ noHandler: (kind) => ({
347
+ kind: "unknown-op",
348
+ message: `no handler for the extension kind "${kind}"`
349
+ }),
350
+ /** An exception of an op, of an extension or of `fromScalar`. */
351
+ threw: (op) => ({
352
+ kind: "threw",
353
+ message: `"${op}" threw an exception`,
354
+ op
355
+ }),
356
+ /** A reference that reads no value. `where` is the part of the path that failed. */
357
+ missing: (key, where) => ({
358
+ kind: "missing-field",
359
+ message: `the record at "${key}" has no value at "${where}"`
360
+ }),
361
+ /** A reference whose getter threw. */
362
+ readThrew: (key, where) => ({
363
+ kind: "threw",
364
+ message: `reading "${where}" at "${key}" threw an exception`
365
+ }),
366
+ /** Two or more arguments or fields that failed (CALL.ARGS, REC.FIELDS). */
367
+ args: (count, what) => ({
368
+ kind: "args",
369
+ message: `${String(count)} ${what} failed`
370
+ }),
371
+ /** The axis table of an evaluation without that table. */
372
+ noTable: (name) => ({
373
+ kind: "no-table",
374
+ message: `the evaluation has no table "${name}"`
375
+ }),
376
+ /** The test `until` of `iterate`, with a value that is not a boolean. */
377
+ untilKind: (value) => ({
378
+ kind: "kind-mismatch",
379
+ message: `the test "until" of "iterate" gave a ${typeof value}, not a boolean`
380
+ }),
381
+ /** The limit of `iterate` with a test that is not true. */
382
+ limit: (limit) => ({
383
+ kind: "limit",
384
+ message: `"iterate" made its ${String(limit)} steps, and its test "until" is not true`
385
+ }),
386
+ /** A value of a row of `fix` of the wrong kind for its join. */
387
+ fixKind: (name, join, kind, value) => ({
388
+ kind: "kind-mismatch",
389
+ message: `the "fix" "${name}" with the join "${join}" needs a ${kind}, not a ${describeType(value)}`
390
+ }),
391
+ /** A value of a row of `fix` that is not a finite number. */
392
+ fixNumber: (name, value) => ({
393
+ kind: "not-finite",
394
+ message: `the "fix" "${name}" gave the value ${String(value)}, not a finite number`
395
+ }),
396
+ /** The limit of the rounds of `fix`. */
397
+ fixLimit: (name, rounds) => ({
398
+ kind: "limit",
399
+ message: `the "fix" "${name}" made its ${String(rounds)} rounds, and its values still change`
400
+ }),
401
+ /** A read of `last` at a key that is not a row. */
402
+ lastKey: (name, key) => ({
403
+ kind: "unknown-key",
404
+ message: `the "fix" "${name}" has no row "${key}"`
405
+ }),
406
+ /** The test of `where`, with a value that is not a boolean. */
407
+ whereKind: (value) => ({
408
+ kind: "kind-mismatch",
409
+ message: `the test of "where" gave a ${typeof value}, not a boolean`
410
+ }),
411
+ /** A domain that accepts the receiver of an op and has no such op. */
412
+ domainNoOp: (domain, op) => ({
413
+ kind: "unknown-op",
414
+ message: `the domain "${domain}" has no op "${op}"`,
415
+ op
416
+ }),
417
+ /** An op without arguments and without a free function. */
418
+ noOp: (op) => ({
419
+ kind: "unknown-op",
420
+ message: `there is no function "${op}"`,
421
+ op
422
+ }),
423
+ /** An op whose receiver no domain accepts. */
424
+ noDomain: (op, self) => ({
425
+ kind: "not-instance",
426
+ message: `no domain accepts the receiver of "${op}" (${describeType(self)})`,
427
+ op
428
+ }),
429
+ /** A special form without the argument at the index `i`. */
430
+ needsArgument: (op, i) => ({
431
+ kind: "bad-expression",
432
+ message: `"${op}" needs argument ${String(i + 1)}`,
433
+ op
434
+ }),
435
+ /** `and` or `or` without arguments. */
436
+ needsArguments: (op) => ({
437
+ kind: "bad-expression",
438
+ message: `"${op}" needs at least 1 argument`,
439
+ op
440
+ }),
441
+ /** An argument of a special form that is not a boolean. */
442
+ notBoolean: (op, i, value) => ({
443
+ kind: "kind-mismatch",
444
+ message: `argument ${String(i + 1)} of "${op}" is a ${describeType(value)}, not a boolean`,
445
+ op
446
+ }),
447
+ /** An argument of an op that does not have the kind of its parameter. */
448
+ badParam: (op, i, value, kind, domain) => ({
449
+ kind: kind === "domain" ? "not-instance" : "kind-mismatch",
450
+ message: `argument ${String(i + 1)} of "${op}" is a ${describeType(value)}, not a ${kind === "domain" ? domain : kind}`,
451
+ op
452
+ }),
453
+ /** An op that gave `undefined` or `null`. */
454
+ noValue: (op) => ({
455
+ kind: "undefined-result",
456
+ message: `"${op}" gave no value`,
457
+ op
458
+ }),
459
+ /** An op that gave a number that is not finite. */
460
+ notFinite: (op, value) => ({
461
+ kind: "not-finite",
462
+ message: `"${op}" gave ${String(value)}`,
463
+ op
464
+ }),
465
+ /** An op that gave a value that its domain does not accept as valid. */
466
+ invalid: (op, domain) => ({
467
+ kind: "invalid-value",
468
+ message: `"${op}" gave a value that is not a valid ${domain}`,
469
+ op
470
+ }),
471
+ /** A check `valid` of a domain that threw. */
472
+ validThrew: (op, domain) => ({
473
+ kind: "threw",
474
+ message: `the "valid" check of "${domain}" threw an exception`,
475
+ op
476
+ }),
477
+ /** A list op whose items must have one kind, with an item of another kind. */
478
+ /** The axis `list` over a value that is not a list (AXIS.LIST). */
479
+ axisList: (value) => ({
480
+ kind: "kind-mismatch",
481
+ message: `the axis "list" needs a list, not a ${describeType(value)}`
482
+ }),
483
+ needsItems: (op, what, item) => ({
484
+ kind: "kind-mismatch",
485
+ message: `"${op}" needs ${what}, but an item is a ${describeType(item)}`,
486
+ op
487
+ }),
488
+ /** A list op that has no items to work with. */
489
+ empty: (op) => ({
490
+ kind: "empty",
491
+ message: `"${op}" has no values to work with`,
492
+ op
493
+ }),
494
+ /** `reduce` with an op name that is not a text. */
495
+ reduceName: (name) => ({
496
+ kind: "kind-mismatch",
497
+ message: `"reduce" needs an op name, but got a ${describeType(name)}`,
498
+ op: "reduce"
499
+ }),
500
+ /** A step of `reduce` or of `sortBy` that no domain gives. */
501
+ noStep: (op, value) => ({
502
+ kind: "unknown-op",
503
+ message: `no domain gives "${op}" for a ${describeType(value)}`,
504
+ op
505
+ })
506
+ };
507
+ /** This function makes the error of a text at a node: the path of the node, with its origin and its focus. */
508
+ function errorAt(t, pos, path, extra = {}) {
509
+ return vexError(t.kind, t.message, {
510
+ path,
511
+ origin: pos.origin,
512
+ focus: pos.focus,
513
+ ...t.op === void 0 ? {} : { op: t.op },
514
+ ...extra
515
+ });
516
+ }
87
517
  // src/item-names.ts
88
518
  /**
89
519
  * The check of the names `as` of a loop over the axis `list` (AXIS.LIST.SCOPE). The package index does not export this
@@ -225,6 +655,41 @@ function iterate(limit, init, step, result, until) {
225
655
  };
226
656
  }
227
657
  /**
658
+ * This function makes a fixed-point column (FIX.ROUNDS). `init` gives the first value of each row. `step` gives the next
659
+ * value of each row, and it reads the last round with `last`. `join` joins each next value to the old value of its row.
660
+ */
661
+ function fix(name, join, init, step) {
662
+ return {
663
+ tag: "fix",
664
+ name,
665
+ join,
666
+ init,
667
+ step
668
+ };
669
+ }
670
+ /** This function makes a read of the value of the focus in the last round of the `fix` with the name `name` (FIX.LAST). */
671
+ function last(name) {
672
+ return {
673
+ tag: "last",
674
+ name
675
+ };
676
+ }
677
+ /** This function makes the limit of `iterate` from the size of the data: the number of targets of an axis (ITERATE.LIMIT.DATA). */
678
+ const dataLimit = (axis) => ({ axis });
679
+ /** This function gives the axis of the data limit of an iteration, or `undefined` for a limit that is a number. */
680
+ const limitAxis = (e) => typeof e.limit === "number" ? void 0 : e.limit.axis;
681
+ /**
682
+ * This function gives the parts of an iteration with a data limit, for a walk that tells the axes apart. The parts are
683
+ * an `each` over the axis, and the iteration without its axis. An iteration with a number has `undefined`.
684
+ */
685
+ function splitLimit(e) {
686
+ const axis = limitAxis(e);
687
+ return axis === void 0 ? void 0 : [each(axis, lit(0)), {
688
+ ...e,
689
+ limit: 0
690
+ }];
691
+ }
692
+ /**
228
693
  * This function makes a function (FN.BIND): the names of its parameters and its body. A function is only the value of
229
694
  * a binding of `let`. The body sees the names of the place of that `let`, so a function cannot call itself.
230
695
  */
@@ -390,10 +855,19 @@ const TAGS = /* @__PURE__ */ new Set([
390
855
  "each",
391
856
  "fold",
392
857
  "iterate",
858
+ "fix",
859
+ "last",
393
860
  "fn",
394
861
  "call",
395
862
  "ext"
396
863
  ]);
864
+ /** The joins of `fix`. */
865
+ const JOINS = /* @__PURE__ */ new Set([
866
+ "or",
867
+ "and",
868
+ "max",
869
+ "min"
870
+ ]);
397
871
  /**
398
872
  * This function gives the reason that a value is not a valid expression, or `undefined` for a valid expression
399
873
  * (EVAL.SHAPE). An expression from a newer version of Vex can have a tag that this version does not know. Unlike
@@ -537,10 +1011,19 @@ function badPart(todo, whole) {
537
1011
  case "iterate": {
538
1012
  const limit = u["limit"];
539
1013
  const names = loopParts(u);
540
- if (typeof limit !== "number" || !Number.isInteger(limit) || limit < 0 || limit > 1e5 || names === void 0) return item;
1014
+ if (names === void 0) return item;
1015
+ if (isObject(limit)) push(true, [limit["axis"]]);
1016
+ else if (typeof limit !== "number" || !Number.isInteger(limit) || limit < 0 || limit > 1e5) return item;
541
1017
  push(false, [...names, ...u["until"] === void 0 ? [] : [u["until"]]]);
542
1018
  break;
543
1019
  }
1020
+ case "fix":
1021
+ if (typeof u["name"] !== "string" || !JOINS.has(u["join"])) return item;
1022
+ push(false, [u["init"], u["step"]]);
1023
+ break;
1024
+ case "last":
1025
+ if (typeof u["name"] !== "string") return item;
1026
+ break;
544
1027
  case "ext":
545
1028
  if (typeof u["kind"] !== "string" || !("data" in u)) return item;
546
1029
  break;
@@ -571,15 +1054,21 @@ function children(e) {
571
1054
  ...addrExprs(e.at),
572
1055
  e.result
573
1056
  ];
574
- case "iterate": return [
575
- ...Object.values(e.init),
576
- ...Object.values(e.step),
577
- ...e.until === void 0 ? [] : [e.until],
578
- e.result
579
- ];
1057
+ case "iterate": {
1058
+ const axis = limitAxis(e);
1059
+ return [
1060
+ ...Object.values(e.init),
1061
+ ...Object.values(e.step),
1062
+ ...axis === void 0 ? [] : axisExprs(axis),
1063
+ ...e.until === void 0 ? [] : [e.until],
1064
+ e.result
1065
+ ];
1066
+ }
1067
+ case "fix": return [e.init, e.step];
580
1068
  case "ref": return addrExprs(e.at);
581
1069
  case "lit":
582
1070
  case "var":
1071
+ case "last":
583
1072
  case "ext": return [];
584
1073
  }
585
1074
  }
@@ -1005,6 +1494,8 @@ function windowTargets(s, at, from, to) {
1005
1494
  return ok(out);
1006
1495
  }
1007
1496
  // src/domain.ts
1497
+ /** This function gives the kind of the items of a result of the kind `list:Kind`, or `undefined` for another kind. */
1498
+ const listItemKind = (r) => r?.startsWith("list:") === true ? r.slice(5) : void 0;
1008
1499
  /** This function makes a domain. The result is frozen. */
1009
1500
  function defineDomain(spec) {
1010
1501
  return Object.freeze({
@@ -1065,87 +1556,43 @@ function domainOf(domains, value) {
1065
1556
  }
1066
1557
  /** This function tells if the `liftScalar` setting lifts the argument at `index`. */
1067
1558
  const liftsAt = (lift, index) => lift === true || Array.isArray(lift) && lift[index] === true;
1068
- // src/checked.ts
1559
+ // src/array-list.ts
1069
1560
  /**
1070
- * The cache of the lists that passed the check of LIST.SHAPE. `isVexList` adds each frozen list that passes its check.
1071
- * The interpreter adds each list that it makes from the items of such lists, because these items passed the check.
1072
- * The package index does not export this module.
1561
+ * This function gives the list of an array (LIST.ARRAY). The key of each item is its position, from "0". A position
1562
+ * without a value, or with `null`, gives an error item from `missing`, as a missing field does (REF.MISSING).
1073
1563
  */
1074
- const CHECKED = /* @__PURE__ */ new WeakSet();
1075
- // src/list.ts
1076
- /** This function makes a list. */
1077
- const vexList = (items) => Object.freeze({
1078
- kind: "vex.list",
1079
- items: Object.freeze([...items])
1080
- });
1081
- /** This function tells if a value is an error value: a text `code`, `kind` and `message`, and a `path` (LIST.SHAPE). */
1082
- const isErrorValue = (u) => {
1083
- if (typeof u !== "object" || u === null) return false;
1084
- const e = u;
1085
- return typeof e.code === "string" && typeof e.kind === "string" && typeof e.message === "string" && Array.isArray(e.path);
1086
- };
1087
- /** This function tells if a value is an item of a list: a text key, and a value or an error value (LIST.SHAPE). */
1088
- const isListItem = (u) => {
1089
- if (typeof u !== "object" || u === null) return false;
1090
- const { key, result } = u;
1091
- if (typeof key !== "string" || typeof result !== "object" || result === null) return false;
1092
- const r = result;
1093
- return r.ok === true ? r.value !== void 0 : r.ok === false && isErrorValue(r.error);
1094
- };
1564
+ function listOfArray(array, missing) {
1565
+ const items = [];
1566
+ for (let i = 0; i < array.length; i++) {
1567
+ const x = array[i];
1568
+ items.push({
1569
+ key: String(i),
1570
+ result: x === void 0 || x === null ? fail(missing(`the array has no value at the position ${String(i)}`)) : ok(x)
1571
+ });
1572
+ }
1573
+ return vexList(items);
1574
+ }
1575
+ /** This function gives a list, the list of an array, or `undefined` for another value (LIST.ARRAY). */
1576
+ const asList = (u, missing) => isVexList(u) ? u : Array.isArray(u) ? listOfArray(u, missing) : void 0;
1095
1577
  /**
1096
- * This function tells if a value is a Vex list (LIST.SHAPE). A list has the kind `vex.list`, and each item has a text key
1097
- * and a result. Another value with the kind `vex.list` is a record, so no list op applies to it. A frozen
1098
- * list passes the check once.
1578
+ * This function tells if a value is a count of `fill`: a whole number from 0 to the limit of `iterate`, 100000
1579
+ * (LIST.FILL). Thus a list of `fill` is not larger than the steps of a loop.
1099
1580
  */
1100
- const isVexList = (u) => {
1101
- if (typeof u !== "object" || u === null) return false;
1102
- if (CHECKED.has(u)) return true;
1103
- const { kind, items } = u;
1104
- if (kind !== "vex.list" || !Array.isArray(items)) return false;
1105
- for (let i = 0; i < items.length; i++) if (!isListItem(items[i])) return false;
1106
- if (Object.isFrozen(u) && Object.isFrozen(items)) CHECKED.add(u);
1107
- return true;
1108
- };
1109
- /**
1110
- * The names of the core list ops. They apply when the first argument is a list. They apply to an array too, when no
1111
- * domain and no function of the host has the op for it (LIST.ARRAY).
1112
- */
1113
- const LIST_OPS = /* @__PURE__ */ new Set([
1114
- "count",
1115
- "sum",
1116
- "min",
1117
- "max",
1118
- "mean",
1119
- "any",
1120
- "all",
1121
- "none",
1122
- "values",
1123
- "keys",
1124
- "reduce",
1125
- "first",
1126
- "errors",
1127
- "sortBy",
1128
- "take",
1129
- "nth",
1130
- "drop",
1131
- "append",
1132
- "flat",
1133
- "without",
1134
- "get",
1135
- "indexOf",
1136
- "distinct",
1137
- "group",
1138
- "join"
1139
- ]);
1140
- /** This function tells if a name is the name of a core list op. */
1141
- const isListOp = (op) => LIST_OPS.has(op);
1142
- // src/codec.ts
1143
- /** This function tells if a value is a record: an object that is not an array. */
1144
- const isRecord = (u) => typeof u === "object" && u !== null && !Array.isArray(u);
1145
- const isPlainRecord = (u) => {
1146
- if (!isRecord(u)) return false;
1147
- const proto = Object.getPrototypeOf(u);
1148
- return proto === Object.prototype || proto === null;
1581
+ const isFillCount = (n) => Number.isSafeInteger(n) && n >= 0 && n <= 1e5;
1582
+ /** This function gives the list of `fill` (LIST.FILL): `n` items with the value `value`, and the keys "0" to "n - 1". */
1583
+ const fillList = (n, value) => vexList(Array.from({ length: n }, (_x, i) => ({
1584
+ key: String(i),
1585
+ result: ok(value)
1586
+ })));
1587
+ /** This function tells if a value can be the value of `indexOf`: a number, a text or a boolean (LIST.INDEXOF). */
1588
+ const isIndexValue = (u) => typeof u === "number" || typeof u === "string" || typeof u === "boolean";
1589
+ // src/codec.ts
1590
+ /** This function tells if a value is a record: an object that is not an array. */
1591
+ const isRecord = (u) => typeof u === "object" && u !== null && !Array.isArray(u);
1592
+ const isPlainRecord = (u) => {
1593
+ if (!isRecord(u)) return false;
1594
+ const proto = Object.getPrototypeOf(u);
1595
+ return proto === Object.prototype || proto === null;
1149
1596
  };
1150
1597
  /** This function gives the JSON form of a value, or the reason why the value has no JSON form. */
1151
1598
  function encodeValue(u, domains) {
@@ -1228,36 +1675,55 @@ function decodeValue(u, domains) {
1228
1675
  }
1229
1676
  return fields(u);
1230
1677
  }
1231
- // src/array-list.ts
1678
+ // src/limit-error.ts
1679
+ /** This function gives the error that decides for a list of errors: `#DEPTH!`, or else the first (EVAL.DEPTH). */
1680
+ const worstError = (errors) => errors.find(isDepthError) ?? errors[0];
1681
+ /** This function gives the message of a data limit above the cap (ITERATE.LIMIT.ERROR). */
1682
+ const overLimitMessage = (count) => `the data limit of "iterate" is ${String(count)}, above the cap of 100000`;
1232
1683
  /**
1233
- * This function gives the list of an array (LIST.ARRAY). The key of each item is its position, from "0". A position
1234
- * without a value, or with `null`, gives an error item from `missing`, as a missing field does (REF.MISSING).
1684
+ * This function gives the error of a data limit that is not valid, with its cause (ITERATE.LIMIT.ERROR). An error of the
1685
+ * run stays as it is: the engine failed or a cycle of cells stopped, not the limit.
1235
1686
  */
1236
- function listOfArray(array, missing) {
1237
- const items = [];
1238
- for (let i = 0; i < array.length; i++) {
1239
- const x = array[i];
1240
- items.push({
1241
- key: String(i),
1242
- result: x === void 0 || x === null ? fail(missing(`the array has no value at the position ${String(i)}`)) : ok(x)
1243
- });
1244
- }
1245
- return vexList(items);
1687
+ const limitError = (cause, details = {}) => isDepthError(cause) || cause.kind === "cycle" ? cause : vexError("limit", "the data limit of \"iterate\" is not valid", {
1688
+ ...details,
1689
+ causes: [cause]
1690
+ });
1691
+ // src/fix.ts
1692
+ /**
1693
+ * These are the rules of a fixed-point column that the closure compiler and the kernel share (FIX.ROUNDS, FIX.JOIN,
1694
+ * FIX.LIMIT). They are the limit of the rounds, the kinds of the values of a row and the join of a row. The package
1695
+ * index exports the rules that the compiler needs too (COMPILE.FIX).
1696
+ */
1697
+ /**
1698
+ * This function gives the largest number of rounds of a column of `rows` rows. A boolean column changes at least one row
1699
+ * in each round before the last, and a row changes one time. A path has fewer rows than the column, so a number
1700
+ * column stops in this bound when its steps follow paths (FIX.LIMIT).
1701
+ */
1702
+ const fixRounds = (rows) => Math.min(rows + 1, MAX_ITERATIONS);
1703
+ /** This function gives the kind of the values of a join. */
1704
+ const joinKind = (join) => join === "or" || join === "and" ? "boolean" : "number";
1705
+ /** This function gives the reason that a value cannot be a value of a row, or `undefined` for a good value (FIX.KIND). */
1706
+ function fixValueError(name, join, value) {
1707
+ const kind = joinKind(join);
1708
+ if (typeof value !== kind) return errorText.fixKind(name, join, kind, value);
1709
+ return kind === "boolean" || Number.isFinite(value) ? void 0 : errorText.fixNumber(name, value);
1246
1710
  }
1247
- /** This function gives a list, the list of an array, or `undefined` for another value (LIST.ARRAY). */
1248
- const asList = (u, missing) => isVexList(u) ? u : Array.isArray(u) ? listOfArray(u, missing) : void 0;
1249
1711
  /**
1250
- * This function tells if a value is a count of `fill`: a whole number from 0 to the limit of `iterate`, 100000
1251
- * (LIST.FILL). Thus a list of `fill` is not larger than the steps of a loop.
1712
+ * This function gives the error that stands for the failed rows of a round, or `undefined` when `#ARGS` must collect them
1713
+ * (FIX.ERROR). `#DEPTH!` wins. `#CYCLE!` comes next, so a cell on a cycle reports the cycle (SHEET.CYCLE).
1252
1714
  */
1253
- const isFillCount = (n) => Number.isSafeInteger(n) && n >= 0 && n <= 1e5;
1254
- /** This function gives the list of `fill` (LIST.FILL): `n` items with the value `value`, and the keys "0" to "n - 1". */
1255
- const fillList = (n, value) => vexList(Array.from({ length: n }, (_x, i) => ({
1256
- key: String(i),
1257
- result: ok(value)
1258
- })));
1259
- /** This function tells if a value can be the value of `indexOf`: a number, a text or a boolean (LIST.INDEXOF). */
1260
- const isIndexValue = (u) => typeof u === "number" || typeof u === "string" || typeof u === "boolean";
1715
+ function worstRow(errors) {
1716
+ return errors.find((x) => x.code === "#DEPTH!") ?? errors.find((x) => x.code === "#CYCLE!") ?? (errors.length === 1 ? errors[0] : void 0);
1717
+ }
1718
+ /** This function joins the next value of a row to its old value (FIX.JOIN). The values have the kind of the join. */
1719
+ function joinValues(join, old, next) {
1720
+ switch (join) {
1721
+ case "or": return old === true || next === true;
1722
+ case "and": return old === true && next === true;
1723
+ case "max": return Math.max(old, next);
1724
+ case "min": return Math.min(old, next);
1725
+ }
1726
+ }
1261
1727
  // src/same.ts
1262
1728
  /**
1263
1729
  * The comparison of the values of Vex for `agree` of the kernel (EVAL.AGREE), and the test of a Vex error. The package
@@ -1306,6 +1772,8 @@ const TERM_KINDS = [
1306
1772
  ["each"],
1307
1773
  ["fold"],
1308
1774
  ["iterate"],
1775
+ ["fix"],
1776
+ ["last"],
1309
1777
  ["ops"],
1310
1778
  ["ext"]
1311
1779
  ];
@@ -1337,6 +1805,12 @@ const NO_VALUE = {
1337
1805
  shape: "one",
1338
1806
  values: [null]
1339
1807
  };
1808
+ /** The limit of `iterate`: a bare whole number, or the size of an axis (ITERATE.LIMIT.DATA). */
1809
+ const LIMIT = {
1810
+ shape: "term",
1811
+ of: "limit",
1812
+ kinds: [["limit"], ["size"]]
1813
+ };
1340
1814
  /** This function gives the shape of a record with these fields and no other fields (DOC.CONSTRUCT). */
1341
1815
  const closed = (fields, required) => ({
1342
1816
  shape: "record",
@@ -1501,12 +1975,7 @@ function worldOfVex() {
1501
1975
  iterate: {
1502
1976
  verbs: { eval: "vex.iterate" },
1503
1977
  parts: closed({
1504
- limit: {
1505
- shape: "number",
1506
- whole: true,
1507
- min: 0,
1508
- max: MAX_ITERATIONS
1509
- },
1978
+ limit: LIMIT,
1510
1979
  init: NAMES,
1511
1980
  step: NAMES,
1512
1981
  until: TERM,
@@ -1520,6 +1989,49 @@ function worldOfVex() {
1520
1989
  scope: LOOP_SCOPE,
1521
1990
  summary: "Up to limit steps, until a test is true, and a result."
1522
1991
  },
1992
+ fix: {
1993
+ verbs: { eval: "vex.fix" },
1994
+ parts: closed({
1995
+ name: { shape: "text" },
1996
+ join: {
1997
+ shape: "one",
1998
+ values: [
1999
+ "or",
2000
+ "and",
2001
+ "max",
2002
+ "min"
2003
+ ]
2004
+ },
2005
+ init: TERM,
2006
+ step: TERM
2007
+ }, [
2008
+ "name",
2009
+ "join",
2010
+ "init",
2011
+ "step"
2012
+ ]),
2013
+ summary: "A column: a step at each row in rounds, until no row changes (step B)."
2014
+ },
2015
+ last: {
2016
+ verbs: { eval: "vex.last" },
2017
+ parts: { shape: "text" },
2018
+ summary: "The value of the focus in the last round of a fix (step B)."
2019
+ },
2020
+ limit: {
2021
+ verbs: { eval: "vex.limit" },
2022
+ parts: {
2023
+ shape: "number",
2024
+ whole: true,
2025
+ min: 0,
2026
+ max: MAX_ITERATIONS
2027
+ },
2028
+ summary: "The limit of iterate as a whole number: the bare number of step A."
2029
+ },
2030
+ size: {
2031
+ verbs: { eval: "vex.size" },
2032
+ parts: closed({ axis: AXIS }, ["axis"]),
2033
+ summary: "The limit of iterate from the data: the number of targets of an axis (step B)."
2034
+ },
1523
2035
  ops: {
1524
2036
  kinds: {},
1525
2037
  fallback: {
@@ -1636,13 +2148,16 @@ var Place = class Place {
1636
2148
  origin;
1637
2149
  focus;
1638
2150
  failure;
1639
- constructor(space, tables, origin, focus, failure) {
2151
+ /** The columns of the `fix` nodes around this position, by name (FIX.LAST). A column is no name of the program. */
2152
+ columns;
2153
+ constructor(space, tables, origin, focus, failure, columns) {
1640
2154
  this[THING] = true;
1641
2155
  this.space = space;
1642
2156
  this.tables = tables;
1643
2157
  this.origin = origin;
1644
2158
  this.focus = focus;
1645
2159
  this.failure = failure;
2160
+ this.columns = columns;
1646
2161
  }
1647
2162
  /** The text of the position for a trace. */
1648
2163
  get label() {
@@ -1650,11 +2165,15 @@ var Place = class Place {
1650
2165
  }
1651
2166
  /** This method gives the position of a key of the same space, with the same origin. */
1652
2167
  to(focus) {
1653
- return new Place(this.space, this.tables, this.origin, focus);
2168
+ return new Place(this.space, this.tables, this.origin, focus, void 0, this.columns);
2169
+ }
2170
+ /** This method gives this position with a new column of a `fix`. */
2171
+ withColumn(name, column) {
2172
+ return new Place(this.space, this.tables, this.origin, this.focus, void 0, new Map(this.columns).set(name, column));
1654
2173
  }
1655
2174
  /** This method gives the position with a failure, for a move that failed. */
1656
2175
  failed(failure) {
1657
- return new Place(this.space, this.tables, this.origin, this.focus, failure);
2176
+ return new Place(this.space, this.tables, this.origin, this.focus, failure, this.columns);
1658
2177
  }
1659
2178
  /** This method reads one field of the record at the focus. */
1660
2179
  deref(key) {
@@ -1918,7 +2437,36 @@ function withItem$1(names, as, t) {
1918
2437
  }
1919
2438
  /** This function gives the names `as` of a loop, or `undefined` (AXIS.LIST.SCOPE). */
1920
2439
  const itemNamesOf = (value) => value.as;
1921
- /** The evaluators of the loops: each, fold and iterate (LOOP.NAMES, FOLD.ORDER, ITERATE.LIMIT). */
2440
+ /**
2441
+ * This function evaluates a part at each row of a column. Each row runs, also after an error (FIX.ERROR).
2442
+ */
2443
+ function rowsOf(part, at, context, name, join) {
2444
+ const out = /* @__PURE__ */ new Map();
2445
+ const errors = [];
2446
+ for (const key of at.space.keys) {
2447
+ const r = part.evaluate({
2448
+ ...context,
2449
+ self: at.to(key)
2450
+ });
2451
+ const wrong = r.ok ? fixValueError(name, join, r.value) : void 0;
2452
+ if (!r.ok) errors.push(r.error);
2453
+ else if (wrong !== void 0) errors.push(kernelError(wrong.kind, wrong.message));
2454
+ else out.set(key, r.value);
2455
+ }
2456
+ if (errors.length === 0) return ok$1(out);
2457
+ return {
2458
+ ok: false,
2459
+ error: worstRow(errors) ?? kernelError("args", `${String(errors.length)} rows failed`, { causes: errors.map(toVexError) })
2460
+ };
2461
+ }
2462
+ /** This function gives the value of the row of the focus. The focus of an item of the axis `list` can be no row (FIX.LAST). */
2463
+ function rowAt(name, column, at) {
2464
+ const value = column?.get(at.focus);
2465
+ if (value !== void 0) return ok$1(value);
2466
+ const { kind, message } = errorText.lastKey(name, at.focus);
2467
+ return failed(kind, message);
2468
+ }
2469
+ /** The evaluators of the loops: each, fold, iterate and fix (LOOP.NAMES, FOLD.ORDER, ITERATE.LIMIT, FIX.ROUNDS). */
1922
2470
  const LOOPS = {
1923
2471
  "vex.each": ({ value, context }) => {
1924
2472
  const found = targetsOf(value, context);
@@ -1963,12 +2511,29 @@ const LOOPS = {
1963
2511
  names
1964
2512
  });
1965
2513
  },
2514
+ "vex.limit": ({ value }) => ok$1(value),
2515
+ "vex.size": ({ value, context }) => {
2516
+ const found = targetsOf(value, context);
2517
+ if (!found.ok) return {
2518
+ ok: false,
2519
+ error: toKernelError(limitError(toVexError(found.error)))
2520
+ };
2521
+ const { targets } = found.value;
2522
+ const cause = worstError(targets.flatMap((t) => t.error ?? []));
2523
+ if (cause !== void 0) return {
2524
+ ok: false,
2525
+ error: toKernelError(limitError(cause))
2526
+ };
2527
+ return targets.length > 1e5 ? failed("limit", overLimitMessage(targets.length)) : ok$1(targets.length);
2528
+ },
1966
2529
  "vex.iterate": ({ value, context }) => {
1967
- const { init, step, until } = partsOf$1(value);
1968
- const limit = value.limit;
2530
+ const { init, limit: bound, step, until } = partsOf$1(value);
1969
2531
  const first = bindAll(init, context, context.names);
1970
2532
  if (!first.ok) return first;
1971
2533
  let names = first.value;
2534
+ const counted = bound.evaluate(context);
2535
+ if (!counted.ok) return counted;
2536
+ const limit = counted.value;
1972
2537
  for (let k = 0;; k++) {
1973
2538
  const here = {
1974
2539
  ...context,
@@ -1992,6 +2557,43 @@ const LOOPS = {
1992
2557
  ...context,
1993
2558
  names
1994
2559
  });
2560
+ },
2561
+ "vex.fix": ({ value, context }) => {
2562
+ const self = selfOf(context);
2563
+ if (!(self instanceof Place)) return {
2564
+ ok: false,
2565
+ error: self
2566
+ };
2567
+ const { name, join } = value;
2568
+ const first = rowsOf(partAt(value, "init"), self, context, name, join);
2569
+ if (!first.ok) return first;
2570
+ let column = first.value;
2571
+ const { keys } = self.space;
2572
+ const limit = fixRounds(keys.length);
2573
+ for (let round = 1; round <= limit; round++) {
2574
+ const stepped = rowsOf(partAt(value, "step"), self.withColumn(name, column), context, name, join);
2575
+ if (!stepped.ok) return stepped;
2576
+ const next = /* @__PURE__ */ new Map();
2577
+ let changed = false;
2578
+ for (const key of keys) {
2579
+ const joined = joinValues(join, column.get(key), stepped.value.get(key));
2580
+ changed ||= joined !== column.get(key);
2581
+ next.set(key, joined);
2582
+ }
2583
+ if (!changed) return rowAt(name, column, self);
2584
+ column = next;
2585
+ }
2586
+ const { kind, message } = errorText.fixLimit(name, limit);
2587
+ return failed(kind, message);
2588
+ },
2589
+ "vex.last": ({ value, context }) => {
2590
+ const self = selfOf(context);
2591
+ if (!(self instanceof Place)) return {
2592
+ ok: false,
2593
+ error: self
2594
+ };
2595
+ const name = value;
2596
+ return rowAt(name, self.columns?.get(name), self);
1995
2597
  }
1996
2598
  };
1997
2599
  /**
@@ -2041,7 +2643,7 @@ function describe(u) {
2041
2643
  return typeof u;
2042
2644
  }
2043
2645
  /** This function applies the test of a domain to a value. A test that throws rejects the value. */
2044
- function accepts(d, x) {
2646
+ function accepts$1(d, x) {
2045
2647
  let accepted = false;
2046
2648
  try {
2047
2649
  accepted = d.is(x);
@@ -2060,7 +2662,7 @@ function methodOf(self, name) {
2060
2662
  function checked(x, op, domains) {
2061
2663
  if (x === void 0 || x === null) return stop("undefined-result", `"${op}" gave no value`);
2062
2664
  if (typeof x === "number" && !Number.isFinite(x)) return stop("not-finite", `"${op}" gave ${String(x)}`);
2063
- const d = domains.find((dom) => accepts(dom, x));
2665
+ const d = domains.find((dom) => accepts$1(dom, x));
2064
2666
  if (d?.valid !== void 0 && !d.valid(x)) return stop("invalid-value", `"${op}" gave a value that is not a valid ${d.name}`);
2065
2667
  return x;
2066
2668
  }
@@ -2083,7 +2685,7 @@ function callFound(found, op, self, args, domains) {
2083
2685
  const params = spec?.params;
2084
2686
  if (params !== void 0) rest.forEach((a, i) => {
2085
2687
  const k = params[i] ?? "any";
2086
- if (k !== "any" && !(k === "domain" ? accepts(domain, a) : typeof a === k)) stop(k === "domain" ? "not-instance" : "kind-mismatch", `argument ${String(i + 1)} of "${op}" is a ${describe(a)}, not a ${k === "domain" ? domain.name : k}`);
2688
+ if (k !== "any" && !(k === "domain" ? accepts$1(domain, a) : typeof a === k)) stop(k === "domain" ? "not-instance" : "kind-mismatch", `argument ${String(i + 1)} of "${op}" is a ${describe(a)}, not a ${k === "domain" ? domain.name : k}`);
2087
2689
  });
2088
2690
  return checked(spec?.fn !== void 0 ? spec.fn(self, ...rest) : found.method.call(self, ...rest), op, domains);
2089
2691
  }
@@ -2150,7 +2752,7 @@ function group(items, keys, strict) {
2150
2752
  }
2151
2753
  /** This function applies a list op (LIST.*). The error items are skipped, except with `{ strict: true }`, and except `#DEPTH!`. */
2152
2754
  function listOp(op, items, rest, domains) {
2153
- const o = WITH_ARGUMENT$1.has(op) ? rest[1] : rest[0];
2755
+ const o = op === "setNth" ? rest[2] : WITH_ARGUMENT$1.has(op) ? rest[1] : rest[0];
2154
2756
  const strict = o?.strict === true;
2155
2757
  if (op === "group") return group(items, rest[0], strict);
2156
2758
  const good = goodOf(items, strict);
@@ -2182,6 +2784,19 @@ function listOp(op, items, rest, domains) {
2182
2784
  if (op === "drop") return vexList(good.slice(n));
2183
2785
  return n < vs.length ? vs[n] : stop("empty", `"nth" has no item at the position ${String(n)}`);
2184
2786
  }
2787
+ case "setNth": {
2788
+ const n = rest[0];
2789
+ if (!Number.isSafeInteger(n) || n < 0) return stop("kind-mismatch", "\"setNth\" needs a whole number from 0");
2790
+ const old = good[n];
2791
+ if (old === void 0) return stop("empty", `"setNth" has no item at the position ${String(n)}`);
2792
+ if (rest[1] === void 0) return stop("bad-expression", "\"setNth\" needs argument 3");
2793
+ const next = [...good];
2794
+ next[n] = {
2795
+ key: old.key,
2796
+ result: ok(rest[1])
2797
+ };
2798
+ return vexList(next);
2799
+ }
2185
2800
  case "append": return vexList([...good, ...otherOf(op, rest[0], strict)]);
2186
2801
  case "without": {
2187
2802
  const gone = new Set(otherOf(op, rest[0], strict).map((it) => it.key));
@@ -2235,7 +2850,7 @@ function sortValues(o, vs, domains) {
2235
2850
  if (by === void 0) return vs;
2236
2851
  if (typeof by !== "string") return stop("kind-mismatch", "\"sortBy\" needs an op name in the option \"by\"");
2237
2852
  return vs.map((x) => {
2238
- const found = domains.filter((d) => accepts(d, x)).map((d) => opOf(d, x, by)).find((f) => f !== void 0);
2853
+ const found = domains.filter((d) => accepts$1(d, x)).map((d) => opOf(d, x, by)).find((f) => f !== void 0);
2239
2854
  return found === void 0 ? stop("unknown-op", `no domain gives "${by}" for a ${describe(x)}`) : callFound(found, by, x, [], domains);
2240
2855
  });
2241
2856
  }
@@ -2253,7 +2868,7 @@ function reduce(name, vs, o, domains) {
2253
2868
  }
2254
2869
  let acc = vs[0];
2255
2870
  for (const x of vs.slice(1)) {
2256
- const found = domains.filter((d) => accepts(d, acc)).map((d) => opOf(d, acc, name)).find((f) => f !== void 0);
2871
+ const found = domains.filter((d) => accepts$1(d, acc)).map((d) => opOf(d, acc, name)).find((f) => f !== void 0);
2257
2872
  if (found === void 0) return stop("unknown-op", `no domain gives "${name}" for a ${describe(acc)}`);
2258
2873
  acc = callFound(found, name, acc, [x], domains);
2259
2874
  }
@@ -2271,7 +2886,7 @@ function dispatch(op, domains, fns) {
2271
2886
  if (listed && isVexList(self)) return listOp(op, self.items, values.slice(1), domains);
2272
2887
  let accepted = false;
2273
2888
  if (values.length > 0) for (const d of domains) {
2274
- if (!accepts(d, self)) continue;
2889
+ if (!accepts$1(d, self)) continue;
2275
2890
  accepted = true;
2276
2891
  const found = opOf(d, self, op);
2277
2892
  if (found !== void 0) return callFound(found, op, self, values.slice(1), domains);
@@ -2443,8 +3058,8 @@ var WriteStop = class {
2443
3058
  this.error = error;
2444
3059
  }
2445
3060
  };
2446
- const NONE = [];
2447
- const term = (e) => ({
3061
+ const NONE$1 = [];
3062
+ const term$1 = (e) => ({
2448
3063
  t: "term",
2449
3064
  e
2450
3065
  });
@@ -2527,7 +3142,7 @@ var Writer = class {
2527
3142
  if (job.t === "move") return this.#move(job.m);
2528
3143
  const e = job.e;
2529
3144
  if (e.tag === "lit") return {
2530
- jobs: NONE,
3145
+ jobs: NONE$1,
2531
3146
  make: () => this.#literal(e.value, job.t === "envelope")
2532
3147
  };
2533
3148
  return this.#envelope(e);
@@ -2543,17 +3158,17 @@ var Writer = class {
2543
3158
  make: (docs) => this.#keep(ref$1("self", ...docs, ...e.path), e)
2544
3159
  };
2545
3160
  case "var": return {
2546
- jobs: NONE,
3161
+ jobs: NONE$1,
2547
3162
  make: () => ref$1("names", e.name)
2548
3163
  };
2549
3164
  case "app": return {
2550
- jobs: e.args.map(term),
3165
+ jobs: e.args.map(term$1),
2551
3166
  make: (docs) => typed(["ops", ...e.op.split(".")], [...docs])
2552
3167
  };
2553
3168
  case "let": {
2554
3169
  const names = Object.keys(e.bind);
2555
3170
  return {
2556
- jobs: [...Object.values(e.bind).map(term), term(e.body)],
3171
+ jobs: [...Object.values(e.bind).map(term$1), term$1(e.body)],
2557
3172
  make: (docs) => typed("let", {
2558
3173
  bind: namesOf(names, docs, 0),
2559
3174
  body: docs[names.length]
@@ -2561,14 +3176,14 @@ var Writer = class {
2561
3176
  };
2562
3177
  }
2563
3178
  case "fn": return {
2564
- jobs: [term(e.body)],
3179
+ jobs: [term$1(e.body)],
2565
3180
  make: (docs) => typed("fn", {
2566
3181
  params: [...e.params],
2567
3182
  body: docs[0]
2568
3183
  })
2569
3184
  };
2570
3185
  case "call": return {
2571
- jobs: e.args.map(term),
3186
+ jobs: e.args.map(term$1),
2572
3187
  make: (docs) => this.#keep(typed("call", {
2573
3188
  fn: ref$1("names", e.fn),
2574
3189
  args: [...docs]
@@ -2577,7 +3192,7 @@ var Writer = class {
2577
3192
  case "rec": {
2578
3193
  const names = Object.keys(e.fields);
2579
3194
  return {
2580
- jobs: Object.values(e.fields).map(term),
3195
+ jobs: Object.values(e.fields).map(term$1),
2581
3196
  make: (docs) => typed("record", namesOf(names, docs, 0))
2582
3197
  };
2583
3198
  }
@@ -2589,7 +3204,7 @@ var Writer = class {
2589
3204
  t: "axis",
2590
3205
  a: e.axis
2591
3206
  },
2592
- term(e.body),
3207
+ term$1(e.body),
2593
3208
  ...at.jobs
2594
3209
  ],
2595
3210
  make: (docs) => {
@@ -2622,9 +3237,9 @@ var Writer = class {
2622
3237
  t: "axis",
2623
3238
  a: e.axis
2624
3239
  },
2625
- ...Object.values(e.init).map(term),
2626
- ...Object.values(e.step).map(term),
2627
- term(e.result),
3240
+ ...Object.values(e.init).map(term$1),
3241
+ ...Object.values(e.step).map(term$1),
3242
+ term$1(e.result),
2628
3243
  ...at.jobs
2629
3244
  ],
2630
3245
  make: (docs) => {
@@ -2655,26 +3270,53 @@ var Writer = class {
2655
3270
  case "iterate": {
2656
3271
  const init = Object.keys(e.init);
2657
3272
  const step = Object.keys(e.step);
2658
- const until = e.until === void 0 ? NONE : [term(e.until)];
3273
+ const until = e.until === void 0 ? NONE$1 : [term$1(e.until)];
2659
3274
  const after = init.length + step.length;
3275
+ const axis = limitAxis(e);
2660
3276
  return {
2661
3277
  jobs: [
2662
- ...Object.values(e.init).map(term),
2663
- ...Object.values(e.step).map(term),
3278
+ ...Object.values(e.init).map(term$1),
3279
+ ...Object.values(e.step).map(term$1),
2664
3280
  ...until,
2665
- term(e.result)
3281
+ term$1(e.result),
3282
+ ...axis === void 0 ? [] : [{
3283
+ t: "axis",
3284
+ a: axis
3285
+ }]
2666
3286
  ],
2667
- make: (docs) => typed("iterate", {
2668
- limit: e.limit,
2669
- init: namesOf(init, docs, 0),
2670
- step: namesOf(step, docs, init.length),
2671
- ...e.until === void 0 ? {} : { until: docs[after] },
2672
- result: docs[after + until.length]
2673
- })
3287
+ make: (docs) => {
3288
+ const first = { init: namesOf(init, docs, 0) };
3289
+ const limit = axis === void 0 ? e.limit : this.#keep(typed("size", { axis: docs[after + until.length + 1] }), e);
3290
+ return typed("iterate", {
3291
+ ...reads ? {
3292
+ ...first,
3293
+ limit
3294
+ } : {
3295
+ limit,
3296
+ ...first
3297
+ },
3298
+ step: namesOf(step, docs, init.length),
3299
+ ...e.until === void 0 ? {} : { until: docs[after] },
3300
+ result: docs[after + until.length]
3301
+ });
3302
+ }
2674
3303
  };
2675
3304
  }
3305
+ case "fix": return {
3306
+ jobs: [term$1(e.init), term$1(e.step)],
3307
+ make: (docs) => typed("fix", {
3308
+ name: e.name,
3309
+ join: e.join,
3310
+ init: docs[0],
3311
+ step: docs[1]
3312
+ })
3313
+ };
3314
+ case "last": return {
3315
+ jobs: NONE$1,
3316
+ make: () => typed("last", e.name)
3317
+ };
2676
3318
  case "ext": return {
2677
- jobs: NONE,
3319
+ jobs: NONE$1,
2678
3320
  make: () => typed(["ext", ...e.kind.split(".")], e.data)
2679
3321
  };
2680
3322
  }
@@ -2682,7 +3324,7 @@ var Writer = class {
2682
3324
  /** This method gives the plan of the field `at` of `each` and `fold`: a reference from `self` with moves only (DOC.ADDRESS). */
2683
3325
  #at(at) {
2684
3326
  if (at === void 0 || at.length === 0) return {
2685
- jobs: NONE,
3327
+ jobs: NONE$1,
2686
3328
  make: () => ({})
2687
3329
  };
2688
3330
  return {
@@ -2712,7 +3354,7 @@ var Writer = class {
2712
3354
  }
2713
3355
  #fixed(type, value) {
2714
3356
  return {
2715
- jobs: NONE,
3357
+ jobs: NONE$1,
2716
3358
  make: () => typed(type, value)
2717
3359
  };
2718
3360
  }
@@ -2727,7 +3369,7 @@ var Writer = class {
2727
3369
  });
2728
3370
  case "table": return this.#fixed(type, { name: a.name });
2729
3371
  case "list": return {
2730
- jobs: [term(a.list)],
3372
+ jobs: [term$1(a.list)],
2731
3373
  make: (docs) => typed(type, { list: docs[0] })
2732
3374
  };
2733
3375
  case "reverse": return {
@@ -2741,7 +3383,7 @@ var Writer = class {
2741
3383
  jobs: [{
2742
3384
  t: "axis",
2743
3385
  a: a.axis
2744
- }, term(a.test)],
3386
+ }, term$1(a.test)],
2745
3387
  make: (docs) => typed(type, {
2746
3388
  axis: docs[0],
2747
3389
  test: docs[1]
@@ -2788,7 +3430,9 @@ function writeDocument(e, opts) {
2788
3430
  * | `rec` | `{ "type": "record", "value": { ...fields } }` |
2789
3431
  * | `each` | `{ "type": "each", "value": { "axis", "as"?, "body", "at"? } }` |
2790
3432
  * | `fold` | `{ "type": "fold", "value": { "axis", "as"?, "init", "step", "result", "at"? } }` |
2791
- * | `iterate` | `{ "type": "iterate", "value": { "limit", "init", "step", "until"?, "result" } }` |
3433
+ * | `iterate` | `{ "type": "iterate", "value": { "limit", "init", "step", "until"?, "result" } }`. A data limit is `{ "type": "size", "value": { "axis" } }`. |
3434
+ * | `fix` | `{ "type": "fix", "value": { "name", "join", "init", "step" } }` |
3435
+ * | `last` | `{ "type": "last", "value": name }` |
2792
3436
  * | `ext` | `{ "type": ["ext", ...keys], "value": data }` |
2793
3437
  * | a move | `{ "type": ["moves", kind], "value": v }` |
2794
3438
  * | an axis | `{ "type": ["axes", name], "value": { ...parameters } }` |
@@ -2918,10 +3562,12 @@ var Reader = class {
2918
3562
  const as = this.#items(f, axis, at);
2919
3563
  return fold(axis, init, step, this.term(f["result"], into(at, "result")), this.#address(f["at"], into(at, "at")), as);
2920
3564
  }
3565
+ case "fix": return fix(f["name"], f["join"], this.term(f["init"], into(at, "init")), this.term(f["step"], into(at, "step")));
3566
+ case "last": return last(u.value);
2921
3567
  default: {
2922
3568
  const [init, step] = this.#loop(f, at);
2923
3569
  const until = f["until"] === void 0 ? void 0 : this.term(f["until"], into(at, "until"));
2924
- return iterate(f["limit"], init, step, this.term(f["result"], into(at, "result")), until);
3570
+ return iterate(this.#limit(f["limit"], into(at, "limit")), init, step, this.term(f["result"], into(at, "result")), until);
2925
3571
  }
2926
3572
  }
2927
3573
  }
@@ -2934,113 +3580,1440 @@ var Reader = class {
2934
3580
  #name(keys, where) {
2935
3581
  return keys.every((k) => typeof k === "string") ? keys.join(".") : bad(where, "a key of the name is not a text");
2936
3582
  }
2937
- /** This method gives the value of a literal from its JSON form (DOC.LITERAL). */
2938
- #value(u, where) {
2939
- const r = decodeValue(u, this.#domains);
2940
- return r.ok ? r.value : bad(where, r.error.message);
3583
+ /** This method gives the value of a literal from its JSON form (DOC.LITERAL). */
3584
+ #value(u, where) {
3585
+ const r = decodeValue(u, this.#domains);
3586
+ return r.ok ? r.value : bad(where, r.error.message);
3587
+ }
3588
+ /** This method reads a record of names and the term of each name. */
3589
+ #names(u, where) {
3590
+ return Object.fromEntries(Object.entries(u).map(([name, x]) => [name, this.term(x, into(where, name))]));
3591
+ }
3592
+ /** This method reads the bindings of a let. A binding can be a function (FN.BIND). */
3593
+ #binds(u, where) {
3594
+ return Object.fromEntries(Object.entries(u).map(([name, x]) => {
3595
+ const at = into(where, name);
3596
+ if (!isDocument(x) || typeName(x.type) !== "fn") return [name, this.term(x, at)];
3597
+ this.#type(x, at);
3598
+ const f = x.value;
3599
+ return [name, fn(f.params, this.term(f.body, into(into(at, "value"), "body")))];
3600
+ }));
3601
+ }
3602
+ /** This method reads the names of a loop. Each name of `step` is a name of `init` (LOOP.NAMES). */
3603
+ #loop(f, at) {
3604
+ const init = this.#names(f["init"], into(at, "init"));
3605
+ const step = this.#names(f["step"], into(at, "step"));
3606
+ const extra = Object.keys(step).find((name) => !Object.hasOwn(init, name));
3607
+ return extra === void 0 ? [init, step] : bad(into(into(at, "step"), extra), `the name "${extra}" of step is not a name of init`);
3608
+ }
3609
+ /**
3610
+ * This method reads the names `as` of a loop (AXIS.LIST.SCOPE). The contract gives a list of distinct texts. The
3611
+ * grammar of Vex needs one or two names, the axis `list` and no name of `init`.
3612
+ */
3613
+ /** This method reads the limit of `iterate`: a bare number, the envelope of a number, or the size of an axis (ITERATE.LIMIT.DATA). */
3614
+ #limit(u, where) {
3615
+ if (!isEnvelope(u)) return u;
3616
+ const value = u.value;
3617
+ return typeof value === "number" ? value : dataLimit(this.#axis(value.axis, into(into(where, "value"), "axis")));
3618
+ }
3619
+ #items(f, axis, at) {
3620
+ const reason = itemNamesError({
3621
+ as: f["as"],
3622
+ axis,
3623
+ init: f["init"]
3624
+ });
3625
+ return reason === void 0 ? f["as"] : bad(into(at, "as"), reason);
3626
+ }
3627
+ /** This method reads a reference: the fields of `self` after its moves, or a name of `names` (DOC.REF). */
3628
+ #ref(path, where) {
3629
+ const [root, ...steps] = path;
3630
+ if (root === "names") return steps.length === 1 && typeof steps[0] === "string" ? v(steps[0]) : bad(where, "a reference to a name has one step: the name");
3631
+ const moves = [];
3632
+ const names = [];
3633
+ steps.forEach((step, i) => {
3634
+ const at = into(where, i + 1);
3635
+ if (typeof step === "string") names.push(step);
3636
+ else if (!isDocument(step)) bad(at, "a step is not a text and not a move");
3637
+ else if (names.length > 0) bad(at, "a move comes after a field. Vex reads the fields at the end of the path");
3638
+ else moves.push(this.#move(step, at));
3639
+ });
3640
+ return ref(names, moves);
3641
+ }
3642
+ /** This method reads the function of a call: a reference to a name (DOC.CALL). */
3643
+ #function(u, where) {
3644
+ const steps = u.value;
3645
+ return steps[0] === "names" && steps.length === 2 && typeof steps[1] === "string" ? steps[1] : bad(where, "the function of a call is a reference to a name: { \"type\": \"ref\", \"value\": [\"names\", name] }");
3646
+ }
3647
+ /** This method reads the field `at` of `each` and `fold`: a reference from `self` with moves only (DOC.ADDRESS). */
3648
+ #address(u, where) {
3649
+ if (u === void 0) return void 0;
3650
+ const e = this.#envelope(u, where);
3651
+ return e.tag === "ref" && e.path.length === 0 ? e.at ?? [] : bad(where, "the address is a reference from \"self\" with moves only: { \"type\": \"ref\", \"value\": [\"self\", ...moves] }");
3652
+ }
3653
+ /**
3654
+ * This method reads a move (DOC.MOVE). The value of `key` and `index` is a term: a text key and a number position are
3655
+ * fixed, and another term is computed. The check gave the other moves their values.
3656
+ */
3657
+ #move(u, where) {
3658
+ const kind = String(this.#type(u, where)[1]);
3659
+ const at = into(where, "value");
3660
+ const value = u.value;
3661
+ switch (kind) {
3662
+ case "key": return typeof value === "string" ? key(value) : key(this.term(value, at));
3663
+ case "index": return typeof value === "number" ? index(value) : index(this.term(value, at));
3664
+ case "offset": return offset(...value);
3665
+ case "other": return other;
3666
+ case "origin": return origin;
3667
+ default: return parent;
3668
+ }
3669
+ }
3670
+ /** This method reads an axis (DOC.AXIS). The check gave it the parameters of its kind. */
3671
+ #axis(u, where) {
3672
+ const name = String(this.#type(u, where)[1]);
3673
+ const at = into(where, "value");
3674
+ const f = u.value;
3675
+ switch (name) {
3676
+ case "list": return {
3677
+ t: name,
3678
+ list: this.term(f["list"], into(at, "list"))
3679
+ };
3680
+ case "reverse": return {
3681
+ t: name,
3682
+ axis: this.#axis(f["axis"], into(at, "axis"))
3683
+ };
3684
+ case "where": return {
3685
+ t: name,
3686
+ axis: this.#axis(f["axis"], into(at, "axis")),
3687
+ test: this.term(f["test"], into(at, "test"))
3688
+ };
3689
+ default: return {
3690
+ t: name,
3691
+ ...f
3692
+ };
3693
+ }
3694
+ }
3695
+ };
3696
+ // src/monotone.ts
3697
+ /** The end of a proof. The methods of `Proof` throw it, and `monotoneError` gives its reason. */
3698
+ var Refusal$1 = class {
3699
+ reason;
3700
+ constructor(reason) {
3701
+ this.reason = reason;
3702
+ }
3703
+ };
3704
+ const STEADY = {
3705
+ dir: 0,
3706
+ tag: void 0
3707
+ };
3708
+ /**
3709
+ * The rules of the list ops. The items of a list come from an axis that does not read the last round. Thus the set of
3710
+ * the items stays the same in each round. Each of these ops ignores the order of the items. `sum` has no rule. The
3711
+ * rounding of a sum of floats depends on the order of the items (FIX.ORDER).
3712
+ */
3713
+ const LIST_RULES = {
3714
+ any: {
3715
+ args: ["up"],
3716
+ returns: "boolean"
3717
+ },
3718
+ all: {
3719
+ args: ["up"],
3720
+ returns: "boolean"
3721
+ },
3722
+ none: {
3723
+ args: ["down"],
3724
+ returns: "boolean"
3725
+ },
3726
+ min: {
3727
+ args: ["up"],
3728
+ returns: "number"
3729
+ },
3730
+ max: {
3731
+ args: ["up"],
3732
+ returns: "number"
3733
+ }
3734
+ };
3735
+ /** This function gives the flow of a literal. The kind of a number or a boolean is known. */
3736
+ function steadyValue(value) {
3737
+ if (typeof value === "number") return {
3738
+ dir: 0,
3739
+ tag: "number"
3740
+ };
3741
+ return typeof value === "boolean" ? {
3742
+ dir: 0,
3743
+ tag: "boolean"
3744
+ } : STEADY;
3745
+ }
3746
+ /** This function gives the axis inside the `where` axes of an axis. */
3747
+ const baseOf = (a) => a.t === "where" ? baseOf(a.axis) : a;
3748
+ /** This function gives the names without the names that a part of the program hides. */
3749
+ function without(names, hidden) {
3750
+ const out = new Map(names);
3751
+ for (const name of hidden) out.delete(name);
3752
+ return out;
3753
+ }
3754
+ /** The proof of the step of one `fix`. */
3755
+ var Proof = class {
3756
+ #fix;
3757
+ #domains;
3758
+ #fns;
3759
+ /** This field is `true` inside a `fix` of the same name: a read there reads that `fix`. */
3760
+ #hidden = false;
3761
+ constructor(fix, opts) {
3762
+ this.#fix = fix;
3763
+ this.#domains = opts.domains ?? [];
3764
+ this.#fns = opts.fns ?? {};
3765
+ }
3766
+ /** This method proves the step. It throws a refusal, or it returns. */
3767
+ prove() {
3768
+ if (this.#flow(this.#fix.step, /* @__PURE__ */ new Map()).dir < 0) this.#refuse("it moves against the last round");
3769
+ }
3770
+ #refuse(why) {
3771
+ throw new Refusal$1(`the step of the "fix" "${this.#fix.name}" does not move one way: ${why}`);
3772
+ }
3773
+ #flow(e, names) {
3774
+ switch (e.tag) {
3775
+ case "lit": return steadyValue(e.value);
3776
+ case "var": return names.get(e.name) ?? STEADY;
3777
+ case "last": return e.name === this.#fix.name && !this.#hidden ? {
3778
+ dir: 1,
3779
+ tag: joinKind(this.#fix.join)
3780
+ } : STEADY;
3781
+ case "let": {
3782
+ const bound = new Map(names);
3783
+ for (const [name, x] of Object.entries(e.bind)) bound.set(name, this.#flow(x, names));
3784
+ return this.#flow(e.body, bound);
3785
+ }
3786
+ case "fn": return this.#flow(e.body, without(names, e.params));
3787
+ case "call":
3788
+ if ((names.get(e.fn)?.dir ?? 0) !== 0) this.#refuse(`the function "${e.fn}" reads the last round`);
3789
+ return this.#steady(e.args, names, `an argument of the function "${e.fn}"`);
3790
+ case "each": return this.#each(e, names);
3791
+ case "app": return this.#app(e, names);
3792
+ case "fix": return this.#inner(e, names);
3793
+ case "rec":
3794
+ case "ref":
3795
+ case "fold":
3796
+ case "iterate":
3797
+ case "ext": return this.#steady(children(e), names, `a node "${e.tag}"`);
3798
+ }
3799
+ }
3800
+ /** This method refuses a part that reads the last round. Only an op or a loop with a rule can take such a part. */
3801
+ #steady(parts, names, what) {
3802
+ for (const x of parts) if (this.#flow(x, names).dir !== 0) this.#refuse(`${what} reads the last round`);
3803
+ return STEADY;
3804
+ }
3805
+ /**
3806
+ * This method reads a `fix` inside the step. Its rounds end in each round of the outer `fix`. Thus a column of the
3807
+ * outer `fix` as an input of the inner `fix` has no proof.
3808
+ */
3809
+ #inner(e, names) {
3810
+ this.#steady([e.init], names, `the start of the "fix" "${e.name}"`);
3811
+ const outer = this.#hidden;
3812
+ this.#hidden ||= e.name === this.#fix.name;
3813
+ this.#steady([e.step], names, `the step of the "fix" "${e.name}"`);
3814
+ this.#hidden = outer;
3815
+ return {
3816
+ dir: 0,
3817
+ tag: joinKind(e.join)
3818
+ };
3819
+ }
3820
+ /** This method reads an `each`. The targets must not read the last round, so each round has the same items. */
3821
+ #each(e, names) {
3822
+ this.#steady([...axisExprs(e.axis), ...addrExprs(e.at)], names, "an axis");
3823
+ const body = this.#flow(e.body, without(names, e.as ?? []));
3824
+ if (body.dir !== 0 && baseOf(e.axis).t === "table") this.#refuse("the axis table leaves the rows of the column");
3825
+ return {
3826
+ dir: body.dir,
3827
+ tag: "list"
3828
+ };
3829
+ }
3830
+ #app(e, names) {
3831
+ const flows = e.args.map((x) => this.#flow(x, names));
3832
+ const [head] = flows;
3833
+ switch (e.op) {
3834
+ case "if":
3835
+ if ((head?.dir ?? 0) !== 0) this.#refuse("the test of \"if\" reads the last round");
3836
+ return this.#joined(flows.slice(1), e.op);
3837
+ case "and":
3838
+ case "or":
3839
+ case "ifError": return this.#joined(flows, e.op);
3840
+ }
3841
+ if (flows.every((x) => x.dir === 0)) return STEADY;
3842
+ const rule = this.#rule(e.op, head?.tag);
3843
+ const moves = flows.map((x, i) => {
3844
+ const move = rule.args[i];
3845
+ if (x.dir !== 0 && move === void 0) this.#refuse(`the argument ${String(i + 1)} of the op "${e.op}" reads the last round`);
3846
+ return move === "down" ? -x.dir : x.dir;
3847
+ });
3848
+ const { returns } = rule;
3849
+ return {
3850
+ dir: this.#one(moves, e.op),
3851
+ tag: returns === "number" || returns === "boolean" ? returns : void 0
3852
+ };
3853
+ }
3854
+ /** This method gives the flow of the branches of a form. Each branch can be the result. */
3855
+ #joined(flows, op) {
3856
+ const [head] = flows;
3857
+ return {
3858
+ dir: this.#one(flows.map((x) => x.dir), op),
3859
+ tag: flows.every((x) => x.tag === head?.tag) ? head?.tag : void 0
3860
+ };
3861
+ }
3862
+ /** This method gives the one direction of the moves of a node. Two directions have no proof. */
3863
+ #one(moves, op) {
3864
+ const up = moves.some((m) => m > 0);
3865
+ if (up && moves.some((m) => m < 0)) this.#refuse(`the op "${op}" reads the last round in both directions`);
3866
+ return up ? 1 : moves.some((m) => m < 0) ? -1 : 0;
3867
+ }
3868
+ /**
3869
+ * This method gives the rule of an op for a receiver of a known kind, in the order of the interpreter. A list op on a
3870
+ * list comes first, then the domains in order, then a function of the host. A receiver of another kind has no rule.
3871
+ */
3872
+ #rule(op, tag) {
3873
+ if (tag === void 0) this.#refuse(`the kind of the first argument of the op "${op}" does not decide the op. Put an argument of a known kind first`);
3874
+ if (tag === "list") return Object.hasOwn(LIST_RULES, op) ? LIST_RULES[op] : this.#noRule(op);
3875
+ const found = [];
3876
+ for (const d of this.#domains) {
3877
+ if (d.primitive !== void 0 && d.primitive !== tag) continue;
3878
+ const spec = Object.hasOwn(d.ops, op) ? d.ops[op] : void 0;
3879
+ if (spec?.fn === void 0) continue;
3880
+ found.push(this.#declared(spec, op));
3881
+ if (d.primitive === tag) return this.#same(found, op);
3882
+ }
3883
+ if (Object.hasOwn(this.#fns, op)) found.push(this.#declared(this.#fns[op], op));
3884
+ return found.length > 0 ? this.#same(found, op) : this.#noRule(op);
3885
+ }
3886
+ #declared(spec, op) {
3887
+ return spec.monotone === void 0 ? this.#noRule(op) : {
3888
+ args: spec.monotone,
3889
+ returns: spec.returns
3890
+ };
3891
+ }
3892
+ /** This method gives the rule of the ops that can apply. They must have the same rule, because the data decides among them. */
3893
+ #same(rules, op) {
3894
+ const first = rules[0];
3895
+ if (rules.some((r) => r.args.join() !== first.args.join())) this.#refuse(`the op "${op}" has two rules, and the data decides among them`);
3896
+ return first;
3897
+ }
3898
+ #noRule(op) {
3899
+ this.#refuse(`the op "${op}" has no rule of direction`);
3900
+ }
3901
+ };
3902
+ /** This function walks a program. `open` has the names of the `fix` nodes around a node (FIX.LAST). */
3903
+ function walk(e, open, opts) {
3904
+ if (e.tag === "last" && !open.has(e.name)) throw new Refusal$1(`the read "last" of "${e.name}" has no "fix" of that name around it`);
3905
+ if (e.tag !== "fix") {
3906
+ for (const x of children(e)) walk(x, open, opts);
3907
+ return;
3908
+ }
3909
+ walk(e.init, open, opts);
3910
+ walk(e.step, /* @__PURE__ */ new Set([...open, e.name]), opts);
3911
+ new Proof(e, opts).prove();
3912
+ }
3913
+ /** This function gives the reason that a program breaks a rule of `fix`, or `undefined` for a program that keeps them (FIX.LAST, FIX.MONOTONE). */
3914
+ function monotoneError(e, opts) {
3915
+ try {
3916
+ walk(e, /* @__PURE__ */ new Set(), opts);
3917
+ return;
3918
+ } catch (thrown) {
3919
+ if (thrown instanceof Refusal$1) return thrown.reason;
3920
+ throw thrown;
3921
+ }
3922
+ }
3923
+ // src/size.ts
3924
+ /**
3925
+ * The check of sizes in the loops of a program (LOOP.SIZE). A step of `fold` or `iterate` gives each name a new value
3926
+ * from the values before the step. When a new value holds two copies of the old lists, the size can double at each step.
3927
+ * For example, a fold over 12 records with the step `append(xs, xs)` makes a list of 4096 items. The check finds such
3928
+ * steps before a run, from the size rules of the ops (LOOP.SIZE.OPS).
3929
+ *
3930
+ * The check is an abstract interpretation. It gives each value five measures: its size, its count, its inner count (the
3931
+ * sum of the counts of the values of its items), the size of its largest item, and its largest part (the largest item of
3932
+ * an item). Each measure is a bound: the largest value of some sums. A sum is a constant, and the measures of the old
3933
+ * values of the loops, each with a coefficient. A coefficient tells one use, a fixed number of uses, more uses, or no
3934
+ * bound. The check also keeps the kinds of each value, because the kind of the receiver selects the op.
3935
+ *
3936
+ * The check reads a program in two ways (LOOP.SIZE.READINGS). The first reading counts a read of a part of a value as a
3937
+ * use of the whole value. The second reading uses the bound of the part. Each reading gives a sound bound, so one
3938
+ * reading that accepts a program makes the program valid.
3939
+ */
3940
+ const NO_TERMS = /* @__PURE__ */ new Map();
3941
+ const NONE = [{
3942
+ base: 0,
3943
+ terms: NO_TERMS
3944
+ }];
3945
+ const constant = (base) => base === 0 ? NONE : [{
3946
+ base,
3947
+ terms: NO_TERMS
3948
+ }];
3949
+ const SOME = constant(1e400);
3950
+ const MEASURES = [
3951
+ "size",
3952
+ "count",
3953
+ "inner",
3954
+ "item",
3955
+ "part"
3956
+ ];
3957
+ /** The most sums of a bound. A bound with more sums becomes one sum, so the work of the check has a limit. */
3958
+ const MOST_SUMS = 8;
3959
+ const ANY = { tags: void 0 };
3960
+ const NO_KIND = { tags: /* @__PURE__ */ new Set() };
3961
+ const kindOf$2 = (tag) => ({ tags: /* @__PURE__ */ new Set([tag]) });
3962
+ const listKind = (item, tag = "list") => ({
3963
+ tags: /* @__PURE__ */ new Set([tag]),
3964
+ item
3965
+ });
3966
+ const NUMBER = kindOf$2("number");
3967
+ const BOOLEAN = kindOf$2("boolean");
3968
+ const STRING = kindOf$2("string");
3969
+ const SCALAR = { tags: /* @__PURE__ */ new Set(["number", "boolean"]) };
3970
+ /** The tags of the values that have no methods: an op of a domain needs its function for them. */
3971
+ const PRIMITIVES = /* @__PURE__ */ new Set([
3972
+ "number",
3973
+ "string",
3974
+ "boolean",
3975
+ "null"
3976
+ ]);
3977
+ /** The tags of the values without a size. */
3978
+ const SCALARS = /* @__PURE__ */ new Set([
3979
+ "number",
3980
+ "boolean",
3981
+ "null"
3982
+ ]);
3983
+ /** The shape of a value without a size, and the shape of a value with a fixed bound. */
3984
+ const zero = (kind) => ({
3985
+ size: NONE,
3986
+ count: NONE,
3987
+ inner: NONE,
3988
+ item: NONE,
3989
+ part: NONE,
3990
+ kind,
3991
+ long: false
3992
+ });
3993
+ const fixed = (kind) => ({
3994
+ size: SOME,
3995
+ count: SOME,
3996
+ inner: SOME,
3997
+ item: SOME,
3998
+ part: SOME,
3999
+ kind,
4000
+ long: false
4001
+ });
4002
+ const isZero = (s) => s.base === 0 && s.terms.size === 0;
4003
+ const isNone$1 = (f) => f.every(isZero);
4004
+ const term = (v, c) => [{
4005
+ base: 0,
4006
+ terms: /* @__PURE__ */ new Map([[v, c]])
4007
+ }];
4008
+ /** This function tells if the sum `a` is at least the sum `b` for each value of the variables. */
4009
+ const covers = (a, b) => a.base >= b.base && [...b.terms].every(([v, c]) => (a.terms.get(v) ?? 0) >= c);
4010
+ /** This function gives one sum that is at least each sum of a bound: the largest constant and the largest coefficients. */
4011
+ function cover(f) {
4012
+ const terms = /* @__PURE__ */ new Map();
4013
+ let base = 0;
4014
+ for (const s of f) {
4015
+ base = Math.max(base, s.base);
4016
+ for (const [v, c] of s.terms) terms.set(v, Math.max(terms.get(v) ?? 0, c));
4017
+ }
4018
+ return {
4019
+ base,
4020
+ terms
4021
+ };
4022
+ }
4023
+ /** This function gives the bound of some sums, without a sum that another sum covers, and with at most `MOST_SUMS` sums. */
4024
+ function bound(sums) {
4025
+ let out = [];
4026
+ for (const s of sums) if (!out.some((o) => covers(o, s))) out = [...out.filter((o) => !covers(s, o)), s];
4027
+ if (out.length > MOST_SUMS) return [cover(out)];
4028
+ return out.length === 0 ? NONE : out;
4029
+ }
4030
+ /** This function gives the sum of two sums: the coefficients of a variable in both sums give more uses. */
4031
+ function add(a, b) {
4032
+ const terms = new Map(a.terms);
4033
+ for (const [v, c] of b.terms) {
4034
+ const o = terms.get(v);
4035
+ terms.set(v, o === void 0 ? c : Math.max(3, o, c));
4036
+ }
4037
+ return {
4038
+ base: a.base + b.base,
4039
+ terms
4040
+ };
4041
+ }
4042
+ /** This function gives the bound of a sum of two values. */
4043
+ function plus(a, b) {
4044
+ if (isNone$1(a)) return b;
4045
+ if (isNone$1(b)) return a;
4046
+ return bound(a.flatMap((x) => b.map((y) => add(x, y))));
4047
+ }
4048
+ /** This function gives the bound of the larger of two values. */
4049
+ const join = (a, b) => bound([...a, ...b]);
4050
+ /** This function gives the bound of a union of two values: each variable with its largest coefficient, and the sum of the constants. */
4051
+ const union = (a, b) => {
4052
+ const all = cover([...a, ...b]);
4053
+ return [{
4054
+ base: cover(a).base + cover(b).base,
4055
+ terms: all.terms
4056
+ }];
4057
+ };
4058
+ /** This function gives the bound of `k` uses of a bound. */
4059
+ function scale(f, k) {
4060
+ if (k === 0) return NONE;
4061
+ if (k === 1) return f;
4062
+ return bound(f.map((s) => ({
4063
+ base: s.base === 0 ? 0 : 1e400,
4064
+ terms: new Map([...s.terms].map(([v, c]) => [v, Math.max(c, k)]))
4065
+ })));
4066
+ }
4067
+ /** This function gives a bound of a product of two sums. A product of two variables gives more uses of both. */
4068
+ function multiply(a, b) {
4069
+ if (isZero(a) || isZero(b)) return NONE;
4070
+ if (a.terms.size === 0) return a.base <= 1 ? [b] : scale([b], 2);
4071
+ if (b.terms.size === 0) return b.base <= 1 ? [a] : scale([a], 2);
4072
+ return scale([add(a, b)], 3);
4073
+ }
4074
+ /** This function gives a bound of a product of two values. */
4075
+ const times = (a, b) => bound(a.flatMap((x) => b.flatMap((y) => multiply(x, y))));
4076
+ /** This function puts a bound in the place of each variable that `sigma` knows. */
4077
+ function subst(f, sigma) {
4078
+ const one = (s) => {
4079
+ let out = constant(s.base);
4080
+ for (const [v, c] of s.terms) {
4081
+ const u = sigma(v);
4082
+ out = plus(out, u === void 0 ? term(v, c) : scale(u, c));
4083
+ }
4084
+ return out;
4085
+ };
4086
+ return bound(f.flatMap(one));
4087
+ }
4088
+ /** This function gives the sum without the variables that `drop` names, and the coefficients of these variables. */
4089
+ function split(s, drop) {
4090
+ const terms = /* @__PURE__ */ new Map();
4091
+ const dropped = /* @__PURE__ */ new Map();
4092
+ for (const [v, c] of s.terms) (drop(v) ? dropped : terms).set(v, c);
4093
+ return {
4094
+ rest: {
4095
+ base: s.base,
4096
+ terms
4097
+ },
4098
+ dropped
4099
+ };
4100
+ }
4101
+ const sameSum = (a, b) => a.base === b.base && a.terms.size === b.terms.size && [...a.terms].every(([v, c]) => b.terms.get(v) === c);
4102
+ const sameForm = (a, b) => a.length === b.length && a.every((x) => b.some((y) => sameSum(x, y)));
4103
+ /** This function tells if a kind can be a list or an array. */
4104
+ const listy = (k) => k.tags === void 0 || k.tags.has("list") || k.tags.has("array");
4105
+ /** This function gives the kind of the items of a value: no kind for a value that is not a list. */
4106
+ const itemOf = (k) => listy(k) ? k.item ?? ANY : NO_KIND;
4107
+ /** This function gives the kind of a value of two kinds. */
4108
+ function joinKind$1(a, b) {
4109
+ if (a.tags === void 0 || b.tags === void 0) return ANY;
4110
+ const tags = /* @__PURE__ */ new Set([...a.tags, ...b.tags]);
4111
+ return listy(a) || listy(b) ? {
4112
+ tags,
4113
+ item: joinKind$1(itemOf(a), itemOf(b))
4114
+ } : { tags };
4115
+ }
4116
+ /** This function tells if each value of the kind `a` has the kind `b`. */
4117
+ function within(a, b) {
4118
+ if (b.tags === void 0) return true;
4119
+ if (a.tags === void 0) return false;
4120
+ for (const t of a.tags) if (!b.tags.has(t)) return false;
4121
+ return !listy(a) || within(itemOf(a), itemOf(b));
4122
+ }
4123
+ const isText = (k) => k?.tags !== void 0 && k.tags.size === 1 && k.tags.has("string");
4124
+ const joinShape = (a, b) => ({
4125
+ size: join(a.size, b.size),
4126
+ count: join(a.count, b.count),
4127
+ inner: join(a.inner, b.inner),
4128
+ item: join(a.item, b.item),
4129
+ part: join(a.part, b.part),
4130
+ kind: joinKind$1(a.kind, b.kind),
4131
+ long: a.long || b.long
4132
+ });
4133
+ /** This function puts a bound in the place of each variable that `sigma` knows, in each measure of a shape. */
4134
+ const substShape = (s, sigma) => ({
4135
+ ...s,
4136
+ size: subst(s.size, sigma),
4137
+ count: subst(s.count, sigma),
4138
+ inner: subst(s.inner, sigma),
4139
+ item: subst(s.item, sigma),
4140
+ part: subst(s.part, sigma)
4141
+ });
4142
+ /** This function gives the coefficient of a use. */
4143
+ function coefOf(use) {
4144
+ switch (use) {
4145
+ case 0:
4146
+ case "number": return 0;
4147
+ case 1: return 1;
4148
+ case "scaled":
4149
+ case "copies":
4150
+ case "text": return 2;
4151
+ case "many":
4152
+ case "each":
4153
+ case "limit": return 3;
4154
+ case "unbounded": return 4;
4155
+ }
4156
+ }
4157
+ /** The letters of the variables of the measures. */
4158
+ const LETTERS = {
4159
+ size: "s",
4160
+ count: "c",
4161
+ inner: "n",
4162
+ item: "t",
4163
+ part: "p"
4164
+ };
4165
+ /** The name of the variable of a measure of a value with the number `id`, for example `s1` for its size. */
4166
+ const variable = (m, id) => `${LETTERS[m]}${String(id)}`;
4167
+ /** The shape of a value with a variable for each measure. A number, a boolean and null have no size. */
4168
+ const shapeOfVar = (id, kind, long) => kind.tags !== void 0 && [...kind.tags].every((t) => SCALARS.has(t)) ? zero(kind) : {
4169
+ size: term(variable("size", id), 1),
4170
+ count: term(variable("count", id), 1),
4171
+ inner: term(variable("inner", id), 1),
4172
+ item: term(variable("item", id), 1),
4173
+ part: term(variable("part", id), 1),
4174
+ kind,
4175
+ long
4176
+ };
4177
+ /** A refusal of the check. The check throws it, and `sizeError` gives its message. */
4178
+ var Refusal = class {
4179
+ message;
4180
+ constructor(message) {
4181
+ this.message = message;
4182
+ }
4183
+ };
4184
+ /** The literal number of an argument, if the argument is a literal number. */
4185
+ const literalNumber = (e) => e?.tag === "lit" && typeof e.value === "number" ? e.value : void 0;
4186
+ /** The tag of the values of a domain: its primitive kind, or its name. */
4187
+ const tagOf = (d) => d.primitive ?? `d:${d.name}`;
4188
+ /** This function tells if a domain accepts a value with a tag: surely, maybe or no. `undefined` is each tag. */
4189
+ function accepts(d, tag) {
4190
+ if (tag === void 0) return "maybe";
4191
+ if (tag === tagOf(d)) return "sure";
4192
+ if (d.primitive !== void 0) return tag.startsWith("d:") ? "maybe" : "no";
4193
+ return "maybe";
4194
+ }
4195
+ /** The number of the nodes that the check reads with the kinds of the names of the loops, before it uses each kind. */
4196
+ const BUDGET = 5e4;
4197
+ /** The check of one program. It keeps the shape of each node, to name the op of a refusal. */
4198
+ var Checker = class {
4199
+ #domains;
4200
+ #fns;
4201
+ #shapes = /* @__PURE__ */ new Map();
4202
+ #open = /* @__PURE__ */ new Map();
4203
+ /** With `true`, the check keeps the largest part as a measure and reads the rules `byParts` (LOOP.SIZE.READINGS). */
4204
+ #parts;
4205
+ #next = 0;
4206
+ #visits = 0;
4207
+ constructor(opts, parts) {
4208
+ this.#domains = opts.domains ?? [];
4209
+ this.#fns = opts.fns;
4210
+ this.#parts = parts;
4211
+ }
4212
+ shape(e, env) {
4213
+ this.#visits++;
4214
+ const found = this.#shape(e, env);
4215
+ const s = this.#parts ? found : {
4216
+ ...found,
4217
+ part: found.item
4218
+ };
4219
+ this.#shapes.set(e, s);
4220
+ return s;
4221
+ }
4222
+ #fresh() {
4223
+ return this.#next++;
4224
+ }
4225
+ #shape(e, env) {
4226
+ switch (e.tag) {
4227
+ case "lit": return this.#literal(e.value);
4228
+ case "ref":
4229
+ for (const x of addrExprs(e.at)) this.shape(x, env);
4230
+ return fixed(ANY);
4231
+ case "var": {
4232
+ const entry = env.get(e.name);
4233
+ return entry === void 0 ? fixed(ANY) : entry.t === "value" ? entry.shape : zero(NO_KIND);
4234
+ }
4235
+ case "ext": return fixed(ANY);
4236
+ case "rec": {
4237
+ const fields = Object.values(e.fields).map((x) => this.shape(x, env));
4238
+ const size = fields.reduce((acc, x) => plus(acc, x.size), SOME);
4239
+ const item = fields.reduce((acc, x) => join(acc, x.size), NONE);
4240
+ const part = fields.reduce((acc, x) => join(acc, x.item), NONE);
4241
+ return {
4242
+ ...fixed(kindOf$2("object")),
4243
+ size,
4244
+ item,
4245
+ part,
4246
+ long: fields.some((x) => x.long)
4247
+ };
4248
+ }
4249
+ case "let": return this.#let(e, env);
4250
+ case "call": return this.#call(e, env);
4251
+ case "app": return this.#app(e, env);
4252
+ case "each": return this.#each(e, env);
4253
+ case "fold":
4254
+ case "iterate": return this.#loop(e, env);
4255
+ case "fix":
4256
+ this.shape(e.init, env);
4257
+ this.shape(e.step, env);
4258
+ return zero(joinKind(e.join) === "boolean" ? BOOLEAN : NUMBER);
4259
+ case "last": return zero(SCALAR);
4260
+ case "fn": return zero(NO_KIND);
4261
+ }
4262
+ }
4263
+ /** This method gives the shape of a literal value: a constant, and its kind. */
4264
+ #literal(value) {
4265
+ if (typeof value === "number") return zero(NUMBER);
4266
+ if (typeof value === "boolean") return zero(BOOLEAN);
4267
+ if (value === null || value === void 0) return zero(kindOf$2("null"));
4268
+ if (typeof value === "string") {
4269
+ const length = constant(value.length);
4270
+ return {
4271
+ ...zero(STRING),
4272
+ size: length,
4273
+ item: length,
4274
+ part: length
4275
+ };
4276
+ }
4277
+ if (isVexList(value)) {
4278
+ const item = value.items.reduce((k, it) => it.result.ok ? joinKind$1(k, this.#literal(it.result.value).kind) : k, NO_KIND);
4279
+ return {
4280
+ ...fixed(listKind(item)),
4281
+ count: constant(value.items.length)
4282
+ };
4283
+ }
4284
+ if (Array.isArray(value)) return {
4285
+ ...fixed(listKind(value.reduce((k, x) => joinKind$1(k, this.#literal(x).kind), NO_KIND), "array")),
4286
+ count: constant(value.length)
4287
+ };
4288
+ const d = this.#domains.find((x) => {
4289
+ try {
4290
+ return x.is(value);
4291
+ } catch {
4292
+ return false;
4293
+ }
4294
+ });
4295
+ return fixed(d === void 0 ? kindOf$2("object") : kindOf$2(tagOf(d)));
4296
+ }
4297
+ #let(e, env) {
4298
+ const inner = new Map(env);
4299
+ for (const [name, b] of Object.entries(e.bind)) if (b.tag === "fn") {
4300
+ const params = b.params.map((p) => [p, this.#fresh()]);
4301
+ const fenv = new Map(env);
4302
+ for (const [p, id] of params) fenv.set(p, {
4303
+ t: "value",
4304
+ shape: shapeOfVar(id, ANY, true)
4305
+ });
4306
+ inner.set(name, {
4307
+ t: "fn",
4308
+ params: params.map(([, id]) => id),
4309
+ result: this.shape(b.body, fenv)
4310
+ });
4311
+ } else inner.set(name, {
4312
+ t: "value",
4313
+ shape: this.shape(b, env)
4314
+ });
4315
+ return this.shape(e.body, inner);
4316
+ }
4317
+ #call(e, env) {
4318
+ const args = e.args.map((a) => this.shape(a, env));
4319
+ const entry = env.get(e.fn);
4320
+ if (entry?.t !== "fn" || entry.params.length !== args.length) return zero(NO_KIND);
4321
+ const bindings = /* @__PURE__ */ new Map();
4322
+ entry.params.forEach((id, i) => {
4323
+ for (const m of MEASURES) bindings.set(variable(m, id), args[i][m]);
4324
+ });
4325
+ const sigma = (v) => bindings.get(v);
4326
+ return {
4327
+ ...substShape(entry.result, sigma),
4328
+ long: entry.result.long || args.some((a) => a.long)
4329
+ };
4330
+ }
4331
+ #app(e, env) {
4332
+ const args = e.args.map((a) => this.shape(a, env));
4333
+ switch (e.op) {
4334
+ case "if":
4335
+ case "ifError": {
4336
+ const [head = zero(NO_KIND), ...rest] = e.op === "if" ? args.slice(1, 3) : args.slice(0, 2);
4337
+ return rest.reduce(joinShape, head);
4338
+ }
4339
+ case "and":
4340
+ case "or": return zero(BOOLEAN);
4341
+ }
4342
+ const { op } = e;
4343
+ const outs = [];
4344
+ let open = false;
4345
+ const listOp = isListOp(op) ? op : void 0;
4346
+ const fn = this.#fns !== void 0 && Object.hasOwn(this.#fns, op) ? this.#fns[op] : void 0;
4347
+ const byFn = () => {
4348
+ const host = fn;
4349
+ if (host.size === void 0) open = true;
4350
+ else outs.push(this.#apply(host.size, args, e.args, kindOfReturn(host.returns, void 0, this.#domains)));
4351
+ };
4352
+ const self = args[0]?.kind;
4353
+ const tags = self === void 0 ? [] : self.tags === void 0 ? [void 0] : [...self.tags];
4354
+ for (const tag of tags) {
4355
+ if (listOp !== void 0 && (tag === void 0 || tag === "list")) {
4356
+ outs.push(this.#list(listOp, args, e.args));
4357
+ if (tag === "list") continue;
4358
+ }
4359
+ const d = this.#domain(op, tag, args, e.args, outs);
4360
+ open ||= d.open;
4361
+ if (d.done) continue;
4362
+ if (fn !== void 0) byFn();
4363
+ else if (listOp !== void 0 && (tag === void 0 || tag === "array")) outs.push(this.#list(listOp, args, e.args));
4364
+ else if (op === "fill") outs.push(this.#list("fill", args, e.args));
4365
+ }
4366
+ if (self === void 0 && fn !== void 0) byFn();
4367
+ if (open) outs.push(unbounded(args));
4368
+ this.#open.set(e, open);
4369
+ return outs.slice(1).reduce(joinShape, outs[0] ?? zero(NO_KIND));
4370
+ }
4371
+ /**
4372
+ * This method adds the shapes of the ops of the domains that can take a receiver with the tag. It gives `true` for an
4373
+ * op without a size rule. A domain that surely takes the receiver and has a function for the op is the last domain,
4374
+ * and then `done` is `true`.
4375
+ */
4376
+ #domain(op, tag, args, exprs, outs) {
4377
+ if (!isOpName(op)) return {
4378
+ open: false,
4379
+ done: false
4380
+ };
4381
+ let open = false;
4382
+ for (const d of this.#domains) {
4383
+ const a = accepts(d, tag);
4384
+ if (a === "no") continue;
4385
+ const spec = Object.hasOwn(d.ops, op) ? d.ops[op] : void 0;
4386
+ const method = (spec !== void 0 || d.methods === "all") && (tag === void 0 || !PRIMITIVES.has(tag));
4387
+ if (spec?.fn === void 0 && !method) continue;
4388
+ const rule = spec === void 0 ? void 0 : ruleOf(d, spec, this.#domains);
4389
+ if (rule === void 0) open = true;
4390
+ else outs.push(this.#apply(rule, args, exprs, kindOfReturn(spec?.returns, d, this.#domains)));
4391
+ if (a === "sure" && spec?.fn !== void 0) return {
4392
+ open,
4393
+ done: true
4394
+ };
4395
+ }
4396
+ return {
4397
+ open,
4398
+ done: false
4399
+ };
4400
+ }
4401
+ /** This method gives the shape of a list op, and the kind of its result. */
4402
+ #list(op, args, exprs) {
4403
+ const item = itemOf(args[0].kind);
4404
+ const s = this.#apply(LIST_SIZES[op], args, exprs, listResult(op, item, args));
4405
+ return op === "group" ? {
4406
+ ...s,
4407
+ long: true
4408
+ } : s;
4409
+ }
4410
+ #apply(rule, args, exprs, kind) {
4411
+ if (rule === "scalar") return zero(kind.tags === void 0 ? SCALAR : kind);
4412
+ if (rule === "fixed") return fixed(kind);
4413
+ if (rule === "reduce") return {
4414
+ ...this.#reduce(args, exprs),
4415
+ kind
4416
+ };
4417
+ const limit = rule.limit === void 0 ? void 0 : literalNumber(exprs[rule.limit]);
4418
+ const open = rule.limit !== void 0 && (limit === void 0 || args.some((a) => a.long));
4419
+ const r = this.#parts && !open ? rule.byParts ?? rule : rule;
4420
+ const sum = (terms, own) => args.reduce((acc, a, i) => {
4421
+ const t = terms[i] ?? r.rest ?? "many";
4422
+ const [use, of] = typeof t === "object" ? t : [t, own];
4423
+ const f = useForm(use, i, a[of], args, exprs, limit);
4424
+ if (own === "item" || own === "part") return join(acc, f);
4425
+ return r.union === true ? union(acc, f) : plus(acc, f);
4426
+ }, NONE);
4427
+ let size = sum(r.size, "size");
4428
+ let count = r.count === void 0 ? size : sum(r.count, "count");
4429
+ const inner = r.inner === void 0 ? size : sum(r.inner, "inner");
4430
+ if (limit !== void 0) count = constant(limit);
4431
+ if (r.constant === true) {
4432
+ size = plus(size, SOME);
4433
+ count = plus(count, SOME);
4434
+ }
4435
+ if (r.keys === "position") size = plus(size, times(count, SOME));
4436
+ const item = r.item === void 0 ? size : sum(r.item, "item");
4437
+ const part = r.part === void 0 ? item : sum(r.part, "part");
4438
+ return {
4439
+ size,
4440
+ count,
4441
+ inner,
4442
+ item,
4443
+ part,
4444
+ kind,
4445
+ long: args.some((a) => a.long)
4446
+ };
4447
+ }
4448
+ /** The rule of `reduce`: the op that the second argument names folds the values of the list (LIST.REDUCE). */
4449
+ #reduce(args, exprs) {
4450
+ const list = args[0];
4451
+ const name = exprs[1]?.tag === "lit" ? exprs[1].value : void 0;
4452
+ if (typeof name !== "string" || !isOpName(name)) return unbounded([list]);
4453
+ let out = fixed(ANY);
4454
+ for (const d of this.#domains) {
4455
+ if (!Object.hasOwn(d.ops, name)) {
4456
+ if (d.methods === "all") return unbounded([list]);
4457
+ continue;
4458
+ }
4459
+ const rule = ruleOf(d, d.ops[name], this.#domains);
4460
+ if (rule === void 0 || rule === "reduce") return unbounded([list]);
4461
+ if (rule === "scalar" || rule === "fixed") continue;
4462
+ const use = (i) => {
4463
+ const t = rule.size[i] ?? rule.rest ?? "many";
4464
+ return coefOf(typeof t === "object" ? t[0] : t);
4465
+ };
4466
+ if (use(0) > 1) return unbounded([list]);
4467
+ const k = rule.union === true ? 1 : Math.max(1, use(1));
4468
+ const size = rule.constant === true ? plus(scale(list.size, k), SOME) : scale(list.size, k);
4469
+ out = joinShape(out, {
4470
+ size,
4471
+ count: size,
4472
+ inner: size,
4473
+ item: size,
4474
+ part: size,
4475
+ kind: ANY,
4476
+ long: list.long
4477
+ });
4478
+ }
4479
+ return out;
4480
+ }
4481
+ #each(e, env) {
4482
+ const list = this.#axis(e.axis, e.at, env);
4483
+ if (list === void 0) {
4484
+ const body = this.shape(e.body, bindItem(env, e.as, fixed(ANY)));
4485
+ return {
4486
+ size: plus(SOME, times(body.size, SOME)),
4487
+ count: SOME,
4488
+ inner: times(body.count, SOME),
4489
+ item: body.size,
4490
+ part: body.item,
4491
+ kind: listKind(body.kind),
4492
+ long: body.long
4493
+ };
4494
+ }
4495
+ const id = this.#fresh();
4496
+ const body = this.shape(e.body, bindItem(env, e.as, shapeOfVar(id, itemOf(list.kind), list.long)));
4497
+ const vars = new Map(MEASURES.map((m) => [variable(m, id), m]));
4498
+ const over = (f, keys) => {
4499
+ const { rest, dropped } = split(cover(f), (v) => vars.has(v));
4500
+ const c = (m) => dropped.get(variable(m, id)) ?? 0;
4501
+ const uses = [
4502
+ c("size"),
4503
+ c("inner"),
4504
+ c("item"),
4505
+ c("part")
4506
+ ].filter((x) => x > 0);
4507
+ const sizes = uses.length === 0 ? 0 : uses.length === 1 ? uses[0] : 3;
4508
+ const whole = scale(list.size, keys && list.long ? Math.max(1, sizes) : sizes);
4509
+ return plus(plus(plus(this.#parts && sizes > 1 && !(keys && list.long) ? scale(times(c("size") > 0 || c("inner") > 0 ? list.item : list.part, list.count), sizes) : whole, keys && !list.long ? times(list.count, SOME) : NONE), scale(list.inner, c("count"))), times([rest], list.count));
4510
+ };
4511
+ const one = itemMeasures(list);
4512
+ const sigma = (v) => {
4513
+ const m = vars.get(v);
4514
+ return m === void 0 ? void 0 : one[m];
4515
+ };
4516
+ return {
4517
+ size: over(body.size, true),
4518
+ count: list.count,
4519
+ inner: over(body.count, false),
4520
+ item: subst(body.size, sigma),
4521
+ part: subst(body.item, sigma),
4522
+ kind: listKind(body.kind),
4523
+ long: list.long || body.long
4524
+ };
4525
+ }
4526
+ /** This method checks the parts of an axis and of an address. It gives the shape of the list of the axis `list`. */
4527
+ #axis(axis, at, env) {
4528
+ const list = listOf(axis);
4529
+ const shape = list === void 0 ? void 0 : this.shape(list, env);
4530
+ for (let x = axis; x.t === "where" || x.t === "reverse"; x = x.axis) if (x.t === "where") this.shape(x.test, env);
4531
+ for (const x of addrExprs(at)) this.shape(x, env);
4532
+ return shape;
4533
+ }
4534
+ #loop(e, env) {
4535
+ const list = e.tag === "fold" ? this.#axis(e.axis, e.at, env) : void 0;
4536
+ const axis = e.tag === "iterate" ? limitAxis(e) : void 0;
4537
+ const sized = axis === void 0 ? void 0 : this.#axis(axis, void 0, env);
4538
+ const names = Object.keys(e.init);
4539
+ const init = new Map(names.map((n) => [n, this.shape(e.init[n], env)]));
4540
+ const ids = new Map(names.map((n) => [n, this.#fresh()]));
4541
+ const stepped = Object.keys(e.step);
4542
+ const item = list === void 0 ? fixed(ANY) : {
4543
+ ...itemMeasures(list),
4544
+ kind: itemOf(list.kind),
4545
+ long: list.long
4546
+ };
4547
+ const each = {
4548
+ kind: ANY,
4549
+ long: true
4550
+ };
4551
+ const start = (n) => init.get(n);
4552
+ const fromInit = (n) => ({
4553
+ kind: start(n).kind,
4554
+ long: start(n).long
4555
+ });
4556
+ const always = () => new Map(names.map((n) => [n, stepped.includes(n) ? each : fromInit(n)]));
4557
+ const run = (assumed) => {
4558
+ const senv = new Map(env);
4559
+ for (const n of names) {
4560
+ const a = assumed.get(n);
4561
+ senv.set(n, {
4562
+ t: "value",
4563
+ shape: shapeOfVar(ids.get(n), a.kind, a.long)
4564
+ });
4565
+ }
4566
+ const ienv = e.tag === "fold" ? bindItem(senv, e.as, item) : senv;
4567
+ return {
4568
+ senv,
4569
+ steps: new Map(stepped.map((n) => [n, this.shape(e.step[n], ienv)]))
4570
+ };
4571
+ };
4572
+ let first;
4573
+ let assumed;
4574
+ if (stepped.length > 0 && this.#visits < BUDGET) {
4575
+ first = run(new Map(names.map((n) => [n, fromInit(n)]))).steps;
4576
+ assumed = new Map(names.map((n) => {
4577
+ const s = first?.get(n);
4578
+ return [n, s === void 0 ? fromInit(n) : {
4579
+ kind: s.kind,
4580
+ long: s.long
4581
+ }];
4582
+ }));
4583
+ } else assumed = always();
4584
+ let senv;
4585
+ let steps;
4586
+ for (let pass = 0;; pass++) {
4587
+ ({senv, steps} = run(assumed));
4588
+ const next = new Map(names.map((n) => {
4589
+ const a = assumed.get(n);
4590
+ const s = steps.get(n);
4591
+ return [n, s === void 0 ? a : {
4592
+ kind: joinKind$1(a.kind, s.kind),
4593
+ long: a.long || s.long
4594
+ }];
4595
+ }));
4596
+ if (names.every((n) => {
4597
+ const a = assumed.get(n);
4598
+ const b = next.get(n);
4599
+ return within(b.kind, a.kind) && (a.long || !b.long);
4600
+ })) break;
4601
+ assumed = pass === 0 && this.#visits < BUDGET ? next : this.#parts ? new Map(names.map((n) => {
4602
+ const b = next.get(n);
4603
+ return [n, stepped.includes(n) ? {
4604
+ kind: ANY,
4605
+ long: b.long
4606
+ } : b];
4607
+ })) : always();
4608
+ }
4609
+ if (e.tag === "iterate" && e.until !== void 0) this.shape(e.until, senv);
4610
+ const loop = new Loop(e, names, ids, steps);
4611
+ loop.check(this.#shapes, this.#open);
4612
+ const sigma = (v) => {
4613
+ for (const n of names) {
4614
+ const id = ids.get(n);
4615
+ const m = MEASURES.find((x) => variable(x, id) === v);
4616
+ if (m !== void 0) return start(n)[m];
4617
+ }
4618
+ };
4619
+ const starts = new Map(names.map((n) => {
4620
+ const a = start(n);
4621
+ const s = first?.get(n);
4622
+ if (s === void 0) return [n, a];
4623
+ return [n, joinShape(a, substShape(s, sigma))];
4624
+ }));
4625
+ const last = loop.last(starts, list?.count ?? sized?.count ?? (e.tag === "iterate" && typeof e.limit === "number" ? constant(e.limit) : SOME));
4626
+ const renv = new Map(env);
4627
+ for (const n of names) {
4628
+ const a = assumed.get(n);
4629
+ const s = last.get(n);
4630
+ const i = start(n);
4631
+ renv.set(n, {
4632
+ t: "value",
4633
+ shape: stepped.includes(n) ? {
4634
+ ...s,
4635
+ kind: joinKind$1(i.kind, a.kind),
4636
+ long: i.long || a.long
4637
+ } : i
4638
+ });
4639
+ }
4640
+ return this.shape(e.result, renv);
4641
+ }
4642
+ };
4643
+ /** This function gives the kind of the result of an op of the domain `d`, or of a function of the host, from `returns` (KIND.RETURNS). */
4644
+ function kindOfReturn(r, d, domains) {
4645
+ if (r === "number" || r === "boolean" || r === "string") return kindOf$2(r);
4646
+ if (r === "domain") return d === void 0 ? ANY : kindOf$2(tagOf(d));
4647
+ if (r?.startsWith("domain:") === true) {
4648
+ const target = domains.find((x) => x.name === r.slice(7));
4649
+ return target === void 0 ? ANY : kindOf$2(tagOf(target));
4650
+ }
4651
+ const item = listItemKind(r);
4652
+ return item === void 0 ? ANY : listKind(kindOf$2(item));
4653
+ }
4654
+ /** This function gives the kind of the result of a list op. `item` is the kind of the items of the receiver. */
4655
+ function listResult(op, item, args) {
4656
+ switch (op) {
4657
+ case "count":
4658
+ case "sum":
4659
+ case "mean":
4660
+ case "min":
4661
+ case "max":
4662
+ case "indexOf": return NUMBER;
4663
+ case "any":
4664
+ case "all":
4665
+ case "none": return BOOLEAN;
4666
+ case "join": return STRING;
4667
+ case "values": return listKind(item, "array");
4668
+ case "keys": return listKind(STRING, "array");
4669
+ case "first":
4670
+ case "nth":
4671
+ case "get": return item;
4672
+ case "sortBy":
4673
+ case "take":
4674
+ case "drop":
4675
+ case "without":
4676
+ case "distinct": return listKind(item);
4677
+ case "append": return listKind(joinKind$1(item, itemOf(args[1]?.kind ?? ANY)));
4678
+ case "setNth": return listKind(joinKind$1(item, args[2]?.kind ?? ANY));
4679
+ case "flat": return listKind(itemOf(item));
4680
+ case "group": return listKind(listKind(item));
4681
+ case "fill": return listKind(args[1]?.kind ?? ANY);
4682
+ case "errors":
4683
+ case "reduce": return ANY;
4684
+ }
4685
+ }
4686
+ /** This function binds the names `as` of a loop: the item gets `item`, and the index is a number. */
4687
+ function bindItem(env, as, item) {
4688
+ if (as === void 0) return env;
4689
+ const out = new Map(env);
4690
+ out.set(as[0], {
4691
+ t: "value",
4692
+ shape: item
4693
+ });
4694
+ if (as[1] !== void 0) out.set(as[1], {
4695
+ t: "value",
4696
+ shape: zero(NUMBER)
4697
+ });
4698
+ return out;
4699
+ }
4700
+ /** The shape of the result of an op without a size rule: no bound in the sizes of its arguments. */
4701
+ function unbounded(args) {
4702
+ const f = scale(args.reduce((acc, a) => plus(acc, a.size), SOME), 4);
4703
+ return {
4704
+ size: f,
4705
+ count: f,
4706
+ inner: f,
4707
+ item: f,
4708
+ part: f,
4709
+ kind: ANY,
4710
+ long: true
4711
+ };
4712
+ }
4713
+ /** The measures of one item of a list. The largest item of the list bounds its size, and the largest part bounds the rest. */
4714
+ const itemMeasures = (list) => ({
4715
+ size: list.item,
4716
+ count: list.item,
4717
+ inner: list.item,
4718
+ item: list.part,
4719
+ part: list.part
4720
+ });
4721
+ /** This function gives the bound of one use of an argument. */
4722
+ function useForm(use, i, form, args, exprs, limit) {
4723
+ switch (use) {
4724
+ case "text": return isText(args[i]?.kind) ? form : scale(form, 2);
4725
+ case "copies": {
4726
+ const n = literalNumber(exprs[0]);
4727
+ return n === 0 ? NONE : n === 1 ? form : scale(form, 2);
4728
+ }
4729
+ case "each": return times(form, args[0].count);
4730
+ case "number": return constant(Math.min(1e5, literalNumber(exprs[i]) ?? 1e400));
4731
+ case "limit": return limit === void 0 ? scale(form, 3) : times(plus(form, SOME), constant(limit));
4732
+ case 0:
4733
+ case 1:
4734
+ case "scaled":
4735
+ case "many":
4736
+ case "unbounded": return scale(form, coefOf(use));
2941
4737
  }
2942
- /** This method reads a record of names and the term of each name. */
2943
- #names(u, where) {
2944
- return Object.fromEntries(Object.entries(u).map(([name, x]) => [name, this.term(x, into(where, name))]));
4738
+ }
4739
+ /** This function tells if a domain holds numbers or booleans. */
4740
+ function scalar(x) {
4741
+ return x?.primitive === "number" || x?.primitive === "boolean";
4742
+ }
4743
+ /**
4744
+ * This function gives the size rule of an op of a domain (LOOP.SIZE.OPS). The rule is the rule of the op, or a rule
4745
+ * from its result kind and from the domain. The function gives `undefined` for an op without a rule.
4746
+ */
4747
+ function ruleOf(d, spec, domains) {
4748
+ if (spec.size !== void 0) return spec.size;
4749
+ const r = spec.returns;
4750
+ if (r === "number" || r === "boolean" || r === "domain" && scalar(d)) return "scalar";
4751
+ if (d.size === "fixed") return "fixed";
4752
+ if (r?.startsWith("domain:") === true) {
4753
+ const target = domains.find((x) => x.name === r.slice(7));
4754
+ if (scalar(target)) return "scalar";
4755
+ if (target?.size === "fixed") return "fixed";
2945
4756
  }
2946
- /** This method reads the bindings of a let. A binding can be a function (FN.BIND). */
2947
- #binds(u, where) {
2948
- return Object.fromEntries(Object.entries(u).map(([name, x]) => {
2949
- const at = into(where, name);
2950
- if (!isDocument(x) || typeName(x.type) !== "fn") return [name, this.term(x, at)];
2951
- this.#type(x, at);
2952
- const f = x.value;
2953
- return [name, fn(f.params, this.term(f.body, into(into(at, "value"), "body")))];
2954
- }));
4757
+ }
4758
+ /** The terms of a sum that read a variable of a cycle. */
4759
+ const inside = (s, cycle) => [...s.terms].filter(([u]) => cycle.has(u));
4760
+ /** This function tells if a sum of a bound reads its cycle more than one time, or with a coefficient other than 1. */
4761
+ const loose = (f, cycle) => f.some((s) => {
4762
+ const terms = inside(s, cycle);
4763
+ return terms.length > 1 || terms.some(([, c]) => c !== 1);
4764
+ });
4765
+ /** The words of a measure in a message. */
4766
+ const WORDS = {
4767
+ size: "size",
4768
+ count: "number of items",
4769
+ inner: "number of inner items",
4770
+ item: "largest item",
4771
+ part: "largest part"
4772
+ };
4773
+ /** This function gives the label of the node of a refusal: an op, a function, a name or a node. */
4774
+ function label(e) {
4775
+ switch (e.tag) {
4776
+ case "app": return `the op "${e.op}"`;
4777
+ case "call": return `the function "${e.fn}"`;
4778
+ case "var": return `the name "${e.name}"`;
4779
+ case "each":
4780
+ case "ext":
4781
+ case "fn":
4782
+ case "fix":
4783
+ case "fold":
4784
+ case "iterate":
4785
+ case "last":
4786
+ case "let":
4787
+ case "lit":
4788
+ case "rec":
4789
+ case "ref": return `a node "${e.tag}"`;
2955
4790
  }
2956
- /** This method reads the names of a loop. Each name of `step` is a name of `init` (LOOP.NAMES). */
2957
- #loop(f, at) {
2958
- const init = this.#names(f["init"], into(at, "init"));
2959
- const step = this.#names(f["step"], into(at, "step"));
2960
- const extra = Object.keys(step).find((name) => !Object.hasOwn(init, name));
2961
- return extra === void 0 ? [init, step] : bad(into(into(at, "step"), extra), `the name "${extra}" of step is not a name of init`);
4791
+ }
4792
+ /** The names of one loop, their steps, and the rule of LOOP.SIZE. */
4793
+ var Loop = class {
4794
+ #owners = /* @__PURE__ */ new Map();
4795
+ /** The cycle of each variable: the variables that its new value reads, and that read it in turn. */
4796
+ #cycles = /* @__PURE__ */ new Map();
4797
+ node;
4798
+ names;
4799
+ steps;
4800
+ constructor(node, names, ids, steps) {
4801
+ this.node = node;
4802
+ this.names = names;
4803
+ this.steps = steps;
4804
+ for (const name of names) for (const measure of MEASURES) this.#owners.set(variable(measure, ids.get(name)), {
4805
+ name,
4806
+ measure
4807
+ });
2962
4808
  }
2963
4809
  /**
2964
- * This method reads the names `as` of a loop (AXIS.LIST.SCOPE). The contract gives a list of distinct texts. The
2965
- * grammar of Vex needs one or two names, the axis `list` and no name of `init`.
4810
+ * This method applies the rule of LOOP.SIZE to the steps, and it throws a refusal. Each sum of a measure of a new value
4811
+ * reads its cycle at most one time, with the coefficient 1. A name without a step keeps its value.
2966
4812
  */
2967
- #items(f, axis, at) {
2968
- const reason = itemNamesError({
2969
- as: f["as"],
2970
- axis,
2971
- init: f["init"]
2972
- });
2973
- return reason === void 0 ? f["as"] : bad(into(at, "as"), reason);
4813
+ check(shapes, open) {
4814
+ const into = /* @__PURE__ */ new Map();
4815
+ const out = /* @__PURE__ */ new Map();
4816
+ for (const [v, o] of this.#owners) {
4817
+ const form = this.steps.get(o.name)?.[o.measure] ?? term(v, 1);
4818
+ into.set(v, form);
4819
+ for (const u of new Set(form.flatMap((s) => [...s.terms.keys()]))) if (this.#owners.has(u)) out.set(u, [...out.get(u) ?? [], v]);
4820
+ }
4821
+ const reach = (from) => {
4822
+ const seen = /* @__PURE__ */ new Set();
4823
+ const todo = [from];
4824
+ for (let x = todo.pop(); x !== void 0; x = todo.pop()) for (const y of out.get(x) ?? []) {
4825
+ if (seen.has(y)) continue;
4826
+ seen.add(y);
4827
+ todo.push(y);
4828
+ }
4829
+ return seen;
4830
+ };
4831
+ const reached = new Map([...this.#owners.keys()].map((v) => [v, reach(v)]));
4832
+ for (const [v, form] of into) {
4833
+ const cycle = new Set([...reached.get(v)].filter((u) => reached.get(u).has(v)));
4834
+ this.#cycles.set(v, cycle);
4835
+ if (!loose(form, cycle)) continue;
4836
+ const o = this.#owners.get(v);
4837
+ const what = form.some((s) => {
4838
+ const terms = inside(s, cycle);
4839
+ return terms.length > 1 || terms.some(([, c]) => c > 2);
4840
+ }) ? `a value that uses the lists of the loop more than one time in its ${WORDS[o.measure]}` : `a ${WORDS[o.measure]} that can grow by a factor at each step`;
4841
+ this.#refuse(o.name, (s) => loose(s[o.measure], cycle), what, shapes, open);
4842
+ }
2974
4843
  }
2975
- /** This method reads a reference: the fields of `self` after its moves, or a name of `names` (DOC.REF). */
2976
- #ref(path, where) {
2977
- const [root, ...steps] = path;
2978
- if (root === "names") return steps.length === 1 && typeof steps[0] === "string" ? v(steps[0]) : bad(where, "a reference to a name has one step: the name");
2979
- const moves = [];
2980
- const names = [];
2981
- steps.forEach((step, i) => {
2982
- const at = into(where, i + 1);
2983
- if (typeof step === "string") names.push(step);
2984
- else if (!isDocument(step)) bad(at, "a step is not a text and not a move");
2985
- else if (names.length > 0) bad(at, "a move comes after a field. Vex reads the fields at the end of the path");
2986
- else moves.push(this.#move(step, at));
4844
+ #refuse(name, bad, what, shapes, open) {
4845
+ const worse = (at) => children(at).find((k) => {
4846
+ const s = shapes.get(k);
4847
+ return s !== void 0 && bad(s);
2987
4848
  });
2988
- return ref(names, moves);
2989
- }
2990
- /** This method reads the function of a call: a reference to a name (DOC.CALL). */
2991
- #function(u, where) {
2992
- const steps = u.value;
2993
- return steps[0] === "names" && steps.length === 2 && typeof steps[1] === "string" ? steps[1] : bad(where, "the function of a call is a reference to a name: { \"type\": \"ref\", \"value\": [\"names\", name] }");
2994
- }
2995
- /** This method reads the field `at` of `each` and `fold`: a reference from `self` with moves only (DOC.ADDRESS). */
2996
- #address(u, where) {
2997
- if (u === void 0) return void 0;
2998
- const e = this.#envelope(u, where);
2999
- return e.tag === "ref" && e.path.length === 0 ? e.at ?? [] : bad(where, "the address is a reference from \"self\" with moves only: { \"type\": \"ref\", \"value\": [\"self\", ...moves] }");
4849
+ let at = this.node.step[name];
4850
+ for (let next = worse(at); next !== void 0; next = worse(at)) at = next;
4851
+ const source = findOpen(at, open);
4852
+ const head = `the expression has a node "${this.node.tag}" whose step gives the name "${name}" ${what}, at ${label(source ?? at)} (LOOP.SIZE)`;
4853
+ throw new Refusal(source === void 0 ? head : `${head}. The op "${source.op}" has no size rule (LOOP.SIZE.OPS)`);
3000
4854
  }
3001
4855
  /**
3002
- * This method reads a move (DOC.MOVE). The value of `key` and `index` is a term: a text key and a number position are
3003
- * fixed, and another term is computed. The check gave the other moves their values.
4856
+ * This method gives a bound of the last value of each name, from the values of `init` and the steps. The number of the
4857
+ * steps is `steps`. Each sum of a measure in a cycle gets at most one measure of its cycle at each step. A sum with a
4858
+ * measure of the cycle adds its other parts one time for each step. A sum without such a measure sets the value again,
4859
+ * so it adds to the bound one time (LOOP.SIZE.BRANCH). The last value starts from the largest first value of the cycle
4860
+ * or of these sums. It adds the parts of the other sums one time for each step. A measure outside a cycle has its first
4861
+ * value or the value of its step.
3004
4862
  */
3005
- #move(u, where) {
3006
- const kind = String(this.#type(u, where)[1]);
3007
- const at = into(where, "value");
3008
- const value = u.value;
3009
- switch (kind) {
3010
- case "key": return typeof value === "string" ? key(value) : key(this.term(value, at));
3011
- case "index": return typeof value === "number" ? index(value) : index(this.term(value, at));
3012
- case "offset": return offset(...value);
3013
- case "other": return other;
3014
- case "origin": return origin;
3015
- default: return parent;
4863
+ last(init, steps) {
4864
+ const first = (v) => {
4865
+ const o = this.#owners.get(v);
4866
+ return init.get(o.name)[o.measure];
4867
+ };
4868
+ const bounds = new Map([...this.#owners.keys()].map((v) => [v, first(v)]));
4869
+ const sigma = (v) => bounds.get(v);
4870
+ const widen = (old, more) => bound(join(old, more).map((s) => s.base === 0 || old.some((o) => o.base === s.base) ? s : {
4871
+ base: 1e400,
4872
+ terms: s.terms
4873
+ }));
4874
+ const stepOf = (v) => {
4875
+ const o = this.#owners.get(v);
4876
+ return this.steps.get(o.name)?.[o.measure];
4877
+ };
4878
+ for (let changed = true; changed;) {
4879
+ changed = false;
4880
+ for (const [v, old] of bounds) {
4881
+ const step = stepOf(v);
4882
+ if (step === void 0) continue;
4883
+ const cycle = this.#cycles.get(v);
4884
+ let next;
4885
+ if (cycle.has(v)) {
4886
+ const members = [...cycle];
4887
+ const start = members.reduce((acc, u) => join(acc, first(u)), NONE);
4888
+ const sums = members.flatMap((u) => stepOf(u).map((x) => split(x, (y) => cycle.has(y))));
4889
+ const sets = subst(bound(sums.filter((x) => x.dropped.size === 0).map((x) => x.rest)), sigma);
4890
+ const adds = subst(bound(sums.filter((x) => x.dropped.size > 0).map((x) => x.rest)), sigma);
4891
+ next = plus(join(start, sets), times(adds, steps));
4892
+ } else next = join(first(v), subst(step, sigma));
4893
+ const wide = widen(old, next);
4894
+ if (sameForm(old, wide)) continue;
4895
+ bounds.set(v, wide);
4896
+ changed = true;
4897
+ }
3016
4898
  }
4899
+ const values = new Map(this.names.map((n) => [n, init.get(n)]));
4900
+ for (const [v, o] of this.#owners) values.set(o.name, {
4901
+ ...values.get(o.name),
4902
+ [o.measure]: bounds.get(v)
4903
+ });
4904
+ return values;
3017
4905
  }
3018
- /** This method reads an axis (DOC.AXIS). The check gave it the parameters of its kind. */
3019
- #axis(u, where) {
3020
- const name = String(this.#type(u, where)[1]);
3021
- const at = into(where, "value");
3022
- const f = u.value;
3023
- switch (name) {
3024
- case "list": return {
3025
- t: name,
3026
- list: this.term(f["list"], into(at, "list"))
3027
- };
3028
- case "reverse": return {
3029
- t: name,
3030
- axis: this.#axis(f["axis"], into(at, "axis"))
3031
- };
3032
- case "where": return {
3033
- t: name,
3034
- axis: this.#axis(f["axis"], into(at, "axis")),
3035
- test: this.term(f["test"], into(at, "test"))
3036
- };
3037
- default: return {
3038
- t: name,
3039
- ...f
3040
- };
3041
- }
4906
+ };
4907
+ /** This function finds an op without a size rule in a node or in its children. */
4908
+ function findOpen(at, open) {
4909
+ const todo = [at];
4910
+ for (let x = todo.pop(); x !== void 0; x = todo.pop()) {
4911
+ if (x.tag === "app" && open.get(x) === true) return x;
4912
+ todo.push(...children(x));
4913
+ }
4914
+ }
4915
+ /** This function reads an expression one time, and it gives the reason of a refusal or `undefined`. */
4916
+ function refusalOf(e, opts, parts) {
4917
+ try {
4918
+ new Checker(opts, parts).shape(e, /* @__PURE__ */ new Map());
4919
+ return;
4920
+ } catch (thrown) {
4921
+ if (thrown instanceof Refusal) return thrown.message;
4922
+ throw thrown;
3042
4923
  }
4924
+ }
4925
+ /**
4926
+ * This function checks the sizes of the loops of an expression (LOOP.SIZE). It gives the reason of a refusal, or
4927
+ * `undefined`. The expression must pass `shapeError` and the limit of the nesting first. Each reading gives a sound
4928
+ * bound, so one reading that accepts the expression makes it valid. A refusal tells the reason of the first reading
4929
+ * (LOOP.SIZE.READINGS).
4930
+ */
4931
+ function sizeError(e, opts = {}) {
4932
+ const reason = refusalOf(e, opts, false);
4933
+ return reason === void 0 || refusalOf(e, opts, true) === void 0 ? void 0 : reason;
4934
+ }
4935
+ // src/constructs.ts
4936
+ /** The construct of an `iterate` with a limit from the data. */
4937
+ const ITERATE_SIZE = "iterate.size";
4938
+ /** The step that each construct of Vex needs. The name of a construct is the tag of its node, or `ITERATE_SIZE`. */
4939
+ const CONSTRUCT_STEPS = {
4940
+ lit: "A",
4941
+ ref: "A",
4942
+ app: "A",
4943
+ let: "A",
4944
+ var: "A",
4945
+ rec: "A",
4946
+ each: "A",
4947
+ fold: "A",
4948
+ iterate: "A",
4949
+ [ITERATE_SIZE]: "B",
4950
+ fix: "B",
4951
+ last: "B",
4952
+ fn: "A",
4953
+ call: "A",
4954
+ ext: "A"
4955
+ };
4956
+ // src/steps.ts
4957
+ /**
4958
+ * The steps of Vex (STEP.LADDER, STEP.LOWEST, STEP.MAX). A step is a level of the power of the language. Step A is a
4959
+ * total formula language. Step B adds limits from the data and fixed points. Step C adds functions that call
4960
+ * themselves. The checker gives the lowest step that a program needs, with the reason. The host option `maxStep` sets
4961
+ * the highest step that the host accepts. The default is B. A program has no field for its step, so a document cannot
4962
+ * raise its own step. The ladder is the ladder of steps of coeval (D116 of coeval), with the table of `constructs.ts`.
4963
+ */
4964
+ /** The steps of Vex, from the lowest to the highest. */
4965
+ const VEX_STEP_NAMES = [
4966
+ "A",
4967
+ "B",
4968
+ "C"
4969
+ ];
4970
+ /** The ladder of the steps of Vex: the steps and the step of each construct. */
4971
+ const VEX_STEPS = /* @__PURE__ */ stepLadder(VEX_STEP_NAMES, CONSTRUCT_STEPS);
4972
+ /** The highest step that a host accepts without the option `maxStep`. */
4973
+ const DEFAULT_MAX_STEP = "B";
4974
+ /**
4975
+ * The walk of an expression: the construct of a node is its tag, and the key of a child is its child index. An
4976
+ * `iterate` with a limit from the data is its own construct (ITERATE.LIMIT.DATA).
4977
+ */
4978
+ const WALK = {
4979
+ construct: (e) => e.tag === "iterate" && limitAxis(e) !== void 0 ? ITERATE_SIZE : e.tag,
4980
+ children: (e) => children(e).map((child, i) => [i, child])
3043
4981
  };
4982
+ /** The position of the highest step of a construct of the table. A limit at that step or higher accepts each program without a walk. The table is frozen, so the module computes this value one time. */
4983
+ const HIGHEST = Math.max(0, ...Object.values(VEX_STEPS.constructs).map((s) => stepRank(VEX_STEPS, s)));
4984
+ const at = (path) => path.length === 0 ? "at the root" : `at the path [${path.join(", ")}]`;
4985
+ /**
4986
+ * This function gives the lowest step that a program needs, with the reason (STEP.LOWEST). The reason names the first
4987
+ * node in the order of `children` whose construct needs that step. The program must have a valid shape (EVAL.SHAPE).
4988
+ */
4989
+ function programStep(e) {
4990
+ const need = stepOf(VEX_STEPS, WALK, e);
4991
+ if (need.reason === void 0) return {
4992
+ step: need.step,
4993
+ reason: `each construct of the program is of step ${need.step}`
4994
+ };
4995
+ const { construct, path } = need.reason;
4996
+ return {
4997
+ step: need.step,
4998
+ reason: `the node "${construct}" ${at(path)} needs step ${need.step}`,
4999
+ construct,
5000
+ path
5001
+ };
5002
+ }
5003
+ /**
5004
+ * This function gives the reason that a host refuses a program for its step, or `undefined` (STEP.MAX). A program of a
5005
+ * step above the option `maxStep` is not valid, and the reason names the step that it needs. A value of `maxStep` that
5006
+ * is not a step of Vex is not valid too. The program must have a valid shape (EVAL.SHAPE).
5007
+ */
5008
+ function stepError(e, opts = {}) {
5009
+ const maxStep = opts.maxStep ?? "B";
5010
+ if (!isStep(VEX_STEPS, maxStep)) return `the option maxStep ${typeof maxStep === "string" ? JSON.stringify(maxStep) : `of the type ${typeof maxStep}`} is not a step of Vex. The steps are ${VEX_STEP_NAMES.join(", ")} (STEP.MAX)`;
5011
+ if (stepRank(VEX_STEPS, maxStep) >= HIGHEST) return void 0;
5012
+ const refusal = checkStep(VEX_STEPS, stepOf(VEX_STEPS, WALK, e), maxStep);
5013
+ if (refusal === void 0) return void 0;
5014
+ const { construct, path } = refusal.reason;
5015
+ return `the program needs step ${refusal.needed}, and the host accepts the steps up to ${maxStep}: the node "${construct}" ${at(path)} needs step ${refusal.needed} (STEP.MAX)`;
5016
+ }
3044
5017
  // src/evaluate.ts
3045
5018
  /**
3046
5019
  * A scope: the names of one `let`, a function, an item or a loop. It is in front of the outer names, and it does not
@@ -3088,6 +5061,11 @@ var Closure = class {
3088
5061
  this.env = env;
3089
5062
  }
3090
5063
  };
5064
+ /** This function gives the error of an origin that is not a key of the space (EVAL.ORIGIN). */
5065
+ const noKeyError = (origin) => vexError("unknown-key", `the space has no key "${origin}"`, {
5066
+ origin,
5067
+ focus: origin
5068
+ });
3091
5069
  /** The deepest nesting of an expression that `compile` accepts (EVAL.NESTING). */
3092
5070
  const MAX_NESTING = 500;
3093
5071
  const DEPTH_MESSAGE = "the evaluation is too deep for the call stack of the engine";
@@ -3102,16 +5080,34 @@ function nestingOf(e) {
3102
5080
  }
3103
5081
  return deepest;
3104
5082
  }
3105
- /**
3106
- * This function compiles an expression or a document (DOC.ENTRY). The result gives the same results and the same traces
3107
- * as `evaluate`, because `evaluate` uses it too.
3108
- */
5083
+ /** This function gives the reason of the refusal of an expression that is nested too deep (EVAL.NESTING), or undefined. */
5084
+ function nestingError(e) {
5085
+ const nesting = nestingOf(e);
5086
+ return nesting > 500 ? `the expression is nested ${String(nesting)} levels deep, and the limit is ${String(500)}` : void 0;
5087
+ }
5088
+ /** This function gives the list ops of `compile` for the options. It keeps the index of each list that `get` read. */
5089
+ function listOps(opts = {}) {
5090
+ const compiler = new Compiler(opts);
5091
+ const names = /* @__PURE__ */ new Map();
5092
+ return {
5093
+ list: (op, list, rest, pos, path) => compiler.listOp(op, list, rest, {
5094
+ pos,
5095
+ env: names
5096
+ }, path),
5097
+ array: (op, array, rest, pos, path) => compiler.arrayOp(op, array, rest, {
5098
+ pos,
5099
+ env: names
5100
+ }, path),
5101
+ fill: (values, pos, path) => compiler.fill(values, {
5102
+ pos,
5103
+ env: names
5104
+ }, path)
5105
+ };
5106
+ }
3109
5107
  function compile(source, opts = {}) {
3110
5108
  const read = isDocument(source) ? fromDocument(source, opts.domains) : ok(source);
3111
5109
  const expr = read.ok ? read.value : source;
3112
- const shape = read.ok ? shapeError(expr) : read.error.message;
3113
- const nesting = shape === void 0 ? nestingOf(expr) : 0;
3114
- const bad = shape ?? (nesting > 500 ? `the expression is nested ${nesting} levels deep, and the limit is 500` : void 0);
5110
+ const bad = (read.ok ? shapeError(expr) : read.error.message) ?? nestingError(expr) ?? sizeError(expr, opts) ?? stepError(expr, opts) ?? monotoneError(expr, opts);
3115
5111
  const kind = read.ok ? "bad-expression" : read.error.kind;
3116
5112
  const root = bad === void 0 ? new Compiler(opts).node(expr, []) : (f) => fail(vexError(kind, bad, {
3117
5113
  path: [],
@@ -3120,10 +5116,7 @@ function compile(source, opts = {}) {
3120
5116
  }));
3121
5117
  const run = (r) => {
3122
5118
  const { space, origin } = r;
3123
- if (!space.has(origin)) return fail(vexError("unknown-key", `the space has no key "${origin}"`, {
3124
- origin,
3125
- focus: origin
3126
- }));
5119
+ if (!space.has(origin)) return fail(noKeyError(origin));
3127
5120
  const env = new Map(Object.entries(r.vars ?? {}).map(([k, val]) => [k, ok(val)]));
3128
5121
  try {
3129
5122
  return root({
@@ -3170,12 +5163,13 @@ const CACHE = /* @__PURE__ */ new WeakMap();
3170
5163
  function compiled(expr, opts) {
3171
5164
  if (typeof expr !== "object" || expr === null) return compile(expr, opts);
3172
5165
  const hit = CACHE.get(expr);
3173
- if (hit !== void 0 && hit.domains === opts.domains && hit.fns === opts.fns && hit.extensions === opts.extensions) return hit.program;
5166
+ if (hit !== void 0 && hit.domains === opts.domains && hit.fns === opts.fns && hit.extensions === opts.extensions && hit.maxStep === opts.maxStep) return hit.program;
3174
5167
  const program = compile(expr, opts);
3175
5168
  CACHE.set(expr, {
3176
5169
  domains: opts.domains,
3177
5170
  fns: opts.fns,
3178
5171
  extensions: opts.extensions,
5172
+ maxStep: opts.maxStep,
3179
5173
  program
3180
5174
  });
3181
5175
  return program;
@@ -3228,6 +5222,8 @@ var Compiler = class {
3228
5222
  #ofType = /* @__PURE__ */ new Map();
3229
5223
  /** The domains without a primitive type. Only they can accept a value of another type, for example an object. */
3230
5224
  #open;
5225
+ /** 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. */
5226
+ #columns = /* @__PURE__ */ new Map();
3231
5227
  constructor(opts) {
3232
5228
  this.#domains = opts.domains ?? [];
3233
5229
  this.#fns = opts.fns;
@@ -3243,6 +5239,10 @@ var Compiler = class {
3243
5239
  ...extra
3244
5240
  }));
3245
5241
  }
5242
+ /** This method gives the error of a text at a node (`errorAt`). */
5243
+ #at(text, f, path, extra) {
5244
+ return fail(errorAt(text, f.pos, path, extra));
5245
+ }
3246
5246
  /** This method gives the error of a position of an array without a value (LIST.ARRAY), at a node. */
3247
5247
  #missing(f, path) {
3248
5248
  return (message) => vexError("missing-field", message, {
@@ -3252,7 +5252,7 @@ var Compiler = class {
3252
5252
  });
3253
5253
  }
3254
5254
  /** 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!`. */
3255
- #fill(values, f, path) {
5255
+ fill(values, f, path) {
3256
5256
  const [n, value] = values;
3257
5257
  if (!isFillCount(n)) return this.#err("kind-mismatch", `"fill" needs a whole number from 0 to 100000, not ${describeType(n)}`, f, path, { op: "fill" });
3258
5258
  if (value === void 0) return this.#err("bad-expression", "\"fill\" needs argument 2", f, path, { op: "fill" });
@@ -3292,8 +5292,8 @@ var Compiler = class {
3292
5292
  const name = e.name;
3293
5293
  return (f, c) => {
3294
5294
  const bound = f.env.get(name);
3295
- 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));
3296
- return this.#emit(c, info, f, bound ?? this.#err("unbound", `the name "${name}" has no binding`, f, path));
5295
+ if (bound?.ok === true && bound.value instanceof Closure) return this.#emit(c, info, f, this.#at(errorText.functionValue(name), f, path));
5296
+ return this.#emit(c, info, f, bound ?? this.#at(errorText.unbound(name), f, path));
3297
5297
  };
3298
5298
  }
3299
5299
  case "fn": return this.#fn(e, path);
@@ -3325,11 +5325,13 @@ var Compiler = class {
3325
5325
  case "each": return this.#each(e, info);
3326
5326
  case "fold": return this.#fold(e, info);
3327
5327
  case "iterate": return this.#iterate(e, info);
5328
+ case "fix": return this.#fix(e, info);
5329
+ case "last": return this.#last(e, info);
3328
5330
  case "ext": {
3329
5331
  const extensions = this.#extensions ?? {};
3330
5332
  const handler = Object.hasOwn(extensions, e.kind) ? extensions[e.kind] : void 0;
3331
5333
  const { kind, data } = e;
3332
- if (handler === void 0) return (f, c) => this.#emit(c, info, f, this.#err("unknown-op", `no handler for the extension kind "${kind}"`, f, path));
5334
+ if (handler === void 0) return (f, c) => this.#emit(c, info, f, this.#at(errorText.noHandler(kind), f, path));
3333
5335
  return (f, c) => this.#emit(c, info, f, this.#locate(this.#guard(() => handler(data, {
3334
5336
  space: c.space,
3335
5337
  position: f.pos,
@@ -3358,11 +5360,11 @@ var Compiler = class {
3358
5360
  const args = this.#nodes(e.args, path);
3359
5361
  return (f, c) => {
3360
5362
  const bound = f.env.get(e.fn);
3361
- if (bound === void 0) return this.#emit(c, info, f, this.#err("unbound", `the function "${e.fn}" has no binding`, f, path));
5363
+ if (bound === void 0) return this.#emit(c, info, f, this.#at(errorText.noFunction(e.fn), f, path));
3362
5364
  if (!bound.ok) return this.#emit(c, info, f, bound);
3363
5365
  const callee = bound.value;
3364
- 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));
3365
- 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));
5366
+ if (!(callee instanceof Closure)) return this.#emit(c, info, f, this.#at(errorText.notFunction(e.fn), f, path));
5367
+ 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));
3366
5368
  const values = [];
3367
5369
  for (const n of args) values.push(n(f, c));
3368
5370
  return this.#emit(c, info, f, callee.body({
@@ -3385,18 +5387,16 @@ var Compiler = class {
3385
5387
  try {
3386
5388
  return run();
3387
5389
  } catch (thrown) {
3388
- return this.#threw(thrown, `"${op}" threw an exception`, f, path, { op });
5390
+ return this.#threw(thrown, errorText.threw(op), f, path);
3389
5391
  }
3390
5392
  }
3391
5393
  /** This method gives the error of an exception: `#DEPTH!` for a full call stack, and `#CALC!` for each other exception. */
3392
- #threw(thrown, message, f, path, extra = {}) {
3393
- return isStackOverflow(thrown) ? this.#err("depth", DEPTH_MESSAGE, f, path, {
3394
- ...extra,
3395
- thrown
3396
- }) : this.#err("threw", message, f, path, {
3397
- ...extra,
3398
- thrown
3399
- });
5394
+ #threw(thrown, text, f, path) {
5395
+ return this.#at(isStackOverflow(thrown) ? {
5396
+ ...text,
5397
+ kind: "depth",
5398
+ message: DEPTH_MESSAGE
5399
+ } : text, f, path, { thrown });
3400
5400
  }
3401
5401
  /**
3402
5402
  * This method compiles an address. Its function gives the key where the address points. The expressions of the
@@ -3444,7 +5444,7 @@ var Compiler = class {
3444
5444
  path: segs,
3445
5445
  ok: false
3446
5446
  }]);
3447
- const missing = (where) => failed(this.#err("missing-field", `the record at "${key}" has no value at "${where}"`, f, path));
5447
+ const missing = (where) => failed(this.#at(errorText.missing(key, where), f, path));
3448
5448
  let value = c.space.get(key);
3449
5449
  if (value === void 0 || value === null) return missing(label === "" ? "(record)" : label);
3450
5450
  for (const { seg, where, valid } of steps) {
@@ -3452,7 +5452,7 @@ var Compiler = class {
3452
5452
  try {
3453
5453
  value = Reflect.get(value, seg);
3454
5454
  } catch (thrown) {
3455
- return failed(this.#threw(thrown, `reading "${where}" at "${key}" threw an exception`, f, path));
5455
+ return failed(this.#threw(thrown, errorText.readThrew(key, where), f, path));
3456
5456
  }
3457
5457
  if (value === void 0 || value === null) return missing(where);
3458
5458
  }
@@ -3477,7 +5477,7 @@ var Compiler = class {
3477
5477
  if (first === void 0) return ok(values);
3478
5478
  const depth = [first, ...errors ?? []].find(isDepthError);
3479
5479
  if (depth !== void 0) return fail(depth);
3480
- return errors === void 0 ? fail(first) : this.#err("args", `${errors.length} ${what} failed`, f, path, { causes: errors });
5480
+ return errors === void 0 ? fail(first) : this.#at(errorText.args(errors.length, what), f, path, { causes: errors });
3481
5481
  }
3482
5482
  #each(e, info) {
3483
5483
  const { path } = info;
@@ -3500,15 +5500,9 @@ var Compiler = class {
3500
5500
  };
3501
5501
  }
3502
5502
  const base = baseAxis(e.axis);
3503
- let inner = c;
3504
- if (base.t === "table") {
3505
- const space = c.tables !== void 0 && Object.hasOwn(c.tables, base.name) ? c.tables[base.name] : void 0;
3506
- if (space === void 0) return this.#emit(c, info, f, this.#err("no-table", `the evaluation has no table "${base.name}"`, f, path));
3507
- inner = {
3508
- ...c,
3509
- space
3510
- };
3511
- }
5503
+ const axisCtx = this.#axisCtx(base, f, c, path);
5504
+ if (!axisCtx.ok) return this.#emit(c, info, f, axisCtx);
5505
+ const inner = axisCtx.value;
3512
5506
  const ts = targets(from, inner);
3513
5507
  if (!ts.ok) return this.#emit(c, info, f, ts);
3514
5508
  const items = ts.value.map((t) => {
@@ -3580,15 +5574,9 @@ var Compiler = class {
3580
5574
  env: f.env
3581
5575
  };
3582
5576
  }
3583
- let inner = c;
3584
- if (base.t === "table") {
3585
- const space = c.tables !== void 0 && Object.hasOwn(c.tables, base.name) ? c.tables[base.name] : void 0;
3586
- if (space === void 0) return this.#emit(c, info, f, this.#err("no-table", `the evaluation has no table "${base.name}"`, f, path));
3587
- inner = {
3588
- ...c,
3589
- space
3590
- };
3591
- }
5577
+ const axisCtx = this.#axisCtx(base, f, c, path);
5578
+ if (!axisCtx.ok) return this.#emit(c, info, f, axisCtx);
5579
+ const inner = axisCtx.value;
3592
5580
  const ts = targets(from, inner);
3593
5581
  if (!ts.ok) return this.#emit(c, info, f, ts);
3594
5582
  for (const t of ts.value) {
@@ -3614,18 +5602,121 @@ var Compiler = class {
3614
5602
  * This method compiles an iteration (ITERATE.LIMIT, ITERATE.UNTIL, ITERATE.ERROR). The test `until` evaluates before
3615
5603
  * each step and after the last step. `result` evaluates with the last values.
3616
5604
  */
5605
+ /**
5606
+ * This method compiles a fixed-point column (FIX.ROUNDS). Each round evaluates each row from the column of the last
5607
+ * round, so the order of the rows has no effect. The first round without a change ends the rounds.
5608
+ */
5609
+ #fix(e, info) {
5610
+ const { path } = info;
5611
+ const { name, join } = e;
5612
+ const init = this.node(e.init, [...path, 0]);
5613
+ const slot = Symbol(name);
5614
+ const outer = this.#columns;
5615
+ this.#columns = new Map(outer).set(name, slot);
5616
+ const step = this.node(e.step, [...path, 1]);
5617
+ this.#columns = outer;
5618
+ return (f, c) => {
5619
+ const { keys } = c.space;
5620
+ const first = this.#rows(e, init, f, f.env, c, path);
5621
+ if (!first.ok) return this.#emit(c, info, f, first);
5622
+ let column = first.value;
5623
+ this.#round(c, info, f, 0, keys, column);
5624
+ const limit = fixRounds(keys.length);
5625
+ for (let round = 1; round <= limit; round++) {
5626
+ const stepped = this.#rows(e, step, f, new Scope(f.env, [slot], [ok(column)]), c, path);
5627
+ if (!stepped.ok) return this.#emit(c, info, f, stepped);
5628
+ const next = /* @__PURE__ */ new Map();
5629
+ const changed = [];
5630
+ for (const key of keys) {
5631
+ const old = column.get(key);
5632
+ const value = joinValues(join, old, stepped.value.get(key));
5633
+ if (value !== old) changed.push(key);
5634
+ next.set(key, value);
5635
+ }
5636
+ this.#round(c, info, f, round, changed, next);
5637
+ if (changed.length === 0) return this.#emit(c, info, f, this.#rowOf(name, column, f, path));
5638
+ column = next;
5639
+ }
5640
+ return this.#emit(c, info, f, this.#at(errorText.fixLimit(name, limit), f, path));
5641
+ };
5642
+ }
5643
+ /** 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. */
5644
+ #rows(e, node, f, env, c, path) {
5645
+ const out = /* @__PURE__ */ new Map();
5646
+ const errors = [];
5647
+ for (const key of c.space.keys) {
5648
+ const frame = {
5649
+ pos: {
5650
+ origin: f.pos.origin,
5651
+ focus: key
5652
+ },
5653
+ env
5654
+ };
5655
+ const r = node(frame, c);
5656
+ const wrong = r.ok ? fixValueError(e.name, e.join, r.value) : void 0;
5657
+ if (!r.ok) errors.push(r.error);
5658
+ else if (wrong !== void 0) errors.push(errorAt(wrong, frame.pos, path));
5659
+ else out.set(key, r.value);
5660
+ }
5661
+ if (errors.length === 0) return ok(out);
5662
+ const worst = worstRow(errors);
5663
+ return worst === void 0 ? this.#at(errorText.args(errors.length, "rows"), f, path, { causes: errors }) : fail(worst);
5664
+ }
5665
+ /** This method adds a round to the trace: the count of the round, the rows that it changed and the column (FIX.TRACE). */
5666
+ #round(c, info, f, round, changed, column) {
5667
+ if (c.trace === void 0) return;
5668
+ const items = [...column].map(([key, value]) => ({
5669
+ key,
5670
+ result: ok(value)
5671
+ }));
5672
+ c.trace.events.push({
5673
+ path: info.path,
5674
+ tag: info.tag,
5675
+ label: `${info.label}: round ${String(round)}, ${String(changed.length)} rows changed`,
5676
+ origin: f.pos.origin,
5677
+ focus: f.pos.focus,
5678
+ round: {
5679
+ index: round,
5680
+ changed
5681
+ },
5682
+ result: ok(vexList(items))
5683
+ });
5684
+ }
5685
+ /** 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). */
5686
+ #rowOf(name, column, f, path) {
5687
+ const value = column.get(f.pos.focus);
5688
+ return value === void 0 ? this.#at(errorText.lastKey(name, f.pos.focus), f, path) : ok(value);
5689
+ }
5690
+ /** This method compiles a read of the last round at the focus (FIX.LAST). The check gives each read a `fix`. */
5691
+ #last(e, info) {
5692
+ const { path } = info;
5693
+ const slot = this.#columns.get(e.name);
5694
+ return (f, c) => {
5695
+ const column = f.env.get(slot);
5696
+ return this.#emit(c, info, f, this.#rowOf(e.name, column.value, f, path));
5697
+ };
5698
+ }
3617
5699
  #iterate(e, info) {
3618
5700
  const { path } = info;
3619
5701
  const names = this.#names(e, path);
3620
- const untilAt = Object.keys(e.init).length + Object.keys(e.step).length;
5702
+ const counter = { next: Object.keys(e.init).length + Object.keys(e.step).length };
5703
+ const axis = limitAxis(e);
5704
+ const size = axis === void 0 ? void 0 : this.#size(axis, path, counter);
5705
+ const untilAt = counter.next;
3621
5706
  const untilPath = [...path, untilAt];
3622
5707
  const until = e.until === void 0 ? void 0 : this.node(e.until, untilPath);
3623
5708
  const result = this.node(e.result, [...path, untilAt + (until === void 0 ? 0 : 1)]);
3624
- const { limit } = e;
5709
+ const fixed = e.limit;
3625
5710
  return (f, c) => {
3626
5711
  const first = names.first(f, c);
3627
5712
  if (!first.ok) return this.#emit(c, info, f, first);
3628
5713
  let env = first.value;
5714
+ let limit = fixed;
5715
+ if (size !== void 0) {
5716
+ const counted = size(f, c);
5717
+ if (!counted.ok) return this.#emit(c, info, f, counted);
5718
+ limit = counted.value;
5719
+ }
3629
5720
  for (let k = 0;; k++) {
3630
5721
  const frame = {
3631
5722
  pos: f.pos,
@@ -3635,10 +5726,10 @@ var Compiler = class {
3635
5726
  const t = until(frame, c);
3636
5727
  if (!t.ok) return this.#emit(c, info, f, t);
3637
5728
  if (t.value === true) break;
3638
- 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));
5729
+ if (t.value !== false) return this.#emit(c, info, f, this.#at(errorText.untilKind(t.value), f, untilPath));
3639
5730
  }
3640
5731
  if (k === limit) {
3641
- if (until !== void 0) return this.#emit(c, info, f, this.#err("limit", `"iterate" made its ${String(limit)} steps, and its test "until" is not true`, f, path));
5732
+ if (until !== void 0) return this.#emit(c, info, f, this.#at(errorText.limit(limit), f, path));
3642
5733
  break;
3643
5734
  }
3644
5735
  const after = names.next(frame, c, env);
@@ -3651,6 +5742,38 @@ var Compiler = class {
3651
5742
  }, c));
3652
5743
  };
3653
5744
  }
5745
+ /**
5746
+ * This method compiles a data limit: the number of targets of an axis (ITERATE.LIMIT.DATA). Each failure of the axis, of
5747
+ * a test or of an item, and a count above the cap, is one error (ITERATE.LIMIT.ERROR).
5748
+ */
5749
+ #size(axis, path, counter) {
5750
+ const targets = this.#targets(axis, path, counter);
5751
+ const base = baseAxis(axis);
5752
+ const invalid = (f, cause) => fail(limitError(cause, {
5753
+ path,
5754
+ origin: f.pos.origin,
5755
+ focus: f.pos.focus
5756
+ }));
5757
+ return (f, c) => {
5758
+ const inner = this.#axisCtx(base, f, c, path);
5759
+ if (!inner.ok) return invalid(f, inner.error);
5760
+ const ts = targets(f, inner.value);
5761
+ if (!ts.ok) return invalid(f, ts.error);
5762
+ const cause = worstError(ts.value.flatMap(({ test }) => test === void 0 || test.ok ? [] : test.error));
5763
+ if (cause !== void 0) return invalid(f, cause);
5764
+ const count = ts.value.length;
5765
+ return count > 1e5 ? this.#err("limit", overLimitMessage(count), f, path) : ok(count);
5766
+ };
5767
+ }
5768
+ /** This method gives the context of an axis: the space of its table for the axis `table`, or `c` (AXIS.TABLE). */
5769
+ #axisCtx(base, f, c, path) {
5770
+ if (base.t !== "table") return ok(c);
5771
+ const space = c.tables !== void 0 && Object.hasOwn(c.tables, base.name) ? c.tables[base.name] : void 0;
5772
+ return space === void 0 ? this.#at(errorText.noTable(base.name), f, path) : ok({
5773
+ ...c,
5774
+ space
5775
+ });
5776
+ }
3654
5777
  /** This method compiles the targets of an axis. For `where`, a failed test keeps the target with its error. */
3655
5778
  #targets(a, path, counter) {
3656
5779
  if (a.t === "table") return (_f, c) => ok(c.space.keys.map((key) => ({ key })));
@@ -3691,7 +5814,7 @@ var Compiler = class {
3691
5814
  else if (r.value === true) out.push(t);
3692
5815
  else if (r.value !== false) out.push({
3693
5816
  key: t.key,
3694
- test: this.#err("kind-mismatch", `the test of "where" gave a ${typeof r.value}, not a boolean`, at, testPath)
5817
+ test: this.#at(errorText.whereKind(r.value), at, testPath)
3695
5818
  });
3696
5819
  }
3697
5820
  return ok(out);
@@ -3707,7 +5830,7 @@ var Compiler = class {
3707
5830
  const r = node(f, c);
3708
5831
  if (!r.ok) return r;
3709
5832
  const listed = asList(r.value, this.#missing(f, path));
3710
- if (listed === void 0) return this.#err("kind-mismatch", `the axis "list" needs a list, not a ${describeType(r.value)}`, f, path);
5833
+ if (listed === void 0) return this.#at(errorText.axisList(r.value), f, path);
3711
5834
  let index = 0;
3712
5835
  const items = listed.items.map(({ key, result }) => result.ok ? {
3713
5836
  key,
@@ -3730,7 +5853,7 @@ var Compiler = class {
3730
5853
  if (!all.ok) return this.#emit(c, info, f, all);
3731
5854
  const values = all.value;
3732
5855
  const self = values[0];
3733
- if (listOp !== void 0 && isVexList(self)) return this.#emit(c, info, f, this.#listOp(listOp, self, values.slice(1), f, path));
5856
+ if (listOp !== void 0 && isVexList(self)) return this.#emit(c, info, f, this.listOp(listOp, self, values.slice(1), f, path));
3734
5857
  let accepted;
3735
5858
  if (values.length > 0) for (const d of this.#domains) {
3736
5859
  if (!safeIs(d, self)) continue;
@@ -3741,23 +5864,23 @@ var Compiler = class {
3741
5864
  if (method !== void 0) return this.#emit(c, info, f, this.#call(d, spec ?? NO_SPEC, (receiver, ...given) => method.apply(receiver, [...given]), self, op, values.slice(1), f, path));
3742
5865
  }
3743
5866
  if (fn !== void 0) return this.#emit(c, info, f, this.#checkResult(this.#invoke(() => fn(...values), op, f, path), f, path, op));
3744
- if (listOp !== void 0 && Array.isArray(self)) return this.#emit(c, info, f, this.#listOp(listOp, listOfArray(self, this.#missing(f, path)), values.slice(1), f, path));
3745
- if (op === "fill") return this.#emit(c, info, f, this.#fill(values, f, path));
3746
- if (accepted !== void 0) return this.#emit(c, info, f, this.#err("unknown-op", `the domain "${accepted.name}" has no op "${op}"`, f, path, { op }));
3747
- if (values.length === 0) return this.#emit(c, info, f, this.#err("unknown-op", `there is no function "${op}"`, f, path, { op }));
3748
- return this.#emit(c, info, f, this.#err("not-instance", `no domain accepts the receiver of "${op}" (${describeType(self)})`, f, path, { op }));
5867
+ if (listOp !== void 0 && Array.isArray(self)) return this.#emit(c, info, f, this.arrayOp(listOp, self, values.slice(1), f, path));
5868
+ if (op === "fill") return this.#emit(c, info, f, this.fill(values, f, path));
5869
+ if (accepted !== void 0) return this.#emit(c, info, f, this.#at(errorText.domainNoOp(accepted.name, op), f, path));
5870
+ if (values.length === 0) return this.#emit(c, info, f, this.#at(errorText.noOp(op), f, path));
5871
+ return this.#emit(c, info, f, this.#at(errorText.noDomain(op, self), f, path));
3749
5872
  };
3750
5873
  }
3751
5874
  #special(op, args, info) {
3752
5875
  const { path } = info;
3753
5876
  const arg = (i, f, c) => {
3754
5877
  const n = args[i];
3755
- return n === void 0 ? this.#err("bad-expression", `"${op}" needs argument ${i + 1}`, f, path, { op }) : n(f, c);
5878
+ return n === void 0 ? this.#at(errorText.needsArgument(op, i), f, path) : n(f, c);
3756
5879
  };
3757
5880
  const bool = (i, f, c) => {
3758
5881
  const r = arg(i, f, c);
3759
5882
  if (!r.ok) return r;
3760
- 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 });
5883
+ return typeof r.value === "boolean" ? ok(r.value) : this.#at(errorText.notBoolean(op, i, r.value), f, path);
3761
5884
  };
3762
5885
  switch (op) {
3763
5886
  case "if": return (f, c) => {
@@ -3768,7 +5891,7 @@ var Compiler = class {
3768
5891
  case "or": {
3769
5892
  const stop = op === "or";
3770
5893
  return (f, c) => {
3771
- if (args.length === 0) return this.#emit(c, info, f, this.#err("bad-expression", `"${op}" needs at least 1 argument`, f, path, { op }));
5894
+ if (args.length === 0) return this.#emit(c, info, f, this.#at(errorText.needsArguments(op), f, path));
3772
5895
  for (let i = 0; i < args.length; i++) {
3773
5896
  const b = bool(i, f, c);
3774
5897
  if (!b.ok) return this.#emit(c, info, f, b);
@@ -3802,16 +5925,13 @@ var Compiler = class {
3802
5925
  }
3803
5926
  if (spec.params !== void 0) for (let i = 0; i < callArgs.length; i++) {
3804
5927
  const kind = spec.params[i] ?? "any";
3805
- if (!matchesKind(kind, callArgs[i], domain)) {
3806
- const k = kind === "domain" ? "not-instance" : "kind-mismatch";
3807
- 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 });
3808
- }
5928
+ if (!matchesKind(kind, callArgs[i], domain)) return this.#at(errorText.badParam(name, i, callArgs[i], kind, domain.name), f, path);
3809
5929
  }
3810
5930
  let value;
3811
5931
  try {
3812
5932
  value = run(self, ...callArgs);
3813
5933
  } catch (thrown) {
3814
- return this.#threw(thrown, `"${name}" threw an exception`, f, path, { op: name });
5934
+ return this.#threw(thrown, errorText.threw(name), f, path);
3815
5935
  }
3816
5936
  return this.#checkResult(ok(value), f, path, name);
3817
5937
  }
@@ -3819,7 +5939,7 @@ var Compiler = class {
3819
5939
  try {
3820
5940
  return ok(run());
3821
5941
  } catch (thrown) {
3822
- return this.#threw(thrown, `"${op}" threw an exception`, f, path, { op });
5942
+ return this.#threw(thrown, errorText.threw(op), f, path);
3823
5943
  }
3824
5944
  }
3825
5945
  /**
@@ -3834,23 +5954,26 @@ var Compiler = class {
3834
5954
  #checkResult(r, f, path, op) {
3835
5955
  if (!r.ok) return r;
3836
5956
  const value = r.value;
3837
- const extra = { op };
3838
- if (value === void 0 || value === null) return this.#err("undefined-result", `"${op}" gave no value`, f, path, extra);
3839
- if (typeof value === "number" && !Number.isFinite(value)) return this.#err("not-finite", `"${op}" gave ${value}`, f, path, extra);
5957
+ if (value === void 0 || value === null) return this.#at(errorText.noValue(op), f, path);
5958
+ if (typeof value === "number" && !Number.isFinite(value)) return this.#at(errorText.notFinite(op, value), f, path);
3840
5959
  const d = this.#domainOf(value);
3841
5960
  if (d?.valid !== void 0) {
3842
5961
  let valid;
3843
5962
  try {
3844
5963
  valid = d.valid(value);
3845
5964
  } catch (thrown) {
3846
- return this.#threw(thrown, `the "valid" check of "${d.name}" threw an exception`, f, path, extra);
5965
+ return this.#threw(thrown, errorText.validThrew(op, d.name), f, path);
3847
5966
  }
3848
- if (!valid) return this.#err("invalid-value", `"${op}" gave a value that is not a valid ${d.name}`, f, path, extra);
5967
+ if (!valid) return this.#at(errorText.invalid(op, d.name), f, path);
3849
5968
  }
3850
5969
  return r;
3851
5970
  }
3852
- #listOp(op, list, rest, f, path) {
3853
- const optsArg = WITH_ARGUMENT.has(op) ? rest[1] : rest[0];
5971
+ /** This method gives the result of a list op on an array (LIST.ARRAY): the list op on the list of its items. */
5972
+ arrayOp(op, array, rest, f, path) {
5973
+ return this.listOp(op, listOfArray(array, this.#missing(f, path)), rest, f, path);
5974
+ }
5975
+ listOp(op, list, rest, f, path) {
5976
+ const optsArg = op === "setNth" ? rest[2] : WITH_ARGUMENT.has(op) ? rest[1] : rest[0];
3854
5977
  const strict = optsArg?.strict === true;
3855
5978
  if (op === "get") return this.#get(list, rest[0], strict, f, path);
3856
5979
  if (op === "group") return this.#group(list, rest[0], strict, f, path);
@@ -3861,13 +5984,13 @@ var Compiler = class {
3861
5984
  for (const it of okItems) okValues.push(valueOf(it));
3862
5985
  const numbers = () => {
3863
5986
  const bad = okValues.find((x) => typeof x !== "number");
3864
- return bad === void 0 ? ok(okValues) : this.#err("kind-mismatch", `"${op}" needs numbers, but an item is a ${describeType(bad)}`, f, path, { op });
5987
+ return bad === void 0 ? ok(okValues) : this.#at(errorText.needsItems(op, "numbers", bad), f, path);
3865
5988
  };
3866
5989
  const booleans = () => {
3867
5990
  const bad = okValues.find((x) => typeof x !== "boolean");
3868
- return bad === void 0 ? ok(okValues) : this.#err("kind-mismatch", `"${op}" needs booleans, but an item is a ${describeType(bad)}`, f, path, { op });
5991
+ return bad === void 0 ? ok(okValues) : this.#at(errorText.needsItems(op, "booleans", bad), f, path);
3869
5992
  };
3870
- const empty = () => this.#err("empty", `"${op}" has no values to work with`, f, path, { op });
5993
+ const empty = () => this.#at(errorText.empty(op), f, path);
3871
5994
  const whole = () => {
3872
5995
  const n = rest[0];
3873
5996
  return Number.isSafeInteger(n) && n >= 0 ? ok(n) : this.#err("kind-mismatch", `"${op}" needs a whole number from 0, not ${describeType(n)}`, f, path, { op });
@@ -3923,6 +6046,19 @@ var Compiler = class {
3923
6046
  if (!i.ok) return i;
3924
6047
  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 });
3925
6048
  }
6049
+ case "setNth": {
6050
+ const i = whole();
6051
+ if (!i.ok) return i;
6052
+ const old = okItems[i.value];
6053
+ if (old === void 0) 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 });
6054
+ if (rest[1] === void 0) return this.#err("bad-expression", "\"setNth\" needs argument 3", f, path, { op });
6055
+ const items = [...okItems];
6056
+ items[i.value] = {
6057
+ key: old.key,
6058
+ result: ok(rest[1])
6059
+ };
6060
+ return ok(checkedList(items));
6061
+ }
3926
6062
  case "count": return ok(okValues.length);
3927
6063
  case "values": return ok(Object.freeze([...okValues]));
3928
6064
  case "keys": return ok(Object.freeze(okItems.map((it) => it.key)));
@@ -4054,7 +6190,7 @@ var Compiler = class {
4054
6190
  op = safeIs(d, x) ? resolveOp(d, x, by) : void 0;
4055
6191
  if (op !== void 0) break;
4056
6192
  }
4057
- if (op === void 0) return this.#err("unknown-op", `no domain gives "${by}" for a ${describeType(x)}`, f, path, { op: by });
6193
+ if (op === void 0) return this.#at(errorText.noStep(by, x), f, path);
4058
6194
  const r = this.#callResolved(op, x, by, [], f, path);
4059
6195
  if (!r.ok) return r;
4060
6196
  out.push(r.value);
@@ -4066,7 +6202,7 @@ var Compiler = class {
4066
6202
  * domain has an identity for the op (LIST.EMPTY). The option `domain` names that domain when more domains have one.
4067
6203
  */
4068
6204
  #reduce(opName, values, f, path, opts) {
4069
- if (typeof opName !== "string") return this.#err("kind-mismatch", `"reduce" needs an op name, but got a ${describeType(opName)}`, f, path, { op: "reduce" });
6205
+ if (typeof opName !== "string") return this.#at(errorText.reduceName(opName), f, path);
4070
6206
  if (values.length === 0) {
4071
6207
  const named = opts?.domain;
4072
6208
  const candidates = this.#domains.filter((d) => Object.hasOwn(d.ops, opName) && d.ops[opName].identity !== void 0 && (named === void 0 || d.name === named));
@@ -4083,7 +6219,7 @@ var Compiler = class {
4083
6219
  for (let i = 1; i < values.length; i++) {
4084
6220
  const d = this.#domains.find((dom) => safeIs(dom, acc) && resolveOp(dom, acc, opName) !== void 0);
4085
6221
  const op = d === void 0 ? void 0 : resolveOp(d, acc, opName);
4086
- if (op === void 0) return this.#err("unknown-op", `no domain gives "${opName}" for a ${describeType(acc)}`, f, path, { op: opName });
6222
+ if (op === void 0) return this.#at(errorText.noStep(opName, acc), f, path);
4087
6223
  const r = this.#callResolved(op, acc, opName, [values[i]], f, path);
4088
6224
  if (!r.ok) return r;
4089
6225
  acc = r.value;
@@ -4183,17 +6319,6 @@ function matchesKind(kind, value, domain) {
4183
6319
  case "any": return true;
4184
6320
  }
4185
6321
  }
4186
- /** This function gives a short name for the type of a value, for error messages. */
4187
- function describeType(u) {
4188
- if (u === null) return "null";
4189
- if (Array.isArray(u)) return "array";
4190
- if (isVexList(u)) return "list";
4191
- if (typeof u === "object") {
4192
- const name = Object.getPrototypeOf(u)?.constructor?.name;
4193
- return typeof name === "string" && name !== "Object" ? name : "object";
4194
- }
4195
- return typeof u;
4196
- }
4197
6322
  /** This function gives the label of a node, for traces. */
4198
6323
  function labelOf(e) {
4199
6324
  switch (e.tag) {
@@ -4207,7 +6332,9 @@ function labelOf(e) {
4207
6332
  case "rec": return `{ ${Object.keys(e.fields).join(", ")} }`;
4208
6333
  case "each":
4209
6334
  case "fold": return e.at === void 0 ? `${e.tag} ${e.axis.t}` : `${e.tag} ${e.axis.t} from ${e.at.map(moveText).join(".")}`;
4210
- case "iterate": return `iterate ${String(e.limit)}`;
6335
+ case "iterate": return `iterate ${typeof e.limit === "number" ? String(e.limit) : `size of ${e.limit.axis.t}`}`;
6336
+ case "fix": return `fix ${e.name} ${e.join}`;
6337
+ case "last": return `last ${e.name}`;
4211
6338
  case "ext": return e.kind;
4212
6339
  }
4213
6340
  }
@@ -4337,7 +6464,17 @@ function deps(e) {
4337
6464
  up: axes
4338
6465
  };
4339
6466
  else if (head === "axis") axis = around;
4340
- }
6467
+ } else if (kind === "fix") axes = {
6468
+ item: {
6469
+ t: "all",
6470
+ at: []
6471
+ },
6472
+ up: axes
6473
+ };
6474
+ else if (kind === "size") axis = {
6475
+ t: nodes.get(parent.doc).limit.axis.t,
6476
+ at: []
6477
+ };
4341
6478
  if (kind === "fn") {
4342
6479
  fn = parent;
4343
6480
  fnVisits.set(parent.doc, parent);
@@ -4522,7 +6659,19 @@ function mapValues(u, f) {
4522
6659
  out["axis"] = a.value;
4523
6660
  return each("init") ?? each("step") ?? child("result") ?? address() ?? ok(out);
4524
6661
  }
4525
- case "iterate": return each("init") ?? each("step") ?? (u["until"] === void 0 ? void 0 : child("until")) ?? child("result") ?? ok(out);
6662
+ case "iterate": {
6663
+ const limit = u["limit"];
6664
+ if (isRecord(limit)) {
6665
+ const a = axis(limit["axis"]);
6666
+ if (!a.ok) return a;
6667
+ out["limit"] = {
6668
+ ...limit,
6669
+ axis: a.value
6670
+ };
6671
+ }
6672
+ return each("init") ?? each("step") ?? (u["until"] === void 0 ? void 0 : child("until")) ?? child("result") ?? ok(out);
6673
+ }
6674
+ case "fix": return child("init") ?? child("step") ?? ok(out);
4526
6675
  case "fn": return child("body") ?? ok(out);
4527
6676
  case "call": return each("args") ?? ok(out);
4528
6677
  case "ref": return address() ?? ok(out);
@@ -4596,12 +6745,11 @@ function kernelPlan(source, opts = {}) {
4596
6745
  let bad;
4597
6746
  if (isDocument(source)) {
4598
6747
  const read = fromDocument(source, domains);
4599
- if (read.ok) doc = source;
4600
- else bad = read.error;
6748
+ const size = read.ok ? nestingError(read.value) ?? sizeError(read.value, opts) ?? stepError(read.value, opts) ?? monotoneError(read.value, opts) : void 0;
6749
+ if (read.ok && size === void 0) doc = source;
6750
+ else bad = read.ok ? vexError("bad-expression", size ?? "") : read.error;
4601
6751
  } else {
4602
- const shape = shapeError(source);
4603
- const nesting = shape === void 0 ? nestingOf(source) : 0;
4604
- const reason = shape ?? (nesting > 500 ? `the expression is nested ${String(nesting)} levels deep, and the limit is ${String(500)}` : void 0);
6752
+ const reason = shapeError(source) ?? nestingError(source) ?? sizeError(source, opts) ?? stepError(source, opts) ?? monotoneError(source, opts);
4605
6753
  if (reason === void 0) doc = writeDocument(source, {
4606
6754
  domains,
4607
6755
  literals: "host",
@@ -4751,11 +6899,18 @@ function traversal(items, env, isStrict = false) {
4751
6899
  */
4752
6900
  /** The extension kind of a cell reference. */
4753
6901
  const CELL_KIND = "vex.cell";
4754
- /** This function makes a cell reference: the column `column` at the address `at` from the focus. */
4755
- const cell = (column, at = []) => ext(CELL_KIND, {
6902
+ /** This function makes the extension node of a cell reference. */
6903
+ const cellRef = (column, at) => ext(CELL_KIND, {
4756
6904
  column,
4757
6905
  at
4758
6906
  });
6907
+ /**
6908
+ * This function makes a read of the column `column` at the address `at` from the focus. An address of fixed moves gives
6909
+ * a cell reference. A computed move is an expression, not data (SHEET.CELL.COMPUTED). Thus it goes in the address of the
6910
+ * axis `window(0, 0)`, and the read is the one item of that axis. Each tier and the JSON form have this form.
6911
+ */
6912
+ const cell = (column, at = []) => isFixedAddr(at) ? cellRef(column, at) : app("first", each(axes.window(0, 0), cellRef(column, []), at), lit({ strict: true }));
6913
+ /** This function tells if the data of an extension is a cell reference: a column, and an address of fixed moves. */
4759
6914
  const isCellRef = (u) => typeof u === "object" && u !== null && typeof u.column === "string" && Array.isArray(u.at) && u.at.every((m) => isMove(m) && moveExpr(m) === void 0);
4760
6915
  /**
4761
6916
  * The compiled programs of the formulas of the columns: one entry for each formula, for the last compiler and options.
@@ -4822,14 +6977,16 @@ function partsOf(axis) {
4822
6977
  * the formulas of its cells. It also gives the directions of their reads of the column itself. A read in the body or
4823
6978
  * in a test of an axis also has the direction of that axis. It walks each expression with a stack, not with recursion.
4824
6979
  */
4825
- function readsOf(t, self) {
4826
- const columns = /* @__PURE__ */ new Set();
6980
+ function readsOf(columns, cells, self) {
6981
+ const read = /* @__PURE__ */ new Set();
4827
6982
  const directions = /* @__PURE__ */ new Set();
4828
- const formula = t.columns.get(self);
4829
- const todo = [...formula === void 0 ? [] : [formula], ...t.cells.get(self)?.values() ?? []].filter((e) => shapeError(e) === void 0).map((e) => [e, void 0]);
6983
+ const formula = columns.get(self);
6984
+ const todo = [...formula === void 0 ? [] : [formula], ...cells.get(self)?.values() ?? []].filter((e) => shapeError(e) === void 0).map((e) => [e, void 0]);
4830
6985
  for (let item = todo.pop(); item !== void 0; item = todo.pop()) {
4831
6986
  const [e, axis] = item;
4832
- if (e.tag === "each" || e.tag === "fold") {
6987
+ const split = e.tag === "iterate" ? splitLimit(e) : void 0;
6988
+ if (split !== void 0) for (const x of split) todo.push([x, axis]);
6989
+ else if (e.tag === "each" || e.tag === "fold") {
4833
6990
  const { base, tests } = partsOf(e.axis);
4834
6991
  for (const x of [...e.tag === "each" ? [e.body] : Object.values(e.step), ...tests]) todo.push([x, base]);
4835
6992
  const list = listOf(e.axis);
@@ -4840,24 +6997,24 @@ function readsOf(t, self) {
4840
6997
  ]) todo.push([x, axis]);
4841
6998
  } else if (e.tag !== "ext") for (const child of children(e)) todo.push([child, axis]);
4842
6999
  else if (e.kind === "vex.cell" && isCellRef(e.data)) {
4843
- columns.add(e.data.column);
7000
+ read.add(e.data.column);
4844
7001
  if (e.data.column === self) for (const m of [...axis === void 0 ? [] : [axis], ...e.data.at]) addDirection(directions, m);
4845
7002
  }
4846
7003
  }
4847
7004
  return {
4848
- columns,
7005
+ columns: read,
4849
7006
  directions
4850
7007
  };
4851
7008
  }
4852
7009
  /**
4853
- * This function gives the columns of a table in an order where each column comes after the columns that it reads.
7010
+ * This function gives the columns of a sheet in an order where each column comes after the columns that it reads.
4854
7011
  * The columns of a cycle keep their order. The columns with formulas of cells only come last.
4855
7012
  */
4856
- function columnOrder(t) {
4857
- const names = /* @__PURE__ */ new Set([...t.columns.keys(), ...t.cells.keys()]);
7013
+ function columnOrder(columns, cells) {
7014
+ const names = /* @__PURE__ */ new Set([...columns.keys(), ...cells.keys()]);
4858
7015
  let left = [...names].map((c) => ({
4859
7016
  c,
4860
- needs: [...readsOf(t, c).columns].filter((x) => x !== c && names.has(x))
7017
+ needs: [...readsOf(columns, cells, c).columns].filter((x) => x !== c && names.has(x))
4861
7018
  }));
4862
7019
  const order = [];
4863
7020
  const placed = /* @__PURE__ */ new Set();
@@ -5239,7 +7396,7 @@ var SheetRun = class SheetRun {
5239
7396
  const t = table === void 0 ? this.#main : this.#byName.get(table);
5240
7397
  if (t === void 0 || this.#top.index >= 0) return;
5241
7398
  const host = this.#top;
5242
- for (const column of columnOrder(t)) for (const key of keyOrder(t.space, readsOf(t, column).directions)) {
7399
+ for (const column of columnOrder(t.columns, t.cells)) for (const key of keyOrder(t.space, readsOf(t.columns, t.cells, column).directions)) {
5243
7400
  const program = this.#programOf(t, column, key);
5244
7401
  if (program === void 0 || doneOf(t, column, key) !== void 0) continue;
5245
7402
  this.#top = this.#filling;
@@ -5308,12 +7465,32 @@ function inItemLoop(build) {
5308
7465
  itemDepth -= 1;
5309
7466
  }
5310
7467
  }
5311
- /** This function tells if the expression reads the name, in one of its parts. It uses a stack, not recursion. */
7468
+ /**
7469
+ * The number of the open steps of `fix`. The name of a column ends with this number. Thus an inner `fix` does not hide
7470
+ * the column around it, also when the chain of the inner `fix` starts at the root (BUILD.FIX).
7471
+ */
7472
+ let fixDepth = 0;
7473
+ /** This function gives the value of `build`, with the next number for the columns inside it. */
7474
+ function inFixStep(build) {
7475
+ fixDepth += 1;
7476
+ try {
7477
+ return build();
7478
+ } finally {
7479
+ fixDepth -= 1;
7480
+ }
7481
+ }
7482
+ /**
7483
+ * This function tells if the expression reads the name, in one of its parts. It uses a stack, not recursion. An `each`
7484
+ * or a `fold` can have the name in its item names (`as`). Then it binds the name again for its body or its step, and
7485
+ * those parts do not count (V-065). A chain made at the same depth of the loops has the same names, so a fold can hold such a chain in its step.
7486
+ */
5312
7487
  function reads(e, name) {
5313
7488
  const todo = [e];
5314
7489
  for (let x = todo.pop(); x !== void 0; x = todo.pop()) {
5315
7490
  if (x.tag === "var" && x.name === name) return true;
5316
- todo.push(...children(x));
7491
+ if (x.tag === "each" && x.as?.includes(name) === true) todo.push(...axisExprs(x.axis), ...addrExprs(x.at));
7492
+ else if (x.tag === "fold" && x.as?.includes(name) === true) todo.push(...Object.values(x.init), ...axisExprs(x.axis), ...addrExprs(x.at), x.result);
7493
+ else todo.push(...children(x));
5317
7494
  }
5318
7495
  return false;
5319
7496
  }
@@ -5528,11 +7705,30 @@ var ChainImpl = class ChainImpl {
5528
7705
  const next = stepExprs(step(vars), unique, this.#s.addr);
5529
7706
  const until = opts?.until === void 0 ? void 0 : toExpr(opts.until(vars), this.#s.addr);
5530
7707
  const r = result(vars);
7708
+ const bound = isChainLike(limit) ? dataLimit({
7709
+ t: "list",
7710
+ list: toExpr(limit, this.#s.addr)
7711
+ }) : limit;
5531
7712
  return chainOf({
5532
7713
  ...this.#s,
5533
- expr: iterate(limit, first, next, toExpr(r, this.#s.addr), until)
7714
+ expr: iterate(bound, first, next, toExpr(r, this.#s.addr), until)
5534
7715
  }, r);
5535
7716
  }
7717
+ fix(name, join, init, step) {
7718
+ const { addr, depth } = this.#s;
7719
+ const column = `${name}$${String(fixDepth)}`;
7720
+ const read = new ChainImpl({
7721
+ ...this.#s,
7722
+ expr: last(column),
7723
+ addr: [],
7724
+ depth: depth + 1
7725
+ });
7726
+ const next = inFixStep(() => toExpr(step(read), addr));
7727
+ return new ChainImpl({
7728
+ ...this.#s,
7729
+ expr: fix(column, join, toExpr(init, addr), next)
7730
+ });
7731
+ }
5536
7732
  #axis(a, body, opts) {
5537
7733
  const { name, start } = this.#bound();
5538
7734
  const inTarget = new ChainImpl({
@@ -5715,6 +7911,9 @@ var ListChainImpl = class ListChainImpl {
5715
7911
  nth(i, opts) {
5716
7912
  return this.#op("nth", [lit(i)], opts);
5717
7913
  }
7914
+ setNth(i, value, opts) {
7915
+ return this.#list("setNth", [typeof i === "number" ? lit(i) : i.program, toExpr(value, this.#s.addr)], opts);
7916
+ }
5718
7917
  get(k, opts) {
5719
7918
  return this.#op("get", [typeof k === "string" ? lit(k) : k.program], opts);
5720
7919
  }
@@ -5931,6 +8130,6 @@ function vex(...domains) {
5931
8130
  withOptions: make
5932
8131
  };
5933
8132
  }
5934
- export { CELL_KIND, LIST_OPS, MAX_DOCUMENT_DEPTH, MAX_ITERATIONS, MAX_NESTING, SPECIAL_FORMS, SheetRun, TERM_KINDS, VEX_WORLD, addrExprs, app, applyMove, axes, axisExprs, axisTargets, call, cell, chainResult, children, codeOf, compile, defineDomain, deps, describeType, domainOf, each, evaluate, explain, ext, fail, findMethod, fixAddr, fn, fold, formatError, formatTrace, fromDocument, getOr, index, isAxis, isDepthError, isDocument, isExpr, isFieldName, isFixedAddr, isListOp, isMove, isNone, isOpName, isSome, isStackOverflow, isVexList, iterate, kernelPlan, key, labelOf, let_, liftsAt, listOf, lit, mapResult, matchesKind, monoids, moveExpr, nestingOf, none, offset, ok, origin, other, parent, parse, previewValue, rec, ref, resolveAddr, resolveOp, safeIs, serialize, shapeError, sizeOf, some, space, toDocument, toKernelError, toOptional, toPath, toVexError, toVexResult, traversal, v, vex, vexChecker, vexDefinitions, vexError, vexList, vexMachine, vexSelf };
8133
+ export { CELL_KIND, CONSTRUCT_STEPS, DEFAULT_MAX_STEP, LIST_OPS, LIST_SIZES, MAX_DOCUMENT_DEPTH, MAX_ITERATIONS, MAX_NESTING, SPECIAL_FORMS, SheetRun, TERM_KINDS, VEX_STEPS, VEX_STEP_NAMES, VEX_WORLD, addrExprs, app, applyMove, asList, axes, axisExprs, axisTargets, call, cell, chainResult, children, codeOf, columnOrder, compile, dataLimit, defineDomain, deps, describeType, domainOf, each, errorAt, errorText, evaluate, explain, ext, fail, findMethod, fix, fixAddr, fixRounds, fixValueError, fn, fold, formatError, formatTrace, fromDocument, getOr, index, isAxis, isCellRef, isDepthError, isDocument, isExpr, isFieldName, isFixedAddr, isListOp, isMove, isNone, isOpName, isSome, isStackOverflow, isVexList, iterate, joinKind, kernelPlan, key, labelOf, last, let_, liftsAt, limitAxis, listItemKind, listOf, listOps, lit, mapResult, matchesKind, monoids, monotoneError, moveExpr, nestingError, nestingOf, noKeyError, none, offset, ok, origin, other, parent, parse, previewValue, programStep, readsOf, rec, ref, resolveAddr, resolveOp, ruleOf, safeIs, serialize, shapeError, sizeError, sizeOf, some, space, splitLimit, stepError, toDocument, toKernelError, toOptional, toPath, toVexError, toVexResult, traversal, v, vex, vexChecker, vexDefinitions, vexError, vexList, vexMachine, vexSelf, worstRow };
5935
8134
 
5936
8135
  //# sourceMappingURL=index.js.map