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