@mark1russell7/vex-compiler 0.8.0 → 0.9.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/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package",
3
3
  "name": "@mark1russell7/vex-compiler",
4
- "version": "0.8.0",
4
+ "version": "0.9.0",
5
5
  "description": "The Vex compiler: generated JavaScript for Vex programs, at run time and at build time, with the results of the interpreter.",
6
6
  "keywords": [
7
7
  "vex",
@@ -43,15 +43,15 @@
43
43
  },
44
44
  "devDependencies": {
45
45
  "@mark1russell7/cue": "github:mark1russell7/cue",
46
- "@mark1russell7/vex-domains": "0.8.0",
47
- "@mark1russell7/vex-testkit": "0.8.0",
46
+ "@mark1russell7/vex-domains": "0.9.0",
47
+ "@mark1russell7/vex-testkit": "0.9.0",
48
48
  "@types/node": "^26.6.4",
49
49
  "fast-check": "^4.10.2",
50
50
  "typescript": "^7.0.2",
51
51
  "vitest": "^5.0.3"
52
52
  },
53
53
  "dependencies": {
54
- "@mark1russell7/vex": "0.8.0"
54
+ "@mark1russell7/vex": "0.9.0"
55
55
  },
56
56
  "scripts": {
57
57
  "build": "tsdown",
package/src/module.ts CHANGED
@@ -132,6 +132,25 @@ interface BoundFn {
132
132
  local: boolean;
133
133
  }
134
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
+
135
154
  /**
136
155
  * A printed function. The levels of the value of its body have a marker for the origin, for the focus and for each
137
156
  * parameter. A call replaces each marker with the levels at the call.
@@ -372,6 +391,12 @@ const COLUMN_WORK = 10;
372
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. */
373
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}++) {`);
374
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
+
375
400
  /** This function tells if an expression has a loop of names: a fold or an iteration. */
376
401
  function hasLoop(e: Expr): boolean {
377
402
  let found = LOOPS.get(e);
@@ -615,6 +640,15 @@ class Printer {
615
640
  readonly #constants = new Map<string, Code>();
616
641
  /** The columns of the run, by the structure of their expression. */
617
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>();
618
652
  /** The expressions whose code is a constant of the run. */
619
653
  readonly #constant = new WeakSet<Expr>();
620
654
  /** The expressions at a place that takes a list: a binding, the head of a list op and the list of an axis. */
@@ -703,6 +737,11 @@ class Printer {
703
737
  return `${prefix}${this.#names++}`;
704
738
  }
705
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
+
706
745
  /** This method gives the code of a name: a read that throws the error of its value, if it can hold an error. */
707
746
  #read(name: Name): Value {
708
747
  const base = { kind: name.kind, deps: name.deps, plain: true, list: name.list };
@@ -727,7 +766,8 @@ class Printer {
727
766
 
728
767
  /**
729
768
  * This method evaluates a constant of the run once, before the loop over the keys, and gives the read of its value. A
730
- * 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.
731
771
  */
732
772
  #hoist(c: Code, lazy = false): Code {
733
773
  if (c.v.deps.size > 0 || (c.v.plain === true && c.s.length === 0)) return c;
@@ -735,10 +775,13 @@ class Printer {
735
775
  const hit = key === undefined ? undefined : this.#constants.get(key);
736
776
  if (hit !== undefined) return hit;
737
777
  const name = this.fresh("c");
738
- if (lazy) this.run.push(`const ${name} = ${this.use("L")}(() => {`, ...ind(c.s), ` return ${c.v.code};`, "});");
739
- else this.run.push(...this.#store(name, c, true));
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));
740
783
  const { list } = c.v;
741
- const read = bare(this.#read(lazy ? { 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 }));
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 }));
742
785
  if (key !== undefined) this.#constants.set(key, read);
743
786
  return read;
744
787
  }
