@mark1russell7/vex-compiler 0.7.0 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/module.ts CHANGED
@@ -19,7 +19,7 @@
19
19
  * schema, and the axes `all`, `others` and `window`. The kinds of each op site must decide its op. Another construct
20
20
  * gives a reason, not code.
21
21
  */
22
- import { addrExprs, children, isFieldName, moveExpr, shapeError, type AnyDomain, type Axis, type Expr, type ExprOf, type Move, type Names, type PrimitiveKind } from "@mark1russell7/vex";
22
+ import { addrExprs, children, isFieldName, lit, moveExpr, shapeError, type AnyDomain, type Axis, type Expr, type ExprOf, type Move, type Names, type PrimitiveKind } from "@mark1russell7/vex";
23
23
  import { factsOf, kindOfDomain, primitiveOf, type Facts, type Kind, type Schema } from "./facts.ts";
24
24
  import { memoNodes } from "./memo.ts";
25
25
 
@@ -55,6 +55,13 @@ interface Value {
55
55
  readonly deps: ReadonlySet<number>;
56
56
  /** True for a literal and for the read of a name: a constant of the run with such code needs no variable of its own. */
57
57
  readonly plain?: boolean;
58
+ /** For a list (LIST.VALUE): the kind of its items. The code is an array of pairs of a key and a value or the sentinel. */
59
+ readonly list?: ListInfo | undefined;
60
+ }
61
+
62
+ /** The facts of a list of the code: the kind of the values of its items, if the printer knows it. */
63
+ interface ListInfo {
64
+ readonly item: Kind | undefined;
58
65
  }
59
66
 
60
67
  /** The code of a node: the statements before its value, and its value. `safe` covers the statements too. */
@@ -69,6 +76,14 @@ interface Name {
69
76
  readonly kind: Kind | undefined;
70
77
  readonly lazy: boolean;
71
78
  readonly deps: ReadonlySet<number>;
79
+ readonly list?: ListInfo | undefined;
80
+ }
81
+
82
+ /** An argument of a call: its code, its kind and its levels. */
83
+ interface Arg {
84
+ readonly code: string;
85
+ readonly kind: Kind | undefined;
86
+ readonly deps: ReadonlySet<number>;
72
87
  }
73
88
 
74
89
  /** The levels of a constant of the run. */
@@ -92,12 +107,68 @@ interface Ctx {
92
107
  readonly focus: string | undefined;
93
108
  /** The level of the focus: 1 at the key of the run, and one more in each axis. */
94
109
  readonly level: number;
110
+ /** The level of the origin: 1 at the key of the run, and the marker of the origin in the body of a function. */
111
+ readonly originLevel: number;
95
112
  readonly env: ReadonlyMap<string, Name>;
96
113
  readonly keys: ReadonlyMap<Expr, Name>;
114
+ /** The bound functions (FN.BIND), with the context of their binding. */
115
+ readonly fns: ReadonlyMap<string, BoundFn>;
116
+ }
117
+
118
+ /**
119
+ * A bound function of the printer (FN.BIND): its node and the context of its binding. It also has one printed
120
+ * JavaScript function for each signature of the arguments of its calls.
121
+ */
122
+ interface BoundFn {
123
+ /** The number of the binding. Two functions with one name are two functions, so a key of a constant needs it. */
124
+ readonly id: number;
125
+ readonly fn: ExprOf<"fn">;
126
+ readonly ctx: Ctx;
127
+ /** The printed function for each signature: the kind of each argument. */
128
+ readonly specs: Map<string, Spec>;
129
+ /** The declarations of the printed functions that read names of the place of the binding. The let prints them. */
130
+ readonly decls: string[];
131
+ /** True when a printed function of the binding is at the place of the binding, not at the start of a run. */
132
+ local: boolean;
133
+ }
134
+
135
+ /**
136
+ * A function that the printer prints at this time. Its parameters, and the bindings at the root of its body, keep their
137
+ * values for the whole call. Thus a part of a loop that reads only them and its target is a column of the call.
138
+ */
139
+ interface CallScope {
140
+ /** The marker of the parameters. */
141
+ readonly param: number;
142
+ /** The level of the focus of the function. A part at a higher level is in a loop of the function. */
143
+ readonly focus: number;
144
+ /** True when the body has a loop in a loop, so a call can read a part of a loop more than once. */
145
+ readonly repeats: boolean;
146
+ /** The variables that the start of the body can read: the parameters, and the bindings at the root of the body. */
147
+ readonly names: Set<string>;
148
+ /** The declarations of the columns of the call. The function prints them at the start of its body. */
149
+ readonly decls: string[];
150
+ /** The root of the body. A let at the root moves it to its body, because its bindings are at the start of the body. */
151
+ root: Expr;
152
+ }
153
+
154
+ /**
155
+ * A printed function. The levels of the value of its body have a marker for the origin, for the focus and for each
156
+ * parameter. A call replaces each marker with the levels at the call.
157
+ */
158
+ interface Spec {
159
+ readonly name: string;
160
+ readonly kind: Kind | undefined;
161
+ readonly safe: boolean;
162
+ readonly deps: ReadonlySet<number>;
163
+ readonly origin: number;
164
+ readonly focus: number;
165
+ readonly param: number;
166
+ /** True when the body reads only constants of the run, its parameters and its position, so it is at the start of a run. */
167
+ readonly global: boolean;
97
168
  }
98
169
 
99
170
  /** The name of a helper of the generated code. */
100
- type Helper = "F" | "C" | "T" | "L" | "Q" | "G" | "B" | "U" | "X" | "I" | "K" | "M" | "M1" | "S";
171
+ type Helper = "F" | "C" | "T" | "L" | "Q" | "G" | "B" | "U" | "X" | "I" | "K" | "M" | "M1" | "S" | "V" | "SB" | "TK" | "NT";
101
172
 
102
173
  /** The helpers of the generated code. A module has only the helpers that it uses. */
