@mark1russell7/vex 0.17.2 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/size.ts ADDED
@@ -0,0 +1,1104 @@
1
+ /**
2
+ * The check of sizes in the loops of a program (LOOP.SIZE). A step of `fold` or `iterate` gives each name a new value
3
+ * from the values before the step. When a new value holds two copies of the old lists, the size can double at each step.
4
+ * For example, a fold over 12 records with the step `append(xs, xs)` makes a list of 4096 items. The check finds such
5
+ * steps before a run, from the size rules of the ops (LOOP.SIZE.OPS).
6
+ *
7
+ * The check is an abstract interpretation. It gives each value five measures: its size, its count, its inner count (the
8
+ * sum of the counts of the values of its items), the size of its largest item, and its largest part (the largest item of
9
+ * an item). Each measure is a bound: the largest value of some sums. A sum is a constant, and the measures of the old
10
+ * values of the loops, each with a coefficient. A coefficient tells one use, a fixed number of uses, more uses, or no
11
+ * bound. The check also keeps the kinds of each value, because the kind of the receiver selects the op.
12
+ *
13
+ * 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
14
+ * use of the whole value. The second reading uses the bound of the part. Each reading gives a sound bound, so one
15
+ * reading that accepts a program makes the program valid.
16
+ */
17
+ import { isOpName, listItemKind, type AnyDomain, type OpSpec, type ReturnKind, type SizeMeasure, type SizeRule, type SizeTerm, type SizeUse } from "./domain.ts";
18
+ import { addrExprs, children, limitAxis, listOf, type Axis, type Expr, type ExprOf, type ItemNames } from "./ir.ts";
19
+ import { joinKind as kindOfJoin } from "./fix.ts";
20
+ import { isListOp, isVexList, LIST_SIZES, type ListOp } from "./list.ts";
21
+
22
+ /** The options of the check of sizes: the domains and the functions of the host, as for `compile`. */
23
+ export interface SizeOptions {
24
+ readonly domains?: readonly AnyDomain[];
25
+ /** The functions of the host. A function with the property `size` has that size rule, and another function has none. */
26
+ readonly fns?: Readonly<Record<string, unknown>>;
27
+ }
28
+
29
+ /** A coefficient: 1 for one use, 2 for a fixed number of uses, 3 for more uses, and 4 for no bound. */
30
+ type Coef = 1 | 2 | 3 | 4;
31
+
32
+ /** A sum: a constant (`Infinity` for a constant without a known value) and a coefficient for each variable. */
33
+ interface Sum {
34
+ readonly base: number;
35
+ readonly terms: ReadonlyMap<string, Coef>;
36
+ }
37
+
38
+ /** A bound: the largest value of some sums (LOOP.SIZE.BRANCH). A bound has at least one sum, and no sum covers another. */
39
+ type Form = readonly Sum[];
40
+
41
+ /** The kinds of a value: a set of tags, or `undefined` for each kind. `item` is the kind of the items of a list. */
42
+ interface Kind {
43
+ readonly tags: ReadonlySet<string> | undefined;
44
+ readonly item?: Kind;
45
+ }
46
+
47
+ /**
48
+ * The measures and the kinds of a value. `long` tells that a key in the value can be long. A key of a record, of a
49
+ * position or of a literal has a fixed bound. A key of `group` is a value of the program.
50
+ */
51
+ interface Shape {
52
+ readonly size: Form;
53
+ readonly count: Form;
54
+ readonly inner: Form;
55
+ readonly item: Form;
56
+ readonly part: Form;
57
+ readonly kind: Kind;
58
+ readonly long: boolean;
59
+ }
60
+
61
+ const NO_TERMS: ReadonlyMap<string, Coef> = new Map();
62
+ const NONE: Form = [{ base: 0, terms: NO_TERMS }];
63
+ const constant = (base: number): Form => (base === 0 ? NONE : [{ base, terms: NO_TERMS }]);
64
+ const SOME = constant(Infinity);
65
+ const MEASURES: readonly SizeMeasure[] = ["size", "count", "inner", "item", "part"];
66
+ /** The most sums of a bound. A bound with more sums becomes one sum, so the work of the check has a limit. */
67
+ const MOST_SUMS = 8;
68
+
69
+ const ANY: Kind = { tags: undefined };
70
+ const NO_KIND: Kind = { tags: new Set() };
71
+ const kindOf = (tag: string): Kind => ({ tags: new Set([tag]) });
72
+ const listKind = (item: Kind, tag = "list"): Kind => ({
73
+ tags: new Set([tag]),
74
+ item,
75
+ });
76
+ const NUMBER = kindOf("number");
77
+ const BOOLEAN = kindOf("boolean");
78
+ const STRING = kindOf("string");
79
+ const SCALAR: Kind = { tags: new Set(["number", "boolean"]) };
80
+ /** The tags of the values that have no methods: an op of a domain needs its function for them. */
81
+ const PRIMITIVES: ReadonlySet<string> = new Set(["number", "string", "boolean", "null"]);
82
+ /** The tags of the values without a size. */
83
+ const SCALARS: ReadonlySet<string> = new Set(["number", "boolean", "null"]);
84
+
85
+ /** The shape of a value without a size, and the shape of a value with a fixed bound. */
86
+ const zero = (kind: Kind): Shape => ({
87
+ size: NONE,
88
+ count: NONE,
89
+ inner: NONE,
90
+ item: NONE,
91
+ part: NONE,
92
+ kind,
93
+ long: false,
94
+ });
95
+ const fixed = (kind: Kind): Shape => ({
96
+ size: SOME,
97
+ count: SOME,
98
+ inner: SOME,
99
+ item: SOME,
100
+ part: SOME,
101
+ kind,
102
+ long: false,
103
+ });
104
+
105
+ const isZero = (s: Sum): boolean => s.base === 0 && s.terms.size === 0;
106
+ const isNone = (f: Form): boolean => f.every(isZero);
107
+ const term = (v: string, c: Coef): Form => [{ base: 0, terms: new Map([[v, c]]) }];
108
+
109
+ /** This function tells if the sum `a` is at least the sum `b` for each value of the variables. */
110
+ const covers = (a: Sum, b: Sum): boolean => a.base >= b.base && [...b.terms].every(([v, c]) => (a.terms.get(v) ?? 0) >= c);
111
+
112
+ /** This function gives one sum that is at least each sum of a bound: the largest constant and the largest coefficients. */
113
+ function cover(f: Form): Sum {
114
+ const terms = new Map<string, Coef>();
115
+ let base = 0;
116
+ for (const s of f) {
117
+ base = Math.max(base, s.base);
118
+ for (const [v, c] of s.terms) terms.set(v, Math.max(terms.get(v) ?? 0, c) as Coef);
119
+ }
120
+ return { base, terms };
121
+ }
122
+
123
+ /** This function gives the bound of some sums, without a sum that another sum covers, and with at most `MOST_SUMS` sums. */
124
+ function bound(sums: readonly Sum[]): Form {
125
+ let out: readonly Sum[] = [];
126
+ for (const s of sums) if (!out.some((o) => covers(o, s))) out = [...out.filter((o) => !covers(s, o)), s];
127
+ if (out.length > MOST_SUMS) return [cover(out)];
128
+ return out.length === 0 ? NONE : out;
129
+ }
130
+
131
+ /** This function gives the sum of two sums: the coefficients of a variable in both sums give more uses. */
132
+ function add(a: Sum, b: Sum): Sum {
133
+ const terms = new Map(a.terms);
134
+ for (const [v, c] of b.terms) {
135
+ const o = terms.get(v);
136
+ terms.set(v, o === undefined ? c : (Math.max(3, o, c) as Coef));
137
+ }
138
+ return { base: a.base + b.base, terms };
139
+ }
140
+
141
+ /** This function gives the bound of a sum of two values. */
142
+ function plus(a: Form, b: Form): Form {
143
+ if (isNone(a)) return b;
144
+ if (isNone(b)) return a;
145
+ return bound(a.flatMap((x) => b.map((y) => add(x, y))));
146
+ }
147
+
148
+ /** This function gives the bound of the larger of two values. */
149
+ const join = (a: Form, b: Form): Form => bound([...a, ...b]);
150
+
151
+ /** This function gives the bound of a union of two values: each variable with its largest coefficient, and the sum of the constants. */
152
+ const union = (a: Form, b: Form): Form => {
153
+ const all = cover([...a, ...b]);
154
+ return [{ base: cover(a).base + cover(b).base, terms: all.terms }];
155
+ };
156
+
157
+ /** This function gives the bound of `k` uses of a bound. */
158
+ function scale(f: Form, k: 0 | Coef): Form {
159
+ if (k === 0) return NONE;
160
+ if (k === 1) return f;
161
+ return bound(f.map((s) => ({ base: s.base === 0 ? 0 : Infinity, terms: new Map([...s.terms].map(([v, c]) => [v, Math.max(c, k) as Coef])) })));
162
+ }
163
+
164
+ /** This function gives a bound of a product of two sums. A product of two variables gives more uses of both. */
165
+ function multiply(a: Sum, b: Sum): Form {
166
+ if (isZero(a) || isZero(b)) return NONE;
167
+ if (a.terms.size === 0) return a.base <= 1 ? [b] : scale([b], 2);
168
+ if (b.terms.size === 0) return b.base <= 1 ? [a] : scale([a], 2);
169
+ return scale([add(a, b)], 3);
170
+ }
171
+
172
+ /** This function gives a bound of a product of two values. */
173
+ const times = (a: Form, b: Form): Form => bound(a.flatMap((x) => b.flatMap((y) => multiply(x, y))));
174
+
175
+ /** This function puts a bound in the place of each variable that `sigma` knows. */
176
+ function subst(f: Form, sigma: (v: string) => Form | undefined): Form {
177
+ const one = (s: Sum): Form => {
178
+ let out = constant(s.base);
179
+ for (const [v, c] of s.terms) {
180
+ const u = sigma(v);
181
+ out = plus(out, u === undefined ? term(v, c) : scale(u, c));
182
+ }
183
+ return out;
184
+ };
185
+ return bound(f.flatMap(one));
186
+ }
187
+
188
+ /** This function gives the sum without the variables that `drop` names, and the coefficients of these variables. */
189
+ function split(s: Sum, drop: (v: string) => boolean): { readonly rest: Sum; readonly dropped: ReadonlyMap<string, Coef> } {
190
+ const terms = new Map<string, Coef>();
191
+ const dropped = new Map<string, Coef>();
192
+ for (const [v, c] of s.terms) (drop(v) ? dropped : terms).set(v, c);
193
+ return { rest: { base: s.base, terms }, dropped };
194
+ }
195
+
196
+ const sameSum = (a: Sum, b: Sum): boolean => a.base === b.base && a.terms.size === b.terms.size && [...a.terms].every(([v, c]) => b.terms.get(v) === c);
197
+ const sameForm = (a: Form, b: Form): boolean => a.length === b.length && a.every((x) => b.some((y) => sameSum(x, y)));
198
+
199
+ /** This function tells if a kind can be a list or an array. */
200
+ const listy = (k: Kind): boolean => k.tags === undefined || k.tags.has("list") || k.tags.has("array");
201
+
202
+ /** This function gives the kind of the items of a value: no kind for a value that is not a list. */
203
+ const itemOf = (k: Kind): Kind => (listy(k) ? (k.item ?? ANY) : NO_KIND);
204
+
205
+ /** This function gives the kind of a value of two kinds. */
206
+ function joinKind(a: Kind, b: Kind): Kind {
207
+ if (a.tags === undefined || b.tags === undefined) return ANY;
208
+ const tags = new Set([...a.tags, ...b.tags]);
209
+ return listy(a) || listy(b) ? { tags, item: joinKind(itemOf(a), itemOf(b)) } : { tags };
210
+ }
211
+
212
+ /** This function tells if each value of the kind `a` has the kind `b`. */
213
+ function within(a: Kind, b: Kind): boolean {
214
+ if (b.tags === undefined) return true;
215
+ if (a.tags === undefined) return false;
216
+ for (const t of a.tags) if (!b.tags.has(t)) return false;
217
+ return !listy(a) || within(itemOf(a), itemOf(b));
218
+ }
219
+
220
+ const isText = (k: Kind | undefined): boolean => k?.tags !== undefined && k.tags.size === 1 && k.tags.has("string");
221
+
222
+ const joinShape = (a: Shape, b: Shape): Shape => ({
223
+ size: join(a.size, b.size),
224
+ count: join(a.count, b.count),
225
+ inner: join(a.inner, b.inner),
226
+ item: join(a.item, b.item),
227
+ part: join(a.part, b.part),
228
+ kind: joinKind(a.kind, b.kind),
229
+ long: a.long || b.long,
230
+ });
231
+
232
+ /** This function puts a bound in the place of each variable that `sigma` knows, in each measure of a shape. */
233
+ const substShape = (s: Shape, sigma: (v: string) => Form | undefined): Shape => ({
234
+ ...s,
235
+ size: subst(s.size, sigma),
236
+ count: subst(s.count, sigma),
237
+ inner: subst(s.inner, sigma),
238
+ item: subst(s.item, sigma),
239
+ part: subst(s.part, sigma),
240
+ });
241
+
242
+ /** This function gives the coefficient of a use. */
243
+ function coefOf(use: SizeUse): 0 | Coef {
244
+ switch (use) {
245
+ case 0:
246
+ case "number":
247
+ return 0;
248
+ case 1:
249
+ return 1;
250
+ case "scaled":
251
+ case "copies":
252
+ case "text":
253
+ return 2;
254
+ case "many":
255
+ case "each":
256
+ case "limit":
257
+ return 3;
258
+ case "unbounded":
259
+ return 4;
260
+ }
261
+ }
262
+
263
+ /** The letters of the variables of the measures. */
264
+ const LETTERS: Readonly<Record<SizeMeasure, string>> = { size: "s", count: "c", inner: "n", item: "t", part: "p" };
265
+ /** The name of the variable of a measure of a value with the number `id`, for example `s1` for its size. */
266
+ const variable = (m: SizeMeasure, id: number): string => `${LETTERS[m]}${String(id)}`;
267
+ /** The shape of a value with a variable for each measure. A number, a boolean and null have no size. */
268
+ const shapeOfVar = (id: number, kind: Kind, long: boolean): Shape =>
269
+ kind.tags !== undefined && [...kind.tags].every((t) => SCALARS.has(t))
270
+ ? zero(kind)
271
+ : {
272
+ size: term(variable("size", id), 1),
273
+ count: term(variable("count", id), 1),
274
+ inner: term(variable("inner", id), 1),
275
+ item: term(variable("item", id), 1),
276
+ part: term(variable("part", id), 1),
277
+ kind,
278
+ long,
279
+ };
280
+
281
+ /** The value of a name in the check: a shape, or the summary of a function (FN.BIND). */
282
+ type Entry =
283
+ | { readonly t: "value"; readonly shape: Shape }
284
+ | {
285
+ readonly t: "fn";
286
+ readonly params: readonly number[];
287
+ readonly result: Shape;
288
+ };
289
+ type Env = ReadonlyMap<string, Entry>;
290
+
291
+ /** A refusal of the check. The check throws it, and `sizeError` gives its message. */
292
+ class Refusal {
293
+ readonly message: string;
294
+ constructor(message: string) {
295
+ this.message = message;
296
+ }
297
+ }
298
+
299
+ /** The literal number of an argument, if the argument is a literal number. */
300
+ const literalNumber = (e: Expr | undefined): number | undefined => (e?.tag === "lit" && typeof e.value === "number" ? e.value : undefined);
301
+
302
+ /** The tag of the values of a domain: its primitive kind, or its name. */
303
+ const tagOf = (d: AnyDomain): string => d.primitive ?? `d:${d.name}`;
304
+
305
+ /** This function tells if a domain accepts a value with a tag: surely, maybe or no. `undefined` is each tag. */
306
+ function accepts(d: AnyDomain, tag: string | undefined): "sure" | "maybe" | "no" {
307
+ if (tag === undefined) return "maybe";
308
+ if (tag === tagOf(d)) return "sure";
309
+ // KIND.PRIMITIVE: a domain with a primitive kind accepts each value of that type and no other value.
310
+ if (d.primitive !== undefined) return tag.startsWith("d:") ? "maybe" : "no";
311
+ return "maybe";
312
+ }
313
+
314
+ /** The number of the nodes that the check reads with the kinds of the names of the loops, before it uses each kind. */
315
+ const BUDGET = 50_000;
316
+
317
+ /** The check of one program. It keeps the shape of each node, to name the op of a refusal. */
318
+ class Checker {
319
+ readonly #domains: readonly AnyDomain[];
320
+ readonly #fns: Readonly<Record<string, unknown>> | undefined;
321
+ readonly #shapes = new Map<Expr, Shape>();
322
+ readonly #open = new Map<Expr, boolean>();
323
+ /** With `true`, the check keeps the largest part as a measure and reads the rules `byParts` (LOOP.SIZE.READINGS). */
324
+ readonly #parts: boolean;
325
+ #next = 0;
326
+ #visits = 0;
327
+
328
+ constructor(opts: SizeOptions, parts: boolean) {
329
+ this.#domains = opts.domains ?? [];
330
+ this.#fns = opts.fns;
331
+ this.#parts = parts;
332
+ }
333
+
334
+ shape(e: Expr, env: Env): Shape {
335
+ this.#visits++;
336
+ const found = this.#shape(e, env);
337
+ // The first reading has no measure under the largest item, so the largest part of a value is its largest item.
338
+ const s = this.#parts ? found : { ...found, part: found.item };
339
+ this.#shapes.set(e, s);
340
+ return s;
341
+ }
342
+
343
+ #fresh(): number {
344
+ return this.#next++;
345
+ }
346
+
347
+ #shape(e: Expr, env: Env): Shape {
348
+ switch (e.tag) {
349
+ case "lit":
350
+ return this.#literal(e.value);
351
+ case "ref":
352
+ for (const x of addrExprs(e.at)) this.shape(x, env);
353
+ return fixed(ANY);
354
+ case "var": {
355
+ const entry = env.get(e.name);
356
+ // A free name is a variable of the caller, so its value does not change in a loop. A function is not a value.
357
+ return entry === undefined ? fixed(ANY) : entry.t === "value" ? entry.shape : zero(NO_KIND);
358
+ }
359
+ case "ext":
360
+ return fixed(ANY);
361
+ case "rec": {
362
+ const fields = Object.values(e.fields).map((x) => this.shape(x, env));
363
+ const size = fields.reduce((acc, x) => plus(acc, x.size), SOME);
364
+ // LOOP.SIZE.PART: the items of a record are its fields, so one field gives the largest item.
365
+ const item = fields.reduce((acc, x) => join(acc, x.size), NONE);
366
+ const part = fields.reduce((acc, x) => join(acc, x.item), NONE);
367
+ return { ...fixed(kindOf("object")), size, item, part, long: fields.some((x) => x.long) };
368
+ }
369
+ case "let":
370
+ return this.#let(e, env);
371
+ case "call":
372
+ return this.#call(e, env);
373
+ case "app":
374
+ return this.#app(e, env);
375
+ case "each":
376
+ return this.#each(e, env);
377
+ case "fold":
378
+ case "iterate":
379
+ return this.#loop(e, env);
380
+ case "fix":
381
+ // A column gives a boolean or a number, so a list of the program cannot grow through it.
382
+ this.shape(e.init, env);
383
+ this.shape(e.step, env);
384
+ return zero(kindOfJoin(e.join) === "boolean" ? BOOLEAN : NUMBER);
385
+ case "last":
386
+ return zero(SCALAR);
387
+ case "fn":
388
+ return zero(NO_KIND);
389
+ }
390
+ }
391
+
392
+ /** This method gives the shape of a literal value: a constant, and its kind. */
393
+ #literal(value: unknown): Shape {
394
+ if (typeof value === "number") return zero(NUMBER);
395
+ if (typeof value === "boolean") return zero(BOOLEAN);
396
+ if (value === null || value === undefined) return zero(kindOf("null"));
397
+ if (typeof value === "string") {
398
+ const length = constant(value.length);
399
+ return { ...zero(STRING), size: length, item: length, part: length };
400
+ }
401
+ if (isVexList(value)) {
402
+ const item = value.items.reduce((k, it) => (it.result.ok ? joinKind(k, this.#literal(it.result.value).kind) : k), NO_KIND);
403
+ return { ...fixed(listKind(item)), count: constant(value.items.length) };
404
+ }
405
+ if (Array.isArray(value))
406
+ return {
407
+ ...fixed(
408
+ listKind(
409
+ value.reduce((k: Kind, x: unknown) => joinKind(k, this.#literal(x).kind), NO_KIND),
410
+ "array",
411
+ ),
412
+ ),
413
+ count: constant(value.length),
414
+ };
415
+ const d = this.#domains.find((x) => {
416
+ try {
417
+ return x.is(value);
418
+ } catch {
419
+ return false;
420
+ }
421
+ });
422
+ return fixed(d === undefined ? kindOf("object") : kindOf(tagOf(d)));
423
+ }
424
+
425
+ #let(e: ExprOf<"let">, env: Env): Shape {
426
+ const inner = new Map(env);
427
+ // FN.TOTAL: a binding does not see the other bindings of its let.
428
+ for (const [name, b] of Object.entries(e.bind)) {
429
+ if (b.tag === "fn") {
430
+ // FN.CALL: the check reads the body one time, with a variable for each parameter. A call puts the shapes of
431
+ // its arguments in the place of the variables.
432
+ const params = b.params.map((p) => [p, this.#fresh()] as const);
433
+ const fenv = new Map(env);
434
+ for (const [p, id] of params) fenv.set(p, { t: "value", shape: shapeOfVar(id, ANY, true) });
435
+ inner.set(name, { t: "fn", params: params.map(([, id]) => id), result: this.shape(b.body, fenv) });
436
+ } else inner.set(name, { t: "value", shape: this.shape(b, env) });
437
+ }
438
+ return this.shape(e.body, inner);
439
+ }
440
+
441
+ #call(e: ExprOf<"call">, env: Env): Shape {
442
+ const args = e.args.map((a) => this.shape(a, env));
443
+ const entry = env.get(e.fn);
444
+ // FN.ARGS: a call of a value, of a missing name or with another number of arguments gives an error.
445
+ if (entry?.t !== "fn" || entry.params.length !== args.length) return zero(NO_KIND);
446
+ const bindings = new Map<string, Form>();
447
+ entry.params.forEach((id, i) => {
448
+ for (const m of MEASURES) bindings.set(variable(m, id), (args[i] as Shape)[m]);
449
+ });
450
+ const sigma = (v: string): Form | undefined => bindings.get(v);
451
+ return { ...substShape(entry.result, sigma), long: entry.result.long || args.some((a) => a.long) };
452
+ }
453
+
454
+ #app(e: ExprOf<"app">, env: Env): Shape {
455
+ const args = e.args.map((a) => this.shape(a, env));
456
+ switch (e.op) {
457
+ case "if":
458
+ case "ifError": {
459
+ // FORM.IF: the test does not add to the size. A missing argument gives an error, which has no size.
460
+ const outs = e.op === "if" ? args.slice(1, 3) : args.slice(0, 2);
461
+ const [head = zero(NO_KIND), ...rest] = outs;
462
+ return rest.reduce(joinShape, head);
463
+ }
464
+ case "and":
465
+ case "or":
466
+ return zero(BOOLEAN);
467
+ }
468
+ const { op } = e;
469
+ const outs: Shape[] = [];
470
+ let open = false;
471
+ const listOp = isListOp(op) ? op : undefined;
472
+ const fn = this.#fns !== undefined && Object.hasOwn(this.#fns, op) ? this.#fns[op] : undefined;
473
+ const byFn = (): void => {
474
+ const host = fn as { readonly size?: SizeRule; readonly returns?: ReturnKind };
475
+ if (host.size === undefined) open = true;
476
+ else outs.push(this.#apply(host.size, args, e.args, kindOfReturn(host.returns, undefined, this.#domains)));
477
+ };
478
+ const self = args[0]?.kind;
479
+ // The order of the interpreter: a list op on a list, the domains in order, a function of the host, a list op on an
480
+ // array (LIST.ARRAY), and fill.
481
+ const tags = self === undefined ? [] : self.tags === undefined ? [undefined] : [...self.tags];
482
+ for (const tag of tags) {
483
+ if (listOp !== undefined && (tag === undefined || tag === "list")) {
484
+ outs.push(this.#list(listOp, args, e.args));
485
+ if (tag === "list") continue;
486
+ }
487
+ const d = this.#domain(op, tag, args, e.args, outs);
488
+ open ||= d.open;
489
+ if (d.done) continue;
490
+ if (fn !== undefined) byFn();
491
+ else if (listOp !== undefined && (tag === undefined || tag === "array")) outs.push(this.#list(listOp, args, e.args));
492
+ else if (op === "fill") outs.push(this.#list("fill", args, e.args));
493
+ }
494
+ if (self === undefined && fn !== undefined) byFn();
495
+ // LOOP.SIZE.OPS: an op without a size rule has no bound (fail closed).
496
+ if (open) outs.push(unbounded(args));
497
+ this.#open.set(e, open);
498
+ // An op that no domain and no function has gives an error, and an error has no size.
499
+ return outs.slice(1).reduce(joinShape, outs[0] ?? zero(NO_KIND));
500
+ }
501
+
502
+ /**
503
+ * This method adds the shapes of the ops of the domains that can take a receiver with the tag. It gives `true` for an
504
+ * op without a size rule. A domain that surely takes the receiver and has a function for the op is the last domain,
505
+ * and then `done` is `true`.
506
+ */
507
+ #domain(
508
+ op: string,
509
+ tag: string | undefined,
510
+ args: readonly Shape[],
511
+ exprs: readonly Expr[],
512
+ outs: Shape[],
513
+ ): { readonly open: boolean; readonly done: boolean } {
514
+ if (!isOpName(op)) return { open: false, done: false };
515
+ let open = false;
516
+ for (const d of this.#domains) {
517
+ const a = accepts(d, tag);
518
+ if (a === "no") continue;
519
+ const spec = Object.hasOwn(d.ops, op) ? (d.ops[op] as OpSpec<unknown>) : undefined;
520
+ // A method needs an object: a number, a text, a boolean and null have no methods (findMethod).
521
+ const method = (spec !== undefined || d.methods === "all") && (tag === undefined || !PRIMITIVES.has(tag));
522
+ if (spec?.fn === undefined && !method) continue;
523
+ const rule = spec === undefined ? undefined : ruleOf(d, spec, this.#domains);
524
+ if (rule === undefined) open = true;
525
+ else outs.push(this.#apply(rule, args, exprs, kindOfReturn(spec?.returns, d, this.#domains)));
526
+ if (a === "sure" && spec?.fn !== undefined) return { open, done: true };
527
+ }
528
+ return { open, done: false };
529
+ }
530
+
531
+ /** This method gives the shape of a list op, and the kind of its result. */
532
+ #list(op: ListOp | "fill", args: readonly Shape[], exprs: readonly Expr[]): Shape {
533
+ // The receiver selects a list op, so the op has a first argument.
534
+ const item = itemOf((args[0] as Shape).kind);
535
+ const s = this.#apply(LIST_SIZES[op], args, exprs, listResult(op, item, args));
536
+ return op === "group" ? { ...s, long: true } : s;
537
+ }
538
+
539
+ #apply(rule: SizeRule, args: readonly Shape[], exprs: readonly Expr[], kind: Kind): Shape {
540
+ // The rule "scalar" tells that the result is a number or a boolean.
541
+ if (rule === "scalar") return zero(kind.tags === undefined ? SCALAR : kind);
542
+ if (rule === "fixed") return fixed(kind);
543
+ if (rule === "reduce") return { ...this.#reduce(args, exprs), kind };
544
+ const limit = rule.limit === undefined ? undefined : literalNumber(exprs[rule.limit]);
545
+ // LOOP.SIZE.PART: a rule with a limit gives a bound for each item, so it needs a literal limit and short keys.
546
+ const open = rule.limit !== undefined && (limit === undefined || args.some((a) => a.long));
547
+ const r = this.#parts && !open ? (rule.byParts ?? rule) : rule;
548
+ const sum = (terms: readonly SizeTerm[], own: SizeMeasure): Form =>
549
+ args.reduce((acc, a, i) => {
550
+ const t = terms[i] ?? r.rest ?? "many";
551
+ const [use, of] = typeof t === "object" ? t : [t, own];
552
+ const f = useForm(use, i, a[of], args, exprs, limit);
553
+ // The largest item of the result is an item of one argument, so the arguments give the largest bound.
554
+ if (own === "item" || own === "part") return join(acc, f);
555
+ return r.union === true ? union(acc, f) : plus(acc, f);
556
+ }, NONE);
557
+ let size = sum(r.size, "size");
558
+ let count = r.count === undefined ? size : sum(r.count, "count");
559
+ const inner = r.inner === undefined ? size : sum(r.inner, "inner");
560
+ if (limit !== undefined) count = constant(limit);
561
+ if (r.constant === true) {
562
+ size = plus(size, SOME);
563
+ count = plus(count, SOME);
564
+ }
565
+ if (r.keys === "position") size = plus(size, times(count, SOME));
566
+ const item = r.item === undefined ? size : sum(r.item, "item");
567
+ const part = r.part === undefined ? item : sum(r.part, "part");
568
+ return { size, count, inner, item, part, kind, long: args.some((a) => a.long) };
569
+ }
570
+
571
+ /** The rule of `reduce`: the op that the second argument names folds the values of the list (LIST.REDUCE). */
572
+ #reduce(args: readonly Shape[], exprs: readonly Expr[]): Shape {
573
+ const list = args[0] as Shape;
574
+ const name = exprs[1]?.tag === "lit" ? exprs[1].value : undefined;
575
+ if (typeof name !== "string" || !isOpName(name)) return unbounded([list]);
576
+ // The empty list gives the identity of the op: a constant.
577
+ let out: Shape = fixed(ANY);
578
+ for (const d of this.#domains) {
579
+ if (!Object.hasOwn(d.ops, name)) {
580
+ if (d.methods === "all") return unbounded([list]);
581
+ continue;
582
+ }
583
+ const rule = ruleOf(d, d.ops[name] as OpSpec<unknown>, this.#domains);
584
+ if (rule === undefined || rule === "reduce") return unbounded([list]);
585
+ if (rule === "scalar" || rule === "fixed") continue;
586
+ const use = (i: number): 0 | Coef => {
587
+ const t = rule.size[i] ?? rule.rest ?? "many";
588
+ return coefOf(typeof t === "object" ? t[0] : t);
589
+ };
590
+ // The first argument is the result of the steps before. More than one use of it doubles at each value.
591
+ const first = use(0);
592
+ if (first > 1) return unbounded([list]);
593
+ // A union holds each key one time, so the result is not larger than the list.
594
+ const k = rule.union === true ? 1 : (Math.max(1, use(1)) as Coef);
595
+ const size = rule.constant === true ? plus(scale(list.size, k), SOME) : scale(list.size, k);
596
+ out = joinShape(out, {
597
+ size,
598
+ count: size,
599
+ inner: size,
600
+ item: size,
601
+ part: size,
602
+ kind: ANY,
603
+ long: list.long,
604
+ });
605
+ }
606
+ return out;
607
+ }
608
+
609
+ #each(e: ExprOf<"each">, env: Env): Shape {
610
+ const list = this.#axis(e.axis, e.at, env);
611
+ if (list === undefined) {
612
+ const body = this.shape(e.body, bindItem(env, e.as, fixed(ANY)));
613
+ // A fixed number of targets: the records of the space.
614
+ return {
615
+ size: plus(SOME, times(body.size, SOME)),
616
+ count: SOME,
617
+ inner: times(body.count, SOME),
618
+ item: body.size,
619
+ part: body.item,
620
+ kind: listKind(body.kind),
621
+ long: body.long,
622
+ };
623
+ }
624
+ const id = this.#fresh();
625
+ const body = this.shape(e.body, bindItem(env, e.as, shapeOfVar(id, itemOf(list.kind), list.long)));
626
+ const vars = new Map(MEASURES.map((m) => [variable(m, id), m]));
627
+ // The sum over the items of a bound of the body: a use of the item adds the measures of the list.
628
+ const over = (f: Form, keys: boolean): Form => {
629
+ // Each item can take another sum of the bound, so the sum over the items uses one sum that covers each sum.
630
+ const { rest, dropped } = split(cover(f), (v) => vars.has(v));
631
+ const c = (m: SizeMeasure): 0 | Coef => dropped.get(variable(m, id)) ?? 0;
632
+ // The inner count, the largest item and the largest part of an item are not larger than its size.
633
+ const uses = [c("size"), c("inner"), c("item"), c("part")].filter((x) => x > 0);
634
+ const sizes = uses.length === 0 ? 0 : uses.length === 1 ? (uses[0] as Coef) : 3;
635
+ // The items keep the keys of the list. A key with a fixed bound adds a constant for each item, and a long key is a
636
+ // part of the size of the list.
637
+ const whole = scale(list.size, keys && list.long ? (Math.max(1, sizes) as Coef) : sizes);
638
+ // LOOP.SIZE.PART: more than one use of each item has the bound of the count of the items times the largest item.
639
+ const values = this.#parts && sizes > 1 && !(keys && list.long) ? scale(times(c("size") > 0 || c("inner") > 0 ? list.item : list.part, list.count), sizes) : whole;
640
+ const short = keys && !list.long ? times(list.count, SOME) : NONE;
641
+ return plus(plus(plus(values, short), scale(list.inner, c("count"))), times([rest], list.count));
642
+ };
643
+ // The largest item of the result is the value of the body for one item of the list.
644
+ const one = itemMeasures(list);
645
+ const sigma = (v: string): Form | undefined => {
646
+ const m = vars.get(v);
647
+ return m === undefined ? undefined : one[m];
648
+ };
649
+ return {
650
+ size: over(body.size, true),
651
+ count: list.count,
652
+ inner: over(body.count, false),
653
+ item: subst(body.size, sigma),
654
+ part: subst(body.item, sigma),
655
+ kind: listKind(body.kind),
656
+ long: list.long || body.long,
657
+ };
658
+ }
659
+
660
+ /** This method checks the parts of an axis and of an address. It gives the shape of the list of the axis `list`. */
661
+ #axis(axis: Axis, at: ExprOf<"each">["at"], env: Env): Shape | undefined {
662
+ const list = listOf(axis);
663
+ const shape = list === undefined ? undefined : this.shape(list, env);
664
+ // The tests of `where` and the address do not add to the size.
665
+ for (let x = axis; x.t === "where" || x.t === "reverse"; x = x.axis) if (x.t === "where") this.shape(x.test, env);
666
+ for (const x of addrExprs(at)) this.shape(x, env);
667
+ return shape;
668
+ }
669
+
670
+ #loop(e: ExprOf<"fold"> | ExprOf<"iterate">, env: Env): Shape {
671
+ const list = e.tag === "fold" ? this.#axis(e.axis, e.at, env) : undefined;
672
+ // ITERATE.LIMIT.DATA: a data limit has the bound of a fold over its axis, and the steps of iterate have no item.
673
+ const axis = e.tag === "iterate" ? limitAxis(e) : undefined;
674
+ const sized = axis === undefined ? undefined : this.#axis(axis, undefined, env);
675
+ const names = Object.keys(e.init);
676
+ const init = new Map(names.map((n) => [n, this.shape(e.init[n] as Expr, env)]));
677
+ const ids = new Map(names.map((n) => [n, this.#fresh()]));
678
+ const stepped = Object.keys(e.step);
679
+ // AXIS.LIST.ITEM: the item of a fold over a list is the value of one item of the list.
680
+ const item: Shape =
681
+ list === undefined
682
+ ? fixed(ANY)
683
+ : { ...itemMeasures(list), kind: itemOf(list.kind), long: list.long };
684
+ // The kinds of the names. The first step reads the values of init. The other steps read the values of the steps: the
685
+ // kinds of the first step, then also the kinds of the next steps, then each kind. A large program uses each kind
686
+ // at once, for each step.
687
+ type Assumed = { readonly kind: Kind; readonly long: boolean };
688
+ const each: Assumed = { kind: ANY, long: true };
689
+ const start = (n: string): Shape => init.get(n) as Shape;
690
+ const fromInit = (n: string): Assumed => ({ kind: start(n).kind, long: start(n).long });
691
+ const always = (): Map<string, Assumed> => new Map(names.map((n) => [n, stepped.includes(n) ? each : fromInit(n)]));
692
+ const run = (assumed: ReadonlyMap<string, Assumed>): { readonly senv: Env; readonly steps: Map<string, Shape> } => {
693
+ const senv = new Map(env);
694
+ for (const n of names) {
695
+ const a = assumed.get(n) as Assumed;
696
+ senv.set(n, { t: "value", shape: shapeOfVar(ids.get(n) as number, a.kind, a.long) });
697
+ }
698
+ const ienv = e.tag === "fold" ? bindItem(senv, e.as, item) : senv;
699
+ return { senv, steps: new Map(stepped.map((n) => [n, this.shape(e.step[n] as Expr, ienv)])) };
700
+ };
701
+ let first: ReadonlyMap<string, Shape> | undefined;
702
+ let assumed: Map<string, Assumed>;
703
+ if (stepped.length > 0 && this.#visits < BUDGET) {
704
+ first = run(new Map(names.map((n) => [n, fromInit(n)]))).steps;
705
+ assumed = new Map(
706
+ names.map((n): [string, Assumed] => {
707
+ const s = first?.get(n);
708
+ return [n, s === undefined ? fromInit(n) : { kind: s.kind, long: s.long }];
709
+ }),
710
+ );
711
+ } else assumed = always();
712
+ let senv: Env;
713
+ let steps: Map<string, Shape>;
714
+ for (let pass = 0; ; pass++) {
715
+ ({ senv, steps } = run(assumed));
716
+ const next = new Map(
717
+ names.map((n): [string, Assumed] => {
718
+ const a = assumed.get(n) as Assumed;
719
+ const s = steps.get(n);
720
+ return [n, s === undefined ? a : { kind: joinKind(a.kind, s.kind), long: a.long || s.long }];
721
+ }),
722
+ );
723
+ const stable = names.every((n) => {
724
+ const a = assumed.get(n) as Assumed;
725
+ const b = next.get(n) as Assumed;
726
+ return within(b.kind, a.kind) && (a.long || !b.long);
727
+ });
728
+ if (stable) break;
729
+ // The second reading keeps the keys that the steps can give: `take` needs them (LOOP.SIZE.PART). Each pass after the
730
+ // first pass only changes the keys from short to long, so the loop ends.
731
+ assumed = pass === 0 && this.#visits < BUDGET ? next : this.#parts ? new Map(names.map((n): [string, Assumed] => {
732
+ const b = next.get(n) as Assumed;
733
+ return [n, stepped.includes(n) ? { kind: ANY, long: b.long } : b];
734
+ })) : always();
735
+ }
736
+ if (e.tag === "iterate" && e.until !== undefined) this.shape(e.until, senv);
737
+ const loop = new Loop(e, names, ids, steps);
738
+ // LOOP.SIZE: the rule applies to the steps after the first step. One step can multiply the values one time.
739
+ loop.check(this.#shapes, this.#open);
740
+ // The values after the first step: the first step reads the values of init.
741
+ const sigma = (v: string): Form | undefined => {
742
+ for (const n of names) {
743
+ const id = ids.get(n) as number;
744
+ const m = MEASURES.find((x) => variable(x, id) === v);
745
+ if (m !== undefined) return start(n)[m];
746
+ }
747
+ return undefined;
748
+ };
749
+ const starts = new Map(
750
+ names.map((n): [string, Shape] => {
751
+ const a = start(n);
752
+ const s = first?.get(n);
753
+ if (s === undefined) return [n, a];
754
+ return [n, joinShape(a, substShape(s, sigma))];
755
+ }),
756
+ );
757
+ const last = loop.last(starts, list?.count ?? sized?.count ?? (e.tag === "iterate" && typeof e.limit === "number" ? constant(e.limit) : SOME));
758
+ const renv = new Map(env);
759
+ for (const n of names) {
760
+ const a = assumed.get(n) as Assumed;
761
+ const s = last.get(n) as Shape;
762
+ const i = start(n);
763
+ // With no step, the result reads the values of init.
764
+ renv.set(n, { t: "value", shape: stepped.includes(n) ? { ...s, kind: joinKind(i.kind, a.kind), long: i.long || a.long } : i });
765
+ }
766
+ return this.shape(e.result, renv);
767
+ }
768
+ }
769
+
770
+ /** 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). */
771
+ function kindOfReturn(r: ReturnKind | undefined, d: AnyDomain | undefined, domains: readonly AnyDomain[]): Kind {
772
+ if (r === "number" || r === "boolean" || r === "string") return kindOf(r);
773
+ if (r === "domain") return d === undefined ? ANY : kindOf(tagOf(d));
774
+ if (r?.startsWith("domain:") === true) {
775
+ const target = domains.find((x) => x.name === r.slice("domain:".length));
776
+ return target === undefined ? ANY : kindOf(tagOf(target));
777
+ }
778
+ const item = listItemKind(r);
779
+ return item === undefined ? ANY : listKind(kindOf(item));
780
+ }
781
+
782
+ /** This function gives the kind of the result of a list op. `item` is the kind of the items of the receiver. */
783
+ function listResult(op: ListOp | "fill", item: Kind, args: readonly Shape[]): Kind {
784
+ switch (op) {
785
+ case "count":
786
+ case "sum":
787
+ case "mean":
788
+ case "min":
789
+ case "max":
790
+ case "indexOf":
791
+ return NUMBER;
792
+ case "any":
793
+ case "all":
794
+ case "none":
795
+ return BOOLEAN;
796
+ case "join":
797
+ return STRING;
798
+ case "values":
799
+ return listKind(item, "array");
800
+ case "keys":
801
+ return listKind(STRING, "array");
802
+ case "first":
803
+ case "nth":
804
+ case "get":
805
+ return item;
806
+ case "sortBy":
807
+ case "take":
808
+ case "drop":
809
+ case "without":
810
+ case "distinct":
811
+ return listKind(item);
812
+ case "append":
813
+ return listKind(joinKind(item, itemOf(args[1]?.kind ?? ANY)));
814
+ case "setNth":
815
+ return listKind(joinKind(item, args[2]?.kind ?? ANY));
816
+ case "flat":
817
+ return listKind(itemOf(item));
818
+ case "group":
819
+ return listKind(listKind(item));
820
+ case "fill":
821
+ return listKind(args[1]?.kind ?? ANY);
822
+ case "errors":
823
+ case "reduce":
824
+ return ANY;
825
+ }
826
+ }
827
+
828
+ /** This function binds the names `as` of a loop: the item gets `item`, and the index is a number. */
829
+ function bindItem(env: Env, as: ItemNames | undefined, item: Shape): Env {
830
+ if (as === undefined) return env;
831
+ const out = new Map(env);
832
+ out.set(as[0], { t: "value", shape: item });
833
+ if (as[1] !== undefined) out.set(as[1], { t: "value", shape: zero(NUMBER) });
834
+ return out;
835
+ }
836
+
837
+ /** The shape of the result of an op without a size rule: no bound in the sizes of its arguments. */
838
+ function unbounded(args: readonly Shape[]): Shape {
839
+ const f = scale(
840
+ args.reduce((acc, a) => plus(acc, a.size), SOME),
841
+ 4,
842
+ );
843
+ return { size: f, count: f, inner: f, item: f, part: f, kind: ANY, long: true };
844
+ }
845
+
846
+ /** The measures of one item of a list. The largest item of the list bounds its size, and the largest part bounds the rest. */
847
+ const itemMeasures = (list: Shape): Readonly<Record<SizeMeasure, Form>> => ({ size: list.item, count: list.item, inner: list.item, item: list.part, part: list.part });
848
+
849
+ /** This function gives the bound of one use of an argument. */
850
+ function useForm(use: SizeUse, i: number, form: Form, args: readonly Shape[], exprs: readonly Expr[], limit: number | undefined): Form {
851
+ switch (use) {
852
+ case "text":
853
+ return isText(args[i]?.kind) ? form : scale(form, 2);
854
+ case "copies": {
855
+ const n = literalNumber(exprs[0]);
856
+ return n === 0 ? NONE : n === 1 ? form : scale(form, 2);
857
+ }
858
+ case "each":
859
+ return times(form, (args[0] as Shape).count);
860
+ case "number":
861
+ // LIST.FILL: a count has the bound 100000.
862
+ return constant(Math.min(100_000, literalNumber(exprs[i]) ?? Infinity));
863
+ case "limit":
864
+ // LOOP.SIZE.PART: each item that the limit keeps has a key with a fixed bound and a value.
865
+ return limit === undefined ? scale(form, 3) : times(plus(form, SOME), constant(limit));
866
+ case 0:
867
+ case 1:
868
+ case "scaled":
869
+ case "many":
870
+ case "unbounded":
871
+ return scale(form, coefOf(use));
872
+ }
873
+ }
874
+
875
+ /** This function tells if a domain holds numbers or booleans. */
876
+ function scalar(x: AnyDomain | undefined): boolean {
877
+ return x?.primitive === "number" || x?.primitive === "boolean";
878
+ }
879
+
880
+ /**
881
+ * 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
882
+ * from its result kind and from the domain. The function gives `undefined` for an op without a rule.
883
+ */
884
+ export function ruleOf(d: AnyDomain, spec: OpSpec<unknown>, domains: readonly AnyDomain[]): SizeRule | undefined {
885
+ if (spec.size !== undefined) return spec.size;
886
+ const r = spec.returns;
887
+ if (r === "number" || r === "boolean" || (r === "domain" && scalar(d))) return "scalar";
888
+ if (d.size === "fixed") return "fixed";
889
+ if (r?.startsWith("domain:") === true) {
890
+ const target = domains.find((x) => x.name === r.slice("domain:".length));
891
+ if (scalar(target)) return "scalar";
892
+ if (target?.size === "fixed") return "fixed";
893
+ }
894
+ return undefined;
895
+ }
896
+
897
+ /** The terms of a sum that read a variable of a cycle. */
898
+ const inside = (s: Sum, cycle: ReadonlySet<string>): readonly (readonly [string, Coef])[] => [...s.terms].filter(([u]) => cycle.has(u));
899
+
900
+ /** This function tells if a sum of a bound reads its cycle more than one time, or with a coefficient other than 1. */
901
+ const loose = (f: Form, cycle: ReadonlySet<string>): boolean =>
902
+ f.some((s) => {
903
+ const terms = inside(s, cycle);
904
+ return terms.length > 1 || terms.some(([, c]) => c !== 1);
905
+ });
906
+
907
+ /** The variable of a measure of a name of a loop. */
908
+ interface Owner {
909
+ readonly name: string;
910
+ readonly measure: SizeMeasure;
911
+ }
912
+
913
+ /** The words of a measure in a message. */
914
+ const WORDS: Readonly<Record<SizeMeasure, string>> = {
915
+ size: "size",
916
+ count: "number of items",
917
+ inner: "number of inner items",
918
+ item: "largest item",
919
+ part: "largest part",
920
+ };
921
+
922
+ /** This function gives the label of the node of a refusal: an op, a function, a name or a node. */
923
+ function label(e: Expr): string {
924
+ switch (e.tag) {
925
+ case "app":
926
+ return `the op "${e.op}"`;
927
+ case "call":
928
+ return `the function "${e.fn}"`;
929
+ case "var":
930
+ return `the name "${e.name}"`;
931
+ case "each":
932
+ case "ext":
933
+ case "fn":
934
+ case "fix":
935
+ case "fold":
936
+ case "iterate":
937
+ case "last":
938
+ case "let":
939
+ case "lit":
940
+ case "rec":
941
+ case "ref":
942
+ return `a node "${e.tag}"`;
943
+ }
944
+ }
945
+
946
+ /** The names of one loop, their steps, and the rule of LOOP.SIZE. */
947
+ class Loop {
948
+ readonly #owners = new Map<string, Owner>();
949
+ /** The cycle of each variable: the variables that its new value reads, and that read it in turn. */
950
+ readonly #cycles = new Map<string, ReadonlySet<string>>();
951
+
952
+ readonly node: ExprOf<"fold"> | ExprOf<"iterate">;
953
+ readonly names: readonly string[];
954
+ readonly steps: ReadonlyMap<string, Shape>;
955
+
956
+ // Node.js starts the speed gate from this source with the types removed, so the class has no parameter properties.
957
+ constructor(node: ExprOf<"fold"> | ExprOf<"iterate">, names: readonly string[], ids: ReadonlyMap<string, number>, steps: ReadonlyMap<string, Shape>) {
958
+ this.node = node;
959
+ this.names = names;
960
+ this.steps = steps;
961
+ for (const name of names)
962
+ for (const measure of MEASURES)
963
+ this.#owners.set(variable(measure, ids.get(name) as number), {
964
+ name,
965
+ measure,
966
+ });
967
+ }
968
+
969
+ /**
970
+ * 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
971
+ * reads its cycle at most one time, with the coefficient 1. A name without a step keeps its value.
972
+ */
973
+ check(shapes: ReadonlyMap<Expr, Shape>, open: ReadonlyMap<Expr, boolean>): void {
974
+ // The graph of the measures: an edge from each variable of a bound of a step to the measure of its name.
975
+ const into = new Map<string, Form>();
976
+ const out = new Map<string, string[]>();
977
+ for (const [v, o] of this.#owners) {
978
+ const form = this.steps.get(o.name)?.[o.measure] ?? term(v, 1);
979
+ into.set(v, form);
980
+ for (const u of new Set(form.flatMap((s) => [...s.terms.keys()]))) if (this.#owners.has(u)) out.set(u, [...(out.get(u) ?? []), v]);
981
+ }
982
+ const reach = (from: string): ReadonlySet<string> => {
983
+ const seen = new Set<string>();
984
+ const todo = [from];
985
+ for (let x = todo.pop(); x !== undefined; x = todo.pop()) {
986
+ for (const y of out.get(x) ?? []) {
987
+ if (seen.has(y)) continue;
988
+ seen.add(y);
989
+ todo.push(y);
990
+ }
991
+ }
992
+ return seen;
993
+ };
994
+ const reached = new Map([...this.#owners.keys()].map((v): [string, ReadonlySet<string>] => [v, reach(v)]));
995
+ for (const [v, form] of into) {
996
+ const cycle = new Set([...(reached.get(v) as ReadonlySet<string>)].filter((u) => (reached.get(u) as ReadonlySet<string>).has(v)));
997
+ this.#cycles.set(v, cycle);
998
+ if (!loose(form, cycle)) continue;
999
+ const o = this.#owners.get(v) as Owner;
1000
+ const twice = form.some((s) => {
1001
+ const terms = inside(s, cycle);
1002
+ return terms.length > 1 || terms.some(([, c]) => c > 2);
1003
+ });
1004
+ const what = twice
1005
+ ? `a value that uses the lists of the loop more than one time in its ${WORDS[o.measure]}`
1006
+ : `a ${WORDS[o.measure]} that can grow by a factor at each step`;
1007
+ this.#refuse(o.name, (s) => loose(s[o.measure], cycle), what, shapes, open);
1008
+ }
1009
+ }
1010
+
1011
+ #refuse(name: string, bad: (s: Shape) => boolean, what: string, shapes: ReadonlyMap<Expr, Shape>, open: ReadonlyMap<Expr, boolean>): never {
1012
+ // The node of the refusal: the deepest node on a path of bad nodes from the step.
1013
+ const worse = (at: Expr): Expr | undefined =>
1014
+ children(at).find((k) => {
1015
+ const s = shapes.get(k);
1016
+ return s !== undefined && bad(s);
1017
+ });
1018
+ let at = this.node.step[name] as Expr;
1019
+ for (let next = worse(at); next !== undefined; next = worse(at)) at = next;
1020
+ const source = findOpen(at, open);
1021
+ const head = `the expression has a node "${this.node.tag}" whose step gives the name "${name}" ${what}, at ${label(source ?? at)} (LOOP.SIZE)`;
1022
+ throw new Refusal(source === undefined ? head : `${head}. The op "${source.op}" has no size rule (LOOP.SIZE.OPS)`);
1023
+ }
1024
+
1025
+ /**
1026
+ * This method gives a bound of the last value of each name, from the values of `init` and the steps. The number of the
1027
+ * 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
1028
+ * measure of the cycle adds its other parts one time for each step. A sum without such a measure sets the value again,
1029
+ * so it adds to the bound one time (LOOP.SIZE.BRANCH). The last value starts from the largest first value of the cycle
1030
+ * 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
1031
+ * value or the value of its step.
1032
+ */
1033
+ last(init: ReadonlyMap<string, Shape>, steps: Form): ReadonlyMap<string, Shape> {
1034
+ const first = (v: string): Form => {
1035
+ const o = this.#owners.get(v) as Owner;
1036
+ return (init.get(o.name) as Shape)[o.measure];
1037
+ };
1038
+ const bounds = new Map([...this.#owners.keys()].map((v) => [v, first(v)]));
1039
+ const sigma = (v: string): Form | undefined => bounds.get(v);
1040
+ // Each pass makes the bounds larger, and the bounds have a finite number of values, so the loop ends. A constant
1041
+ // that is new in a bound becomes a constant without a known value.
1042
+ const widen = (old: Form, more: Form): Form => bound(join(old, more).map((s) => (s.base === 0 || old.some((o) => o.base === s.base) ? s : { base: Infinity, terms: s.terms })));
1043
+ const stepOf = (v: string): Form | undefined => {
1044
+ const o = this.#owners.get(v) as Owner;
1045
+ return this.steps.get(o.name)?.[o.measure];
1046
+ };
1047
+ for (let changed = true; changed;) {
1048
+ changed = false;
1049
+ for (const [v, old] of bounds) {
1050
+ const step = stepOf(v);
1051
+ if (step === undefined) continue;
1052
+ const cycle = this.#cycles.get(v) as ReadonlySet<string>;
1053
+ let next: Form;
1054
+ if (cycle.has(v)) {
1055
+ const members = [...cycle];
1056
+ const start = members.reduce((acc, u) => join(acc, first(u)), NONE);
1057
+ const sums = members.flatMap((u) => (stepOf(u) as Form).map((x) => split(x, (y) => cycle.has(y))));
1058
+ const sets = subst(bound(sums.filter((x) => x.dropped.size === 0).map((x) => x.rest)), sigma);
1059
+ const adds = subst(bound(sums.filter((x) => x.dropped.size > 0).map((x) => x.rest)), sigma);
1060
+ next = plus(join(start, sets), times(adds, steps));
1061
+ } else next = join(first(v), subst(step, sigma));
1062
+ const wide = widen(old, next);
1063
+ if (sameForm(old, wide)) continue;
1064
+ bounds.set(v, wide);
1065
+ changed = true;
1066
+ }
1067
+ }
1068
+ const values = new Map(this.names.map((n) => [n, init.get(n) as Shape]));
1069
+ for (const [v, o] of this.#owners) values.set(o.name, { ...(values.get(o.name) as Shape), [o.measure]: bounds.get(v) as Form });
1070
+ return values;
1071
+ }
1072
+ }
1073
+
1074
+ /** This function finds an op without a size rule in a node or in its children. */
1075
+ function findOpen(at: Expr, open: ReadonlyMap<Expr, boolean>): ExprOf<"app"> | undefined {
1076
+ const todo = [at];
1077
+ for (let x = todo.pop(); x !== undefined; x = todo.pop()) {
1078
+ if (x.tag === "app" && open.get(x) === true) return x;
1079
+ todo.push(...children(x));
1080
+ }
1081
+ return undefined;
1082
+ }
1083
+
1084
+ /** This function reads an expression one time, and it gives the reason of a refusal or `undefined`. */
1085
+ function refusalOf(e: Expr, opts: SizeOptions, parts: boolean): string | undefined {
1086
+ try {
1087
+ new Checker(opts, parts).shape(e, new Map());
1088
+ return undefined;
1089
+ } catch (thrown) {
1090
+ if (thrown instanceof Refusal) return thrown.message;
1091
+ throw thrown;
1092
+ }
1093
+ }
1094
+
1095
+ /**
1096
+ * This function checks the sizes of the loops of an expression (LOOP.SIZE). It gives the reason of a refusal, or
1097
+ * `undefined`. The expression must pass `shapeError` and the limit of the nesting first. Each reading gives a sound
1098
+ * bound, so one reading that accepts the expression makes it valid. A refusal tells the reason of the first reading
1099
+ * (LOOP.SIZE.READINGS).
1100
+ */
1101
+ export function sizeError(e: Expr, opts: SizeOptions = {}): string | undefined {
1102
+ const reason = refusalOf(e, opts, false);
1103
+ return reason === undefined || refusalOf(e, opts, true) === undefined ? undefined : reason;
1104
+ }