@@ -788,10 +831,30 @@ class Printer {
788
831
  */
789
832
  #columnar(e: Expr, c: Code, ctx: Ctx): boolean {
790
833
  // A node of the memo has the level 1, so a column has a focus.
791
- if (ctx.level < 2 || c.v.deps.size !== 1 || !c.v.deps.has(ctx.level) || this.#work(e) < COLUMN_WORK) return false;
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;
792
837
  // A node of the memo with keys keeps its costly part for each value of its keys already.
793
838
  if (this.#keyed(e)) return false;
794
- return [...namesOf(e)].every((name) => (ctx.env.get(name)?.deps.size ?? 0) === 0) && !this.#callsLocal(e, ctx);
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;
795
858
  }
796
859
 
797
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. */
@@ -806,10 +869,30 @@ class Printer {
806
869
  return (this.#memo.get(e)?.length ?? 0) > 0 || children(e).some((x) => this.#keyed(x));
807
870
  }
808
871
 
809
- /** This method gives the work of an expression: a node of the memo and a constant of the run are one read each. */
810
- #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 {
811
877
  if (this.#memo.has(e) || this.#constant.has(e)) return 1;
812
- 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;
813
896
  }
814
897
 
815
898
  /** This method gives the read of a column of the run. Two parts with the same structure share one column. */
@@ -818,9 +901,12 @@ class Printer {
818
901
  let name = this.#columns.get(key);
819
902
  if (name === undefined) {
820
903
  name = this.fresh("col");
821
- 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};`, "});");
822
907
  this.#columns.set(key, name);
823
908
  }
909
+ this.#columned.add(e);
824
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 });
825
911
  }
826
912
 
@@ -985,6 +1071,11 @@ class Printer {
985
1071
  const s: string[] = [];
986
1072
  let deps = new Set<number>();
987
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;
988
1079
  for (const [name, x] of Object.entries(e.bind)) {
989
1080
  // A binding sees the context of the let, so a function cannot call itself.
990
1081
  if (x.tag === "fn") {
@@ -1005,9 +1096,11 @@ class Printer {
1005
1096
  const b = this.fresh("b");
1006
1097
  s.push(...this.#store(b, c));
1007
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);
1008
1100
  // The statements of the binding read its keys, so the let is not a constant of the run.
1009
1101
  deps = new Set([...deps, ...c.v.deps]);
1010
1102
  }
1103
+ if (root !== undefined) root.root = e.body;
1011
1104
  const body = this.expr(e.body, { ...ctx, env, fns });
1012
1105
  // A function that reads names of the place of the binding comes after them, before the body.
1013
1106
  return { s: [...s, ...bound.flatMap((b) => b.decls), ...body.s], v: { ...body.v, deps: new Set([...deps, ...body.v.deps]) } };
@@ -1064,13 +1157,19 @@ class Printer {
1064
1157
  const env = new Map(bound.ctx.env);
1065
1158
  // A parameter hides a function of its name, because a read looks at the values first.
1066
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);
1067
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();
1068
1164
  const markers = new Set([origin, focus, param]);
1069
1165
  const global = [...body.v.deps].every((d) => markers.has(d));
1070
1166
  const name = this.fresh("fn");
1167
+ if (hasLoop(bound.fn.body) || this.#defers(body)) this.#deferred.add(name);
1071
1168
  const position = body.v.deps.has(origin) ? [k, o] : body.v.deps.has(focus) ? [k] : [];
1072
1169
  const head = `const ${name} = (${[...names, ...position].join(", ")}) =>`;
1073
- const decl = body.s.length === 0 ? [`${head} ${body.v.code};`] : [`${head} {`, ...ind(body.s), ` return ${body.v.code};`, "};"];
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};`, "};"];
1074
1173
  (global ? this.run : bound.decls).push(...decl);
1075
1174
  if (!global) bound.local = true;
1076
1175
  const spec: Spec = { name, kind: body.v.kind, safe: body.v.safe, deps: body.v.deps, origin, focus, param, global };