@mark1russell7/vex-compiler 0.0.0-stage → 0.8.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 ADDED
@@ -0,0 +1,3736 @@
1
+ import { MAX_NESTING, addrExprs, axisTargets, children, compile, findMethod, fixAddr, isFieldName, isListOp, isOpName, isStackOverflow, isVexList, liftsAt, listOf, lit, matchesKind, moveExpr, nestingOf, ok, resolveAddr, safeIs, shapeError, vexList } from "@mark1russell7/vex";
2
+ //#region src/facts.ts
3
+ /**
4
+ * The facts of the options that the printer uses (docs/COMPILER.md §13.2). For each op site, they give the domain
5
+ * whose op the interpreter takes first, and the kinds and the lifts of its parameters. The facts come from the op
6
+ * tables, so the same options always give the same facts, and the same source.
7
+ */
8
+ /**
9
+ * The most bodies of functions that tier 2 puts at the calls of one program. A function that calls another function
10
+ * twice doubles its body, so a chain of such functions grows fast. A module prints each function once.
11
+ */
12
+ const MAX_CALLS = 1e4;
13
+ /** The list ops that give a list or read a position of a list (LIST.SORT, LIST.TAKE, LIST.NTH). */
14
+ const ORDER_OPS = /* @__PURE__ */ new Set([
15
+ "sortBy",
16
+ "take",
17
+ "nth"
18
+ ]);
19
+ /**
20
+ * This function gives the reason that tier 2 cannot take a program with lists as values. The reason is the axis `list`
21
+ * or an op on the order of a list. Tier 1 evaluates such a program. It uses a stack, not recursion.
22
+ */
23
+ function listReason(expr) {
24
+ const todo = [expr];
25
+ for (let x = todo.pop(); x !== void 0; x = todo.pop()) {
26
+ if ((x.tag === "each" || x.tag === "fold") && listOf(x.axis) !== void 0) return "the program has the axis \"list\", and tier 2 does not have lists as values yet";
27
+ if (x.tag === "app" && ORDER_OPS.has(x.op)) return `the program has the list op "${x.op}", and tier 2 does not have lists as values yet`;
28
+ todo.push(...children(x));
29
+ }
30
+ }
31
+ /** This function gives the kind of the values of a domain. */
32
+ const kindOfDomain = (d) => d.primitive ?? `domain:${d.name}`;
33
+ /** This function gives a kind if it is a primitive type, else `undefined`. */
34
+ const primitiveOf = (k) => k === "number" || k === "string" || k === "boolean" ? k : void 0;
35
+ const NO_SPEC = Object.freeze({});
36
+ /** This function gives the op of a name in a domain, or `undefined` for a domain without the op. */
37
+ function entryOf(domain, name) {
38
+ if (!isOpName(name)) return void 0;
39
+ const declared = Object.hasOwn(domain.ops, name) ? domain.ops[name] : void 0;
40
+ if (declared === void 0) return domain.methods === "all" ? {
41
+ domain,
42
+ spec: NO_SPEC,
43
+ fn: void 0
44
+ } : void 0;
45
+ return {
46
+ domain,
47
+ spec: declared,
48
+ fn: declared.fn
49
+ };
50
+ }
51
+ const FREE$1 = Object.freeze({ t: "free" });
52
+ const STATIC_FREE = Object.freeze({ t: "free" });
53
+ /** This function gives the kind of the result of an op of a domain, if the op declares it. */
54
+ function returnsOf(domain, kind) {
55
+ if (kind === "domain") return kindOfDomain(domain);
56
+ return kind === "any" ? void 0 : kind;
57
+ }
58
+ /** This function tells if an argument of a kind fits a parameter, or `undefined` if the kind of the argument is unknown. */
59
+ function fits(domain, param, arg) {
60
+ if (param === void 0 || param === "any") return true;
61
+ if (arg === void 0) return void 0;
62
+ return arg === (param === "domain" ? kindOfDomain(domain) : param);
63
+ }
64
+ /**
65
+ * This function tells if a domain accepts a value of a kind. A domain with a primitive type accepts its type, and a
66
+ * domain without one accepts the values of its kind. For another value, it gives `undefined`: its `is` can accept it.
67
+ */
68
+ function accepts(d, kind) {
69
+ if (d.primitive !== void 0) return d.primitive === kind;
70
+ return kind === kindOfDomain(d) ? true : void 0;
71
+ }
72
+ /** This function gives the facts of a set of options. */
73
+ function factsOf(options) {
74
+ const domains = options.domains ?? [];
75
+ const fns = options.fns;
76
+ const last = domains.findLastIndex((d) => d.valid !== void 0);
77
+ return {
78
+ checks: domains.slice(0, last + 1).map((d) => d.valid !== void 0),
79
+ staticSite(name, kinds) {
80
+ const [self, ...args] = kinds;
81
+ if (self === void 0) return void 0;
82
+ for (const [i, d] of domains.entries()) {
83
+ const takes = accepts(d, self);
84
+ if (takes === void 0) return void 0;
85
+ const e = takes ? entryOf(d, name) : void 0;
86
+ if (e?.fn === void 0) {
87
+ if (takes && d.primitive === void 0) return void 0;
88
+ continue;
89
+ }
90
+ if (d.fromScalar !== void 0 && args.some((a, j) => a !== "string" && a !== "boolean" && liftsAt(e.spec.liftScalar, j))) return void 0;
91
+ const ok = args.map((a, j) => fits(d, e.spec.params?.[j], a));
92
+ if (ok.includes(void 0)) return void 0;
93
+ return {
94
+ t: "fn",
95
+ domain: i,
96
+ bad: ok.includes(false),
97
+ returns: returnsOf(d, e.spec.returns)
98
+ };
99
+ }
100
+ return fns !== void 0 && Object.hasOwn(fns, name) ? STATIC_FREE : void 0;
101
+ },
102
+ checkOf(kind) {
103
+ for (const [i, d] of domains.entries()) {
104
+ const takes = accepts(d, kind);
105
+ if (takes === void 0) return void 0;
106
+ if (takes) return i;
107
+ }
108
+ return -1;
109
+ },
110
+ site(name, arity) {
111
+ if (arity === 0 || isListOp(name)) return void 0;
112
+ const index = domains.findIndex((d) => entryOf(d, name) !== void 0);
113
+ if (index < 0) return fns !== void 0 && Object.hasOwn(fns, name) ? FREE$1 : void 0;
114
+ const e = entryOf(domains[index], name);
115
+ return {
116
+ t: "op",
117
+ domain: index,
118
+ method: e.fn === void 0,
119
+ params: e.spec.params,
120
+ lift: e.domain.fromScalar === void 0 ? void 0 : e.spec.liftScalar
121
+ };
122
+ }
123
+ };
124
+ }
125
+ //#endregion
126
+ //#region src/loop.ts
127
+ const local = (n) => ({
128
+ t: "local",
129
+ n
130
+ });
131
+ const constant = (i) => ({
132
+ t: "const",
133
+ i
134
+ });
135
+ const num = (v) => ({
136
+ t: "num",
137
+ v
138
+ });
139
+ const bool = (v) => ({
140
+ t: "bool",
141
+ v
142
+ });
143
+ const FALLBACK_EXPR = { t: "fallback" };
144
+ const RETURN = Object.freeze({ t: "return" });
145
+ const array = (...items) => ({
146
+ t: "array",
147
+ items
148
+ });
149
+ const prim = (op, ...args) => ({
150
+ t: "prim",
151
+ op,
152
+ args
153
+ });
154
+ const call$1 = (fn, ...args) => ({
155
+ t: "call",
156
+ fn,
157
+ args
158
+ });
159
+ //#endregion
160
+ //#region src/js.ts
161
+ /**
162
+ * The back end of JavaScript source (docs/COMPILER.md §3.4). It prints a program of the loop IR as the body of a
163
+ * function with the parameters `K` (the constants) and `R` (the runtime).
164
+ *
165
+ * The source has no name and no literal of the program as text: it reads each one from `K`, by its index (§5). The
166
+ * same program and the same facts always give the same source.
167
+ *
168
+ * With the facts of the options, each op site gets its fast path in the source (§13.2). Each site then has its own
169
+ * inline caches in the engine, and a guard sends each other case to the dispatch of the runtime.
170
+ */
171
+ /** This function gives the call of the dispatch of a site. With more than 3 values, the dispatch takes an array. */
172
+ function generic(x, site, values) {
173
+ return x.args.length <= 3 ? `${site}(${values.join(", ")})` : `${site}([${values.join(", ")}])`;
174
+ }
175
+ /** This function gives the check of an argument of the kind `kind`, for an op of the domain `d`. */
176
+ function kindCheck(kind, a, d) {
177
+ if (kind === "domain") return [`${d}.is(${a})`];
178
+ if (kind === "number" || kind === "boolean" || kind === "string") return [`typeof ${a} === "${kind}"`];
179
+ return [];
180
+ }
181
+ const name = (n) => `l${n}`;
182
+ /** This function prints the source of a program. The body gives the function of the program. */
183
+ function printJs(p, facts) {
184
+ const used = /* @__PURE__ */ new Set();
185
+ const constants = /* @__PURE__ */ new Set();
186
+ const sites = /* @__PURE__ */ new Map();
187
+ const domains = /* @__PURE__ */ new Set();
188
+ const fns = /* @__PURE__ */ new Map();
189
+ let threw = false;
190
+ let siteLabels = 0;
191
+ const expr = (x) => {
192
+ switch (x.t) {
193
+ case "const":
194
+ constants.add(x.i);
195
+ return `k${x.i}`;
196
+ case "local": return name(x.n);
197
+ case "num":
198
+ case "bool": return String(x.v);
199
+ case "fallback": return "F";
200
+ case "array": return `[${x.items.map(expr).join(", ")}]`;
201
+ case "call":
202
+ used.add(x.fn);
203
+ return `${x.fn}_(${x.args.map(expr).join(", ")})`;
204
+ case "op": return generic(x, siteOf(x), x.args.map(expr));
205
+ case "memo":
206
+ sites.set(`mo${x.id}`, "R.memo()");
207
+ return `mo${x.id}`;
208
+ case "targets": {
209
+ const site = `a${x.axis}`;
210
+ sites.set(site, `R.axis(${expr(constant(x.axis))})`);
211
+ return `${site}(${x.args.map(expr).join(", ")})`;
212
+ }
213
+ case "prim": {
214
+ const [a, b, c, d, e] = x.args.map(expr);
215
+ switch (x.op) {
216
+ case "!": return `(!${a})`;
217
+ case "min":
218
+ case "max": return `Math.${x.op}(${a}, ${b})`;
219
+ case "isNumber": return `(typeof ${a} === "number")`;
220
+ case "isBoolean": return `(typeof ${a} === "boolean")`;
221
+ case "isString": return `(typeof ${a} === "string")`;
222
+ case "isValue": return `(${a} !== undefined && ${a} !== null)`;
223
+ case "isObject": return `(typeof ${a} === "object" || typeof ${a} === "function")`;
224
+ case "get": return `${a}.get(${b})`;
225
+ case "member": return `${a}[${b}]`;
226
+ case "records": return `${a}.records`;
227
+ case "recordAt": return `(${a} !== undefined ? ${a}[${b}] : ${c}.get(${d}))`;
228
+ case "keysOf": return `${a}.keys`;
229
+ case "idxOf": return `${a}.idx`;
230
+ case "memoGet": return `${a}.get(${b}, ${c})`;
231
+ case "memoPut": return `${a}.put(${b}, ${c}, ${d}, ${e})`;
232
+ case "entryValue": return `${a}.v`;
233
+ case "entryOk": return `${a}.ok`;
234
+ case "+":
235
+ case "/":
236
+ case "===":
237
+ case "!==":
238
+ case "||":
239
+ case "&&": return `(${a} ${x.op} ${b})`;
240
+ }
241
+ }
242
+ }
243
+ };
244
+ function siteOf(x) {
245
+ const site = `s${x.name}_${x.args.length}`;
246
+ sites.set(site, `R.site(${expr(constant(x.name))}, ${x.args.length})`);
247
+ return site;
248
+ }
249
+ const domain = (i) => {
250
+ domains.add(i);
251
+ return `d${i}`;
252
+ };
253
+ const resultChecks = (out, checks, indent) => {
254
+ lines.push(`${indent}if (${out} !== F) {`);
255
+ lines.push(`${indent} if (${out} === undefined || ${out} === null || (typeof ${out} === "number" && !Number.isFinite(${out}))) ${out} = F;`);
256
+ checks.forEach((valid, i) => {
257
+ const d = domain(i);
258
+ lines.push(valid ? `${indent} else if (${d}.is(${out})) { try { if (!${d}.valid(${out})) ${out} = F; } catch (e) { ${out} = threw_(e); } }` : `${indent} else if (${d}.is(${out})) {}`);
259
+ });
260
+ lines.push(`${indent}}`);
261
+ };
262
+ /**
263
+ * The fast path of an op site that assigns the local `n`. A method site guards the method of the last receiver and
264
+ * the domain of the receiver, and a site of a function guards the domain. Then the site checks the arguments, calls
265
+ * the op in a `try`, and checks the result. A number that the op lifts, and each failed guard, go to the dispatch.
266
+ */
267
+ const siteBlock = (n, x, indent) => {
268
+ const attempt = (call, ind) => {
269
+ threw = true;
270
+ lines.push(`${ind}try { ${name(n)} = ${call}; } catch (e) { ${name(n)} = threw_(e); }`);
271
+ };
272
+ const st = facts.staticSite(p.constants[x.name], x.kinds);
273
+ if (st !== void 0) {
274
+ staticBlock(n, x, st, indent, attempt);
275
+ return true;
276
+ }
277
+ const f = facts.site(p.constants[x.name], x.args.length);
278
+ switch (f?.t) {
279
+ case void 0: return false;
280
+ case "free": {
281
+ const site = siteOf(x);
282
+ sites.set(`${site}_f`, `${site}.free`);
283
+ attempt(`${site}_f(${x.args.map(expr).join(", ")})`, indent);
284
+ resultChecks(name(n), facts.checks, indent);
285
+ return true;
286
+ }
287
+ case "op":
288
+ opBlock(n, x, f, indent, attempt);
289
+ return true;
290
+ }
291
+ };
292
+ /**
293
+ * The block of a static site (KIND.STATIC). The kinds of its values decide its op, so the site uses the function of the
294
+ * op with no guard. A result of another kind breaks the declaration of the op. Then the program stops, and tier 1
295
+ * evaluates it.
296
+ */
297
+ const staticBlock = (n, x, st, indent, attempt) => {
298
+ const out = name(n);
299
+ const values = x.args.map(expr);
300
+ if (st.t === "free") {
301
+ const site = siteOf(x);
302
+ sites.set(`${site}_f`, `${site}.free`);
303
+ attempt(`${site}_f(${values.join(", ")})`, indent);
304
+ resultChecks(out, facts.checks, indent);
305
+ return;
306
+ }
307
+ if (st.bad) {
308
+ lines.push(`${indent}${out} = F;`);
309
+ return;
310
+ }
311
+ const f = `f${x.name}_${st.domain}`;
312
+ fns.set(f, `${domain(st.domain)}.ops[${expr(constant(x.name))}].fn`);
313
+ attempt(`${f}(${values.join(", ")})`, indent);
314
+ const kind = st.returns;
315
+ if (kind === void 0) {
316
+ resultChecks(out, facts.checks, indent);
317
+ return;
318
+ }
319
+ lines.push(`${indent}if (${out} !== F && typeof ${out} !== "${kind}") return F; // the kind of the result`);
320
+ if (kind === "number") lines.push(`${indent}if (${out} !== F && !Number.isFinite(${out})) ${out} = F;`);
321
+ const check = facts.checkOf(kind);
322
+ if (check === void 0) resultChecks(out, facts.checks, indent);
323
+ else if (facts.checks[check] === true) {
324
+ const d = domain(check);
325
+ lines.push(`${indent}if (${out} !== F) { try { if (!${d}.valid(${out})) ${out} = F; } catch (e) { ${out} = threw_(e); } }`);
326
+ }
327
+ };
328
+ const opBlock = (n, x, f, indent, attempt) => {
329
+ const site = siteOf(x);
330
+ const values = x.args.map(expr);
331
+ const out = name(n);
332
+ const label = `S${siteLabels++}`;
333
+ const [self, ...args] = values;
334
+ const d = domain(f.domain);
335
+ lines.push(`${indent}${label}: {`);
336
+ let inner;
337
+ let call;
338
+ if (f.method) {
339
+ const m = `m${label}`;
340
+ lines.push(`${indent} if (typeof ${self} === "object" && ${self} !== null) {`, `${indent} const ${m} = ${site}.m;`);
341
+ lines.push(`${indent} if (${m} !== undefined && ${self}[${expr(constant(x.name))}] === ${m} && ${d}.is(${self})) {`);
342
+ inner = `${indent} `;
343
+ call = `${self}[${expr(constant(x.name))}](${args.join(", ")})`;
344
+ } else {
345
+ sites.set(`${site}_f`, `${site}.fn`);
346
+ lines.push(`${indent} if (${d}.is(${self})) {`);
347
+ inner = `${indent} `;
348
+ call = `${site}_f(${values.join(", ")})`;
349
+ }
350
+ const lifted = args.filter((_a, i) => liftsAt(f.lift, i)).map((a) => `typeof ${a} === "number"`);
351
+ if (lifted.length > 0) lines.push(`${inner}if (${lifted.join(" || ")}) { ${out} = ${generic(x, site, values)}; break ${label}; }`);
352
+ const kinds = args.flatMap((a, i) => kindCheck(f.params?.[i], a, d));
353
+ if (kinds.length > 0) lines.push(`${inner}if (!(${kinds.join(" && ")})) { ${out} = F; break ${label}; }`);
354
+ attempt(call, inner);
355
+ resultChecks(out, facts.checks, inner);
356
+ lines.push(`${inner}break ${label};`);
357
+ if (f.method) lines.push(`${indent} }`);
358
+ lines.push(`${indent} }`, `${indent} ${out} = ${generic(x, site, values)};`, `${indent}}`);
359
+ };
360
+ const action = (f) => {
361
+ switch (f.t) {
362
+ case "return": return "return F;";
363
+ case "break": return `break L${f.label};`;
364
+ case "continue": return f.strict === void 0 ? `continue L${f.label};` : `{ if (${expr(f.strict.cond)}) ${action(f.strict.else)} continue L${f.label}; }`;
365
+ }
366
+ };
367
+ const lines = [];
368
+ const stmts = (ss, indent) => {
369
+ for (const s of ss) stmt(s, indent);
370
+ };
371
+ const stmt = (s, indent) => {
372
+ switch (s.t) {
373
+ case "let":
374
+ case "set":
375
+ if (s.value.t === "op" && siteBlock(s.n, s.value, indent)) return;
376
+ lines.push(`${indent}${name(s.n)} = ${expr(s.value)};`);
377
+ return;
378
+ case "check":
379
+ lines.push(`${indent}if (!(${expr(s.ok)})) ${action(s.fail)} // ${s.reason}`);
380
+ return;
381
+ case "fail":
382
+ lines.push(`${indent}${action(s.fail)}`);
383
+ return;
384
+ case "if":
385
+ lines.push(`${indent}if (${expr(s.cond)}) {`);
386
+ stmts(s.yes, `${indent} `);
387
+ if (s.no.length > 0) {
388
+ lines.push(`${indent}} else {`);
389
+ stmts(s.no, `${indent} `);
390
+ }
391
+ lines.push(`${indent}}`);
392
+ return;
393
+ case "loop": {
394
+ const [a, i] = [name(s.array), name(s.index)];
395
+ lines.push(`${indent}${a} = ${expr(s.over)};`);
396
+ lines.push(`${indent}L${s.label}: for (${i} = 0; ${i} < ${a}.length; ${i}++) {`);
397
+ lines.push(`${indent} ${name(s.item)} = ${a}[${i}];`);
398
+ stmts(s.body, `${indent} `);
399
+ lines.push(`${indent}}`);
400
+ return;
401
+ }
402
+ case "block":
403
+ lines.push(`${indent}L${s.label}: {`);
404
+ stmts(s.body, `${indent} `);
405
+ lines.push(`${indent}}`);
406
+ return;
407
+ case "repeat":
408
+ lines.push(`${indent}L${s.label}: for (;;) {`);
409
+ stmts(s.body, `${indent} `);
410
+ lines.push(`${indent}}`);
411
+ return;
412
+ case "next":
413
+ lines.push(`${indent}continue;`);
414
+ return;
415
+ case "push":
416
+ lines.push(`${indent}${name(s.n)}.push(${expr(s.value)});`);
417
+ return;
418
+ case "return":
419
+ lines.push(`${indent}return ${expr(s.value)};`);
420
+ return;
421
+ }
422
+ };
423
+ stmts(p.body, " ");
424
+ const params = Array.from({ length: 4 }, (_, n) => name(n));
425
+ const locals = Array.from({ length: p.locals - 4 }, (_, n) => name(n + 4));
426
+ const head = [
427
+ `"use strict";`,
428
+ `const F = R.F;`,
429
+ ...[...used].map((fn) => `const ${fn}_ = R.${fn};`),
430
+ ...[...constants].map((i) => `const k${i} = K[${i}];`),
431
+ ...[...sites].map(([site, init]) => `const ${site} = ${init};`),
432
+ ...[...domains].map((i) => `const d${i} = R.domain(${i});`),
433
+ ...[...fns].map(([f, init]) => `const ${f} = ${init};`),
434
+ ...threw ? [`const threw_ = R.threw;`] : [],
435
+ `return function vex(${params.join(", ")}) {`,
436
+ ...locals.length > 0 ? [` let ${locals.join(", ")};`] : [],
437
+ ` try {`
438
+ ];
439
+ const tail = [
440
+ ` } catch {`,
441
+ ` return F;`,
442
+ ` }`,
443
+ `};`,
444
+ ``
445
+ ];
446
+ return [
447
+ ...head,
448
+ ...lines,
449
+ ...tail
450
+ ].join("\n");
451
+ }
452
+ //#endregion
453
+ //#region src/memo.ts
454
+ /**
455
+ * The memo of a program (docs/COMPILER.md §7.2 and §7.3). The value of some nodes depends only on the space and on a
456
+ * few values that the node reads from outside: its keys. A program keeps the value of such a node for each space and
457
+ * each value of its keys. Thus a run at each key of a space evaluates the node once for each value of its keys.
458
+ *
459
+ * - `AVERAGE(all.Score)` has no keys, so it evaluates once for each space.
460
+ * - "The largest width in the column of the origin" has one key, the column of the origin. It evaluates once for each
461
+ * column, not once for each origin.
462
+ *
463
+ * A key reads the origin or a name from outside the node, and nothing that the node changes. Inside the node, the
464
+ * value of the key replaces the key. Thus the value of the node depends only on the space and the values of the keys.
465
+ */
466
+ /** A read of the focus of the expression, outside its own loops. */
467
+ const FOCUS = 1;
468
+ /** A move to the origin. */
469
+ const ORIGIN = 2;
470
+ /** A name that the node does not bind: a variable of the run, or a binding outside the node. */
471
+ const FREE = 4;
472
+ /** A name that the node binds, outside the expression. */
473
+ const INTERNAL = 8;
474
+ /** An extension or an axis table. An extension can read each part of the evaluation, and a table is another space. */
475
+ const OPAQUE = 16;
476
+ /** A move to the origin or a free name inside a loop of the expression. Such a loop is a part of a node, not a key. */
477
+ const DEEP = 32;
478
+ /** This function gives the axis inside the `where` axes of an axis, and the tests of the `where` axes. */
479
+ function parts(a) {
480
+ const tests = [];
481
+ let x = a;
482
+ while (x.t === "where") {
483
+ tests.push(x.test);
484
+ x = x.axis;
485
+ }
486
+ return {
487
+ base: x,
488
+ tests
489
+ };
490
+ }
491
+ /** This function adds `DEEP` to a read of the origin or of a free name inside a loop. */
492
+ const inLoop = (r, top) => top || (r & 6) === 0 ? r : r | DEEP;
493
+ /**
494
+ * This function gives the reads of an address: the focus at the top of the expression, or the origin, or nothing. A
495
+ * move from the focus or the origin can fail, so the address reads its start also before a fixed key (V-052).
496
+ */
497
+ function addressReads(at, top) {
498
+ let start = top ? FOCUS : 0;
499
+ let found = 0;
500
+ at?.forEach((m) => {
501
+ if (m.t === "key" || m.t === "index") start = 0;
502
+ else if (m.t === "origin") start = ORIGIN;
503
+ else found |= start;
504
+ });
505
+ return inLoop(found | start, top);
506
+ }
507
+ /**
508
+ * This function gives the reads of `e`. `outer` has the names that the node binds outside `e`, and `inner` has the
509
+ * names that `e` binds above this part. `top` is true outside the loops of `e`.
510
+ */
511
+ function reads(e, outer, inner, top) {
512
+ switch (e.tag) {
513
+ case "lit": return 0;
514
+ case "var": return inner.has(e.name) ? 0 : outer.has(e.name) ? INTERNAL : inLoop(FREE, top);
515
+ case "ext":
516
+ case "fold":
517
+ case "iterate":
518
+ case "fn":
519
+ case "call": return OPAQUE;
520
+ case "ref": return addrExprs(e.at).reduce((r, x) => r | reads(x, outer, inner, top), addressReads(e.at, top));
521
+ case "app": return e.args.reduce((r, x) => r | reads(x, outer, inner, top), 0);
522
+ case "rec": return Object.values(e.fields).reduce((r, x) => r | reads(x, outer, inner, top), 0);
523
+ case "let": return Object.values(e.bind).reduce((r, x) => r | reads(x, outer, inner, top), 0) | reads(e.body, outer, /* @__PURE__ */ new Set([...inner, ...Object.keys(e.bind)]), top);
524
+ case "each": {
525
+ const { base, tests } = parts(e.axis);
526
+ const targets = base.t === "table" || listOf(e.axis) !== void 0 ? OPAQUE : base.t === "all" && (e.at ?? []).length === 0 ? 0 : addressReads(e.at, top);
527
+ const at = addrExprs(e.at).reduce((r, x) => r | reads(x, outer, inner, top), targets);
528
+ return [e.body, ...tests].reduce((r, x) => r | reads(x, outer, inner, false), at);
529
+ }
530
+ }
531
+ }
532
+ /** This function joins the keys of the parts of an expression. A part that cannot be in the memo makes the expression the same. */
533
+ function all(xs) {
534
+ return xs.every((x) => x !== void 0) ? xs.flatMap((x) => x ?? []) : void 0;
535
+ }
536
+ /**
537
+ * This function gives the keys of the part `e` of a node, or `undefined` if the part cannot be in the memo. `top` is
538
+ * true outside the loops of the node, and `outer` has the names that the node binds above `e`. The node itself (`root`)
539
+ * is not a key of itself.
540
+ */
541
+ function keysOf(e, top, outer, pure, root = false) {
542
+ const r = reads(e, outer, /* @__PURE__ */ new Set(), true);
543
+ if ((r & (22 | (top ? FOCUS : 0))) === 0) {
544
+ if (!root) pure.add(e);
545
+ return [];
546
+ }
547
+ if (!root && (r & 57) === 0) return [e];
548
+ switch (e.tag) {
549
+ case "app": return all(e.args.map((x) => keysOf(x, top, outer, pure)));
550
+ case "rec": return all(Object.values(e.fields).map((x) => keysOf(x, top, outer, pure)));
551
+ case "let": {
552
+ const inner = /* @__PURE__ */ new Set([...outer, ...Object.keys(e.bind)]);
553
+ return all([...Object.values(e.bind).map((x) => keysOf(x, top, outer, pure)), keysOf(e.body, top, inner, pure)]);
554
+ }
555
+ case "each": {
556
+ const { base, tests } = parts(e.axis);
557
+ if (base.t === "table" || listOf(e.axis) !== void 0 || (base.t !== "all" || (e.at ?? []).length > 0) && addressReads(e.at, top) !== 0) return void 0;
558
+ if (addrExprs(e.at).some((x) => reads(x, outer, /* @__PURE__ */ new Set(), top) !== 0)) return void 0;
559
+ return all([e.body, ...tests].map((x) => keysOf(x, false, outer, pure)));
560
+ }
561
+ case "lit":
562
+ case "ref":
563
+ case "var":
564
+ case "ext":
565
+ case "fold":
566
+ case "iterate":
567
+ case "fn":
568
+ case "call": return;
569
+ }
570
+ }
571
+ /** This function tells if an expression has a loop outside its keys and outside the parts that have a memo of their own. */
572
+ function loopOutside(e, keys) {
573
+ if (keys.has(e)) return false;
574
+ switch (e.tag) {
575
+ case "each":
576
+ case "fold":
577
+ case "iterate": return true;
578
+ case "app": return e.args.some((x) => loopOutside(x, keys));
579
+ case "rec": return Object.values(e.fields).some((x) => loopOutside(x, keys));
580
+ case "let": return [...Object.values(e.bind), e.body].some((x) => loopOutside(x, keys));
581
+ case "ref": return addrExprs(e.at).some((x) => loopOutside(x, keys));
582
+ case "lit":
583
+ case "var":
584
+ case "ext":
585
+ case "fn":
586
+ case "call": return false;
587
+ }
588
+ }
589
+ /** This function gives the `let` expressions above an `each`, and the `each`, or `undefined` for another expression. */
590
+ function eachUnderLets$1(e) {
591
+ const lets = [];
592
+ let x = e;
593
+ while (x?.tag === "let") {
594
+ lets.push(x);
595
+ x = x.body;
596
+ }
597
+ return x?.tag === "each" ? {
598
+ lets,
599
+ each: x
600
+ } : void 0;
601
+ }
602
+ /**
603
+ * This function gives the nodes of `expr` that a program keeps in its memo, each with its keys. Each such node has a
604
+ * loop outside its keys. A node inside such a node can be in the memo too. Thus the first evaluation of the outer
605
+ * node evaluates the inner node once.
606
+ */
607
+ function memoNodes(expr) {
608
+ const out = /* @__PURE__ */ new Map();
609
+ const visit = (e) => {
610
+ const pure = /* @__PURE__ */ new Set();
611
+ const keys = keysOf(e, true, /* @__PURE__ */ new Set(), pure, true);
612
+ if (keys !== void 0 && loopOutside(e, /* @__PURE__ */ new Set([...keys, ...pure]))) out.set(e, keys);
613
+ if (e.tag === "app") {
614
+ const [first, ...rest] = e.args;
615
+ const fused = isListOp(e.op) ? eachUnderLets$1(first) : void 0;
616
+ if (fused === void 0) {
617
+ if (first !== void 0) visit(first);
618
+ } else {
619
+ for (const l of fused.lets) Object.values(l.bind).forEach(visit);
620
+ [
621
+ fused.each.body,
622
+ ...parts(fused.each.axis).tests,
623
+ ...addrExprs(fused.each.at)
624
+ ].forEach(visit);
625
+ }
626
+ rest.forEach(visit);
627
+ } else if (e.tag === "rec") Object.values(e.fields).forEach(visit);
628
+ else if (e.tag === "let") {
629
+ Object.values(e.bind).forEach(visit);
630
+ visit(e.body);
631
+ } else if (e.tag === "each") [
632
+ e.body,
633
+ ...parts(e.axis).tests,
634
+ ...addrExprs(e.at)
635
+ ].forEach(visit);
636
+ else if (e.tag === "ref") addrExprs(e.at).forEach(visit);
637
+ };
638
+ visit(expr);
639
+ return out;
640
+ }
641
+ //#endregion
642
+ //#region src/lower.ts
643
+ /**
644
+ * The lowering: a Vex expression becomes a program of the loop IR (docs/COMPILER.md §3.3). A list op over a direct
645
+ * `each` becomes one loop with a running value, so it makes no list.
646
+ *
647
+ * Each value that the interpreter can give as an error has a check. The block of the check tells what a failure does
648
+ * (`Fail`). A list op skips an error item, and an error in the first argument of `ifError` gives the second argument.
649
+ * Each other error stops the program with `FALLBACK`.
650
+ */
651
+ /** The error of an expression that the compiler cannot lower. Then the program operates in tier 1. */
652
+ var Unsupported = class extends Error {};
653
+ const block = (fail) => ({
654
+ stmts: [],
655
+ fail
656
+ });
657
+ /** This function gives the axis inside the `where` axes of an axis. */
658
+ const baseAxis = (a) => a.t === "where" ? baseAxis(a.axis) : a;
659
+ /** This function gives the tests of the `where` axes of an axis, from the inside out, as the interpreter applies them. */
660
+ function whereTests(a) {
661
+ const out = [];
662
+ for (let x = a; x.t === "where"; x = x.axis) out.unshift(x.test);
663
+ return out;
664
+ }
665
+ /** This function gives the `each` under the `let` expressions of a list argument, or `undefined`. */
666
+ function eachUnderLets(e) {
667
+ let x = e;
668
+ while (x?.tag === "let") x = x.body;
669
+ return x?.tag === "each" ? x : void 0;
670
+ }
671
+ /** The kinds of the values of the primitive operations that always give a boolean. */
672
+ const BOOLEAN_PRIMS = /* @__PURE__ */ new Set([
673
+ "!",
674
+ "===",
675
+ "!==",
676
+ "isNumber",
677
+ "isBoolean",
678
+ "isString",
679
+ "isValue",
680
+ "isObject"
681
+ ]);
682
+ /** The checks of the kinds of a schema. */
683
+ const KIND_CHECKS = {
684
+ number: "isNumber",
685
+ string: "isString",
686
+ boolean: "isBoolean"
687
+ };
688
+ /** This function gives the kind of two values in the branches of a form, if they have the same kind. */
689
+ const join$1 = (a, b) => a === b ? a : void 0;
690
+ /**
691
+ * This function lowers an expression into a program of the loop IR. It throws `Unsupported` for an expression it cannot
692
+ * lower. The facts of the options decide the op of a site whose values have known kinds (KIND.STATIC).
693
+ */
694
+ function lower(expr, facts = factsOf({}), schema = {}) {
695
+ const shape = shapeError(expr);
696
+ if (shape !== void 0) throw new Unsupported(shape);
697
+ if (nestingOf(expr) > MAX_NESTING) throw new Unsupported(`the expression is nested deeper than ${MAX_NESTING} levels`);
698
+ const lists = listReason(expr);
699
+ if (lists !== void 0) throw new Unsupported(lists);
700
+ const l = new Lowerer(memoNodes(expr), facts, schema);
701
+ const b = block(RETURN);
702
+ l.check(b, call$1("has", local(0), local(1)), "the origin is a key of the space");
703
+ const top = {
704
+ space: local(0),
705
+ origin: local(1),
706
+ focus: local(1),
707
+ env: /* @__PURE__ */ new Map(),
708
+ fns: /* @__PURE__ */ new Map(),
709
+ rec: prim("get", local(0), local(1))
710
+ };
711
+ const value = l.expr(expr, top, [], b);
712
+ b.stmts.push({
713
+ t: "return",
714
+ value
715
+ });
716
+ return {
717
+ body: b.stmts,
718
+ locals: l.locals,
719
+ constants: l.constants
720
+ };
721
+ }
722
+ var Lowerer = class {
723
+ locals = 4;
724
+ labels = 0;
725
+ memos = 0;
726
+ /** The number of bodies of functions that the lowering put at calls (MAX_CALLS). */
727
+ #calls = 0;
728
+ #memo;
729
+ /** The keys of the nodes of the memo whose code the lowering makes, with their values. */
730
+ #keys = /* @__PURE__ */ new Map();
731
+ #facts;
732
+ #schema;
733
+ /** The kind of each local whose kind the lowering knows. A local gets its kind where it gets its value. */
734
+ #kinds = /* @__PURE__ */ new Map();
735
+ constructor(memo, facts, schema) {
736
+ this.#memo = memo;
737
+ this.#facts = facts;
738
+ this.#schema = schema;
739
+ }
740
+ /** This method gives the kind of a value, if the lowering knows it. */
741
+ kindOf(x) {
742
+ if (x.t === "const") {
743
+ const t = typeof this.constants[x.i];
744
+ return t === "number" || t === "string" || t === "boolean" ? t : void 0;
745
+ }
746
+ if (x.t === "local") return this.#kinds.get(x.n);
747
+ return x.t === "prim" && BOOLEAN_PRIMS.has(x.op) ? "boolean" : void 0;
748
+ }
749
+ /** This method gives a local the kind `kind`. A value that is not a local keeps its kind. */
750
+ #typed(x, kind) {
751
+ if (x.t === "local" && kind !== void 0) this.#kinds.set(x.n, kind);
752
+ return x;
753
+ }
754
+ /**
755
+ * This method checks the kind that the schema declares for a value. A failure is no error of the interpreter, so it
756
+ * stops the program, and tier 1 evaluates it.
757
+ */
758
+ #declared(b, x, kind, reason) {
759
+ if (kind === void 0) return x;
760
+ b.stmts.push({
761
+ t: "check",
762
+ ok: prim(KIND_CHECKS[kind], x),
763
+ reason,
764
+ fail: RETURN
765
+ });
766
+ return this.#typed(x, kind);
767
+ }
768
+ constants = [];
769
+ #pool = /* @__PURE__ */ new Map();
770
+ /** This method gives the index of the constant of a value. The same value has one constant. A map key does not tell 0 from -0, so -0 has its own. */
771
+ index(value) {
772
+ const k = Object.is(value, -0) ? NEGATIVE_ZERO$1 : value;
773
+ let i = this.#pool.get(k);
774
+ if (i === void 0) {
775
+ i = this.constants.push(value) - 1;
776
+ this.#pool.set(k, i);
777
+ }
778
+ return i;
779
+ }
780
+ /** This method gives the constant of a value. */
781
+ constant(value) {
782
+ return constant(this.index(value));
783
+ }
784
+ /** This method gives the number of a new local of a kind. */
785
+ typedLocal(kind) {
786
+ const n = this.locals++;
787
+ this.#kinds.set(n, kind);
788
+ return n;
789
+ }
790
+ /** This method gives a new local with a value. */
791
+ value(b, value) {
792
+ const n = this.locals++;
793
+ b.stmts.push({
794
+ t: "let",
795
+ n,
796
+ value
797
+ });
798
+ return local(n);
799
+ }
800
+ check(b, ok, reason) {
801
+ b.stmts.push({
802
+ t: "check",
803
+ ok,
804
+ reason,
805
+ fail: b.fail
806
+ });
807
+ }
808
+ /** This method gives a new local with the value of a call of the runtime, and a check that the value is not `FALLBACK`. */
809
+ checked(b, value, reason) {
810
+ const x = this.value(b, value);
811
+ this.check(b, prim("!==", x, FALLBACK_EXPR), reason);
812
+ return x;
813
+ }
814
+ /** This method adds a failure: the interpreter always gives an error here. */
815
+ fail(b) {
816
+ b.stmts.push({
817
+ t: "fail",
818
+ fail: b.fail
819
+ });
820
+ return FALLBACK_EXPR;
821
+ }
822
+ expr(e, s, path, b) {
823
+ const key = this.#keys.get(e);
824
+ if (key !== void 0) {
825
+ if (key.ok !== void 0) this.check(b, key.ok, "a key with a value");
826
+ return key.value;
827
+ }
828
+ const keys = this.#memo.get(e);
829
+ return keys === void 0 ? this.#node(e, s, path, b) : this.#memoized(e, keys, s, path, b);
830
+ }
831
+ /** This method lowers a node itself, without the memo. */
832
+ #node(e, s, path, b) {
833
+ switch (e.tag) {
834
+ case "lit": return this.constant(e.value);
835
+ case "ref": return this.#ref(e, s, path, b);
836
+ case "var": {
837
+ const bound = s.env.get(e.name);
838
+ if (bound === void 0 && s.fns.has(e.name)) return this.fail(b);
839
+ if (bound === void 0) {
840
+ const x = this.checked(b, call$1("var", local(2), this.constant(e.name)), "a variable");
841
+ return this.#declared(b, x, primitiveOf(this.#schema.vars?.[e.name]), "a variable of the schema");
842
+ }
843
+ if (bound.ok !== void 0) this.check(b, bound.ok, "a binding with a value");
844
+ return bound.value;
845
+ }
846
+ case "let": return this.expr(e.body, {
847
+ ...s,
848
+ ...this.#bind(e, s, path, b)
849
+ }, [...path, Object.keys(e.bind).length], b);
850
+ /* v8 ignore next -- @preserve */
851
+ case "fn": return this.fail(b);
852
+ case "call": return this.#call(e, s, path, b);
853
+ case "rec": {
854
+ const values = Object.values(e.fields).map((x, i) => this.expr(x, s, [...path, i], b));
855
+ return this.value(b, call$1("rec", this.constant(Object.keys(e.fields)), array(...values)));
856
+ }
857
+ case "app": return this.#app(e, s, path, b);
858
+ case "fold": return this.#fold(e, s, path, b);
859
+ case "iterate": return this.#iterate(e, s, path, b);
860
+ case "each": {
861
+ const keys = this.locals++;
862
+ const values = this.locals++;
863
+ b.stmts.push({
864
+ t: "let",
865
+ n: keys,
866
+ value: array()
867
+ }, {
868
+ t: "let",
869
+ n: values,
870
+ value: array()
871
+ });
872
+ this.#loop(e, s, path, b, () => RETURN, (body, key, v) => {
873
+ body.stmts.push({
874
+ t: "push",
875
+ n: keys,
876
+ value: key
877
+ }, {
878
+ t: "push",
879
+ n: values,
880
+ value: v
881
+ });
882
+ });
883
+ return this.value(b, call$1("list", local(keys), local(values)));
884
+ }
885
+ case "ext": {
886
+ const x = this.value(b, call$1("ext", this.constant(e.kind), this.constant(e.data), s.space, s.origin, s.focus, this.constant(path)));
887
+ b.stmts.push({
888
+ t: "check",
889
+ ok: prim("!==", x, FALLBACK_EXPR),
890
+ reason: "an extension",
891
+ fail: RETURN
892
+ });
893
+ return x;
894
+ }
895
+ }
896
+ }
897
+ /**
898
+ * This method gives the value of a node that depends only on the space (§7.2). The memo has an entry for each space.
899
+ * Without the entry of the space, the node evaluates in a block, and an error of it makes an entry without a value.
900
+ * An exception stops the program, so the memo gets no entry for it.
901
+ */
902
+ #memoized(e, keys, s, path, b) {
903
+ const memo = {
904
+ t: "memo",
905
+ id: this.memos++
906
+ };
907
+ const values = keys.map((k) => this.#attempt(b, (inner) => this.expr(k, s, path, inner)));
908
+ const tuple = array(...values.flatMap((k) => [k.value, flag(k)]));
909
+ const h = this.locals++;
910
+ const outer = this.#keys;
911
+ this.#keys = new Map([...outer, ...keys.map((k, i) => [k, values[i]])]);
912
+ const compute = block(b.fail);
913
+ const node = this.#attempt(compute, (inner) => this.#node(e, s, path, inner));
914
+ this.#keys = outer;
915
+ compute.stmts.push({
916
+ t: "set",
917
+ n: h,
918
+ value: prim("memoPut", memo, s.space, tuple, node.value, flag(node))
919
+ });
920
+ b.stmts.push({
921
+ t: "let",
922
+ n: h,
923
+ value: prim("memoGet", memo, s.space, tuple)
924
+ }, {
925
+ t: "if",
926
+ cond: prim("!", prim("isValue", local(h))),
927
+ yes: compute.stmts,
928
+ no: []
929
+ });
930
+ this.check(b, prim("entryOk", local(h)), "a value of the memo");
931
+ return this.#typed(this.value(b, prim("entryValue", local(h))), this.kindOf(node.value));
932
+ }
933
+ /**
934
+ * This method evaluates an expression in a block whose errors end the block, as a binding does. It gives the value
935
+ * and the flag that tells if the value exists. Without statements, the expression always has a value, so it gets no flag.
936
+ */
937
+ #attempt(b, make) {
938
+ const label = this.labels++;
939
+ const attempt = block({
940
+ t: "break",
941
+ label
942
+ });
943
+ const value = make(attempt);
944
+ if (attempt.stmts.length === 0) return { value };
945
+ const v = this.locals++;
946
+ const ok = this.locals++;
947
+ this.#typed(local(v), this.kindOf(value));
948
+ attempt.stmts.push({
949
+ t: "set",
950
+ n: v,
951
+ value
952
+ }, {
953
+ t: "set",
954
+ n: ok,
955
+ value: bool(true)
956
+ });
957
+ b.stmts.push({
958
+ t: "let",
959
+ n: ok,
960
+ value: bool(false)
961
+ }, {
962
+ t: "block",
963
+ label,
964
+ body: attempt.stmts
965
+ });
966
+ return {
967
+ value: local(v),
968
+ ok: local(ok)
969
+ };
970
+ }
971
+ /**
972
+ * This method reads a field, as `ref` of the interpreter: the record of the key, and then each segment of the path.
973
+ * A segment that cannot name a field always gives an error.
974
+ */
975
+ #ref(e, s, path, b) {
976
+ const record = e.at === void 0 || e.at.length === 0 ? s.rec : prim("get", s.space, this.#address(e.at, s, path, 0, b));
977
+ if (!e.path.every(isFieldName)) return this.fail(b);
978
+ const n = this.locals++;
979
+ const x = local(n);
980
+ b.stmts.push({
981
+ t: "let",
982
+ n,
983
+ value: record
984
+ });
985
+ this.check(b, prim("isValue", x), "a record");
986
+ for (const seg of e.path) {
987
+ this.check(b, prim("isObject", x), "an object");
988
+ b.stmts.push({
989
+ t: "set",
990
+ n,
991
+ value: prim("member", x, this.constant(seg))
992
+ });
993
+ this.check(b, prim("isValue", x), "a field");
994
+ }
995
+ const [field, ...more] = e.path;
996
+ return field === void 0 || more.length > 0 ? x : this.#declared(b, x, primitiveOf(this.#schema.fields?.[field]), "a field of the schema");
997
+ }
998
+ /**
999
+ * This method binds the names of a `let`. The interpreter evaluates each binding in the scope outside the `let`. An
1000
+ * error of a binding is an error only where the body reads the name. Thus an error ends the block of the binding, and
1001
+ * a flag tells each read of the name that the binding has no value.
1002
+ */
1003
+ #bind(e, s, path, b) {
1004
+ const env = new Map(s.env);
1005
+ const fns = new Map(s.fns);
1006
+ Object.entries(e.bind).forEach(([name, x], i) => {
1007
+ if (x.tag === "fn") {
1008
+ fns.set(name, {
1009
+ fn: x,
1010
+ path: [...path, i],
1011
+ scope: s
1012
+ });
1013
+ env.delete(name);
1014
+ } else env.set(name, this.#attempt(b, (inner) => this.expr(x, s, [...path, i], inner)));
1015
+ });
1016
+ return {
1017
+ env,
1018
+ fns
1019
+ };
1020
+ }
1021
+ /**
1022
+ * This method lowers a call (FN.CALL). The body of the function goes at the place of the call, with the values of the
1023
+ * arguments for its parameters. The body sees the names of the place of its binding. A call that is not valid goes
1024
+ * to tier 1.
1025
+ */
1026
+ #call(e, s, path, b) {
1027
+ const bound = s.env.has(e.fn) ? void 0 : s.fns.get(e.fn);
1028
+ if (bound?.fn.params.length !== e.args.length) return this.fail(b);
1029
+ if (++this.#calls > 1e4) throw new Unsupported(`the calls put the bodies of functions in more than ${String(MAX_CALLS)} places`);
1030
+ const env = new Map(bound.scope.env);
1031
+ bound.fn.params.forEach((p, i) => env.set(p, this.#attempt(b, (inner) => this.expr(e.args[i], s, [...path, i], inner))));
1032
+ return this.expr(bound.fn.body, {
1033
+ ...s,
1034
+ env,
1035
+ fns: bound.scope.fns
1036
+ }, [...bound.path, 0], b);
1037
+ }
1038
+ #app(e, s, path, b) {
1039
+ const { op, args } = e;
1040
+ switch (op) {
1041
+ case "if": return this.#if(args, s, path, b);
1042
+ case "and":
1043
+ case "or": return args.length === 0 ? this.fail(b) : this.#andOr(op === "or", args, 0, s, path, b);
1044
+ case "ifError": return this.#ifError(args, s, path, b);
1045
+ }
1046
+ if (isListOp(op)) {
1047
+ const target = eachUnderLets(args[0]);
1048
+ if (target !== void 0) return this.#fused(op, e, target, s, path, b);
1049
+ }
1050
+ const values = args.map((x, i) => this.expr(x, s, [...path, i], b));
1051
+ const kinds = values.map((x) => this.kindOf(x));
1052
+ const site = this.#facts.staticSite(op, kinds);
1053
+ const x = this.checked(b, {
1054
+ t: "op",
1055
+ name: this.index(op),
1056
+ args: values,
1057
+ kinds
1058
+ }, "an op");
1059
+ return this.#typed(x, site?.t === "fn" ? primitiveOf(site.returns) : void 0);
1060
+ }
1061
+ /** The condition must be a boolean. Only the branch that the condition selects is evaluated. */
1062
+ #if(args, s, path, b) {
1063
+ const [cond, yes, no] = args;
1064
+ if (cond === void 0) return this.fail(b);
1065
+ const c = this.#boolean(this.expr(cond, s, [...path, 0], b), b);
1066
+ const r = this.locals++;
1067
+ const kinds = [];
1068
+ const branch = (x, i) => {
1069
+ const inner = block(b.fail);
1070
+ const value = x === void 0 ? this.fail(inner) : this.expr(x, s, [...path, i], inner);
1071
+ kinds.push(this.kindOf(value));
1072
+ inner.stmts.push({
1073
+ t: "set",
1074
+ n: r,
1075
+ value
1076
+ });
1077
+ return inner.stmts;
1078
+ };
1079
+ b.stmts.push({
1080
+ t: "if",
1081
+ cond: c,
1082
+ yes: branch(yes, 1),
1083
+ no: branch(no, 2)
1084
+ });
1085
+ return this.#typed(local(r), join$1(kinds[0], kinds[1]));
1086
+ }
1087
+ /** `or` stops at the first `true`, and `and` at the first `false`. Each argument before the stop must be a boolean. */
1088
+ #andOr(isOr, args, i, s, path, b, r = this.locals++) {
1089
+ const x = this.#boolean(this.expr(args[i], s, [...path, i], b), b);
1090
+ this.#typed(local(r), "boolean");
1091
+ if (i === args.length - 1) b.stmts.push({
1092
+ t: "set",
1093
+ n: r,
1094
+ value: x
1095
+ });
1096
+ else {
1097
+ const rest = block(b.fail);
1098
+ this.#andOr(isOr, args, i + 1, s, path, rest, r);
1099
+ const stop = [{
1100
+ t: "set",
1101
+ n: r,
1102
+ value: bool(isOr)
1103
+ }];
1104
+ b.stmts.push(isOr ? {
1105
+ t: "if",
1106
+ cond: x,
1107
+ yes: stop,
1108
+ no: rest.stmts
1109
+ } : {
1110
+ t: "if",
1111
+ cond: x,
1112
+ yes: rest.stmts,
1113
+ no: stop
1114
+ });
1115
+ }
1116
+ return local(r);
1117
+ }
1118
+ /**
1119
+ * The value of the first argument, or else the value of the second argument. An error of the first argument ends its
1120
+ * block. An exception, for example #DEPTH!, stops the program, so `ifError` does not hide it (EVAL.DEPTH).
1121
+ */
1122
+ #ifError(args, s, path, b) {
1123
+ const [first, second] = args;
1124
+ if (first === void 0) return this.fail(b);
1125
+ const label = this.labels++;
1126
+ const r = this.locals++;
1127
+ const ok = this.locals++;
1128
+ const attempt = block({
1129
+ t: "break",
1130
+ label
1131
+ });
1132
+ const value = this.expr(first, s, [...path, 0], attempt);
1133
+ attempt.stmts.push({
1134
+ t: "set",
1135
+ n: r,
1136
+ value
1137
+ }, {
1138
+ t: "set",
1139
+ n: ok,
1140
+ value: bool(true)
1141
+ });
1142
+ const otherwise = block(b.fail);
1143
+ const fallback = second === void 0 ? this.fail(otherwise) : this.expr(second, s, [...path, 1], otherwise);
1144
+ otherwise.stmts.push({
1145
+ t: "set",
1146
+ n: r,
1147
+ value: fallback
1148
+ });
1149
+ b.stmts.push({
1150
+ t: "let",
1151
+ n: ok,
1152
+ value: bool(false)
1153
+ }, {
1154
+ t: "block",
1155
+ label,
1156
+ body: attempt.stmts
1157
+ }, {
1158
+ t: "if",
1159
+ cond: prim("!", local(ok)),
1160
+ yes: otherwise.stmts,
1161
+ no: []
1162
+ });
1163
+ return this.#typed(local(r), join$1(this.kindOf(value), this.kindOf(fallback)));
1164
+ }
1165
+ /** A value of a known kind needs no check. */
1166
+ #boolean(x, b) {
1167
+ if (this.kindOf(x) !== "boolean") this.check(b, prim("isBoolean", x), "a boolean");
1168
+ return x;
1169
+ }
1170
+ #number(x, b) {
1171
+ if (this.kindOf(x) !== "number") this.check(b, prim("isNumber", x), "a number");
1172
+ return x;
1173
+ }
1174
+ /**
1175
+ * This method lowers a list op over an `each` into one loop. Like the interpreter, the loop skips an error item, and
1176
+ * with the option `strict` the list op fails at an error item. `errors` gives the error values, so an error item of
1177
+ * `errors` stops the program.
1178
+ */
1179
+ #fused(op, e, target, s, path, b) {
1180
+ let inner = s;
1181
+ let at = [...path, 0];
1182
+ for (let x = e.args[0]; x.tag === "let"; x = x.body) {
1183
+ inner = {
1184
+ ...inner,
1185
+ ...this.#bind(x, inner, at, b)
1186
+ };
1187
+ at = [...at, Object.keys(x.bind).length];
1188
+ }
1189
+ const rest = e.args.slice(1).map((x, i) => this.expr(x, s, [...path, i + 1], b));
1190
+ const options = op === "reduce" ? rest[1] : rest[0];
1191
+ const strict = options === void 0 ? void 0 : this.value(b, prim("===", call$1("opts", options), bool(true)));
1192
+ const name = rest[0];
1193
+ if (op === "reduce") {
1194
+ if (name === void 0) return this.fail(b);
1195
+ this.check(b, prim("isString", name), "an op name");
1196
+ }
1197
+ const items = (label) => {
1198
+ if (op === "errors") return RETURN;
1199
+ return strict === void 0 ? {
1200
+ t: "continue",
1201
+ label
1202
+ } : {
1203
+ t: "continue",
1204
+ label,
1205
+ strict: {
1206
+ cond: strict,
1207
+ else: b.fail
1208
+ }
1209
+ };
1210
+ };
1211
+ const acc = this.locals++;
1212
+ const n = this.typedLocal("number");
1213
+ const init = (value) => {
1214
+ b.stmts.push({
1215
+ t: "let",
1216
+ n: acc,
1217
+ value
1218
+ });
1219
+ };
1220
+ b.stmts.push({
1221
+ t: "let",
1222
+ n,
1223
+ value: num(0)
1224
+ });
1225
+ const count = (body) => {
1226
+ body.stmts.push({
1227
+ t: "set",
1228
+ n,
1229
+ value: prim("+", local(n), num(1))
1230
+ });
1231
+ };
1232
+ const opCheck = (body) => ({
1233
+ stmts: body.stmts,
1234
+ fail: b.fail
1235
+ });
1236
+ const firstThen = (body, v, then) => {
1237
+ const later = block(b.fail);
1238
+ later.stmts.push({
1239
+ t: "set",
1240
+ n: acc,
1241
+ value: then(later)
1242
+ });
1243
+ body.stmts.push({
1244
+ t: "if",
1245
+ cond: prim("===", local(n), num(0)),
1246
+ yes: [{
1247
+ t: "set",
1248
+ n: acc,
1249
+ value: v
1250
+ }],
1251
+ no: later.stmts
1252
+ });
1253
+ };
1254
+ const nonEmpty = () => {
1255
+ this.check(b, prim("!==", local(n), num(0)), "a list that is not empty");
1256
+ };
1257
+ switch (op) {
1258
+ case "count":
1259
+ this.#loop(target, inner, at, b, items, (body) => count(body));
1260
+ return local(n);
1261
+ case "sum":
1262
+ case "mean":
1263
+ init(num(0));
1264
+ this.#loop(target, inner, at, b, items, (body, _key, v) => {
1265
+ body.stmts.push({
1266
+ t: "set",
1267
+ n: acc,
1268
+ value: prim("+", local(acc), this.#number(v, opCheck(body)))
1269
+ });
1270
+ count(body);
1271
+ });
1272
+ if (op === "sum") return this.#typed(this.checked(b, call$1("result", local(acc)), "a finite sum"), "number");
1273
+ nonEmpty();
1274
+ return this.#typed(this.checked(b, call$1("result", prim("/", local(acc), local(n))), "a finite mean"), "number");
1275
+ case "min":
1276
+ case "max":
1277
+ this.#loop(target, inner, at, b, items, (body, _key, v) => {
1278
+ this.#number(v, opCheck(body));
1279
+ firstThen(body, v, () => prim(op, local(acc), v));
1280
+ count(body);
1281
+ });
1282
+ nonEmpty();
1283
+ return this.#typed(local(acc), "number");
1284
+ case "any":
1285
+ case "all":
1286
+ case "none":
1287
+ init(bool(op === "all"));
1288
+ this.#loop(target, inner, at, b, items, (body, _key, v) => {
1289
+ body.stmts.push({
1290
+ t: "set",
1291
+ n: acc,
1292
+ value: prim(op === "all" ? "&&" : "||", local(acc), this.#boolean(v, opCheck(body)))
1293
+ });
1294
+ });
1295
+ return op === "none" ? prim("!", local(acc)) : this.#typed(local(acc), "boolean");
1296
+ case "first":
1297
+ this.#loop(target, inner, at, b, items, (body, _key, v) => {
1298
+ firstThen(body, v, () => local(acc));
1299
+ count(body);
1300
+ });
1301
+ nonEmpty();
1302
+ return local(acc);
1303
+ case "values":
1304
+ case "keys":
1305
+ init(array());
1306
+ this.#loop(target, inner, at, b, items, (body, key, v) => {
1307
+ body.stmts.push({
1308
+ t: "push",
1309
+ n: acc,
1310
+ value: op === "keys" ? key : v
1311
+ });
1312
+ });
1313
+ return this.value(b, call$1("frozen", local(acc)));
1314
+ case "errors":
1315
+ this.#loop(target, inner, at, b, items, () => void 0);
1316
+ return this.value(b, call$1("frozen", array()));
1317
+ case "reduce":
1318
+ this.#loop(target, inner, at, b, items, (body, _key, v) => {
1319
+ firstThen(body, v, (later) => this.checked(later, call$1("step", name, local(acc), v), "a step of reduce"));
1320
+ count(body);
1321
+ });
1322
+ nonEmpty();
1323
+ return local(acc);
1324
+ case "sortBy":
1325
+ case "take":
1326
+ case "nth":
1327
+ /* v8 ignore next -- @preserve */
1328
+ throw new Unsupported(`the list op "${op}"`);
1329
+ }
1330
+ }
1331
+ /**
1332
+ * This method lowers the loop over the targets of an axis. The tests of `where` and the body evaluate at each target
1333
+ * in a block whose failure is `items(label)`. Then `onItem` adds the statements for the value of the body.
1334
+ */
1335
+ /**
1336
+ * This method gives the key of an address. The expressions of its computed moves evaluate first, at the position of
1337
+ * the node, and their child indexes start at `first` (NAV.COMPUTED).
1338
+ */
1339
+ #address(at, s, path, first, b) {
1340
+ const values = addrExprs(at).map((x, i) => this.expr(x, s, [...path, first + i], b));
1341
+ const args = [
1342
+ s.space,
1343
+ s.origin,
1344
+ s.focus,
1345
+ this.constant(at),
1346
+ ...values.length === 0 ? [] : [array(...values)]
1347
+ ];
1348
+ return this.checked(b, call$1("addr", ...args), "an address");
1349
+ }
1350
+ #loop(e, s, path, b, items, onItem) {
1351
+ this.#targetLoop(e.axis, e.at, s, path, 1, b, items, (body, key, at) => {
1352
+ onItem(body, key, this.expr(e.body, at, [...path, 0], body));
1353
+ });
1354
+ }
1355
+ /**
1356
+ * This method lowers the loop over the targets of an axis with the address `addr`. The tests of `where` have the child
1357
+ * indexes from `firstTest`, and the expressions of the address come after them. `each` adds the statements of a target.
1358
+ */
1359
+ #targetLoop(axis, addr, s, path, firstTest, b, items, each) {
1360
+ const from = addr === void 0 || addr.length === 0 ? s.focus : this.#address(addr, s, path, firstTest + whereTests(axis).length, b);
1361
+ const base = baseAxis(axis);
1362
+ let space = s.space;
1363
+ let over;
1364
+ let skip;
1365
+ let idx;
1366
+ if (base.t === "table") {
1367
+ space = this.checked(b, call$1("table", local(3), this.constant(base.name)), "a table");
1368
+ over = call$1("keys", space);
1369
+ } else if (base.t === "all" || base.t === "others") {
1370
+ over = call$1("keys", s.space);
1371
+ if (base.t === "others") skip = from;
1372
+ } else {
1373
+ const targets = this.checked(b, {
1374
+ t: "targets",
1375
+ axis: this.index(base),
1376
+ args: [
1377
+ s.space,
1378
+ s.origin,
1379
+ from
1380
+ ]
1381
+ }, "the targets of an axis");
1382
+ over = prim("keysOf", targets);
1383
+ idx = this.value(b, prim("idxOf", targets));
1384
+ }
1385
+ const records = this.value(b, prim("records", space));
1386
+ const label = this.labels++;
1387
+ const array_ = this.locals++;
1388
+ const index = this.locals++;
1389
+ const item = this.locals++;
1390
+ const key = local(item);
1391
+ const body = block(items(label));
1392
+ if (skip !== void 0) body.stmts.push({
1393
+ t: "if",
1394
+ cond: prim("===", key, skip),
1395
+ yes: [{ t: "next" }],
1396
+ no: []
1397
+ });
1398
+ const slot = idx === void 0 ? local(index) : prim("member", idx, local(index));
1399
+ const at = {
1400
+ space,
1401
+ origin: base.t === "table" ? key : s.origin,
1402
+ focus: key,
1403
+ env: s.env,
1404
+ fns: s.fns,
1405
+ rec: prim("recordAt", records, slot, space, key)
1406
+ };
1407
+ whereTests(axis).forEach((test, i) => {
1408
+ const ok = this.#boolean(this.expr(test, at, [...path, firstTest + i], body), body);
1409
+ body.stmts.push({
1410
+ t: "if",
1411
+ cond: prim("!", ok),
1412
+ yes: [{ t: "next" }],
1413
+ no: []
1414
+ });
1415
+ });
1416
+ each(body, key, at);
1417
+ b.stmts.push({
1418
+ t: "loop",
1419
+ label,
1420
+ item,
1421
+ index,
1422
+ array: array_,
1423
+ over,
1424
+ body: body.stmts
1425
+ });
1426
+ }
1427
+ /** This method gives a local for each name of a loop, with its first value at the node (LOOP.NAMES). */
1428
+ #loopNames(init, s, path, b) {
1429
+ const env = new Map(s.env);
1430
+ const locals = /* @__PURE__ */ new Map();
1431
+ Object.entries(init).forEach(([name, x], i) => {
1432
+ const value = this.expr(x, s, [...path, i], b);
1433
+ const n = this.locals++;
1434
+ b.stmts.push({
1435
+ t: "let",
1436
+ n,
1437
+ value
1438
+ });
1439
+ this.#typed(local(n), this.kindOf(value));
1440
+ env.set(name, { value: local(n) });
1441
+ locals.set(name, n);
1442
+ });
1443
+ return {
1444
+ env,
1445
+ locals
1446
+ };
1447
+ }
1448
+ /**
1449
+ * This method lowers one step of a loop: each new value first, and then each name gets its value. A name keeps the
1450
+ * kind of its first value, so a new value of another kind stops the program, and tier 1 evaluates it.
1451
+ */
1452
+ #loopStep(step, s, path, first, b, locals) {
1453
+ const values = Object.entries(step).map(([name, x], i) => {
1454
+ const n = locals.get(name);
1455
+ const value = this.value(b, this.expr(x, s, [...path, first + i], b));
1456
+ return [n, this.#declared(b, value, this.kindOf(local(n)), "a value of the kind of a name of a loop")];
1457
+ });
1458
+ for (const [n, value] of values) b.stmts.push({
1459
+ t: "set",
1460
+ n,
1461
+ value
1462
+ });
1463
+ }
1464
+ /** This method lowers an iteration (ITERATE.LIMIT, ITERATE.UNTIL): a repeated block with a count of its steps. */
1465
+ #iterate(e, s, path, b) {
1466
+ const first = Object.keys(e.init).length;
1467
+ const tests = first + Object.keys(e.step).length;
1468
+ const { env, locals } = this.#loopNames(e.init, s, path, b);
1469
+ const inner = {
1470
+ ...s,
1471
+ env
1472
+ };
1473
+ const label = this.labels++;
1474
+ const k = this.typedLocal("number");
1475
+ b.stmts.push({
1476
+ t: "let",
1477
+ n: k,
1478
+ value: num(0)
1479
+ });
1480
+ const body = block(b.fail);
1481
+ if (e.until !== void 0) {
1482
+ const stop = this.#boolean(this.expr(e.until, inner, [...path, tests], body), body);
1483
+ body.stmts.push({
1484
+ t: "check",
1485
+ ok: prim("!", stop),
1486
+ reason: "the test until",
1487
+ fail: {
1488
+ t: "break",
1489
+ label
1490
+ }
1491
+ });
1492
+ }
1493
+ body.stmts.push({
1494
+ t: "check",
1495
+ ok: prim("!==", local(k), num(e.limit)),
1496
+ reason: "the limit of iterate",
1497
+ fail: e.until === void 0 ? {
1498
+ t: "break",
1499
+ label
1500
+ } : b.fail
1501
+ });
1502
+ this.#loopStep(e.step, inner, path, first, body, locals);
1503
+ body.stmts.push({
1504
+ t: "set",
1505
+ n: k,
1506
+ value: prim("+", local(k), num(1))
1507
+ });
1508
+ b.stmts.push({
1509
+ t: "repeat",
1510
+ label,
1511
+ body: body.stmts
1512
+ });
1513
+ return this.expr(e.result, inner, [...path, tests + (e.until === void 0 ? 0 : 1)], b);
1514
+ }
1515
+ /** This method lowers a fold (FOLD.ORDER): the loop over the targets, with a step at each target. */
1516
+ #fold(e, s, path, b) {
1517
+ const first = Object.keys(e.init).length;
1518
+ const tests = first + Object.keys(e.step).length;
1519
+ const { env, locals } = this.#loopNames(e.init, s, path, b);
1520
+ this.#targetLoop(e.axis, e.at, s, path, tests, b, () => b.fail, (body, _key, at) => {
1521
+ this.#loopStep(e.step, {
1522
+ ...at,
1523
+ env
1524
+ }, path, first, body, locals);
1525
+ });
1526
+ return this.expr(e.result, {
1527
+ ...s,
1528
+ env
1529
+ }, [...path, tests + whereTests(e.axis).length + addrExprs(e.at).length], b);
1530
+ }
1531
+ };
1532
+ const NEGATIVE_ZERO$1 = Symbol("-0");
1533
+ /** This function gives the flag of a bound value: its local, or `true` for a value without a flag. */
1534
+ const flag = (b) => b.ok ?? bool(true);
1535
+ //#endregion
1536
+ //#region src/runtime.ts
1537
+ /**
1538
+ * The runtime of generated code. Each function follows the rule of the interpreter of the core. Where the interpreter
1539
+ * gives an error value, the function gives `FALLBACK`, and tier 1 then does the evaluation again (docs/COMPILER.md §4.1).
1540
+ * Thus the runtime makes no error values and no `Result` objects.
1541
+ *
1542
+ * Generated code uses the runtime inside a `try`, and an exception gives `FALLBACK` for the whole program. A function
1543
+ * of the runtime catches an exception only where the interpreter makes a value of it. In an op, it is `#CALC!`, and in
1544
+ * `safeIs`, it is `false`. A full call stack is `#DEPTH!`, which no list op and no `ifError` hides, so it goes on to
1545
+ * the program.
1546
+ */
1547
+ /** The value of a program that stops at a failed check. */
1548
+ const FALLBACK = Symbol("vex.fallback");
1549
+ /** A map key does not tell 0 from -0, but an op can. Thus -0 has its own key. */
1550
+ const NEGATIVE_ZERO = Symbol("-0");
1551
+ /** This function tells if a memo keeps an entry with these keys: keys without objects and functions. */
1552
+ const kept = (keys) => keys.every((k) => (typeof k !== "object" || k === null) && typeof k !== "function");
1553
+ /** This function makes the runtime of one set of options. */
1554
+ function createRuntime(options) {
1555
+ const domains = options.domains ?? [];
1556
+ const fns = options.fns;
1557
+ const extensions = options.extensions ?? {};
1558
+ const F = FALLBACK;
1559
+ const threw = (thrown) => {
1560
+ if (isStackOverflow(thrown)) throw thrown;
1561
+ return F;
1562
+ };
1563
+ const checked = (value) => {
1564
+ if (value === void 0 || value === null) return F;
1565
+ if (typeof value === "number" && !Number.isFinite(value)) return F;
1566
+ for (const d of domains) if (safeIs(d, value)) return d.valid === void 0 || d.valid(value) ? value : F;
1567
+ return value;
1568
+ };
1569
+ const invoke = (e, call, rest) => {
1570
+ try {
1571
+ const lift = e.spec.liftScalar;
1572
+ const from = e.domain.fromScalar;
1573
+ const args = lift && from !== void 0 ? rest.map((a, i) => typeof a === "number" && liftsAt(lift, i) ? from(a) : a) : rest;
1574
+ const params = e.spec.params;
1575
+ if (params !== void 0 && !args.every((a, i) => matchesKind(params[i] ?? "any", a, e.domain))) return F;
1576
+ return checked(call(args));
1577
+ } catch (thrown) {
1578
+ return threw(thrown);
1579
+ }
1580
+ };
1581
+ const dispatch = (entries, name, values, seen) => {
1582
+ const [self, ...rest] = values;
1583
+ for (const e of entries) {
1584
+ if (e === void 0 || !safeIs(e.domain, self)) continue;
1585
+ const fn = e.fn;
1586
+ if (fn !== void 0) return invoke(e, (args) => fn(self, ...args), rest);
1587
+ const method = findMethod(self, name);
1588
+ if (method === void 0) continue;
1589
+ seen?.(method);
1590
+ return invoke(e, (args) => method.apply(self, [...args]), rest);
1591
+ }
1592
+ };
1593
+ const entriesOf = (name) => domains.map((d) => entryOf(d, name));
1594
+ const stepEntries = /* @__PURE__ */ new Map();
1595
+ const indexes = /* @__PURE__ */ new WeakMap();
1596
+ const indexOf = (s) => {
1597
+ let m = indexes.get(s);
1598
+ if (m === void 0) {
1599
+ m = new Map(s.keys.map((k, i) => [k, i]));
1600
+ indexes.set(s, m);
1601
+ }
1602
+ return m;
1603
+ };
1604
+ return {
1605
+ F,
1606
+ has: (s, key) => s.has(key),
1607
+ addr(s, origin, focus, at, values) {
1608
+ const pos = {
1609
+ origin,
1610
+ focus
1611
+ };
1612
+ const fixed = values === void 0 ? void 0 : fixAddr(at, values, pos);
1613
+ if (fixed?.ok === false) return F;
1614
+ const r = resolveAddr(s, pos, fixed === void 0 ? at : fixed.value);
1615
+ return r.ok ? r.value : F;
1616
+ },
1617
+ axis(axis) {
1618
+ const cache = /* @__PURE__ */ new WeakMap();
1619
+ return (s, origin, focus) => {
1620
+ let byFocus = cache.get(s);
1621
+ if (byFocus === void 0) {
1622
+ byFocus = /* @__PURE__ */ new Map();
1623
+ cache.set(s, byFocus);
1624
+ }
1625
+ let targets = byFocus.get(focus);
1626
+ if (targets === void 0) {
1627
+ const r = axisTargets(s, {
1628
+ origin,
1629
+ focus
1630
+ }, axis);
1631
+ const index = indexOf(s);
1632
+ targets = r.ok ? {
1633
+ keys: r.value,
1634
+ idx: r.value.map((k) => index.get(k))
1635
+ } : F;
1636
+ byFocus.set(focus, targets);
1637
+ }
1638
+ return targets;
1639
+ };
1640
+ },
1641
+ table(tables, name) {
1642
+ return (tables !== void 0 && Object.hasOwn(tables, name) ? tables[name] : void 0) ?? F;
1643
+ },
1644
+ keys: (s) => s.keys,
1645
+ site(name, arity) {
1646
+ const entries = entriesOf(name);
1647
+ const listOp = isListOp(name);
1648
+ const fn = fns !== void 0 && Object.hasOwn(fns, name) ? fns[name] : void 0;
1649
+ const generic = (values) => {
1650
+ if (listOp && isVexList(values[0])) throw new Error("tier 1 gives a list op on a list value");
1651
+ if (values.length > 0) {
1652
+ const r = dispatch(entries, name, values, (m) => {
1653
+ site.m = m;
1654
+ });
1655
+ if (r !== void 0) return r;
1656
+ }
1657
+ try {
1658
+ return fn === void 0 ? F : checked(fn(...values));
1659
+ } catch (thrown) {
1660
+ return threw(thrown);
1661
+ }
1662
+ };
1663
+ const site = Object.assign(arity <= 3 ? (...values) => generic(values) : generic, {
1664
+ m: void 0,
1665
+ fn: entries.find((e) => e !== void 0)?.fn,
1666
+ free: fn
1667
+ });
1668
+ return site;
1669
+ },
1670
+ memo() {
1671
+ const spaces = /* @__PURE__ */ new WeakMap();
1672
+ const level = (s, keys, make) => {
1673
+ let at = spaces.get(s);
1674
+ if (at === void 0) {
1675
+ if (!make) return void 0;
1676
+ at = {};
1677
+ spaces.set(s, at);
1678
+ }
1679
+ for (const k of keys) {
1680
+ const slot = Object.is(k, -0) ? NEGATIVE_ZERO : k;
1681
+ let next = at.next?.get(slot);
1682
+ if (next === void 0) {
1683
+ if (!make) return void 0;
1684
+ next = {};
1685
+ (at.next ??= /* @__PURE__ */ new Map()).set(slot, next);
1686
+ }
1687
+ at = next;
1688
+ }
1689
+ return at;
1690
+ };
1691
+ return {
1692
+ get: (s, keys) => level(s, keys, false)?.entry,
1693
+ put(s, keys, v, ok) {
1694
+ const e = {
1695
+ v,
1696
+ ok
1697
+ };
1698
+ if (kept(keys)) level(s, keys, true).entry = e;
1699
+ return e;
1700
+ }
1701
+ };
1702
+ },
1703
+ domain: (index) => domains[index],
1704
+ threw,
1705
+ step(name, acc, value) {
1706
+ let entries = stepEntries.get(name);
1707
+ if (entries === void 0) {
1708
+ entries = entriesOf(name);
1709
+ stepEntries.set(name, entries);
1710
+ }
1711
+ return dispatch(entries, name, [acc, value]) ?? F;
1712
+ },
1713
+ result(value) {
1714
+ try {
1715
+ return checked(value);
1716
+ } catch (thrown) {
1717
+ return threw(thrown);
1718
+ }
1719
+ },
1720
+ opts: (value) => value?.strict,
1721
+ rec(names, values) {
1722
+ const out = {};
1723
+ names.forEach((n, i) => {
1724
+ out[n] = values[i];
1725
+ });
1726
+ return Object.freeze(out);
1727
+ },
1728
+ list: (keys, values) => vexList(keys.map((key, i) => ({
1729
+ key,
1730
+ result: {
1731
+ ok: true,
1732
+ value: values[i]
1733
+ }
1734
+ }))),
1735
+ frozen: (values) => Object.freeze([...values]),
1736
+ ext(kind, data, s, origin, focus, path) {
1737
+ const handler = Object.hasOwn(extensions, kind) ? extensions[kind] : void 0;
1738
+ if (handler === void 0) return F;
1739
+ const r = handler(data, {
1740
+ space: s,
1741
+ position: {
1742
+ origin,
1743
+ focus
1744
+ },
1745
+ path
1746
+ });
1747
+ return r.ok ? r.value : F;
1748
+ },
1749
+ var(vars, name) {
1750
+ return vars !== void 0 && Object.prototype.propertyIsEnumerable.call(vars, name) ? vars[name] : F;
1751
+ }
1752
+ };
1753
+ }
1754
+ //#endregion
1755
+ //#region src/tiers.ts
1756
+ /**
1757
+ * The tiers (docs/COMPILER.md §2.1). Tier 2 is generated JavaScript. Tier 1 is the closure compiler of the core, and it
1758
+ * gives each result that tier 2 cannot give. Thus a tiered program gives the results of the interpreter.
1759
+ */
1760
+ /**
1761
+ * This function lowers an expression and prints its source for the options. The op tables of the domains give the
1762
+ * fast path of each op site. It is pure, so a build can use it.
1763
+ */
1764
+ function generate(expr, options = {}) {
1765
+ try {
1766
+ const facts = factsOf(options);
1767
+ const program = lower(expr, facts, options.schema);
1768
+ return {
1769
+ ok: true,
1770
+ program,
1771
+ source: printJs(program, facts),
1772
+ options
1773
+ };
1774
+ } catch (thrown) {
1775
+ return {
1776
+ ok: false,
1777
+ reason: thrown instanceof Unsupported ? thrown.message : "the lowering threw an exception"
1778
+ };
1779
+ }
1780
+ }
1781
+ /**
1782
+ * This function makes the function of tier 2 with `new Function`, with the options of the source. It throws on a page
1783
+ * that does not permit `new Function`.
1784
+ */
1785
+ function load(generated) {
1786
+ return new Function("K", "R", generated.source)(generated.program.constants, createRuntime(generated.options));
1787
+ }
1788
+ /**
1789
+ * This function compiles an expression into tier 2 if it can, and else into tier 1. After a failed check of tier 2,
1790
+ * tier 1 does that evaluation again. A run with a trace and `explain` always use tier 1, because tier 2 makes no trace.
1791
+ */
1792
+ function tiered(expr, options = {}) {
1793
+ const slow = compile(expr, options);
1794
+ const generated = generate(expr, options);
1795
+ let fast;
1796
+ let reason;
1797
+ if (generated.ok) try {
1798
+ fast = load(generated);
1799
+ } catch {
1800
+ reason = "the page does not permit new Function";
1801
+ }
1802
+ else reason = generated.reason;
1803
+ const stats = {
1804
+ runs: 0,
1805
+ fallbacks: 0
1806
+ };
1807
+ return {
1808
+ expr,
1809
+ tier: fast === void 0 ? 1 : 2,
1810
+ ...reason === void 0 ? {} : { reason },
1811
+ stats,
1812
+ run(r) {
1813
+ stats.runs++;
1814
+ if (fast === void 0 || r.trace !== void 0) return slow.run(r);
1815
+ const value = fast(r.space, r.origin, r.vars, r.tables);
1816
+ if (value !== FALLBACK) return ok(value);
1817
+ stats.fallbacks++;
1818
+ return slow.run(r);
1819
+ },
1820
+ explain: (r) => slow.explain(r)
1821
+ };
1822
+ }
1823
+ //#endregion
1824
+ //#region src/module.ts
1825
+ /**
1826
+ * Standalone modules (docs/COMPILER.md §4.4 and §6). `emitModule` prints a program as an ES module that has no import of
1827
+ * Vex. A host that guarantees the kinds of its input uses it without the interpreter, for example ireko at build time.
1828
+ *
1829
+ * The module gives the results of the interpreter for each input that keeps the schema. It checks the schema once, at
1830
+ * the start of a run, and an input against the schema throws a `VexContractError`. An error of Vex is a value too:
1831
+ * the run gives `VEX_ERROR` at its key.
1832
+ *
1833
+ * The printer gives statements and loops, as a person writes them. A binding is a variable, and a list op is a `for`
1834
+ * loop with a running value. An error of Vex is a thrown sentinel. A binding, `ifError` and an item of a list op catch
1835
+ * it, as in the interpreter. A node of the memo and the key of the run catch it too. Each op is the function of its
1836
+ * domain, as text, so it has the bits of the interpreter (§4.2).
1837
+ *
1838
+ * A part of the program that depends on no key of the space is a constant of the run. The module evaluates it once,
1839
+ * before the loop over the keys. A node of the memo is one function of its other keys, with a map of its values. The
1840
+ * nodes with the same expression share the function.
1841
+ *
1842
+ * The printer takes a part of the language. It takes an array space of records, the fields and the variables of the
1843
+ * schema, and the axes `all`, `others` and `window`. The kinds of each op site must decide its op. Another construct
1844
+ * gives a reason, not code.
1845
+ */
1846
+ /** The error of a construct that a standalone module does not have. */
1847
+ var NotStandalone = class extends Error {};
1848
+ /** The levels of a constant of the run. */
1849
+ const NO_DEPS = /* @__PURE__ */ new Set();
1850
+ /** This function gives the levels of some codes together. */
1851
+ const depsOf = (...xs) => new Set(xs.flatMap((x) => [...x.v.deps]));
1852
+ /** This function gives the statements of some codes, in order. */
1853
+ const stmtsOf = (...xs) => xs.flatMap((x) => x.s);
1854
+ /** This function indents some statements by one level. */
1855
+ const ind = (xs) => xs.map((x) => ` ${x}`);
1856
+ /** The helpers of the generated code. A module has only the helpers that it uses. */
1857
+ const HELPERS = {
1858
+ F: "function F() { throw E; }",
1859
+ C: "function C(m) { throw new VexContractError(m); }",
1860
+ T: "function T(f) { try { return f(); } catch { return E; } }",
1861
+ L: "function L(f) { let done = false, v; return () => { if (!done) { done = true; try { v = f(); } catch { v = E; } } return v; }; }",
1862
+ Q: "function Q(f) { const m = []; return (j) => { let v = m[j]; if (v === undefined) { try { v = f(j); } catch { v = E; } m[j] = v; } return v; }; }",
1863
+ G: "function G(x) { return x === E ? F() : x; }",
1864
+ B: "function B(x) { return typeof x === \"boolean\" ? x : F(); }",
1865
+ U: "function U(x) { return typeof x === \"number\" ? x : F(); }",
1866
+ X: "function X(t, n) { return t >= 0 && t < n ? t : F(); }",
1867
+ I: "function I(t, n) { return Number.isInteger(t) && t >= 0 && t < n ? t : F(); }",
1868
+ K: "function K(k, n) { return typeof k === \"string\" && /^(0|[1-9]\\d*)$/.test(k) && +k < n ? +k : F(); }",
1869
+ V: "function V(l, s) { if (s && l.some((x) => x[1] === E)) F(); return l.filter((x) => x[1] !== E); }",
1870
+ SB: [
1871
+ "function SB(l, s) {",
1872
+ " const o = V(l, s);",
1873
+ " const t = o.length > 0 ? typeof o[0][1] : \"number\";",
1874
+ " for (const [, v] of o) if (typeof v !== t || (t !== \"number\" && t !== \"string\") || v !== v) F();",
1875
+ " return o.sort((a, b) => (a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0));",
1876
+ "}"
1877
+ ].join("\n"),
1878
+ TK: "function TK(l, n, s) { const o = V(l, s); return Number.isSafeInteger(n) && n >= 0 ? o.slice(0, n) : F(); }",
1879
+ NT: "function NT(l, i, s) { const o = V(l, s); return Number.isSafeInteger(i) && i >= 0 && i < o.length ? o[i][1] : F(); }",
1880
+ M1: [
1881
+ "function M1(f) {",
1882
+ " const m = new Map();",
1883
+ " return (k) => {",
1884
+ " const s = Object.is(k, -0) ? Z : k;",
1885
+ " let r = m.get(s);",
1886
+ " if (r === undefined) {",
1887
+ " try { r = f(k); } catch { r = E; }",
1888
+ " m.set(s, r);",
1889
+ " }",
1890
+ " return G(r);",
1891
+ " };",
1892
+ "}"
1893
+ ].join("\n"),
1894
+ M: [
1895
+ "function M(f) {",
1896
+ " const root = new Map();",
1897
+ " return (...k) => {",
1898
+ " let m = root;",
1899
+ " for (const x of k.slice(0, -1)) {",
1900
+ " const s = Object.is(x, -0) ? Z : x;",
1901
+ " let c = m.get(s);",
1902
+ " if (c === undefined) m.set(s, (c = new Map()));",
1903
+ " m = c;",
1904
+ " }",
1905
+ " const last = k.at(-1);",
1906
+ " const s = Object.is(last, -0) ? Z : last;",
1907
+ " let r = m.get(s);",
1908
+ " if (r === undefined) {",
1909
+ " try { r = f(...k); } catch { r = E; }",
1910
+ " m.set(s, r);",
1911
+ " }",
1912
+ " return G(r);",
1913
+ " };",
1914
+ "}"
1915
+ ].join("\n")
1916
+ };
1917
+ /**
1918
+ * This function gives the code of the helper S, a node of the memo that keeps its items (Printer.#cached). The helper
1919
+ * has only the parts that the nodes of the module need:
1920
+ *
1921
+ * - `group`: the groups of the values of the key (mode 1).
1922
+ * - `prefix`: the prefixes of the items (mode 2).
1923
+ * - `strict`: the option strict of a list op.
1924
+ * - `ok`: the check of the kind of a value.
1925
+ * - `pre`: the tests before the test of the key.
1926
+ *
1927
+ * The node gives `key` for the value of each item, and `val` for the value of an item from its index. It gives `test`
1928
+ * for the test of the key.
1929
+ */
1930
+ const helperS = (has) => {
1931
+ const on = (f, ...lines) => has.has(f) ? lines : [];
1932
+ const strict = has.has("strict");
1933
+ const ok = has.has("ok");
1934
+ const fails = [...strict ? ["x === E"] : [], ...ok ? ["x === W"] : []].join(" || ");
1935
+ const skips = strict ? "x === N || (x === E && !strict)" : "x === N || x === E";
1936
+ return [
1937
+ "function S(n, mode, strict, a0, step, result, key, val, test, pre, ok) {",
1938
+ " let ts, js, xs, bad, reach, gs, mono, pa, pc, pe;",
1939
+ " const value = (i) => {",
1940
+ " let x = xs[i];",
1941
+ " if (x === undefined) {",
1942
+ " x = val(js[i]);",
1943
+ ...on("ok", " if (ok && x !== E && x !== N && !ok(x)) x = W;"),
1944
+ " xs[i] = x;",
1945
+ " }",
1946
+ " return x;",
1947
+ " };",
1948
+ " return M1((q) => {",
1949
+ " if (ts === undefined) {",
1950
+ " ts = [];",
1951
+ " js = [];",
1952
+ " xs = [];",
1953
+ ...on("strict", " bad = false;", " reach = 0;"),
1954
+ " for (let j = 0; j < n; j++) {",
1955
+ " try {",
1956
+ ...on("pre", " if (pre && !pre(j)) continue;"),
1957
+ ...on("strict", " reach++;"),
1958
+ " const t = key(j);",
1959
+ " if (mode && t !== t) continue;",
1960
+ " ts.push(t);",
1961
+ " js.push(j);",
1962
+ " } catch {",
1963
+ ...on("strict", " bad = true;"),
1964
+ " }",
1965
+ " }",
1966
+ ...on("group", " if (mode === 1) {", " gs = new Map();", " for (let i = 0; i < ts.length; i++) {", " let g = gs.get(ts[i]);", " if (g === undefined) gs.set(ts[i], (g = []));", " g.push(i);", " }", " }"),
1967
+ ...on("prefix", " if (mode === 2) {", " mono = true;", " for (let i = 1; i < ts.length; i++) if (!(ts[i - 1] <= ts[i])) mono = false;", " pa = [a0];", " pc = [0];", " pe = [false];", " }"),
1968
+ " }",
1969
+ strict ? " if (q === E) return strict && (bad || reach > 0) ? F() : result(a0, 0);" : " if (q === E) return result(a0, 0);",
1970
+ ...on("strict", " if (strict && bad) F();"),
1971
+ " let a = a0, c = 0;",
1972
+ " const add = (i) => {",
1973
+ " const x = value(i);",
1974
+ ` if (${skips}) return;`,
1975
+ ...fails === "" ? [] : [` if (${fails}) F();`],
1976
+ " a = step(a, c, x);",
1977
+ " c++;",
1978
+ " };",
1979
+ ...on("group", " if (mode === 1) {", " const g = gs.get(q);", " if (g !== undefined) for (const i of g) add(i);", " return result(a, c);", " }"),
1980
+ ...on("prefix", " if (mode === 2 && mono) {", " let lo = 0, hi = ts.length;", " while (lo < hi) {", " const h = (lo + hi) >> 1;", " if (test(ts[h], q)) lo = h + 1;", " else hi = h;", " }", " for (let i = pa.length - 1; i < lo; i++) {", " let x = value(i), b = pa[i], d = pc[i], err = pe[i];", ...fails === "" ? [" if (x !== N && x !== E) {"] : [` if (${fails.replace("x === E", "(x === E && strict)")}) err = true;`, " else if (x !== N && x !== E) {"], " b = step(b, d, x);", " d++;", " }", " pa.push(b);", " pc.push(d);", " pe.push(err);", " }", " if (pe[lo]) F();", " return result(pa[lo], pc[lo]);", " }"),
1981
+ " for (let i = 0; i < ts.length; i++) if (test(ts[i], q)) add(i);",
1982
+ " return result(a, c);",
1983
+ " });",
1984
+ "}"
1985
+ ].join("\n");
1986
+ };
1987
+ /** The step of the running value of first and of count: the name of its function in a module, and its code. */
1988
+ const FIRST_STEP = ["s_first", "(a, c, x) => (c === 0 ? x : a)"];
1989
+ /** The step of the running value of each list op: the name of its function in a module, and its code. */
1990
+ const STEPS = {
1991
+ count: FIRST_STEP,
1992
+ first: FIRST_STEP,
1993
+ sum: ["s_add", "(a, c, x) => a + x"],
1994
+ mean: ["s_add", "(a, c, x) => a + x"],
1995
+ min: ["s_min", "(a, c, x) => (c === 0 ? x : Math.min(a, x))"],
1996
+ max: ["s_max", "(a, c, x) => (c === 0 ? x : Math.max(a, x))"],
1997
+ any: ["s_or", "(a, c, x) => a || x"],
1998
+ none: ["s_or", "(a, c, x) => a || x"],
1999
+ all: ["s_and", "(a, c, x) => a && x"]
2000
+ };
2001
+ /** The helpers that each helper uses. */
2002
+ const NEEDS = {
2003
+ F: [],
2004
+ C: [],
2005
+ T: [],
2006
+ L: [],
2007
+ Q: [],
2008
+ G: ["F"],
2009
+ B: ["F"],
2010
+ U: ["F"],
2011
+ X: ["F"],
2012
+ I: ["F"],
2013
+ K: ["F"],
2014
+ M: ["G"],
2015
+ M1: ["G"],
2016
+ S: ["M1", "F"],
2017
+ V: ["F"],
2018
+ SB: ["V", "F"],
2019
+ TK: ["V", "F"],
2020
+ NT: ["V", "F"]
2021
+ };
2022
+ /** The list ops of a standalone module. */
2023
+ const LIST_OPS = /* @__PURE__ */ new Set([
2024
+ "count",
2025
+ "sum",
2026
+ "mean",
2027
+ "min",
2028
+ "max",
2029
+ "any",
2030
+ "all",
2031
+ "none",
2032
+ "first"
2033
+ ]);
2034
+ const NUMBER_LIST_OPS = /* @__PURE__ */ new Set([
2035
+ "count",
2036
+ "sum",
2037
+ "mean",
2038
+ "min",
2039
+ "max"
2040
+ ]);
2041
+ const BOOLEAN_LIST_OPS = /* @__PURE__ */ new Set([
2042
+ "any",
2043
+ "all",
2044
+ "none"
2045
+ ]);
2046
+ /** This function gives the kind of the result of a list op: first gives the kind of its items. */
2047
+ const listKind = (op, item) => NUMBER_LIST_OPS.has(op) ? "number" : BOOLEAN_LIST_OPS.has(op) ? "boolean" : item;
2048
+ const LOOPS = /* @__PURE__ */ new WeakMap();
2049
+ /** This function gives the names that an expression reads, also the names that it binds itself. */
2050
+ function namesOf(e, out = /* @__PURE__ */ new Set()) {
2051
+ if (e.tag === "var") out.add(e.name);
2052
+ for (const x of children(e)) namesOf(x, out);
2053
+ return out;
2054
+ }
2055
+ /**
2056
+ * The smallest work of an expression in a column of the run. The work is the number of nodes. A node of the memo and a
2057
+ * constant of the run count as one node each. A part with less work costs less than the read of its column.
2058
+ */
2059
+ const COLUMN_WORK = 10;
2060
+ /** This function gives the head of a loop over targets: from `lo` up to `hi`, or from `hi` down to `lo` in the reverse order. */
2061
+ const forHead = (j, lo, hi, reverse) => reverse ? `for (let ${j} = ${hi} - 1; ${j} >= ${lo}; ${j}--) {` : `for (let ${j} = ${lo}; ${j} < ${hi}; ${j}++) {`;
2062
+ /** This function tells if an expression has a loop of names: a fold or an iteration. */
2063
+ function hasLoop(e) {
2064
+ let found = LOOPS.get(e);
2065
+ if (found === void 0) {
2066
+ found = e.tag === "fold" || e.tag === "iterate" || children(e).some(hasLoop);
2067
+ LOOPS.set(e, found);
2068
+ }
2069
+ return found;
2070
+ }
2071
+ /**
2072
+ * This function tells if a node of the memo has a loop of its own. Such a loop is outside its keys and outside the nodes
2073
+ * of the memo in it. A node without one combines the values of other nodes, and a function of its own only costs time.
2074
+ */
2075
+ function ownLoop(e, root, memo, keys) {
2076
+ if (e !== root && (memo.has(e) || keys.has(e))) return false;
2077
+ return e.tag === "each" || children(e).some((x) => ownLoop(x, root, memo, keys));
2078
+ }
2079
+ /** This function gives the nodes of the memo of an expression that have a loop of their own, with their keys. */
2080
+ function memoOf(expr) {
2081
+ const all = memoNodes(expr);
2082
+ return new Map([...all].filter(([e, keys]) => ownLoop(e, e, all, new Set(keys))));
2083
+ }
2084
+ /** This function tells if an expression contains the expression `x`, the same object. */
2085
+ function contains(e, x) {
2086
+ return e === x || children(e).some((c) => contains(c, x));
2087
+ }
2088
+ /** This function gives the base of an axis and its tests in the order of evaluation. */
2089
+ function testsOf(axis) {
2090
+ const tests = [];
2091
+ let base = axis;
2092
+ while (base.t === "where") {
2093
+ tests.unshift(base.test);
2094
+ base = base.axis;
2095
+ }
2096
+ return {
2097
+ base,
2098
+ tests
2099
+ };
2100
+ }
2101
+ /**
2102
+ * This function gives the parts of a test `and`, and of each part that is a test `and` too. `and` stops at the first
2103
+ * `false`, as a chain of tests does, and each part must be a boolean.
2104
+ */
2105
+ function partsOf(t) {
2106
+ return t.tag === "app" && t.op === "and" && t.args.length > 0 ? t.args.flatMap(partsOf) : [t];
2107
+ }
2108
+ /** This function gives the kind of two values in the branches of a form, if they have the same kind. */
2109
+ const join = (a, b) => a === b ? a : void 0;
2110
+ /** This function gives a value that is a constant of the run, with plain code. */
2111
+ const plainValue = (code, kind) => ({
2112
+ code,
2113
+ kind,
2114
+ safe: true,
2115
+ deps: NO_DEPS,
2116
+ plain: true
2117
+ });
2118
+ /** This function gives the code of a value with no statements. */
2119
+ const bare = (v) => ({
2120
+ s: [],
2121
+ v
2122
+ });
2123
+ /** This function gives the code of a literal. A value that is not a finite number, a text, a boolean or null has no code. */
2124
+ function literal(value) {
2125
+ if (typeof value === "number") {
2126
+ if (!Number.isFinite(value)) throw new NotStandalone("a literal is a number that is not finite");
2127
+ return plainValue(Object.is(value, -0) ? "-0" : String(value), "number");
2128
+ }
2129
+ if (typeof value === "string") return plainValue(JSON.stringify(value), "string");
2130
+ if (typeof value === "boolean") return plainValue(String(value), "boolean");
2131
+ if (value === null) return plainValue("null", void 0);
2132
+ throw new NotStandalone("a literal is not a number, a text, a boolean or null");
2133
+ }
2134
+ /**
2135
+ * This function gives a text that is the same for two expressions with the same structure. -0 is not 0. A part with a
2136
+ * token gives the token, so the text does not depend on that part. A token is an object, and a literal of a module is
2137
+ * not, so a token is not the text of a literal.
2138
+ */
2139
+ function canonical(e, token) {
2140
+ return JSON.stringify(e, (_name, x) => token(x) ?? (Object.is(x, -0) ? { "-0": 0 } : x));
2141
+ }
2142
+ /** The values of each kind that `copied` gives to a function and to its copy. */
2143
+ const SAMPLES = {
2144
+ number: [
2145
+ 0,
2146
+ 1,
2147
+ -1,
2148
+ 2.5,
2149
+ -0,
2150
+ 1e300,
2151
+ -7
2152
+ ],
2153
+ string: [
2154
+ "",
2155
+ "a",
2156
+ "ab c"
2157
+ ],
2158
+ boolean: [true, false]
2159
+ };
2160
+ /** This function gives each list of arguments with one sample of each parameter, from the samples of each parameter. */
2161
+ function samples(each) {
2162
+ return each.reduce((acc, values) => acc.flatMap((xs) => values.map((x) => [...xs, x])), [[]]);
2163
+ }
2164
+ /** This function gives the text of plain data, with -0 apart from 0. */
2165
+ const dataText = (x) => canonical(x, () => void 0);
2166
+ /** This function tells if two values are the same: the same primitive, or plain data with the same structure. */
2167
+ function same(a, b) {
2168
+ if (Object.is(a, b)) return true;
2169
+ if (typeof a !== "object" || a === null || typeof b !== "object" || b === null || Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) return false;
2170
+ return dataText(a) === dataText(b);
2171
+ }
2172
+ /** This function gives the value of a call, or that it threw. */
2173
+ function call(f) {
2174
+ try {
2175
+ return {
2176
+ threw: false,
2177
+ value: f()
2178
+ };
2179
+ } catch {
2180
+ return { threw: true };
2181
+ }
2182
+ }
2183
+ /** This function tells if two calls give the same: the same value, or an exception in both. */
2184
+ function sameCall(a, b) {
2185
+ const x = call(a);
2186
+ const y = call(b);
2187
+ return x.threw === y.threw && same(x.value, y.value);
2188
+ }
2189
+ /**
2190
+ * This function gives the source of a function of a domain, for a copy in a module. The source must be an expression:
2191
+ * the source of a native function or of a method does not compile as one. A copy must give the values of the function:
2192
+ * a function that reads a name outside itself gives an exception in the copy. Thus the copy and the function must give
2193
+ * the same for the samples of their kinds.
2194
+ */
2195
+ function copied(f, each, what) {
2196
+ const src = Function.prototype.toString.call(f);
2197
+ let copy;
2198
+ try {
2199
+ copy = new Function(`"use strict"; return (${src});`)();
2200
+ } catch {
2201
+ throw new NotStandalone(`${what} has no source that a module can copy`);
2202
+ }
2203
+ const fn = f;
2204
+ if (!samples(each).every((xs) => sameCall(() => fn(...xs), () => copy(...xs)))) throw new NotStandalone(`${what} reads a name outside itself, so a module cannot copy it`);
2205
+ return src;
2206
+ }
2207
+ /** The functions that an inline form can use. They do not throw for numbers. */
2208
+ const CALLS = /* @__PURE__ */ new Set([
2209
+ "Math.abs",
2210
+ "Math.ceil",
2211
+ "Math.floor",
2212
+ "Math.round",
2213
+ "Math.trunc",
2214
+ "Math.sign",
2215
+ "Math.sqrt",
2216
+ "Math.cbrt",
2217
+ "Math.exp",
2218
+ "Math.log",
2219
+ "Math.log10",
2220
+ "Math.log2",
2221
+ "Math.min",
2222
+ "Math.max",
2223
+ "Math.pow",
2224
+ "Math.hypot",
2225
+ "Math.sin",
2226
+ "Math.cos",
2227
+ "Math.tan",
2228
+ "Math.atan2",
2229
+ "Number.isFinite"
2230
+ ]);
2231
+ /**
2232
+ * This function gives the inline form of the source of an arrow function. The body of the function must be an
2233
+ * expression of operators, numbers, its parameters and the functions of `CALLS`. Such a body cannot throw for primitive
2234
+ * values (§7.1). The inline form is the text of the function itself, so it has its bits.
2235
+ */
2236
+ function inlineForm(src) {
2237
+ const m = /^\(?\s*((?:[A-Za-z_$][\w$]*\s*,\s*)*[A-Za-z_$][\w$]*)\s*\)?\s*=>\s*([\s\S]*)/.exec(src);
2238
+ if (m === null) return void 0;
2239
+ const params = m[1].split(",").map((x) => x.trim());
2240
+ const parts = [];
2241
+ const uses = params.map(() => 0);
2242
+ let text = "";
2243
+ const split = m[2].split(/([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)?)/);
2244
+ for (const [i, t] of split.entries()) if (i % 2 === 0) {
2245
+ if (!/^(?:\d|\.\d|\s|===?|!==?|<=|>=|[+\-*/%<>!?:(),&|^~])*$/.test(t) || /\+\+|--|\)\s*\(/.test(t)) return void 0;
2246
+ text += t;
2247
+ } else if (CALLS.has(t)) text += t;
2248
+ else {
2249
+ const p = params.indexOf(t);
2250
+ if (p < 0 || /^\s*\(/.test(split[i + 1])) return void 0;
2251
+ parts.push(text, p);
2252
+ text = "";
2253
+ uses[p] = uses[p] + 1;
2254
+ }
2255
+ parts.push(text);
2256
+ return {
2257
+ params,
2258
+ parts,
2259
+ uses
2260
+ };
2261
+ }
2262
+ /** This function gives the text of an inline form without spaces, with `#i` for the parameter `at(i)`. */
2263
+ const patternOf = (form, at) => form.parts.map((p) => typeof p === "number" ? `#${at(p)}` : p.replaceAll(/\s/g, "")).join("");
2264
+ var Printer = class {
2265
+ #facts;
2266
+ #domains;
2267
+ #schema;
2268
+ #memo;
2269
+ helpers = /* @__PURE__ */ new Set();
2270
+ /** The declarations at the top of the module: the functions of the domains and the checks of the results. */
2271
+ top = /* @__PURE__ */ new Map();
2272
+ /** The statements at the start of a run: the constants of the run and the functions of the memo. */
2273
+ run = [];
2274
+ /** The variables of the schema that the program reads. */
2275
+ vars = /* @__PURE__ */ new Map();
2276
+ /** True when the module has a node of the memo, so it needs the key of -0. */
2277
+ memos = false;
2278
+ /** The parts of the helper S that the nodes of the memo that keep their items need (helperS). */
2279
+ features = /* @__PURE__ */ new Set();
2280
+ #names = 0;
2281
+ /** The number of the next bound function, and of the next printed function. */
2282
+ #fnIds = 0;
2283
+ #printed = 0;
2284
+ /** The level of the names of the next loop. It is far above the levels of the axes, so the two do not meet. */
2285
+ #loops = 1e6;
2286
+ /** The node of the memo whose function the printer prints, so it prints the node itself. */
2287
+ #inside;
2288
+ #structures = /* @__PURE__ */ new Map();
2289
+ #kinds = /* @__PURE__ */ new Map();
2290
+ #ops = /* @__PURE__ */ new Map();
2291
+ /** The inline form of each function of an op, or undefined for a function that the module calls. */
2292
+ #forms = /* @__PURE__ */ new Map();
2293
+ /** The functions of ops that the module calls, not in an inline form. */
2294
+ #called = /* @__PURE__ */ new Set();
2295
+ /** The key of the expression of each code that is a constant of the run, and the read of each hoisted constant by key. */
2296
+ #keyOf = /* @__PURE__ */ new WeakMap();
2297
+ #constants = /* @__PURE__ */ new Map();
2298
+ /** The columns of the run, by the structure of their expression. */
2299
+ #columns = /* @__PURE__ */ new Map();
2300
+ /** The expressions whose code is a constant of the run. */
2301
+ #constant = /* @__PURE__ */ new WeakSet();
2302
+ /** The expressions at a place that takes a list: a binding, the head of a list op and the list of an axis. */
2303
+ #wantList = /* @__PURE__ */ new WeakSet();
2304
+ /** The facts of the list of each function of the memo whose value is a list. */
2305
+ #lists = /* @__PURE__ */ new Map();
2306
+ constructor(expr, options) {
2307
+ this.#domains = options.domains ?? [];
2308
+ this.#facts = factsOf({ domains: this.#domains });
2309
+ this.#schema = options.schema;
2310
+ this.#memo = memoOf(expr);
2311
+ }
2312
+ use(name) {
2313
+ this.helpers.add(name);
2314
+ return name;
2315
+ }
2316
+ /**
2317
+ * This method gives the check of a result of a kind, or undefined for a result that needs no check. A number must be
2318
+ * finite, and the domain of the kind can check the value with valid. The law checker of the test kit checks the
2319
+ * declaration `returns` of each op (KIND.RETURNS), so the module trusts the kind itself.
2320
+ */
2321
+ check(kind) {
2322
+ const name = `k_${kind.replace(":", "_")}`;
2323
+ if (!this.top.has(name)) {
2324
+ const d = this.#facts.checkOf(kind);
2325
+ if (d === void 0) throw new NotStandalone(`a domain without a primitive type comes before the domain of a ${kind}`);
2326
+ const domain = this.#domains[d];
2327
+ const valid = domain?.valid === void 0 ? void 0 : this.#valid(d, domain.name, kind, domain.valid);
2328
+ const conds = [...kind === "number" ? ["Number.isFinite(x)"] : [], ...valid === void 0 ? [] : [`${valid}(x)`]];
2329
+ if (conds.length === 0) return void 0;
2330
+ this.top.set(name, `const ${name} = (x) => (${conds.join(" && ")} ? x : ${this.use("F")}());`);
2331
+ }
2332
+ return name;
2333
+ }
2334
+ /** This method gives the code of a result with its check, if it needs one. */
2335
+ #checked(kind, code) {
2336
+ const k = this.check(kind);
2337
+ return k === void 0 ? code : `${k}(${code})`;
2338
+ }
2339
+ #valid(d, domain, kind, valid) {
2340
+ const name = `v_${d}`;
2341
+ const src = copied(valid, [this.#samples(kind)], `the check "valid" of the domain ${domain}`);
2342
+ const form = inlineForm(src);
2343
+ if (kind === "number" && form !== void 0 && patternOf(form, (p) => p) === "Number.isFinite(#0)") return void 0;
2344
+ this.top.set(name, `const ${name} = ${src};`);
2345
+ return name;
2346
+ }
2347
+ /** This method gives the samples of a kind: the samples of a primitive type, or the samples of a domain (KIND.DOMAIN). */
2348
+ #samples(kind) {
2349
+ const primitive = primitiveOf(kind);
2350
+ if (primitive !== void 0) return SAMPLES[primitive];
2351
+ const d = this.#domains.find((x) => kindOfDomain(x) === kind);
2352
+ if (d.samples === void 0) throw new NotStandalone(`the domain ${d.name} gives no samples, so a module cannot check a copy of its op`);
2353
+ return d.samples();
2354
+ }
2355
+ /**
2356
+ * This method gives the code of a check of the kind of an input. The check is a test of its JavaScript type, or the
2357
+ * copy of `is` of a domain. The code is true for an input against the kind.
2358
+ */
2359
+ against(kind, input) {
2360
+ const primitive = primitiveOf(kind);
2361
+ if (primitive !== void 0) return `typeof ${input} !== "${primitive}"`;
2362
+ const d = this.#domains.findIndex((x) => kindOfDomain(x) === kind);
2363
+ const domain = this.#domains[d];
2364
+ if (domain === void 0) throw new NotStandalone(`the schema has the kind ${kind}, and no domain has it`);
2365
+ const name = `is_${String(d)}`;
2366
+ if (!this.top.has(name)) {
2367
+ const src = copied(domain.is, [[
2368
+ ...SAMPLES.number,
2369
+ ...SAMPLES.string,
2370
+ ...SAMPLES.boolean,
2371
+ null,
2372
+ {},
2373
+ [],
2374
+ ...this.#samples(kind)
2375
+ ]], `the test "is" of the domain ${domain.name}`);
2376
+ this.top.set(name, `const ${name} = ${src};`);
2377
+ }
2378
+ return `!${name}(${input})`;
2379
+ }
2380
+ /** This method gives a new name for the code. */
2381
+ fresh(prefix) {
2382
+ return `${prefix}${this.#names++}`;
2383
+ }
2384
+ /** This method gives the code of a name: a read that throws the error of its value, if it can hold an error. */
2385
+ #read(name) {
2386
+ const base = {
2387
+ kind: name.kind,
2388
+ deps: name.deps,
2389
+ plain: true,
2390
+ list: name.list
2391
+ };
2392
+ return name.lazy ? {
2393
+ ...base,
2394
+ code: `${this.use("G")}(${name.code})`,
2395
+ safe: false,
2396
+ held: name.code
2397
+ } : {
2398
+ ...base,
2399
+ code: name.code,
2400
+ safe: true
2401
+ };
2402
+ }
2403
+ /** This method gives the name of a constant of the run, from the read of its value. */
2404
+ #nameOf(v) {
2405
+ return {
2406
+ code: v.held ?? v.code,
2407
+ kind: v.kind,
2408
+ lazy: v.held !== void 0,
2409
+ deps: NO_DEPS,
2410
+ list: v.list
2411
+ };
2412
+ }
2413
+ /**
2414
+ * This method gives the statements that put the value of a code, or the error sentinel, into a new variable `name`.
2415
+ * A constant of the run without statements uses the helper `T`: it evaluates once, so its closure costs little.
2416
+ */
2417
+ #store(name, c, run = false) {
2418
+ if (c.v.safe) return [...c.s, `const ${name} = ${c.v.code};`];
2419
+ if (c.s.length === 0 && c.v.held !== void 0) return [`const ${name} = ${c.v.held};`];
2420
+ if (run && c.s.length === 0) return [`const ${name} = ${this.use("T")}(() => ${c.v.code});`];
2421
+ return [
2422
+ `let ${name};`,
2423
+ "try {",
2424
+ ...ind(c.s),
2425
+ ` ${name} = ${c.v.code};`,
2426
+ "} catch {",
2427
+ ` ${name} = E;`,
2428
+ "}"
2429
+ ];
2430
+ }
2431
+ /**
2432
+ * This method evaluates a constant of the run once, before the loop over the keys, and gives the read of its value. A
2433
+ * constant with a loop (`lazy`) evaluates on its first read instead, as a branch of the interpreter does.
2434
+ */
2435
+ #hoist(c, lazy = false) {
2436
+ if (c.v.deps.size > 0 || c.v.plain === true && c.s.length === 0) return c;
2437
+ const key = this.#keyOf.get(c);
2438
+ const hit = key === void 0 ? void 0 : this.#constants.get(key);
2439
+ if (hit !== void 0) return hit;
2440
+ const name = this.fresh("c");
2441
+ if (lazy) this.run.push(`const ${name} = ${this.use("L")}(() => {`, ...ind(c.s), ` return ${c.v.code};`, "});");
2442
+ else this.run.push(...this.#store(name, c, true));
2443
+ const { list } = c.v;
2444
+ const read = bare(this.#read(lazy ? {
2445
+ code: `${name}()`,
2446
+ kind: c.v.kind,
2447
+ lazy: true,
2448
+ deps: NO_DEPS,
2449
+ list
2450
+ } : {
2451
+ code: name,
2452
+ kind: c.v.kind,
2453
+ lazy: !c.v.safe,
2454
+ deps: NO_DEPS,
2455
+ list
2456
+ }));
2457
+ if (key !== void 0) this.#constants.set(key, read);
2458
+ return read;
2459
+ }
2460
+ /**
2461
+ * This method gives the parts of a node with levels `deps`. When the node is not a constant of the run, each part that
2462
+ * is a constant evaluates once, before the loop. A node that is a constant keeps its parts, and its parent decides.
2463
+ */
2464
+ #settle(parts, deps, exprs = []) {
2465
+ return deps.size === 0 ? parts : parts.map((x, i) => this.#hoist(x, exprs[i] !== void 0 && hasLoop(exprs[i])));
2466
+ }
2467
+ expr(e, ctx) {
2468
+ const key = ctx.keys.get(e);
2469
+ if (key !== void 0) return bare(this.#read(key));
2470
+ const keys = this.#memo.get(e);
2471
+ const c = keys !== void 0 && this.#inside !== e ? this.#memoized(e, keys, ctx) : this.#node(e, ctx);
2472
+ if (c.v.deps.size === 0) {
2473
+ this.#keyOf.set(c, this.#constKey(e, ctx));
2474
+ this.#constant.add(e);
2475
+ }
2476
+ if (c.v.list !== void 0 && !this.#wantList.has(e)) throw new NotStandalone("a list is a value of the program");
2477
+ return this.#columnar(e, c, ctx) ? this.#column(e, c, ctx) : c;
2478
+ }
2479
+ /** This method gives the code of a list at a place that takes a list (LIST.VALUE): an each, a name, sortBy or take. */
2480
+ #listOf(e, ctx) {
2481
+ this.#wantList.add(e);
2482
+ const c = this.expr(e, ctx);
2483
+ if (c.v.list === void 0) throw new NotStandalone("a list op on a value that is not a list");
2484
+ return c;
2485
+ }
2486
+ /** This method tells if an expression gives a list at a place that takes one: an each, sortBy, take or a name of a list. */
2487
+ #isList(e, ctx) {
2488
+ if (e.tag === "each") return true;
2489
+ if (e.tag === "app") return e.op === "sortBy" || e.op === "take";
2490
+ return e.tag === "var" && ctx.env.get(e.name)?.list !== void 0;
2491
+ }
2492
+ /**
2493
+ * This method tells if a part of a loop over the targets is a column of the run. Its value depends only on the
2494
+ * target and on the constants of the run, so each run computes it once for each record. Each name that it reads
2495
+ * from outside is a constant of the run, so its code can be outside the loop.
2496
+ */
2497
+ #columnar(e, c, ctx) {
2498
+ if (ctx.level < 2 || c.v.deps.size !== 1 || !c.v.deps.has(ctx.level) || this.#work(e) < COLUMN_WORK) return false;
2499
+ if (this.#keyed(e)) return false;
2500
+ return [...namesOf(e)].every((name) => (ctx.env.get(name)?.deps.size ?? 0) === 0) && !this.#callsLocal(e, ctx);
2501
+ }
2502
+ /** This method tells if an expression calls a function that is at the place of its binding, not at the start of a run. */
2503
+ #callsLocal(e, ctx) {
2504
+ if (e.tag === "call" && ctx.fns.get(e.fn)?.local === true) return true;
2505
+ return children(e).some((x) => this.#callsLocal(x, ctx));
2506
+ }
2507
+ /** This method tells if an expression has a node of the memo with keys in it. */
2508
+ #keyed(e) {
2509
+ return (this.#memo.get(e)?.length ?? 0) > 0 || children(e).some((x) => this.#keyed(x));
2510
+ }
2511
+ /** This method gives the work of an expression: a node of the memo and a constant of the run are one read each. */
2512
+ #work(e) {
2513
+ if (this.#memo.has(e) || this.#constant.has(e)) return 1;
2514
+ return children(e).reduce((sum, x) => sum + this.#work(x), 1);
2515
+ }
2516
+ /** This method gives the read of a column of the run. Two parts with the same structure share one column. */
2517
+ #column(e, c, ctx) {
2518
+ const key = this.#constKey(e, ctx);
2519
+ let name = this.#columns.get(key);
2520
+ if (name === void 0) {
2521
+ name = this.fresh("col");
2522
+ this.run.push(`const ${name} = ${this.use("Q")}((${ctx.focus}) => {`, ...ind(c.s), ` return ${c.v.code};`, "});");
2523
+ this.#columns.set(key, name);
2524
+ }
2525
+ return bare({
2526
+ code: `${this.use("G")}(${name}(${ctx.focus}))`,
2527
+ kind: c.v.kind,
2528
+ safe: false,
2529
+ deps: c.v.deps,
2530
+ list: c.v.list
2531
+ });
2532
+ }
2533
+ #node(e, ctx) {
2534
+ switch (e.tag) {
2535
+ case "lit": return bare(literal(e.value));
2536
+ case "ref": return this.#ref(e, ctx);
2537
+ case "var": return bare(this.#var(e.name, ctx));
2538
+ case "let": return this.#let(e, ctx);
2539
+ /* v8 ignore next -- @preserve */
2540
+ case "fn": throw new NotStandalone("a function outside the bindings of a let");
2541
+ case "call": return this.#call(e, ctx);
2542
+ case "rec": {
2543
+ const names = Object.keys(e.fields);
2544
+ const raw = Object.values(e.fields).map((x) => this.expr(x, ctx));
2545
+ const deps = depsOf(...raw);
2546
+ const fields = this.#settle(raw, deps, Object.values(e.fields));
2547
+ const code = `({ ${fields.map((x, i) => `${JSON.stringify(names[i])}: ${x.v.code}`).join(", ")} })`;
2548
+ return {
2549
+ s: stmtsOf(...fields),
2550
+ v: {
2551
+ code,
2552
+ kind: void 0,
2553
+ safe: fields.every((x) => x.v.safe),
2554
+ deps
2555
+ }
2556
+ };
2557
+ }
2558
+ case "app": return this.#app(e, ctx);
2559
+ case "each": return this.#eachList(e, ctx);
2560
+ case "fold": return this.#fold(e, ctx);
2561
+ case "iterate": return this.#iterate(e, ctx);
2562
+ case "ext": throw new NotStandalone(`the extension "${e.kind}"`);
2563
+ }
2564
+ }
2565
+ /**
2566
+ * This method gives the code of the index of an address from the focus. `values` has the code of the value of each
2567
+ * computed move, in order (NAV.COMPUTED).
2568
+ */
2569
+ #address(at, ctx, values) {
2570
+ let index = ctx.focus;
2571
+ let next = 0;
2572
+ let fails = false;
2573
+ const checks = [];
2574
+ for (const m of at) {
2575
+ if (fails && index !== void 0 && m.t !== "offset" && m.t !== "other") checks.push(index);
2576
+ index = moveExpr(m) === void 0 ? this.#move(m, index, ctx.origin) : this.#computed(m, values[next++]);
2577
+ fails = m.t !== "origin";
2578
+ }
2579
+ /* v8 ignore next -- @preserve */
2580
+ if (index === void 0) throw new NotStandalone("a node of the memo reads its focus");
2581
+ return checks.length === 0 ? index : `(${[...checks, index].join(", ")})`;
2582
+ }
2583
+ /** This method gives the code of the index of a computed move, from the code of its value. */
2584
+ #computed(m, value) {
2585
+ return `${this.use(m.t === "key" ? "K" : "I")}(${value.v.code}, n)`;
2586
+ }
2587
+ #move(m, focus, origin) {
2588
+ const F = this.use("F");
2589
+ switch (m.t) {
2590
+ case "origin":
2591
+ /* v8 ignore next -- @preserve */
2592
+ if (origin === void 0) throw new NotStandalone("a node of the memo reads its origin");
2593
+ return origin;
2594
+ case "key": return typeof m.key === "string" && /^(0|[1-9]\d*)$/.test(m.key) ? `(${m.key} < n ? ${m.key} : ${F}())` : `${F}()`;
2595
+ case "index": return typeof m.i === "number" && Number.isInteger(m.i) && m.i >= 0 ? `(${m.i} < n ? ${m.i} : ${F}())` : `${F}()`;
2596
+ case "offset": {
2597
+ const [d, ...more] = m.d;
2598
+ /* v8 ignore next -- @preserve */
2599
+ if (focus === void 0) throw new NotStandalone("a node of the memo reads its focus");
2600
+ if (d === void 0 || more.length > 0 || !Number.isInteger(d)) return `${F}()`;
2601
+ return `${this.use("X")}(${focus} + ${d}, n)`;
2602
+ }
2603
+ case "other":
2604
+ /* v8 ignore next -- @preserve */
2605
+ if (focus === void 0) throw new NotStandalone("a node of the memo reads its focus");
2606
+ return `(n === 2 ? 1 - ${focus} : ${F}())`;
2607
+ case "parent": return `${F}()`;
2608
+ }
2609
+ }
2610
+ #ref(e, ctx) {
2611
+ const [field, ...more] = e.path;
2612
+ const kind = field === void 0 ? void 0 : this.#schema.fields?.[field];
2613
+ if (field === void 0 || more.length > 0 || !isFieldName(field) || kind === void 0) throw new NotStandalone(`a read of a field that is not in the schema: "${e.path.join(".")}"`);
2614
+ const at = e.at ?? [];
2615
+ const safe = at.every((m) => m.t === "origin");
2616
+ const values = this.#addressValues(at, ctx);
2617
+ const deps = this.#addressDeps(at, ctx, values);
2618
+ const parts = this.#settle(values, deps);
2619
+ return {
2620
+ s: stmtsOf(...parts),
2621
+ v: {
2622
+ code: `R[${this.#address(at, ctx, parts)}][${JSON.stringify(field)}]`,
2623
+ kind,
2624
+ safe,
2625
+ deps
2626
+ }
2627
+ };
2628
+ }
2629
+ /** This method gives the code of the expressions of the computed moves of an address. They evaluate at the node. */
2630
+ #addressValues(at, ctx) {
2631
+ return addrExprs(at).map((x) => this.expr(x, ctx));
2632
+ }
2633
+ /**
2634
+ * This method gives the levels of the key of an address. The focus and the origin have their level, and a fixed key
2635
+ * has no level. A computed move has the levels of its value.
2636
+ */
2637
+ #addressDeps(at, ctx, values) {
2638
+ let deps = /* @__PURE__ */ new Set([ctx.level]);
2639
+ let next = 0;
2640
+ let fails = false;
2641
+ const kept = /* @__PURE__ */ new Set();
2642
+ for (const m of at) {
2643
+ if (fails) for (const d of deps) kept.add(d);
2644
+ if (moveExpr(m) !== void 0) deps = values[next++].v.deps;
2645
+ else if (m.t === "origin") deps = /* @__PURE__ */ new Set([ctx.originLevel]);
2646
+ else if (m.t === "key" || m.t === "index" || m.t === "parent") deps = NO_DEPS;
2647
+ fails = m.t !== "origin";
2648
+ }
2649
+ return /* @__PURE__ */ new Set([...deps, ...kept]);
2650
+ }
2651
+ #var(name, ctx) {
2652
+ const bound = ctx.env.get(name);
2653
+ if (bound !== void 0) return this.#read(bound);
2654
+ if (ctx.fns.has(name)) throw new NotStandalone(`the name "${name}" is a function, not a value`);
2655
+ const kind = this.#schema.vars?.[name];
2656
+ if (kind === void 0) throw new NotStandalone(`a variable that is not in the schema: "${name}"`);
2657
+ let code = this.vars.get(name);
2658
+ if (code === void 0) {
2659
+ code = `v${this.vars.size}`;
2660
+ this.vars.set(name, code);
2661
+ }
2662
+ return plainValue(code, kind);
2663
+ }
2664
+ /**
2665
+ * A binding is a variable. A binding with an error is an error only where the body reads its name, so the variable
2666
+ * can hold the sentinel. A binding that is a constant of the run is the variable of that constant.
2667
+ */
2668
+ #let(e, ctx) {
2669
+ const env = new Map(ctx.env);
2670
+ const fns = new Map(ctx.fns);
2671
+ const s = [];
2672
+ let deps = /* @__PURE__ */ new Set();
2673
+ const bound = [];
2674
+ for (const [name, x] of Object.entries(e.bind)) {
2675
+ if (x.tag === "fn") {
2676
+ const b = {
2677
+ id: this.#fnIds++,
2678
+ fn: x,
2679
+ ctx,
2680
+ specs: /* @__PURE__ */ new Map(),
2681
+ decls: [],
2682
+ local: false
2683
+ };
2684
+ bound.push(b);
2685
+ fns.set(name, b);
2686
+ env.delete(name);
2687
+ continue;
2688
+ }
2689
+ this.#wantList.add(x);
2690
+ const c = this.#hoist(this.expr(x, ctx), hasLoop(x));
2691
+ if (c.v.deps.size === 0) {
2692
+ env.set(name, this.#nameOf(c.v));
2693
+ continue;
2694
+ }
2695
+ const b = this.fresh("b");
2696
+ s.push(...this.#store(b, c));
2697
+ env.set(name, {
2698
+ code: b,
2699
+ kind: c.v.kind,
2700
+ lazy: !c.v.safe,
2701
+ deps: c.v.deps,
2702
+ list: c.v.list
2703
+ });
2704
+ deps = /* @__PURE__ */ new Set([...deps, ...c.v.deps]);
2705
+ }
2706
+ const body = this.expr(e.body, {
2707
+ ...ctx,
2708
+ env,
2709
+ fns
2710
+ });
2711
+ return {
2712
+ s: [
2713
+ ...s,
2714
+ ...bound.flatMap((b) => b.decls),
2715
+ ...body.s
2716
+ ],
2717
+ v: {
2718
+ ...body.v,
2719
+ deps: /* @__PURE__ */ new Set([...deps, ...body.v.deps])
2720
+ }
2721
+ };
2722
+ }
2723
+ /**
2724
+ * This method prints a call (FN.CALL). Each argument evaluates at the place of the call, as a binding of a let. The
2725
+ * call goes to the printed function of the signature of its arguments, with the focus and the origin if it reads them.
2726
+ */
2727
+ #call(e, ctx) {
2728
+ const bound = ctx.env.has(e.fn) ? void 0 : ctx.fns.get(e.fn);
2729
+ if (bound === void 0) throw new NotStandalone(`a call of "${e.fn}", which is not a function`);
2730
+ if (bound.fn.params.length !== e.args.length) throw new NotStandalone(`a call of "${e.fn}" with ${String(e.args.length)} arguments, not ${String(bound.fn.params.length)}`);
2731
+ const s = [];
2732
+ const args = e.args.map((x) => {
2733
+ const c = this.#hoist(this.expr(x, ctx), hasLoop(x));
2734
+ if (c.v.safe) {
2735
+ s.push(...c.s);
2736
+ return {
2737
+ code: c.v.code,
2738
+ kind: c.v.kind,
2739
+ deps: c.v.deps
2740
+ };
2741
+ }
2742
+ if (c.s.length === 0 && c.v.held !== void 0) return {
2743
+ code: c.v.held,
2744
+ kind: c.v.kind,
2745
+ deps: c.v.deps
2746
+ };
2747
+ const b = this.fresh("b");
2748
+ s.push(...this.#store(b, c));
2749
+ return {
2750
+ code: b,
2751
+ kind: c.v.kind,
2752
+ deps: c.v.deps
2753
+ };
2754
+ });
2755
+ const sig = JSON.stringify(args.map((a) => a.kind ?? null));
2756
+ const spec = bound.specs.get(sig) ?? this.#printFn(bound, args, sig);
2757
+ const levels = (d) => d === spec.origin ? [ctx.originLevel] : d === spec.focus ? [ctx.level] : d === spec.param ? [] : [d];
2758
+ const deps = /* @__PURE__ */ new Set([...args.flatMap((a) => [...a.deps]), ...[...spec.deps].flatMap(levels)]);
2759
+ const position = spec.deps.has(spec.origin) ? [ctx.focus, ctx.origin] : spec.deps.has(spec.focus) ? [ctx.focus] : [];
2760
+ return {
2761
+ s,
2762
+ v: {
2763
+ code: `${spec.name}(${[...args.map((a) => a.code), ...position].join(", ")})`,
2764
+ kind: spec.kind,
2765
+ safe: spec.safe,
2766
+ deps
2767
+ }
2768
+ };
2769
+ }
2770
+ /**
2771
+ * This method prints a bound function for one signature of its arguments, as one JavaScript function. Its parameters
2772
+ * are the arguments, then the focus and the origin, if the body reads them. A function that reads a name of the place
2773
+ * of its binding is at that place. Each other function is at the start of a run, so a constant of the run can call it.
2774
+ */
2775
+ #printFn(bound, args, sig) {
2776
+ const origin = 2e6 + 1e3 * this.#printed++;
2777
+ const focus = origin + 1;
2778
+ const param = -origin;
2779
+ const names = args.map(() => this.fresh("p"));
2780
+ const k = this.fresh("k");
2781
+ const o = this.fresh("o");
2782
+ const env = new Map(bound.ctx.env);
2783
+ bound.fn.params.forEach((p, i) => env.set(p, {
2784
+ code: names[i],
2785
+ kind: args[i].kind,
2786
+ lazy: true,
2787
+ deps: /* @__PURE__ */ new Set([param])
2788
+ }));
2789
+ const body = this.expr(bound.fn.body, {
2790
+ origin: o,
2791
+ focus: k,
2792
+ level: focus,
2793
+ originLevel: origin,
2794
+ env,
2795
+ fns: bound.ctx.fns,
2796
+ keys: /* @__PURE__ */ new Map()
2797
+ });
2798
+ const markers = /* @__PURE__ */ new Set([
2799
+ origin,
2800
+ focus,
2801
+ param
2802
+ ]);
2803
+ const global = [...body.v.deps].every((d) => markers.has(d));
2804
+ const name = this.fresh("fn");
2805
+ const position = body.v.deps.has(origin) ? [k, o] : body.v.deps.has(focus) ? [k] : [];
2806
+ const head = `const ${name} = (${[...names, ...position].join(", ")}) =>`;
2807
+ const decl = body.s.length === 0 ? [`${head} ${body.v.code};`] : [
2808
+ `${head} {`,
2809
+ ...ind(body.s),
2810
+ ` return ${body.v.code};`,
2811
+ "};"
2812
+ ];
2813
+ (global ? this.run : bound.decls).push(...decl);
2814
+ if (!global) bound.local = true;
2815
+ const spec = {
2816
+ name,
2817
+ kind: body.v.kind,
2818
+ safe: body.v.safe,
2819
+ deps: body.v.deps,
2820
+ origin,
2821
+ focus,
2822
+ param,
2823
+ global
2824
+ };
2825
+ bound.specs.set(sig, spec);
2826
+ return spec;
2827
+ }
2828
+ #boolean(v) {
2829
+ return v.kind === "boolean" ? v.code : `${this.use("B")}(${v.code})`;
2830
+ }
2831
+ /** A condition is safe when it is a safe boolean. */
2832
+ #safeBoolean(v) {
2833
+ return v.safe && v.kind === "boolean";
2834
+ }
2835
+ #app(e, ctx) {
2836
+ const { op, args } = e;
2837
+ if (op === "if") return this.#if(args, ctx);
2838
+ if (op === "and" || op === "or") return this.#andOr(op === "and", args, ctx);
2839
+ if (op === "ifError") return this.#ifError(args, ctx);
2840
+ const [head] = args;
2841
+ if (LIST_OPS.has(op) && head?.tag === "each") return this.#list(op, head, args.slice(1), ctx);
2842
+ if (head !== void 0 && (op === "sortBy" || op === "take")) return this.#order(op, head, args.slice(1), ctx);
2843
+ if (head !== void 0 && (LIST_OPS.has(op) || op === "nth") && this.#isList(head, ctx)) return this.#overList(op, head, args.slice(1), ctx);
2844
+ const raw = args.map((x) => this.expr(x, ctx));
2845
+ const deps = depsOf(...raw);
2846
+ const values = this.#settle(raw, deps, args);
2847
+ const site = this.#facts.staticSite(op, values.map((x) => x.v.kind));
2848
+ if (site?.t !== "fn") throw new NotStandalone(`the kinds of the values of "${op}" do not decide its op`);
2849
+ if (site.bad) return {
2850
+ s: stmtsOf(...values),
2851
+ v: {
2852
+ code: `${this.use("F")}()`,
2853
+ kind: site.returns,
2854
+ safe: false,
2855
+ deps
2856
+ }
2857
+ };
2858
+ if (site.returns === void 0) throw new NotStandalone(`the op "${op}" does not declare the kind of its result`);
2859
+ const d = this.#domains[site.domain];
2860
+ const name = `op_${site.domain}_${this.#opIndex(op)}`;
2861
+ if (!this.#forms.has(name)) {
2862
+ const fn = d.ops[op].fn;
2863
+ const kinds = values.map((x) => x.v.kind).filter((k) => k !== void 0);
2864
+ const src = copied(fn, kinds.map((k) => this.#samples(k)), `the op "${op}" of the domain ${d.name}`);
2865
+ this.#forms.set(name, kinds.every((k) => primitiveOf(k) !== void 0) ? inlineForm(src) : void 0);
2866
+ this.top.set(name, `const ${name} = ${src};`);
2867
+ }
2868
+ const form = this.#forms.get(name);
2869
+ if (form !== void 0 && form.params.length === values.length && values.every((x, i) => form.uses[i] === 1 || x.v.plain === true && x.v.safe && form.uses[i] > 0)) {
2870
+ const text = form.parts.map((x) => typeof x === "number" ? `(${values[x].v.code})` : x).join("");
2871
+ const checked = this.check(site.returns);
2872
+ const code = checked === void 0 ? `(${text})` : `${checked}(${text})`;
2873
+ return {
2874
+ s: stmtsOf(...values),
2875
+ v: {
2876
+ code,
2877
+ kind: site.returns,
2878
+ safe: checked === void 0 && values.every((x) => x.v.safe),
2879
+ deps
2880
+ }
2881
+ };
2882
+ }
2883
+ this.#called.add(name);
2884
+ const code = this.#checked(site.returns, `${name}(${values.map((x) => x.v.code).join(", ")})`);
2885
+ return {
2886
+ s: stmtsOf(...values),
2887
+ v: {
2888
+ code,
2889
+ kind: site.returns,
2890
+ safe: false,
2891
+ deps
2892
+ }
2893
+ };
2894
+ }
2895
+ /** The condition must be a boolean. Only the branch that the condition selects is evaluated. */
2896
+ #if(args, ctx) {
2897
+ if (args.length !== 3) throw new NotStandalone("an if without three arguments");
2898
+ const [c, a, b] = args;
2899
+ const raw = [
2900
+ this.expr(c, ctx),
2901
+ this.expr(a, ctx),
2902
+ this.expr(b, ctx)
2903
+ ];
2904
+ const deps = depsOf(...raw);
2905
+ const [cond, yes, no] = this.#settle(raw, deps, [
2906
+ c,
2907
+ a,
2908
+ b
2909
+ ]);
2910
+ const v = {
2911
+ kind: join(yes.v.kind, no.v.kind),
2912
+ safe: this.#safeBoolean(cond.v) && yes.v.safe && no.v.safe,
2913
+ deps
2914
+ };
2915
+ if (yes.s.length === 0 && no.s.length === 0) return {
2916
+ s: cond.s,
2917
+ v: {
2918
+ ...v,
2919
+ code: `(${this.#boolean(cond.v)} ? ${yes.v.code} : ${no.v.code})`
2920
+ }
2921
+ };
2922
+ const t = this.fresh("t");
2923
+ return {
2924
+ s: [
2925
+ ...cond.s,
2926
+ `let ${t};`,
2927
+ `if (${this.#boolean(cond.v)}) {`,
2928
+ ...ind(yes.s),
2929
+ ` ${t} = ${yes.v.code};`,
2930
+ "} else {",
2931
+ ...ind(no.s),
2932
+ ` ${t} = ${no.v.code};`,
2933
+ "}"
2934
+ ],
2935
+ v: {
2936
+ ...v,
2937
+ code: t
2938
+ }
2939
+ };
2940
+ }
2941
+ /** `and` stops at the first `false`, and `or` at the first `true`. Each argument before the stop must be a boolean. */
2942
+ #andOr(and, args, ctx) {
2943
+ if (args.length === 0) throw new NotStandalone(`an ${and ? "and" : "or"} without arguments`);
2944
+ const raw = args.map((x) => this.expr(x, ctx));
2945
+ const deps = depsOf(...raw);
2946
+ const parts = this.#settle(raw, deps, args);
2947
+ const v = {
2948
+ kind: "boolean",
2949
+ safe: parts.every((x) => this.#safeBoolean(x.v)),
2950
+ deps
2951
+ };
2952
+ const [first, ...rest] = parts;
2953
+ if (rest.every((x) => x.s.length === 0)) return {
2954
+ s: first.s,
2955
+ v: {
2956
+ ...v,
2957
+ code: `(${parts.map((x) => this.#boolean(x.v)).join(and ? " && " : " || ")})`
2958
+ }
2959
+ };
2960
+ const t = this.fresh("t");
2961
+ const s = [...first.s, `let ${t} = ${this.#boolean(first.v)};`];
2962
+ for (const x of rest) s.push(`if (${and ? "" : "!"}${t}) {`, ...ind(x.s), ` ${t} = ${this.#boolean(x.v)};`, "}");
2963
+ return {
2964
+ s,
2965
+ v: {
2966
+ ...v,
2967
+ code: t
2968
+ }
2969
+ };
2970
+ }
2971
+ /** The value of the first argument, or else the value of the second argument. */
2972
+ #ifError(args, ctx) {
2973
+ if (args.length !== 2) throw new NotStandalone("an ifError without two arguments");
2974
+ const [a, b] = args;
2975
+ const raw = [this.expr(a, ctx), this.expr(b, ctx)];
2976
+ const deps = depsOf(...raw);
2977
+ const [first, second] = this.#settle(raw, deps, [a, b]);
2978
+ if (first.v.safe) return first;
2979
+ const t = this.fresh("t");
2980
+ return {
2981
+ s: [
2982
+ `let ${t};`,
2983
+ "try {",
2984
+ ...ind(first.s),
2985
+ ` ${t} = ${first.v.code};`,
2986
+ "} catch {",
2987
+ ...ind(second.s),
2988
+ ` ${t} = ${second.v.code};`,
2989
+ "}"
2990
+ ],
2991
+ v: {
2992
+ code: t,
2993
+ kind: join(first.v.kind, second.v.kind),
2994
+ safe: second.v.safe,
2995
+ deps
2996
+ }
2997
+ };
2998
+ }
2999
+ #opIndex(op) {
3000
+ let i = this.#ops.get(op);
3001
+ if (i === void 0) {
3002
+ i = this.#ops.size;
3003
+ this.#ops.set(op, i);
3004
+ }
3005
+ return i;
3006
+ }
3007
+ /**
3008
+ * This method gives the option strict of a list op. The options must be one literal with only strict. Only a literal
3009
+ * has a value, so another expression gives the reason too.
3010
+ */
3011
+ #strict(op, rest) {
3012
+ const [options, ...more] = rest;
3013
+ if (more.length > 0) throw new NotStandalone(`"${op}" with more than one option`);
3014
+ if (options === void 0) return false;
3015
+ const opts = options.value;
3016
+ if (typeof opts !== "object" || opts === null || Object.keys(opts).some((k) => k !== "strict")) throw new NotStandalone(`the options of "${op}" are not a literal with strict`);
3017
+ return opts.strict === true;
3018
+ }
3019
+ /**
3020
+ * A list op over an axis: one `for` loop with a running value. An item with an error is skipped, and with `strict` it
3021
+ * is an error of the list op. A value of the wrong kind is an error of the list op, as in the interpreter.
3022
+ */
3023
+ /**
3024
+ * This method gives the loop over the targets of an axis: the statements before it, its bounds and the key that it
3025
+ * skips. `start` has the levels of the address, and `inner` is the position at a target. The axes all, others and
3026
+ * window have a loop.
3027
+ */
3028
+ #targetLoop(axis, at, ctx) {
3029
+ const { base: outer, tests } = testsOf(axis);
3030
+ const reverse = outer.t === "reverse";
3031
+ const base = outer.t === "reverse" ? outer.axis : outer;
3032
+ const j = this.fresh("j");
3033
+ const inner = {
3034
+ ...ctx,
3035
+ focus: j,
3036
+ level: ctx.level + 1
3037
+ };
3038
+ if (base.t === "list") {
3039
+ if (at.length > 0) throw new NotStandalone("the axis \"list\" with an address");
3040
+ const list = this.#hoist(this.#listOf(base.list, ctx), hasLoop(base.list));
3041
+ const a = this.fresh("A");
3042
+ const q = this.fresh("q");
3043
+ const head = reverse ? `for (let ${q} = ${a}.length - 1; ${q} >= 0; ${q}--) {` : `for (let ${q} = 0; ${q} < ${a}.length; ${q}++) {`;
3044
+ const key = [`const ${j} = ${a}[${q}][0];`];
3045
+ const check = [`if (${a}[${q}][1] === E) ${this.use("F")}();`];
3046
+ return {
3047
+ s: [...list.s, `const ${a} = ${list.v.code};`],
3048
+ j,
3049
+ head,
3050
+ key,
3051
+ check,
3052
+ skip: void 0,
3053
+ fixed: false,
3054
+ start: list.v.deps,
3055
+ startSafe: list.v.safe,
3056
+ tests,
3057
+ inner
3058
+ };
3059
+ }
3060
+ const s = [];
3061
+ let lo = "0";
3062
+ let hi = "n";
3063
+ let skip;
3064
+ let start = NO_DEPS;
3065
+ const f = base.t === "all" && at.length === 0 ? void 0 : this.fresh("f");
3066
+ if (f !== void 0) {
3067
+ const values = this.#addressValues(at, ctx);
3068
+ start = this.#addressDeps(at, ctx, values);
3069
+ const parts = this.#settle(values, start);
3070
+ s.push(...stmtsOf(...parts), `const ${f} = ${this.#address(at, ctx, parts)};`);
3071
+ }
3072
+ if (base.t === "others") skip = f;
3073
+ else if (base.t === "window") {
3074
+ if (!Number.isInteger(base.from) || !Number.isInteger(base.to)) throw new NotStandalone("the axis \"window\" with a bound that is not an integer");
3075
+ const h = this.fresh("h");
3076
+ lo = `Math.max(0, ${f} + Math.max(${base.from}, -n))`;
3077
+ s.push(`const ${h} = Math.min(n, ${f} + Math.min(${base.to}, n) + 1);`);
3078
+ hi = h;
3079
+ } else if (base.t !== "all") throw new NotStandalone(`the axis "${base.t}"`);
3080
+ const startSafe = at.every((m) => m.t === "origin");
3081
+ return {
3082
+ s,
3083
+ j,
3084
+ head: forHead(j, lo, hi, reverse),
3085
+ key: [],
3086
+ check: [],
3087
+ skip,
3088
+ fixed: f === void 0,
3089
+ start,
3090
+ startSafe,
3091
+ tests,
3092
+ inner
3093
+ };
3094
+ }
3095
+ #list(op, target, rest, ctx) {
3096
+ const strict = this.#strict(op, rest);
3097
+ const at = target.at ?? [];
3098
+ const { s, j, head, key, check, skip, fixed, start, startSafe, tests, inner } = this.#targetLoop(target.axis, at, ctx);
3099
+ const { level } = inner;
3100
+ const testCodes = tests.map((t) => this.#hoist(this.expr(t, inner), hasLoop(t)));
3101
+ const body = this.#hoist(this.expr(target.body, inner), hasLoop(target.body));
3102
+ if (op === "count" && fixed && tests.length === 0 && body.v.safe) return bare(plainValue("n", "number"));
3103
+ const deps = new Set([...start, ...[body, ...testCodes].flatMap((x) => [...x.v.deps])].filter((d) => d !== level));
3104
+ const r = this.#reduction(op, body.v.kind);
3105
+ const { v } = r;
3106
+ s.push(r.init);
3107
+ const item = [
3108
+ ...check,
3109
+ ...testCodes.flatMap((t) => [...t.s, `if (!${this.#boolean(t.v)}) continue;`]),
3110
+ ...body.s
3111
+ ];
3112
+ const safeItem = check.length === 0 && body.v.safe && testCodes.every((t) => this.#safeBoolean(t.v));
3113
+ const loop = [
3114
+ ...key,
3115
+ ...skip === void 0 ? [] : [`if (${j} === ${skip}) continue;`],
3116
+ ...safeItem ? [...item, `const ${v} = ${body.v.code};`] : [
3117
+ `let ${v};`,
3118
+ "try {",
3119
+ ...ind(item),
3120
+ ` ${v} = ${body.v.code};`,
3121
+ "} catch {",
3122
+ strict ? ` ${this.use("F")}();` : " continue;",
3123
+ "}"
3124
+ ],
3125
+ r.step
3126
+ ];
3127
+ s.push(head, ...ind(loop), "}");
3128
+ const safe = startSafe && !strict && (op === "count" || BOOLEAN_LIST_OPS.has(op) && body.v.kind === "boolean");
3129
+ return {
3130
+ s,
3131
+ v: {
3132
+ code: r.result,
3133
+ kind: listKind(op, body.v.kind),
3134
+ safe,
3135
+ deps
3136
+ }
3137
+ };
3138
+ }
3139
+ /**
3140
+ * This method gives the parts of a list op that reduces the values of its items. The parts are the variable `v` of
3141
+ * the value of an item, the first statement, the step and the result. A value of the wrong kind is an error of the op.
3142
+ */
3143
+ #reduction(op, kind) {
3144
+ const a = this.fresh("a");
3145
+ const n = this.fresh("n");
3146
+ const v = this.fresh("x");
3147
+ const num = kind === "number" ? v : `${this.use("U")}(${v})`;
3148
+ const bool = kind === "boolean" ? v : `${this.use("B")}(${v})`;
3149
+ const inits = {
3150
+ count: `let ${n} = 0;`,
3151
+ sum: `let ${a} = 0;`,
3152
+ mean: `let ${a} = 0, ${n} = 0;`,
3153
+ any: `let ${a} = false;`,
3154
+ none: `let ${a} = false;`,
3155
+ all: `let ${a} = true;`
3156
+ };
3157
+ const steps = {
3158
+ count: `${n}++;`,
3159
+ sum: `${a} += ${num};`,
3160
+ mean: `${a} += ${num}; ${n}++;`,
3161
+ min: `${a} = ${n}++ === 0 ? ${num} : Math.min(${a}, ${num});`,
3162
+ max: `${a} = ${n}++ === 0 ? ${num} : Math.max(${a}, ${num});`,
3163
+ any: `if (${bool}) ${a} = true;`,
3164
+ none: `if (${bool}) ${a} = true;`,
3165
+ all: `if (!${bool}) ${a} = false;`,
3166
+ first: `if (${n}++ === 0) ${a} = ${v};`
3167
+ };
3168
+ const F = this.use("F");
3169
+ const results = {
3170
+ count: n,
3171
+ sum: this.#checked("number", a),
3172
+ mean: `(${n} === 0 ? ${F}() : ${this.#checked("number", `${a} / ${n}`)})`,
3173
+ any: a,
3174
+ all: a,
3175
+ none: `!${a}`
3176
+ };
3177
+ return {
3178
+ v,
3179
+ init: inits[op] ?? `let ${a}, ${n} = 0;`,
3180
+ step: steps[op],
3181
+ result: results[op] ?? `(${n} === 0 ? ${F}() : ${a})`
3182
+ };
3183
+ }
3184
+ /**
3185
+ * This method prints a list as an array (LIST.VALUE): a pair of the key and the value of each item. A test that
3186
+ * fails, a body that fails and an error item of the axis list give the error sentinel as the value.
3187
+ */
3188
+ #eachList(e, ctx) {
3189
+ const at = e.at ?? [];
3190
+ const { s, j, head, key, check, skip, start, startSafe, tests, inner } = this.#targetLoop(e.axis, at, ctx);
3191
+ const testCodes = tests.map((t) => this.#hoist(this.expr(t, inner), hasLoop(t)));
3192
+ const body = this.#hoist(this.expr(e.body, inner), hasLoop(e.body));
3193
+ const deps = new Set([...start, ...[body, ...testCodes].flatMap((x) => [...x.v.deps])].filter((d) => d !== inner.level));
3194
+ const list = this.fresh("L");
3195
+ const v = this.fresh("x");
3196
+ const item = [
3197
+ ...check,
3198
+ ...testCodes.flatMap((t) => [...t.s, `if (!${this.#boolean(t.v)}) continue;`]),
3199
+ ...body.s
3200
+ ];
3201
+ const safeItem = check.length === 0 && body.v.safe && testCodes.every((t) => this.#safeBoolean(t.v));
3202
+ const loop = [
3203
+ ...key,
3204
+ ...skip === void 0 ? [] : [`if (${j} === ${skip}) continue;`],
3205
+ ...safeItem ? [...item, `${list}.push([${j}, ${body.v.code}]);`] : [
3206
+ `let ${v};`,
3207
+ "try {",
3208
+ ...ind(item),
3209
+ ` ${v} = ${body.v.code};`,
3210
+ "} catch {",
3211
+ ` ${v} = E;`,
3212
+ "}",
3213
+ `${list}.push([${j}, ${v}]);`
3214
+ ]
3215
+ ];
3216
+ return {
3217
+ s: [
3218
+ ...s,
3219
+ `const ${list} = [];`,
3220
+ head,
3221
+ ...ind(loop),
3222
+ "}"
3223
+ ],
3224
+ v: {
3225
+ code: list,
3226
+ kind: void 0,
3227
+ safe: startSafe,
3228
+ deps,
3229
+ list: { item: body.v.kind }
3230
+ }
3231
+ };
3232
+ }
3233
+ /**
3234
+ * This method prints sortBy and take (LIST.SORT, LIST.TAKE): a new array from the array of a list. An error item is
3235
+ * not in the new list, and with strict it is the error of the op.
3236
+ */
3237
+ #order(op, head, rest, ctx) {
3238
+ const list = this.#listOf(head, ctx);
3239
+ const exprs = [head, ...op === "take" ? [rest[0] ?? lit(null)] : []];
3240
+ const strict = this.#strict(op, rest.slice(exprs.length - 1));
3241
+ const raw = [list, ...exprs.slice(1).map((x) => this.expr(x, ctx))];
3242
+ const deps = depsOf(...raw);
3243
+ const parts = this.#settle(raw, deps, exprs);
3244
+ const item = list.v.list.item;
3245
+ return {
3246
+ s: stmtsOf(...parts),
3247
+ v: {
3248
+ code: `${this.use(op === "sortBy" ? "SB" : "TK")}(${[...parts.map((x) => x.v.code), String(strict)].join(", ")})`,
3249
+ kind: void 0,
3250
+ safe: false,
3251
+ deps,
3252
+ list: { item }
3253
+ }
3254
+ };
3255
+ }
3256
+ /** This method prints a list op over a list that is not an each: a loop over its array, and nth (LIST.NTH). */
3257
+ #overList(op, head, rest, ctx) {
3258
+ const list = this.#listOf(head, ctx);
3259
+ const exprs = [head, ...op === "nth" ? [rest[0] ?? lit(null)] : []];
3260
+ const strict = this.#strict(op, rest.slice(exprs.length - 1));
3261
+ const raw = [list, ...exprs.slice(1).map((x) => this.expr(x, ctx))];
3262
+ const deps = depsOf(...raw);
3263
+ const parts = this.#settle(raw, deps, exprs);
3264
+ const [l] = parts;
3265
+ const item = list.v.list.item;
3266
+ if (op === "nth") return {
3267
+ s: stmtsOf(...parts),
3268
+ v: {
3269
+ code: `${this.use("NT")}(${[...parts.map((x) => x.v.code), String(strict)].join(", ")})`,
3270
+ kind: item,
3271
+ safe: false,
3272
+ deps
3273
+ }
3274
+ };
3275
+ const r = this.#reduction(op, item);
3276
+ const { v } = r;
3277
+ return {
3278
+ s: [
3279
+ ...l.s,
3280
+ r.init,
3281
+ `for (const [, ${v}] of ${l.v.code}) {`,
3282
+ ` if (${v} === E) ${strict ? `${this.use("F")}();` : "continue;"}`,
3283
+ ` ${r.step}`,
3284
+ "}"
3285
+ ],
3286
+ v: {
3287
+ code: r.result,
3288
+ kind: listKind(op, item),
3289
+ safe: false,
3290
+ deps
3291
+ }
3292
+ };
3293
+ }
3294
+ /**
3295
+ * This method gives the names of a loop (LOOP.NAMES): a variable for each name of `init`, with its first value at the
3296
+ * node. Inside the loop, each name has the level `loop`. Thus a part that reads a name stays in the loop. A loop that
3297
+ * reads no key of the run is a constant of the run.
3298
+ */
3299
+ #loopNames(init, ctx, loop) {
3300
+ const s = [];
3301
+ const env = new Map(ctx.env);
3302
+ const vars = /* @__PURE__ */ new Map();
3303
+ const deps = /* @__PURE__ */ new Set();
3304
+ for (const [name, x] of Object.entries(init)) {
3305
+ const c = this.expr(x, ctx);
3306
+ if (c.v.kind === void 0) throw new NotStandalone(`the first value of the name "${name}" of a loop has no kind`);
3307
+ const v = this.fresh("l");
3308
+ s.push(...c.s, `let ${v} = ${c.v.code};`);
3309
+ const read = {
3310
+ code: v,
3311
+ kind: c.v.kind,
3312
+ lazy: false,
3313
+ deps: /* @__PURE__ */ new Set([loop])
3314
+ };
3315
+ env.set(name, read);
3316
+ vars.set(name, read);
3317
+ for (const d of c.v.deps) deps.add(d);
3318
+ }
3319
+ return {
3320
+ s,
3321
+ env,
3322
+ vars,
3323
+ deps
3324
+ };
3325
+ }
3326
+ /** This method gives the statements of one step of a loop: each new value first, and then each name gets its value. */
3327
+ #loopStep(step, inner, vars) {
3328
+ const s = [];
3329
+ const sets = [];
3330
+ const deps = /* @__PURE__ */ new Set();
3331
+ for (const [name, x] of Object.entries(step)) {
3332
+ const c = this.#hoist(this.expr(x, inner), hasLoop(x));
3333
+ const v = vars.get(name);
3334
+ if (c.v.kind !== v.kind) throw new NotStandalone(`a step of a loop changes the kind of the name "${name}"`);
3335
+ const t = this.fresh("t");
3336
+ s.push(...c.s, `const ${t} = ${c.v.code};`);
3337
+ sets.push(`${v.code} = ${t};`);
3338
+ for (const d of c.v.deps) deps.add(d);
3339
+ }
3340
+ return {
3341
+ s: [...s, ...sets],
3342
+ deps
3343
+ };
3344
+ }
3345
+ /**
3346
+ * An iteration (ITERATE.LIMIT, ITERATE.UNTIL): a `for` loop with a variable for each name. An error of a value, of the
3347
+ * test or of the result throws, so it is the value of the iteration.
3348
+ */
3349
+ #iterate(e, ctx) {
3350
+ const loop = this.#loops++;
3351
+ const names = this.#loopNames(e.init, ctx, loop);
3352
+ const inner = {
3353
+ ...ctx,
3354
+ env: names.env
3355
+ };
3356
+ const until = e.until === void 0 ? void 0 : this.expr(e.until, inner);
3357
+ const step = this.#loopStep(e.step, inner, names.vars);
3358
+ const result = this.expr(e.result, inner);
3359
+ const k = this.fresh("k");
3360
+ const body = [
3361
+ ...until === void 0 ? [] : [...until.s, `if (${this.#boolean(until.v)}) break;`],
3362
+ `if (${k} === ${String(e.limit)}) ${until === void 0 ? "break;" : `${this.use("F")}();`}`,
3363
+ ...step.s
3364
+ ];
3365
+ const inside = [
3366
+ ...until?.v.deps ?? [],
3367
+ ...step.deps,
3368
+ ...result.v.deps
3369
+ ].filter((d) => d !== loop);
3370
+ const deps = /* @__PURE__ */ new Set([...names.deps, ...inside]);
3371
+ return {
3372
+ s: [
3373
+ ...names.s,
3374
+ `for (let ${k} = 0; ; ${k}++) {`,
3375
+ ...ind(body),
3376
+ "}",
3377
+ ...result.s
3378
+ ],
3379
+ v: {
3380
+ code: result.v.code,
3381
+ kind: result.v.kind,
3382
+ safe: false,
3383
+ deps
3384
+ }
3385
+ };
3386
+ }
3387
+ /**
3388
+ * A fold (FOLD.ORDER, FOLD.ERROR): the loop over the targets of an axis, with a variable for each name. The tests read
3389
+ * only the names outside the fold. An error throws, so it is the value of the fold.
3390
+ */
3391
+ #fold(e, ctx) {
3392
+ const loop = this.#loops++;
3393
+ const names = this.#loopNames(e.init, ctx, loop);
3394
+ const t = this.#targetLoop(e.axis, e.at ?? [], ctx);
3395
+ const tests = t.tests.map((x) => this.#hoist(this.expr(x, t.inner), hasLoop(x)));
3396
+ const step = this.#loopStep(e.step, {
3397
+ ...t.inner,
3398
+ env: names.env
3399
+ }, names.vars);
3400
+ const result = this.expr(e.result, {
3401
+ ...ctx,
3402
+ env: names.env
3403
+ });
3404
+ const body = [
3405
+ ...t.key,
3406
+ ...t.skip === void 0 ? [] : [`if (${t.j} === ${t.skip}) continue;`],
3407
+ ...t.check,
3408
+ ...tests.flatMap((c) => [...c.s, `if (!${this.#boolean(c.v)}) continue;`]),
3409
+ ...step.s
3410
+ ];
3411
+ const inside = [...tests.flatMap((c) => [...c.v.deps]), ...step.deps].filter((d) => d !== loop && d !== t.inner.level);
3412
+ const deps = /* @__PURE__ */ new Set([
3413
+ ...names.deps,
3414
+ ...t.start,
3415
+ ...inside,
3416
+ ...[...result.v.deps].filter((d) => d !== loop)
3417
+ ]);
3418
+ return {
3419
+ s: [
3420
+ ...names.s,
3421
+ ...t.s,
3422
+ t.head,
3423
+ ...ind(body),
3424
+ "}",
3425
+ ...result.s
3426
+ ],
3427
+ v: {
3428
+ code: result.v.code,
3429
+ kind: result.v.kind,
3430
+ safe: false,
3431
+ deps
3432
+ }
3433
+ };
3434
+ }
3435
+ /**
3436
+ * A node of the memo: one function of its keys for each structure, with an entry for each value of the keys. A key
3437
+ * that is a constant of the run is the variable of that constant, not a key of the function. A node with no other key
3438
+ * is a constant of the run itself.
3439
+ */
3440
+ #memoized(e, keys, ctx) {
3441
+ const values = keys.map((k) => this.#hoist(this.expr(k, ctx)));
3442
+ const varying = keys.filter((_k, i) => values[i].v.deps.size > 0);
3443
+ const params = varying.map(() => this.fresh("q"));
3444
+ const names = new Map(keys.map((k, i) => {
3445
+ const x = values[i].v;
3446
+ const p = varying.indexOf(k);
3447
+ return [k, p < 0 ? this.#nameOf(x) : {
3448
+ code: params[p],
3449
+ kind: x.kind,
3450
+ lazy: true,
3451
+ deps: /* @__PURE__ */ new Set([1])
3452
+ }];
3453
+ }));
3454
+ const outer = this.#inside;
3455
+ this.#inside = e;
3456
+ const bodyCtx = {
3457
+ origin: void 0,
3458
+ focus: void 0,
3459
+ level: 1,
3460
+ originLevel: 1,
3461
+ env: /* @__PURE__ */ new Map(),
3462
+ fns: /* @__PURE__ */ new Map(),
3463
+ keys: names
3464
+ };
3465
+ if (varying.length === 0) {
3466
+ const body = this.#hoist(this.expr(e, bodyCtx));
3467
+ this.#inside = outer;
3468
+ return body;
3469
+ }
3470
+ const tokens = new Map(keys.map((k, i) => [k, varying.includes(k) ? {
3471
+ "#": varying.indexOf(k),
3472
+ kind: values[i].v.kind
3473
+ } : { "@": names.get(k).code }]));
3474
+ const structure = canonical(e, (x) => tokens.get(x));
3475
+ let fn = this.#structures.get(structure);
3476
+ if (fn === void 0) {
3477
+ fn = this.fresh("m");
3478
+ this.#structures.set(structure, fn);
3479
+ this.memos = true;
3480
+ const cached = varying.length === 1 ? this.#cached(e, varying[0], bodyCtx, fn) : void 0;
3481
+ if (cached !== void 0) {
3482
+ this.#kinds.set(fn, cached.kind);
3483
+ this.run.push(...cached.lines);
3484
+ } else {
3485
+ const body = this.expr(e, bodyCtx);
3486
+ this.#kinds.set(fn, body.v.kind);
3487
+ this.#lists.set(fn, body.v.list);
3488
+ this.run.push(`const ${fn} = ${this.use(params.length === 1 ? "M1" : "M")}((${params.join(", ")}) => {`, ...ind(body.s), ` return ${body.v.code};`, "});");
3489
+ }
3490
+ }
3491
+ this.#inside = outer;
3492
+ const s = [];
3493
+ const args = varying.map((k) => {
3494
+ const c = values[keys.indexOf(k)];
3495
+ if (c.v.safe && c.s.length === 0) return c.v.code;
3496
+ if (c.s.length === 0 && c.v.held !== void 0) return c.v.held;
3497
+ const t = this.fresh("k");
3498
+ s.push(...this.#store(t, c));
3499
+ return t;
3500
+ });
3501
+ return {
3502
+ s,
3503
+ v: {
3504
+ code: `${fn}(${args.join(", ")})`,
3505
+ kind: this.#kinds.get(fn),
3506
+ safe: false,
3507
+ deps: depsOf(...values),
3508
+ list: this.#lists.get(fn)
3509
+ }
3510
+ };
3511
+ }
3512
+ /**
3513
+ * This method gives the code of a node of the memo whose key is only in one test of a list op: `test(T, key)`. Such a
3514
+ * node keeps its items in the helper `S`. One pass gives the tests before the test of the key and the value `T` of each
3515
+ * item. The rest of an item evaluates once, at the first key whose test is true.
3516
+ *
3517
+ * With the test `===`, each value `T` has a group of items. With `<` or `<=` and values `T` that do not decrease, the
3518
+ * items whose test is true are a prefix. Each prefix keeps its running value. The values add in the order of the items, so the result has the bits of the interpreter. An error before the test
3519
+ * of the key is an error of the item at each key. An error after it is an error at the keys whose test is true.
3520
+ */
3521
+ #cached(e, key, bodyCtx, fn) {
3522
+ const { op, args } = e;
3523
+ if (!LIST_OPS.has(op)) return void 0;
3524
+ const [target, ...rest] = args;
3525
+ if (target.tag !== "each" || (target.at ?? []).length > 0) return void 0;
3526
+ const strict = this.#strict(op, rest);
3527
+ const kind = bodyCtx.keys.get(key).kind;
3528
+ const { base, tests: raw } = testsOf(target.axis);
3529
+ const tests = raw.flatMap(partsOf);
3530
+ const at = tests.findIndex((t) => contains(t, key));
3531
+ const test = tests[at];
3532
+ if (base.t !== "all" || test?.tag !== "app" || test.args.length !== 2 || contains(target.body, key) || tests.some((t, i) => i !== at && contains(t, key))) return void 0;
3533
+ const [l, r] = test.args;
3534
+ const keyFirst = l === key;
3535
+ const other = keyFirst ? r : l;
3536
+ if (!keyFirst && r !== key || contains(other, key)) return void 0;
3537
+ const j = this.fresh("j");
3538
+ const loop = {
3539
+ ...bodyCtx,
3540
+ focus: j,
3541
+ level: 2
3542
+ };
3543
+ const t = this.#hoist(this.expr(other, loop));
3544
+ const site = this.#facts.staticSite(test.op, keyFirst ? [kind, t.v.kind] : [t.v.kind, kind]);
3545
+ if (site?.t !== "fn" || site.bad || site.returns !== "boolean" || this.check("boolean") !== void 0) return void 0;
3546
+ const form = inlineForm(Function.prototype.toString.call(this.#domains[site.domain].ops[test.op].fn));
3547
+ if (form?.params.length !== 2) return void 0;
3548
+ const before = tests.slice(0, at).map((x) => this.#hoist(this.expr(x, loop)));
3549
+ const after = tests.slice(at + 1).map((x) => this.#hoist(this.expr(x, loop)));
3550
+ const body = this.#hoist(this.expr(target.body, loop));
3551
+ const B = (v) => this.#boolean(v);
3552
+ const pattern = patternOf(form, (p) => keyFirst ? 1 - p : p);
3553
+ const mode = pattern === "#0===#1" || pattern === "#1===#0" ? 1 : [
3554
+ "#0<#1",
3555
+ "#0<=#1",
3556
+ "#1>#0",
3557
+ "#1>=#0"
3558
+ ].includes(pattern) ? 2 : 0;
3559
+ const testArgs = keyFirst ? ["q", "t"] : ["t", "q"];
3560
+ const keyTest = form.parts.map((p) => typeof p === "number" ? `(${testArgs[p]})` : p).join("");
3561
+ if (mode === 1) this.features.add("group");
3562
+ if (mode === 2) this.features.add("prefix");
3563
+ if (strict) this.features.add("strict");
3564
+ const F = this.use("F");
3565
+ const arrow = (lines, code) => lines.length === 0 ? [`(${j}) => ${code}`] : [
3566
+ `(${j}) => {`,
3567
+ ...ind(lines),
3568
+ ` return ${code};`,
3569
+ "}"
3570
+ ];
3571
+ const pre = before.length === 0 ? void 0 : before.every((x) => x.s.length === 0) ? arrow([], before.map((x) => B(x.v)).join(" && ")) : arrow(before.flatMap((x, i) => [...x.s, ...i < before.length - 1 ? [`if (!${B(x.v)}) return false;`] : []]), B(before.at(-1).v));
3572
+ const value = after.length === 0 && body.v.safe && body.s.length === 0 ? arrow([], body.v.code) : [
3573
+ `(${j}) => {`,
3574
+ " try {",
3575
+ ...ind(ind([...after.flatMap((x) => [...x.s, `if (!${B(x.v)}) return N;`]), ...body.s])),
3576
+ ` return ${body.v.code};`,
3577
+ " } catch {",
3578
+ " return E;",
3579
+ " }",
3580
+ "}"
3581
+ ];
3582
+ const [stepName, stepCode] = STEPS[op];
3583
+ this.top.set(stepName, `const ${stepName} = ${stepCode};`);
3584
+ const [resultName, resultCode] = {
3585
+ count: () => ["r_count", "(a, c) => c"],
3586
+ sum: () => [this.check("number") ?? "r_id", "(a) => a"],
3587
+ mean: () => ["r_mean", `(a, c) => (c === 0 ? ${F}() : ${this.#checked("number", "a / c")})`],
3588
+ any: () => ["r_id", "(a) => a"],
3589
+ all: () => ["r_id", "(a) => a"],
3590
+ none: () => ["r_not", "(a) => !a"]
3591
+ }[op]?.() ?? ["r_one", `(a, c) => (c === 0 ? ${F}() : a)`];
3592
+ if (!this.top.has(resultName)) this.top.set(resultName, `const ${resultName} = ${resultCode};`);
3593
+ const a0 = op === "sum" || op === "mean" ? "0" : op === "all" ? "true" : BOOLEAN_LIST_OPS.has(op) ? "false" : "undefined";
3594
+ const needs = op === "count" ? void 0 : listKind(op, void 0);
3595
+ const ok = needs === void 0 || body.v.kind === needs ? [] : [`(x) => typeof x === "${needs}"`];
3596
+ if (ok.length > 0) this.features.add("ok");
3597
+ if (pre !== void 0) this.features.add("pre");
3598
+ const fns = [
3599
+ arrow(t.s, t.v.code),
3600
+ value,
3601
+ [`(t, q) => ${keyTest}`],
3602
+ ...pre === void 0 && ok.length === 0 ? [] : [pre ?? ["undefined"]],
3603
+ ...ok.length === 0 ? [] : [ok]
3604
+ ];
3605
+ const lines = fns.flatMap((x, i) => [...x.slice(0, -1), `${x.at(-1) ?? ""}${i < fns.length - 1 ? "," : ""}`]);
3606
+ return {
3607
+ lines: [
3608
+ `const ${fn} = ${this.use("S")}(n, ${mode}, ${String(strict)}, ${a0}, ${stepName}, ${resultName},`,
3609
+ ...ind(lines),
3610
+ ");"
3611
+ ],
3612
+ kind: listKind(op, body.v.kind)
3613
+ };
3614
+ }
3615
+ /** This method gives the code of the program at the key of the run. A constant of the run evaluates once. */
3616
+ root(expr) {
3617
+ const c = this.#hoist(this.expr(expr, {
3618
+ origin: "o",
3619
+ focus: "o",
3620
+ level: 1,
3621
+ originLevel: 1,
3622
+ env: /* @__PURE__ */ new Map(),
3623
+ fns: /* @__PURE__ */ new Map(),
3624
+ keys: /* @__PURE__ */ new Map()
3625
+ }));
3626
+ for (const [name, form] of this.#forms) if (form !== void 0 && !this.#called.has(name)) this.top.delete(name);
3627
+ return c;
3628
+ }
3629
+ /**
3630
+ * This method gives a text that is the same for two expressions with the same structure and the same reads. A name
3631
+ * that the expression does not bind gives its variable in the code, and a key of the memo gives its variable too.
3632
+ */
3633
+ #constKey(e, ctx) {
3634
+ return canonical(e, (x) => {
3635
+ const key = ctx.keys.get(x);
3636
+ if (key !== void 0) return { "@": key.code };
3637
+ const node = x;
3638
+ if (node?.tag === "var") return { $: ctx.env.get(node.name)?.code ?? node.name };
3639
+ return node?.tag === "call" ? {
3640
+ "()": node.fn,
3641
+ of: ctx.fns.get(node.fn)?.id ?? null,
3642
+ args: node.args
3643
+ } : void 0;
3644
+ });
3645
+ }
3646
+ };
3647
+ /**
3648
+ * This function prints a program as a standalone ES module. The module exports `VexContractError`, `VEX_ERROR` and a
3649
+ * function that takes the records and the variables and gives the value at each key. It is pure, so a build can use it.
3650
+ */
3651
+ function emitModule(expr, options) {
3652
+ const name = options.name ?? "run";
3653
+ if (!/^[A-Za-z_$][\w$]*$/.test(name)) return {
3654
+ ok: false,
3655
+ reason: `the name "${name}" is not a JavaScript name`
3656
+ };
3657
+ const shape = shapeError(expr);
3658
+ if (shape !== void 0) return {
3659
+ ok: false,
3660
+ reason: shape
3661
+ };
3662
+ const p = new Printer(expr, options);
3663
+ let value;
3664
+ try {
3665
+ value = p.root(expr);
3666
+ } catch (thrown) {
3667
+ if (!(thrown instanceof NotStandalone)) throw thrown;
3668
+ return {
3669
+ ok: false,
3670
+ reason: thrown.message
3671
+ };
3672
+ }
3673
+ p.use("C");
3674
+ const helpers = /* @__PURE__ */ new Set();
3675
+ const add = (h) => {
3676
+ for (const x of NEEDS[h]) add(x);
3677
+ helpers.add(h);
3678
+ };
3679
+ const fields = Object.entries(options.schema.fields ?? {});
3680
+ const vars = Object.entries(options.schema.vars ?? {});
3681
+ let fieldChecks;
3682
+ let varChecks;
3683
+ try {
3684
+ fieldChecks = fields.map(([f, k]) => ` || ${p.against(k, `r[${JSON.stringify(f)}]`)}`).join("");
3685
+ varChecks = vars.map(([v, k]) => ` || ${p.against(k, `vars[${JSON.stringify(v)}]`)}`).join("");
3686
+ } catch (thrown) {
3687
+ if (!(thrown instanceof NotStandalone)) throw thrown;
3688
+ return {
3689
+ ok: false,
3690
+ reason: thrown.message
3691
+ };
3692
+ }
3693
+ [...p.helpers].toSorted().forEach(add);
3694
+ return {
3695
+ ok: true,
3696
+ source: [
3697
+ "// Generated by @mark1russell7/vex-compiler from a Vex program. Do not edit.",
3698
+ "/** The error of a run whose input does not keep the schema of the program. */",
3699
+ "export class VexContractError extends Error {}",
3700
+ "/** The value of a key where the program gives an error of Vex. */",
3701
+ "export const VEX_ERROR = Object.freeze({ vexError: true });",
3702
+ "const E = {};",
3703
+ ...p.memos ? ["const Z = {};"] : [],
3704
+ ...helpers.has("S") ? ["const N = {}, W = {};"] : [],
3705
+ ...[...helpers].map((h) => h === "S" ? helperS(p.features) : HELPERS[h]),
3706
+ ...p.top.values(),
3707
+ `export function ${name}(records, vars) {`,
3708
+ " if (!Array.isArray(records)) C(\"the records are not an array\");",
3709
+ " const R = records;",
3710
+ " const n = R.length;",
3711
+ " for (let i = 0; i < n; i++) {",
3712
+ " const r = R[i];",
3713
+ ` if (typeof r !== "object" || r === null${fieldChecks}) C(\`the record \${i} does not keep the schema\`);`,
3714
+ " }",
3715
+ ` if (typeof vars !== "object" || vars === null${varChecks}) C("the variables do not keep the schema");`,
3716
+ ...[...p.vars].map(([v, code]) => ` const ${code} = vars[${JSON.stringify(v)}];`),
3717
+ ...ind(p.run),
3718
+ " const out = [];",
3719
+ " for (let o = 0; o < n; o++) {",
3720
+ " try {",
3721
+ ...ind(ind(ind(value.s))),
3722
+ ` out.push(${value.v.code});`,
3723
+ " } catch {",
3724
+ " out.push(VEX_ERROR);",
3725
+ " }",
3726
+ " }",
3727
+ " return out;",
3728
+ "}",
3729
+ ""
3730
+ ].join("\n")
3731
+ };
3732
+ }
3733
+ //#endregion
3734
+ export { FALLBACK, createRuntime, emitModule, generate, load, tiered };
3735
+
3736
+ //# sourceMappingURL=index.js.map