103
174
  const HELPERS: Readonly<Record<Exclude<Helper, "S">, string>> = {
@@ -117,6 +188,19 @@ const HELPERS: Readonly<Record<Exclude<Helper, "S">, string>> = {
117
188
  // The index of a computed position, and of a computed key: a key of an array space is the text of its index.
118
189
  I: "function I(t, n) { return Number.isInteger(t) && t >= 0 && t < n ? t : F(); }",
119
190
  K: 'function K(k, n) { return typeof k === "string" && /^(0|[1-9]\\d*)$/.test(k) && +k < n ? +k : F(); }',
191
+ // The ops on the order of a list (LIST.SORT, LIST.TAKE, LIST.NTH) work on the items with values. With strict, an
192
+ // error item is the error of the op. A sort is stable, and the values are numbers without NaN or texts of one kind.
193
+ V: "function V(l, s) { if (s && l.some((x) => x[1] === E)) F(); return l.filter((x) => x[1] !== E); }",
194
+ SB: [
195
+ "function SB(l, s) {",
196
+ " const o = V(l, s);",
197
+ " const t = o.length > 0 ? typeof o[0][1] : \"number\";",
198
+ " for (const [, v] of o) if (typeof v !== t || (t !== \"number\" && t !== \"string\") || v !== v) F();",
199
+ " return o.sort((a, b) => (a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0));",
200
+ "}",
201
+ ].join("\n"),
202
+ TK: "function TK(l, n, s) { const o = V(l, s); return Number.isSafeInteger(n) && n >= 0 ? o.slice(0, n) : F(); }",
203
+ NT: "function NT(l, i, s) { const o = V(l, s); return Number.isSafeInteger(i) && i >= 0 && i < o.length ? o[i][1] : F(); }",
120
204
  // The memo of a function of one key, and of more keys. -0 has its own entry, because an op can tell it from 0.
121
205
  M1: [
122
206
  "function M1(f) {",
@@ -273,7 +357,13 @@ const STEPS: Readonly<Record<string, readonly [string, string]>> = {
273
357
  };
274
358
 
275
359
  /** The helpers that each helper uses. */
276
- const NEEDS: Readonly<Record<Helper, readonly Helper[]>> = { F: [], C: [], T: [], L: [], Q: [], G: ["F"], B: ["F"], U: ["F"], X: ["F"], I: ["F"], K: ["F"], M: ["G"], M1: ["G"], S: ["M1", "F"] };
360
+ const NEEDS: Readonly<Record<Helper, readonly Helper[]>> = {
361
+ F: [], C: [], T: [], L: [], Q: [], G: ["F"], B: ["F"], U: ["F"], X: ["F"], I: ["F"], K: ["F"], M: ["G"], M1: ["G"], S: ["M1", "F"],
362
+ // Only SB, TK and NT use V, and they need F too, so the need of V only completes the list.
363
+ // Stryker disable next-line ArrayDeclaration: see the comment above
364
+ V: ["F"],
365
+ SB: ["V", "F"], TK: ["V", "F"], NT: ["V", "F"],
366
+ };
277
367
 
278
368
  /** The list ops of a standalone module. */
279
369
  const LIST_OPS: ReadonlySet<string> = new Set(["count", "sum", "mean", "min", "max", "any", "all", "none", "first"]);
@@ -298,6 +388,15 @@ function namesOf(e: Expr, out = new Set<string>()): Set<string> {
298
388
  */
299
389
  const COLUMN_WORK = 10;
300
390
 
391
+ /** This function gives the head of a loop over targets: from `lo` up to `hi`, or from `hi` down to `lo` in the reverse order. */
392
+ const forHead = (j: string, lo: string, hi: string, reverse: boolean): string => (reverse ? `for (let ${j} = ${hi} - 1; ${j} >= ${lo}; ${j}--) {` : `for (let ${j} = ${lo}; ${j} < ${hi}; ${j}++) {`);
393
+
394
+ /** This function tells if an expression has a loop in a loop: an axis, a fold or an iteration in another one. */
395
+ function nestsLoops(e: Expr, inLoop = false): boolean {
396
+ const loop = e.tag === "each" || e.tag === "fold" || e.tag === "iterate";
397
+ return (loop && inLoop) || children(e).some((x) => nestsLoops(x, inLoop || loop));
398
+ }
399
+
301
400
  /** This function tells if an expression has a loop of names: a fold or an iteration. */
302
401
  function hasLoop(e: Expr): boolean {
303
402
  let found = LOOPS.get(e);
@@ -522,6 +621,9 @@ class Printer {
522
621
  /** The parts of the helper S that the nodes of the memo that keep their items need (helperS). */
523
622
  readonly features = new Set<Feature>();
524
623
  #names = 0;
624
+ /** The number of the next bound function, and of the next printed function. */
625
+ #fnIds = 0;
626
+ #printed = 0;
525
627
  /** The level of the names of the next loop. It is far above the levels of the axes, so the two do not meet. */
526
628
  #loops = 1_000_000;
527
629
  /** The node of the memo whose function the printer prints, so it prints the node itself. */
@@ -538,8 +640,21 @@ class Printer {
538
640
  readonly #constants = new Map<string, Code>();
539
641
  /** The columns of the run, by the structure of their expression. */
540
642
  readonly #columns = new Map<string, string>();
643
+ /** The expressions whose code is the read of a column of the run. */
644
+ readonly #columned = new WeakSet<Expr>();
645
+ /** The lazy constants of the run, and the printed functions that have a loop: code that reads one waits for its read. */
646
+ readonly #deferred = new Set<string>();
647
+ /** The functions that the printer prints at this time, the innermost last. */
648
+ // Stryker disable next-line ArrayDeclaration: a value that is not a scope has no field repeats or root, so it acts as no scope
649
+ readonly #scopes: CallScope[] = [];
650
+ /** The work of the body of each bound function, by the number of its binding. */
651
+ readonly #fnWork = new Map<number, number>();
541
652
  /** The expressions whose code is a constant of the run. */
542
653
  readonly #constant = new WeakSet<Expr>();
654
+ /** The expressions at a place that takes a list: a binding, the head of a list op and the list of an axis. */
655
+ readonly #wantList = new WeakSet<Expr>();
656
+ /** The facts of the list of each function of the memo whose value is a list. */
657
+ readonly #lists = new Map<string, ListInfo | undefined>();
543
658
 
544
659
  constructor(expr: Expr, options: ModuleOptions) {
545
660
  this.#domains = options.domains ?? [];
@@ -622,15 +737,20 @@ class Printer {
622
737
  return `${prefix}${this.#names++}`;
623
738
  }
624
739
 
740
+ /** This method tells if code reads a lazy constant of the run, or calls a printed function that has a loop. */
741
+ #defers(c: Code): boolean {
742
+ return [c.v.code, ...c.s].some((line) => [...line.matchAll(/\b(c\d+|fn\d+)\(/g)].some((m) => this.#deferred.has(m[1] as string)));
743
+ }
744
+
625
745
  /** This method gives the code of a name: a read that throws the error of its value, if it can hold an error. */
626
746
  #read(name: Name): Value {
627
- const base = { kind: name.kind, deps: name.deps, plain: true };
747
+ const base = { kind: name.kind, deps: name.deps, plain: true, list: name.list };
628
748
  return name.lazy ? { ...base, code: `${this.use("G")}(${name.code})`, safe: false, held: name.code } : { ...base, code: name.code, safe: true };
629
749
  }
630
750
 
631
751
  /** This method gives the name of a constant of the run, from the read of its value. */
632
752
  #nameOf(v: Value): Name {
633
- return { code: v.held ?? v.code, kind: v.kind, lazy: v.held !== undefined, deps: NO_DEPS };
753
+ return { code: v.held ?? v.code, kind: v.kind, lazy: v.held !== undefined, deps: NO_DEPS, list: v.list };
634
754
  }
635
755
 
636
756
  /**
@@ -646,7 +766,8 @@ class Printer {
646
766
 
647
767
  /**
648
768
  * This method evaluates a constant of the run once, before the loop over the keys, and gives the read of its value. A
649
- * constant with a loop (`lazy`) evaluates on its first read instead, as a branch of the interpreter does.
769
+ * constant with a loop (`lazy`) evaluates on its first read instead, as a branch of the interpreter does. So does a
770
+ * constant that reads a lazy constant or calls a function with a loop. Else it starts that loop before the run.
650
771
  */
651
772
  #hoist(c: Code, lazy = false): Code {
652
773
  if (c.v.deps.size > 0 || (c.v.plain === true && c.s.length === 0)) return c;
@@ -654,9 +775,13 @@ class Printer {
654
775
  const hit = key === undefined ? undefined : this.#constants.get(key);
655
776
  if (hit !== undefined) return hit;
656
777
  const name = this.fresh("c");
657
- if (lazy) this.run.push(`const ${name} = ${this.use("L")}(() => {`, ...ind(c.s), ` return ${c.v.code};`, "});");
658
- else this.run.push(...this.#store(name, c, true));
659
- const read = bare(this.#read(lazy ? { code: `${name}()`, kind: c.v.kind, lazy: true, deps: NO_DEPS } : { code: name, kind: c.v.kind, lazy: !c.v.safe, deps: NO_DEPS }));
778
+ const deferred = lazy || this.#defers(c);
779
+ if (deferred) {
780
+ this.#deferred.add(name);
781
+ this.run.push(`const ${name} = ${this.use("L")}(() => {`, ...ind(c.s), ` return ${c.v.code};`, "});");
782
+ } else this.run.push(...this.#store(name, c, true));
783
+ const { list } = c.v;
784
+ const read = bare(this.#read(deferred ? { code: `${name}()`, kind: c.v.kind, lazy: true, deps: NO_DEPS, list } : { code: name, kind: c.v.kind, lazy: !c.v.safe, deps: NO_DEPS, list }));
660
785
  if (key !== undefined) this.#constants.set(key, read);
661
786
  return read;
662
787
  }
@@ -679,19 +804,64 @@ class Printer {
679
804
  this.#keyOf.set(c, this.#constKey(e, ctx));
680
805
  this.#constant.add(e);
681
806
  }
807
+ // A list is a value only at a place that takes a list. A result, an argument and a field take no list.
808
+ if (c.v.list !== undefined && !this.#wantList.has(e)) throw new NotStandalone("a list is a value of the program");
682
809
  return this.#columnar(e, c, ctx) ? this.#column(e, c, ctx) : c;
683
810
  }
684
811
 
812
+ /** This method gives the code of a list at a place that takes a list (LIST.VALUE): an each, a name, sortBy or take. */
813
+ #listOf(e: Expr, ctx: Ctx): Code {
814
+ this.#wantList.add(e);
815
+ const c = this.expr(e, ctx);
816
+ if (c.v.list === undefined) throw new NotStandalone("a list op on a value that is not a list");
817
+ return c;
818
+ }
819
+
820
+ /** This method tells if an expression gives a list at a place that takes one: an each, sortBy, take or a name of a list. */
821
+ #isList(e: Expr, ctx: Ctx): boolean {
822
+ if (e.tag === "each") return true;
823
+ if (e.tag === "app") return e.op === "sortBy" || e.op === "take";
824
+ return e.tag === "var" && ctx.env.get(e.name)?.list !== undefined;
825
+ }
826
+
685
827
  /**
686
828
  * This method tells if a part of a loop over the targets is a column of the run. Its value depends only on the
687
829
  * target and on the constants of the run, so each run computes it once for each record. Each name that it reads
688
830
  * from outside is a constant of the run, so its code can be outside the loop.
689
831
  */
690
832
  #columnar(e: Expr, c: Code, ctx: Ctx): boolean {
691
- if (ctx.level < 2 || ctx.focus === undefined || c.v.deps.size !== 1 || !c.v.deps.has(ctx.level) || this.#work(e) < COLUMN_WORK) return false;
833
+ // A node of the memo has the level 1, so a column has a focus.
834
+ if (ctx.level < 2 || !c.v.deps.has(ctx.level) || this.#work(e, ctx.fns) < COLUMN_WORK) return false;
835
+ const scope = this.#callScope(c, ctx);
836
+ if (c.v.deps.size !== 1 && scope === undefined) return false;
692
837
  // A node of the memo with keys keeps its costly part for each value of its keys already.
693
838
  if (this.#keyed(e)) return false;
694
- return [...namesOf(e)].every((name) => (ctx.env.get(name)?.deps.size ?? 0) === 0);
839
+ const visible = (name: string): boolean => {
840
+ const bound = ctx.env.get(name);
841
+ return (bound?.deps.size ?? 0) === 0 || (scope?.names.has((bound as Name).code) ?? false);
842
+ };
843
+ return [...namesOf(e)].every(visible) && !this.#callsLocal(e, ctx);
844
+ }
845
+
846
+ /**
847
+ * This method gives the function whose call can hold a column of a part. The part is in a loop of the function, and it
848
+ * reads a parameter. The body of the function has a loop in a loop, so a call can read the part more than once. Each
849
+ * name that the part reads is a parameter, a binding at the root of the body or a constant (`#columnar`). So the
850
+ * part depends only on its target and on values that one call does not change. These are the parameters, the focus
851
+ * and the origin. The levels in a node of the memo start at 1, far below the focus of a function. So a node of the
852
+ * memo holds no column of a call.
853
+ */
854
+ #callScope(c: Code, ctx: Ctx): CallScope | undefined {
855
+ const scope = this.#scopes.at(-1);
856
+ // A part that reads a parameter reads a variable of this function, so its structure gives no column of another function.
857
+ return scope !== undefined && scope.repeats && ctx.level > scope.focus && c.v.deps.has(scope.param) ? scope : undefined;
858
+ }
859
+
860
+ /** This method tells if an expression calls a function that is at the place of its binding, not at the start of a run. */
861
+ #callsLocal(e: Expr, ctx: Ctx): boolean {
862
+ // Stryker disable next-line ConditionalExpression: a node that is not a call has no field fn, so the map gives undefined
863
+ if (e.tag === "call" && ctx.fns.get(e.fn)?.local === true) return true;
864
+ return children(e).some((x) => this.#callsLocal(x, ctx));
695
865
  }
696
866
 
697
867
  /** This method tells if an expression has a node of the memo with keys in it. */
@@ -699,10 +869,30 @@ class Printer {
699
869
  return (this.#memo.get(e)?.length ?? 0) > 0 || children(e).some((x) => this.#keyed(x));
700
870
  }
701
871
 
702
- /** This method gives the work of an expression: a node of the memo and a constant of the run are one read each. */
703
- #work(e: Expr): number {
872
+ /**
873
+ * This method gives the work of an expression: a node of the memo and a constant of the run are one read each. A call
874
+ * adds the work of the body of its function, because the body evaluates at each call.
875
+ */
876
+ #work(e: Expr, fns: ReadonlyMap<string, BoundFn>): number {
704
877
  if (this.#memo.has(e) || this.#constant.has(e)) return 1;
705
- return children(e).reduce((sum, x) => sum + this.#work(x), 1);
878
+ // Stryker disable next-line ConditionalExpression: a node that is not a call has no field fn, so the map gives undefined
879
+ const body = e.tag === "call" ? this.#bodyWork(fns.get(e.fn)) : 0;
880
+ return children(e).reduce((sum, x) => sum + this.#work(x, fns), 1 + body);
881
+ }
882
+
883
+ /**
884
+ * This method gives the work of the body of a function, once for each function. Thus a chain of calls costs no more
885
+ * than its functions. A body that is a column of the run is one read. A body sees the functions of the place of its
886
+ * binding, and no function calls itself (FN.TOTAL).
887
+ */
888
+ #bodyWork(bound: BoundFn | undefined): number {
889
+ if (bound === undefined) return 0;
890
+ let work = this.#fnWork.get(bound.id);
891
+ if (work === undefined) {
892
+ work = this.#columned.has(bound.fn.body) ? 1 : this.#work(bound.fn.body, bound.ctx.fns);
893
+ this.#fnWork.set(bound.id, work);
894
+ }
895
+ return work;
706
896
  }
707
897
 
708
898
  /** This method gives the read of a column of the run. Two parts with the same structure share one column. */
@@ -711,10 +901,13 @@ class Printer {
711
901
  let name = this.#columns.get(key);
712
902
  if (name === undefined) {
713
903
  name = this.fresh("col");
714
- this.run.push(`const ${name} = ${this.use("Q")}((${ctx.focus as string}) => {`, ...ind(c.s), ` return ${c.v.code};`, "});");
904
+ // A column of a call is at the start of the body of its function, so each call has its own.
905
+ const scope = this.#callScope(c, ctx);
906
+ (scope?.decls ?? this.run).push(`const ${name} = ${this.use("Q")}((${ctx.focus as string}) => {`, ...ind(c.s), ` return ${c.v.code};`, "});");
715
907
  this.#columns.set(key, name);
716
908
  }
717
- return bare({ code: `${this.use("G")}(${name}(${ctx.focus as string}))`, kind: c.v.kind, safe: false, deps: c.v.deps });
909
+ this.#columned.add(e);
910
+ return bare({ code: `${this.use("G")}(${name}(${ctx.focus as string}))`, kind: c.v.kind, safe: false, deps: c.v.deps, list: c.v.list });
718
911
  }
719
912
 
720
913
  #node(e: Expr, ctx: Ctx): Code {
@@ -727,6 +920,12 @@ class Printer {
727
920
  return bare(this.#var(e.name, ctx));
728
921
  case "let":
729
922
  return this.#let(e, ctx);
923
+ // A function is only a binding of let, so the check of the shape stops this node first.
924
+ // Stryker disable next-line all: see the comment above
925
+ /* v8 ignore next -- @preserve */
926
+ case "fn": throw new NotStandalone("a function outside the bindings of a let");
927
+ case "call":
928
+ return this.#call(e, ctx);
730
929
  case "rec": {
731
930
  const names = Object.keys(e.fields);
732
931
  const raw = Object.values(e.fields).map((x) => this.expr(x, ctx));
@@ -739,7 +938,7 @@ class Printer {
739
938
  case "app":
740
939
  return this.#app(e, ctx);
741
940
  case "each":
742
- throw new NotStandalone("a list is a value of the program");
941
+ return this.#eachList(e, ctx);
743
942
  case "fold":
744
943
  return this.#fold(e, ctx);
745
944
  case "iterate":
@@ -840,7 +1039,7 @@ class Printer {
840
1039
  for (const m of at) {
841
1040
  if (fails) for (const d of deps) kept.add(d);
842
1041
  if (moveExpr(m) !== undefined) deps = (values[next++] as Code).v.deps;
843
- else if (m.t === "origin") deps = new Set([1]);
1042
+ else if (m.t === "origin") deps = new Set([ctx.originLevel]);
844
1043
  else if (m.t === "key" || m.t === "index" || m.t === "parent") deps = NO_DEPS;
845
1044
  fails = m.t !== "origin";
846
1045
  }
@@ -850,6 +1049,8 @@ class Printer {
850
1049
  #var(name: string, ctx: Ctx): Value {
851
1050
  const bound = ctx.env.get(name);
852
1051
  if (bound !== undefined) return this.#read(bound);
1052
+ // A name of a loop hides a function with its name, so this check comes after the names of the scope.
1053
+ if (ctx.fns.has(name)) throw new NotStandalone(`the name "${name}" is a function, not a value`);
853
1054
  const kind = this.#schema.vars?.[name];
854
1055
  if (kind === undefined) throw new NotStandalone(`a variable that is not in the schema: "${name}"`);
855
1056
  let code = this.vars.get(name);
@@ -866,9 +1067,27 @@ class Printer {
866
1067
  */
867
1068
  #let(e: ExprOf<"let">, ctx: Ctx): Code {
868
1069
  const env = new Map(ctx.env);
1070
+ const fns = new Map(ctx.fns);
869
1071
  const s: string[] = [];
870
1072
  let deps = new Set<number>();
1073
+ const bound: BoundFn[] = [];
1074
+ // The bindings of a let at the root of the body of a function are at the start of the body, so a column of the
1075
+ // call can read them. A let at the root that is a node of the memo binds variables of its function of the memo, but
1076
+ // the memo holds no column of a call (`#callScope`), so these names have no reader.
1077
+ const scope = this.#scopes.at(-1);
1078
+ const root = scope !== undefined && scope.root === e ? scope : undefined;
871
1079
  for (const [name, x] of Object.entries(e.bind)) {
1080
+ // A binding sees the context of the let, so a function cannot call itself.
1081
+ if (x.tag === "fn") {
1082
+ // Stryker disable next-line UpdateOperator: the numbers of the bindings only need to be distinct
1083
+ const b: BoundFn = { id: this.#fnIds++, fn: x, ctx, specs: new Map(), decls: [], local: false };
1084
+ bound.push(b);
1085
+ fns.set(name, b);
1086
+ env.delete(name);
1087
+ continue;
1088
+ }
1089
+ // A binding takes a list (LIST.VALUE). A value hides a function of its name, because a read looks at the values first.
1090
+ this.#wantList.add(x);
872
1091
  const c = this.#hoist(this.expr(x, ctx), hasLoop(x));
873
1092
  if (c.v.deps.size === 0) {
874
1093
  env.set(name, this.#nameOf(c.v));
@@ -876,12 +1095,86 @@ class Printer {
876
1095
  }
877
1096
  const b = this.fresh("b");
878
1097
  s.push(...this.#store(b, c));
879
- env.set(name, { code: b, kind: c.v.kind, lazy: !c.v.safe, deps: c.v.deps });
1098
+ env.set(name, { code: b, kind: c.v.kind, lazy: !c.v.safe, deps: c.v.deps, list: c.v.list });
1099
+ root?.names.add(b);
880
1100
  // The statements of the binding read its keys, so the let is not a constant of the run.
881
1101
  deps = new Set([...deps, ...c.v.deps]);
882
1102
  }
883
- const body = this.expr(e.body, { ...ctx, env });
884
- return { s: [...s, ...body.s], v: { ...body.v, deps: new Set([...deps, ...body.v.deps]) } };
1103
+ if (root !== undefined) root.root = e.body;
1104
+ const body = this.expr(e.body, { ...ctx, env, fns });
1105
+ // A function that reads names of the place of the binding comes after them, before the body.
1106
+ return { s: [...s, ...bound.flatMap((b) => b.decls), ...body.s], v: { ...body.v, deps: new Set([...deps, ...body.v.deps]) } };
1107
+ }
1108
+
1109
+ /**
1110
+ * This method prints a call (FN.CALL). Each argument evaluates at the place of the call, as a binding of a let. The
1111
+ * call goes to the printed function of the signature of its arguments, with the focus and the origin if it reads them.
1112
+ */
1113
+ #call(e: ExprOf<"call">, ctx: Ctx): Code {
1114
+ const bound = ctx.env.has(e.fn) ? undefined : ctx.fns.get(e.fn);
1115
+ if (bound === undefined) throw new NotStandalone(`a call of "${e.fn}", which is not a function`);
1116
+ if (bound.fn.params.length !== e.args.length) throw new NotStandalone(`a call of "${e.fn}" with ${String(e.args.length)} arguments, not ${String(bound.fn.params.length)}`);
1117
+ const s: string[] = [];
1118
+ const args = e.args.map((x): Arg => {
1119
+ const c = this.#hoist(this.expr(x, ctx), hasLoop(x));
1120
+ // A value that cannot throw is the argument itself. A read of a name that can hold the error passes the name.
1121
+ if (c.v.safe) {
1122
+ s.push(...c.s);
1123
+ return { code: c.v.code, kind: c.v.kind, deps: c.v.deps };
1124
+ }
1125
+ // Stryker disable next-line ConditionalExpression: the statements with a read of a name bind other names and do not throw, so the read alone has the same value
1126
+ if (c.s.length === 0 && c.v.held !== undefined) return { code: c.v.held, kind: c.v.kind, deps: c.v.deps };
1127
+ const b = this.fresh("b");
1128
+ s.push(...this.#store(b, c));
1129
+ return { code: b, kind: c.v.kind, deps: c.v.deps };
1130
+ });
1131
+ // Each parameter can hold the error of its argument, so one function serves the arguments of one kind.
1132
+ const sig = JSON.stringify(args.map((a) => a.kind ?? null));
1133
+ const spec = bound.specs.get(sig) ?? this.#printFn(bound, args, sig);
1134
+ // Each marker becomes the levels at the call. The levels of the arguments count for each call, because their
1135
+ // statements read their keys, so the marker of the parameters gives no level.
1136
+ const levels = (d: number): readonly number[] => (d === spec.origin ? [ctx.originLevel] : d === spec.focus ? [ctx.level] : d === spec.param ? [] : [d]);
1137
+ const deps = new Set([...args.flatMap((a) => [...a.deps]), ...[...spec.deps].flatMap(levels)]);
1138
+ const position = spec.deps.has(spec.origin) ? [ctx.focus, ctx.origin] : spec.deps.has(spec.focus) ? [ctx.focus] : [];
1139
+ return { s, v: { code: `${spec.name}(${[...args.map((a) => a.code), ...position].join(", ")})`, kind: spec.kind, safe: spec.safe, deps } };
1140
+ }
1141
+
1142
+ /**
1143
+ * This method prints a bound function for one signature of its arguments, as one JavaScript function. Its parameters
1144
+ * are the arguments, then the focus and the origin, if the body reads them. A function that reads a name of the place
1145
+ * of its binding is at that place. Each other function is at the start of a run, so a constant of the run can call it.
1146
+ */
1147
+ #printFn(bound: BoundFn, args: readonly Arg[], sig: string): Spec {
1148
+ // The markers are far from the levels of the axes and of the loops, so they do not meet them. They only need to be
1149
+ // distinct.
1150
+ // Stryker disable next-line ArithmeticOperator,UpdateOperator: see the comment above
1151
+ const origin = 2_000_000 + 1000 * this.#printed++;
1152
+ const focus = origin + 1;
1153
+ const param = -origin;
1154
+ const names = args.map(() => this.fresh("p"));
1155
+ const k = this.fresh("k");
1156
+ const o = this.fresh("o");
1157
+ const env = new Map(bound.ctx.env);
1158
+ // A parameter hides a function of its name, because a read looks at the values first.
1159
+ bound.fn.params.forEach((p, i) => env.set(p, { code: names[i] as string, kind: (args[i] as Arg).kind, lazy: true, deps: new Set([param]) }));
1160
+ const scope: CallScope = { param, focus, repeats: nestsLoops(bound.fn.body), names: new Set(names), decls: [], root: bound.fn.body };
1161
+ this.#scopes.push(scope);
1162
+ const body = this.expr(bound.fn.body, { origin: o, focus: k, level: focus, originLevel: origin, env, fns: bound.ctx.fns, keys: new Map() });
1163
+ this.#scopes.pop();
1164
+ const markers = new Set([origin, focus, param]);
1165
+ const global = [...body.v.deps].every((d) => markers.has(d));
1166
+ const name = this.fresh("fn");
1167
+ if (hasLoop(bound.fn.body) || this.#defers(body)) this.#deferred.add(name);
1168
+ const position = body.v.deps.has(origin) ? [k, o] : body.v.deps.has(focus) ? [k] : [];
1169
+ const head = `const ${name} = (${[...names, ...position].join(", ")}) =>`;
1170
+ // The columns of the call come first. Each one reads a binding of the root only after the binding has its value.
1171
+ const s = [...scope.decls, ...body.s];
1172
+ const decl = s.length === 0 ? [`${head} ${body.v.code};`] : [`${head} {`, ...ind(s), ` return ${body.v.code};`, "};"];
1173
+ (global ? this.run : bound.decls).push(...decl);
1174
+ if (!global) bound.local = true;
1175
+ const spec: Spec = { name, kind: body.v.kind, safe: body.v.safe, deps: body.v.deps, origin, focus, param, global };
1176
+ bound.specs.set(sig, spec);
1177
+ return spec;
885
1178
  }
886
1179
 
887
1180
  #boolean(v: Value): string {
@@ -900,6 +1193,8 @@ class Printer {
900
1193
  if (op === "ifError") return this.#ifError(args, ctx);
901
1194
  const [head] = args;
902
1195
  if (LIST_OPS.has(op) && head?.tag === "each") return this.#list(op, head, args.slice(1), ctx);
1196
+ if (head !== undefined && (op === "sortBy" || op === "take")) return this.#order(op, head, args.slice(1), ctx);
1197
+ if (head !== undefined && (LIST_OPS.has(op) || op === "nth") && this.#isList(head, ctx)) return this.#overList(op, head, args.slice(1), ctx);
903
1198
  const raw = args.map((x) => this.expr(x, ctx));
904
1199
  const deps = depsOf(...raw);
905
1200
  const values = this.#settle(raw, deps, args);
@@ -1010,17 +1305,36 @@ class Printer {
1010
1305
  #targetLoop(axis: Axis, at: readonly Move[], ctx: Ctx): {
1011
1306
  readonly s: string[];
1012
1307
  readonly j: string;
1013
- readonly lo: string;
1014
- readonly hi: string;
1308
+ /** The head of the loop, and the statements at the start of each item before the try and inside it. */
1309
+ readonly head: string;
1310
+ readonly key: readonly string[];
1311
+ readonly check: readonly string[];
1015
1312
  readonly skip: string | undefined;
1016
1313
  readonly fixed: boolean;
1017
1314
  readonly start: ReadonlySet<number>;
1315
+ /** True when the statements before the loop cannot throw. */
1316
+ readonly startSafe: boolean;
1018
1317
  readonly tests: readonly Expr[];
1019
1318
  readonly inner: Ctx;
1020
1319
  } {
1021
- const { base, tests } = testsOf(axis);
1320
+ const { base: outer, tests } = testsOf(axis);
1321
+ // The reverse order of an axis is a loop from its end (AXIS.REVERSE). The validation keeps a base axis inside.
1322
+ const reverse = outer.t === "reverse";
1323
+ const base = outer.t === "reverse" ? outer.axis : outer;
1022
1324
  const j = this.fresh("j");
1023
1325
  const inner: Ctx = { ...ctx, focus: j, level: ctx.level + 1 };
1326
+ // The axis list goes over the array of its list (AXIS.LIST). The list evaluates at the node, before the loop, and an
1327
+ // error item is an item that fails.
1328
+ if (base.t === "list") {
1329
+ if (at.length > 0) throw new NotStandalone('the axis "list" with an address');
1330
+ const list = this.#hoist(this.#listOf(base.list, ctx), hasLoop(base.list));
1331
+ const a = this.fresh("A");
1332
+ const q = this.fresh("q");
1333
+ const head = reverse ? `for (let ${q} = ${a}.length - 1; ${q} >= 0; ${q}--) {` : `for (let ${q} = 0; ${q} < ${a}.length; ${q}++) {`;
1334
+ const key = [`const ${j} = ${a}[${q}][0];`];
1335
+ const check = [`if (${a}[${q}][1] === E) ${this.use("F")}();`];
1336
+ return { s: [...list.s, `const ${a} = ${list.v.code};`], j, head, key, check, skip: undefined, fixed: false, start: list.v.deps, startSafe: list.v.safe, tests, inner };
1337
+ }
1024
1338
  const s: string[] = [];
1025
1339
  let lo = "0";
1026
1340
  let hi = "n";
@@ -1043,13 +1357,14 @@ class Printer {
1043
1357
  s.push(`const ${h} = Math.min(n, ${f as string} + Math.min(${base.to}, n) + 1);`);
1044
1358
  hi = h;
1045
1359
  } else if (base.t !== "all") throw new NotStandalone(`the axis "${base.t}"`);
1046
- return { s, j, lo, hi, skip, fixed: f === undefined, start, tests, inner };
1360
+ const startSafe = at.every((m) => m.t === "origin");
1361
+ return { s, j, head: forHead(j, lo, hi, reverse), key: [], check: [], skip, fixed: f === undefined, start, startSafe, tests, inner };
1047
1362
  }
1048
1363
 
1049
1364
  #list(op: string, target: ExprOf<"each">, rest: readonly Expr[], ctx: Ctx): Code {
1050
1365
  const strict = this.#strict(op, rest);
1051
1366
  const at = target.at ?? [];
1052
- const { s, j, lo, hi, skip, fixed, start, tests, inner } = this.#targetLoop(target.axis, at, ctx);
1367
+ const { s, j, head, key, check, skip, fixed, start, startSafe, tests, inner } = this.#targetLoop(target.axis, at, ctx);
1053
1368
  const { level } = inner;
1054
1369
  // Inside the loop, a constant of the run evaluates once, before the loop over the keys of the run.
1055
1370
  const testCodes = tests.map((t) => this.#hoist(this.expr(t, inner), hasLoop(t)));
@@ -1057,12 +1372,37 @@ class Printer {
1057
1372
  // A count of all the items, whose body cannot fail, is the count of the records. A safe body covers its statements.
1058
1373
  if (op === "count" && fixed && tests.length === 0 && body.v.safe) return bare(plainValue("n", "number"));
1059
1374
  const deps = new Set([...start, ...[body, ...testCodes].flatMap((x) => [...x.v.deps])].filter((d) => d !== level));
1375
+ const r = this.#reduction(op, body.v.kind);
1376
+ const { v } = r;
1377
+ s.push(r.init);
1378
+ const item = [...check, ...testCodes.flatMap((t) => [...t.s, `if (!${this.#boolean(t.v)}) continue;`]), ...body.s];
1379
+ // An item whose tests and body cannot fail needs no try.
1380
+ const safeItem = check.length === 0 && body.v.safe && testCodes.every((t) => this.#safeBoolean(t.v));
1381
+ const loop = [
1382
+ ...key,
1383
+ ...(skip === undefined ? [] : [`if (${j} === ${skip}) continue;`]),
1384
+ ...(safeItem
1385
+ ? [...item, `const ${v} = ${body.v.code};`]
1386
+ : [`let ${v};`, "try {", ...ind(item), ` ${v} = ${body.v.code};`, "} catch {", strict ? ` ${this.use("F")}();` : " continue;", "}"]),
1387
+ r.step,
1388
+ ];
1389
+ s.push(head, ...ind(loop), "}");
1390
+ // A count without strict, and any, all and none over booleans without strict, cannot fail. The address of the axis
1391
+ // can fail, except at the focus or at the origin.
1392
+ const safe = startSafe && !strict && (op === "count" || (BOOLEAN_LIST_OPS.has(op) && body.v.kind === "boolean"));
1393
+ return { s, v: { code: r.result, kind: listKind(op, body.v.kind), safe, deps } };
1394
+ }
1395
+
1396
+ /**
1397
+ * This method gives the parts of a list op that reduces the values of its items. The parts are the variable `v` of
1398
+ * the value of an item, the first statement, the step and the result. A value of the wrong kind is an error of the op.
1399
+ */
1400
+ #reduction(op: string, kind: Kind | undefined): { readonly v: string; readonly init: string; readonly step: string; readonly result: string } {
1060
1401
  const a = this.fresh("a");
1061
1402
  const n = this.fresh("n");
1062
1403
  const v = this.fresh("x");
1063
- const num = body.v.kind === "number" ? v : `${this.use("U")}(${v})`;
1064
- const bool = body.v.kind === "boolean" ? v : `${this.use("B")}(${v})`;
1065
- const F = this.use("F");
1404
+ const num = kind === "number" ? v : `${this.use("U")}(${v})`;
1405
+ const bool = kind === "boolean" ? v : `${this.use("B")}(${v})`;
1066
1406
  const inits: Readonly<Record<string, string>> = {
1067
1407
  count: `let ${n} = 0;`,
1068
1408
  sum: `let ${a} = 0;`,
@@ -1071,7 +1411,6 @@ class Printer {
1071
1411
  none: `let ${a} = false;`,
1072
1412
  all: `let ${a} = true;`,
1073
1413
  };
1074
- s.push(inits[op] ?? `let ${a}, ${n} = 0;`);
1075
1414
  const steps: Readonly<Record<string, string>> = {
1076
1415
  count: `${n}++;`,
1077
1416
  sum: `${a} += ${num};`,
@@ -1083,17 +1422,7 @@ class Printer {
1083
1422
  all: `if (!${bool}) ${a} = false;`,
1084
1423
  first: `if (${n}++ === 0) ${a} = ${v};`,
1085
1424
  };
1086
- const item = [...testCodes.flatMap((t) => [...t.s, `if (!${this.#boolean(t.v)}) continue;`]), ...body.s];
1087
- // An item whose tests and body cannot fail needs no try.
1088
- const safeItem = body.v.safe && testCodes.every((t) => this.#safeBoolean(t.v));
1089
- const loop = [
1090
- ...(skip === undefined ? [] : [`if (${j} === ${skip}) continue;`]),
1091
- ...(safeItem
1092
- ? [...item, `const ${v} = ${body.v.code};`]
1093
- : [`let ${v};`, "try {", ...ind(item), ` ${v} = ${body.v.code};`, "} catch {", strict ? ` ${F}();` : " continue;", "}"]),
1094
- steps[op] as string,
1095
- ];
1096
- s.push(`for (let ${j} = ${lo}; ${j} < ${hi}; ${j}++) {`, ...ind(loop), "}");
1425
+ const F = this.use("F");
1097
1426
  const results: Readonly<Record<string, string>> = {
1098
1427
  count: n,
1099
1428
  sum: this.#checked("number", a),
@@ -1102,12 +1431,63 @@ class Printer {
1102
1431
  all: a,
1103
1432
  none: `!${a}`,
1104
1433
  };
1105
- const code = results[op] ?? `(${n} === 0 ? ${F}() : ${a})`;
1106
- // A count without strict, and any, all and none over booleans without strict, cannot fail. The address of the axis
1107
- // can fail, except at the focus or at the origin.
1108
- const startSafe = at.every((m) => m.t === "origin");
1109
- const safe = startSafe && !strict && (op === "count" || (BOOLEAN_LIST_OPS.has(op) && body.v.kind === "boolean"));
1110
- return { s, v: { code, kind: listKind(op, body.v.kind), safe, deps } };
1434
+ return { v, init: inits[op] ?? `let ${a}, ${n} = 0;`, step: steps[op] as string, result: results[op] ?? `(${n} === 0 ? ${F}() : ${a})` };
1435
+ }
1436
+
1437
+ /**
1438
+ * This method prints a list as an array (LIST.VALUE): a pair of the key and the value of each item. A test that
1439
+ * fails, a body that fails and an error item of the axis list give the error sentinel as the value.
1440
+ */
1441
+ #eachList(e: ExprOf<"each">, ctx: Ctx): Code {
1442
+ const at = e.at ?? [];
1443
+ const { s, j, head, key, check, skip, start, startSafe, tests, inner } = this.#targetLoop(e.axis, at, ctx);
1444
+ const testCodes = tests.map((t) => this.#hoist(this.expr(t, inner), hasLoop(t)));
1445
+ const body = this.#hoist(this.expr(e.body, inner), hasLoop(e.body));
1446
+ const deps = new Set([...start, ...[body, ...testCodes].flatMap((x) => [...x.v.deps])].filter((d) => d !== inner.level));
1447
+ const list = this.fresh("L");
1448
+ const v = this.fresh("x");
1449
+ const item = [...check, ...testCodes.flatMap((t) => [...t.s, `if (!${this.#boolean(t.v)}) continue;`]), ...body.s];
1450
+ const safeItem = check.length === 0 && body.v.safe && testCodes.every((t) => this.#safeBoolean(t.v));
1451
+ const loop = [
1452
+ ...key,
1453
+ ...(skip === undefined ? [] : [`if (${j} === ${skip}) continue;`]),
1454
+ ...(safeItem ? [...item, `${list}.push([${j}, ${body.v.code}]);`] : [`let ${v};`, "try {", ...ind(item), ` ${v} = ${body.v.code};`, "} catch {", ` ${v} = E;`, "}", `${list}.push([${j}, ${v}]);`]),
1455
+ ];
1456
+ return { s: [...s, `const ${list} = [];`, head, ...ind(loop), "}"], v: { code: list, kind: undefined, safe: startSafe, deps, list: { item: body.v.kind } } };
1457
+ }
1458
+
1459
+ /**
1460
+ * This method prints sortBy and take (LIST.SORT, LIST.TAKE): a new array from the array of a list. An error item is
1461
+ * not in the new list, and with strict it is the error of the op.
1462
+ */
1463
+ #order(op: "sortBy" | "take", head: Expr, rest: readonly Expr[], ctx: Ctx): Code {
1464
+ const list = this.#listOf(head, ctx);
1465
+ // A missing count is the literal null, which is not a whole number, so take gives its error.
1466
+ const exprs = [head, ...(op === "take" ? [rest[0] ?? lit(null)] : [])];
1467
+ const strict = this.#strict(op, rest.slice(exprs.length - 1));
1468
+ const raw = [list, ...exprs.slice(1).map((x) => this.expr(x, ctx))];
1469
+ const deps = depsOf(...raw);
1470
+ const parts = this.#settle(raw, deps, exprs);
1471
+ const item = (list.v.list as ListInfo).item;
1472
+ return { s: stmtsOf(...parts), v: { code: `${this.use(op === "sortBy" ? "SB" : "TK")}(${[...parts.map((x) => x.v.code), String(strict)].join(", ")})`, kind: undefined, safe: false, deps, list: { item } } };
1473
+ }
1474
+
1475
+ /** This method prints a list op over a list that is not an each: a loop over its array, and nth (LIST.NTH). */
1476
+ #overList(op: string, head: Expr, rest: readonly Expr[], ctx: Ctx): Code {
1477
+ const list = this.#listOf(head, ctx);
1478
+ // A missing position is the literal null, which is not a whole number, so nth gives its error.
1479
+ const exprs = [head, ...(op === "nth" ? [rest[0] ?? lit(null)] : [])];
1480
+ const strict = this.#strict(op, rest.slice(exprs.length - 1));
1481
+ const raw = [list, ...exprs.slice(1).map((x) => this.expr(x, ctx))];
1482
+ const deps = depsOf(...raw);
1483
+ const parts = this.#settle(raw, deps, exprs);
1484
+ const [l] = parts as [Code];
1485
+ const item = (list.v.list as ListInfo).item;
1486
+ if (op === "nth") return { s: stmtsOf(...parts), v: { code: `${this.use("NT")}(${[...parts.map((x) => x.v.code), String(strict)].join(", ")})`, kind: item, safe: false, deps } };
1487
+ const r = this.#reduction(op, item);
1488
+ const { v } = r;
1489
+ const s = [...l.s, r.init, `for (const [, ${v}] of ${l.v.code}) {`, ` if (${v} === E) ${strict ? `${this.use("F")}();` : "continue;"}`, ` ${r.step}`, "}"];
1490
+ return { s, v: { code: r.result, kind: listKind(op, item), safe: false, deps } };
1111
1491
  }
1112
1492
 
1113
1493
  /**
@@ -1186,14 +1566,15 @@ class Printer {
1186
1566
  const step = this.#loopStep(e.step, { ...t.inner, env: names.env }, names.vars);
1187
1567
  const result = this.expr(e.result, { ...ctx, env: names.env });
1188
1568
  const body = [
1569
+ ...t.key,
1189
1570
  ...(t.skip === undefined ? [] : [`if (${t.j} === ${t.skip}) continue;`]),
1571
+ ...t.check,
1190
1572
  ...tests.flatMap((c) => [...c.s, `if (!${this.#boolean(c.v)}) continue;`]),
1191
1573
  ...step.s,
1192
1574
  ];
1193
1575
  const inside = [...tests.flatMap((c) => [...c.v.deps]), ...step.deps].filter((d) => d !== loop && d !== t.inner.level);
1194
1576
  const deps = new Set([...names.deps, ...t.start, ...inside, ...[...result.v.deps].filter((d) => d !== loop)]);
1195
- const head = `for (let ${t.j} = ${t.lo}; ${t.j} < ${t.hi}; ${t.j}++) {`;
1196
- return { s: [...names.s, ...t.s, head, ...ind(body), "}", ...result.s], v: { code: result.v.code, kind: result.v.kind, safe: false, deps } };
1577
+ return { s: [...names.s, ...t.s, t.head, ...ind(body), "}", ...result.s], v: { code: result.v.code, kind: result.v.kind, safe: false, deps } };
1197
1578
  }
1198
1579
 
1199
1580
  /**
@@ -1214,7 +1595,7 @@ class Printer {
1214
1595
  );
1215
1596
  const outer = this.#inside;
1216
1597
  this.#inside = e;
1217
- const bodyCtx: Ctx = { origin: undefined, focus: undefined, level: 1, env: new Map(), keys: names };
1598
+ const bodyCtx: Ctx = { origin: undefined, focus: undefined, level: 1, originLevel: 1, env: new Map(), fns: new Map(), keys: names };
1218
1599
  if (varying.length === 0) {
1219
1600
  const body = this.#hoist(this.expr(e, bodyCtx));
1220
1601
  this.#inside = outer;
@@ -1237,6 +1618,7 @@ class Printer {
1237
1618
  // The loop of the node gives statements.
1238
1619
  const body = this.expr(e, bodyCtx);
1239
1620
  this.#kinds.set(fn, body.v.kind);
1621
+ this.#lists.set(fn, body.v.list);
1240
1622
  this.run.push(`const ${fn} = ${this.use(params.length === 1 ? "M1" : "M")}((${params.join(", ")}) => {`, ...ind(body.s), ` return ${body.v.code};`, "});");
1241
1623
  }
1242
1624
  }
@@ -1251,7 +1633,7 @@ class Printer {
1251
1633
  s.push(...this.#store(t, c));
1252
1634
  return t;
1253
1635
  });
1254
- return { s, v: { code: `${fn}(${args.join(", ")})`, kind: this.#kinds.get(fn), safe: false, deps: depsOf(...values) } };
1636
+ return { s, v: { code: `${fn}(${args.join(", ")})`, kind: this.#kinds.get(fn), safe: false, deps: depsOf(...values), list: this.#lists.get(fn) } };
1255
1637
  }
1256
1638
 
1257
1639
  /**
@@ -1338,7 +1720,7 @@ class Printer {
1338
1720
 
1339
1721
  /** This method gives the code of the program at the key of the run. A constant of the run evaluates once. */
1340
1722
  root(expr: Expr): Code {
1341
- const c = this.#hoist(this.expr(expr, { origin: "o", focus: "o", level: 1, env: new Map(), keys: new Map() }));
1723
+ const c = this.#hoist(this.expr(expr, { origin: "o", focus: "o", level: 1, originLevel: 1, env: new Map(), fns: new Map(), keys: new Map() }));
1342
1724
  // A function of an op with an inline form at each of its sites needs no declaration.
1343
1725
  for (const [name, form] of this.#forms) if (form !== undefined && !this.#called.has(name)) this.top.delete(name);
1344
1726
  return c;
@@ -1354,7 +1736,10 @@ class Printer {
1354
1736
  return canonical(e, (x) => {
1355
1737
  const key = ctx.keys.get(x as Expr);
1356
1738
  if (key !== undefined) return { "@": key.code };
1357
- return (x as Expr | undefined)?.tag === "var" ? { $: ctx.env.get((x as ExprOf<"var">).name)?.code ?? (x as ExprOf<"var">).name } : undefined;
1739
+ const node = x as Expr | undefined;
1740
+ if (node?.tag === "var") return { $: ctx.env.get(node.name)?.code ?? node.name };
1741
+ // A call gives the number of the binding of its function, so two functions with one name give two keys.
1742
+ return node?.tag === "call" ? { "()": node.fn, of: ctx.fns.get(node.fn)?.id ?? null, args: node.args } : undefined;
1358
1743
  });
1359
1744
  }
1360
1745
  }