@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/src/memo.ts ADDED
@@ -0,0 +1,223 @@
1
+ /**
2
+ * 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
3
+ * few values that the node reads from outside: its keys. A program keeps the value of such a node for each space and
4
+ * each value of its keys. Thus a run at each key of a space evaluates the node once for each value of its keys.
5
+ *
6
+ * - `AVERAGE(all.Score)` has no keys, so it evaluates once for each space.
7
+ * - "The largest width in the column of the origin" has one key, the column of the origin. It evaluates once for each
8
+ * column, not once for each origin.
9
+ *
10
+ * A key reads the origin or a name from outside the node, and nothing that the node changes. Inside the node, the
11
+ * value of the key replaces the key. Thus the value of the node depends only on the space and the values of the keys.
12
+ */
13
+ import { addrExprs, isListOp, type Addr, type Axis, type Expr } from "@mark1russell7/vex";
14
+
15
+ /** A read of the focus of the expression, outside its own loops. */
16
+ const FOCUS = 1;
17
+ /** A move to the origin. */
18
+ const ORIGIN = 2;
19
+ /** A name that the node does not bind: a variable of the run, or a binding outside the node. */
20
+ const FREE = 4;
21
+ /** A name that the node binds, outside the expression. */
22
+ const INTERNAL = 8;
23
+ /** An extension or an axis table. An extension can read each part of the evaluation, and a table is another space. */
24
+ const OPAQUE = 16;
25
+ /** 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. */
26
+ const DEEP = 32;
27
+
28
+ /** This function gives the axis inside the `where` axes of an axis, and the tests of the `where` axes. */
29
+ function parts(a: Axis): { readonly base: Exclude<Axis, { readonly t: "where" }>; readonly tests: readonly Expr[] } {
30
+ // Stryker disable next-line ArrayDeclaration: a test that is not an expression reads nothing, and it has no keys
31
+ const tests: Expr[] = [];
32
+ let x: Axis = a;
33
+ while (x.t === "where") {
34
+ tests.push(x.test);
35
+ x = x.axis;
36
+ }
37
+ return { base: x, tests };
38
+ }
39
+
40
+ /** This function adds `DEEP` to a read of the origin or of a free name inside a loop. */
41
+ const inLoop = (r: number, top: boolean): number => (top || (r & (ORIGIN | FREE)) === 0 ? r : r | DEEP);
42
+
43
+ /**
44
+ * This function gives the reads of an address: the focus at the top of the expression, or the origin, or nothing. A
45
+ * move from the focus or the origin can fail, so the address reads its start also before a fixed key (V-052).
46
+ */
47
+ function addressReads(at: Addr | undefined, top: boolean): number {
48
+ let start = top ? FOCUS : 0;
49
+ let found = 0;
50
+ at?.forEach((m) => {
51
+ if (m.t === "key" || m.t === "index") start = 0;
52
+ else if (m.t === "origin") start = ORIGIN;
53
+ else found |= start;
54
+ });
55
+ return inLoop(found | start, top);
56
+ }
57
+
58
+ /**
59
+ * This function gives the reads of `e`. `outer` has the names that the node binds outside `e`, and `inner` has the
60
+ * names that `e` binds above this part. `top` is true outside the loops of `e`.
61
+ */
62
+ function reads(e: Expr, outer: ReadonlySet<string>, inner: ReadonlySet<string>, top: boolean): number {
63
+ switch (e.tag) {
64
+ // A missing case gives undefined, and a bitwise operation counts it as 0.
65
+ // Stryker disable next-line StringLiteral: see the comment above
66
+ case "lit":
67
+ return 0;
68
+ case "var":
69
+ return inner.has(e.name) ? 0 : outer.has(e.name) ? INTERNAL : inLoop(FREE, top);
70
+ case "ext":
71
+ // A loop of names is not in the memo yet, so a node with one is not either.
72
+ case "fold":
73
+ case "iterate":
74
+ return OPAQUE;
75
+ case "ref":
76
+ // The expressions of computed moves evaluate at the position of the node (NAV.COMPUTED).
77
+ return addrExprs(e.at).reduce((r, x) => r | reads(x, outer, inner, top), addressReads(e.at, top));
78
+ case "app":
79
+ return e.args.reduce((r, x) => r | reads(x, outer, inner, top), 0);
80
+ case "rec":
81
+ return Object.values(e.fields).reduce((r, x) => r | reads(x, outer, inner, top), 0);
82
+ case "let": {
83
+ const binds = Object.values(e.bind).reduce((r, x) => r | reads(x, outer, inner, top), 0);
84
+ return binds | reads(e.body, outer, new Set([...inner, ...Object.keys(e.bind)]), top);
85
+ }
86
+ case "each": {
87
+ const { base, tests } = parts(e.axis);
88
+ // The targets of `all` do not depend on the focus, but its address can fail (V-051). Each other axis starts at its
89
+ // address.
90
+ const targets = base.t === "table" ? OPAQUE : base.t === "all" && (e.at ?? []).length === 0 ? 0 : addressReads(e.at, top);
91
+ const at = addrExprs(e.at).reduce((r, x) => r | reads(x, outer, inner, top), targets);
92
+ return [e.body, ...tests].reduce((r, x) => r | reads(x, outer, inner, false), at);
93
+ }
94
+ }
95
+ }
96
+
97
+ /** This function joins the keys of the parts of an expression. A part that cannot be in the memo makes the expression the same. */
98
+ function all(xs: readonly (readonly Expr[] | undefined)[]): readonly Expr[] | undefined {
99
+ // Stryker disable next-line ArrayDeclaration: after the check, each part has its keys, so no one reads the default list
100
+ return xs.every((x) => x !== undefined) ? xs.flatMap((x) => x ?? []) : undefined;
101
+ }
102
+
103
+ /**
104
+ * This function gives the keys of the part `e` of a node, or `undefined` if the part cannot be in the memo. `top` is
105
+ * true outside the loops of the node, and `outer` has the names that the node binds above `e`. The node itself (`root`)
106
+ * is not a key of itself.
107
+ */
108
+ function keysOf(e: Expr, top: boolean, outer: ReadonlySet<string>, pure: Set<Expr>, root = false): readonly Expr[] | undefined {
109
+ const r = reads(e, outer, new Set(), true);
110
+ // In a loop of the node, the focus is a target of the node, and the node can read it. A part that depends only on
111
+ // the space has a memo of its own, if it has a loop.
112
+ if ((r & (ORIGIN | FREE | OPAQUE | (top ? FOCUS : 0))) === 0) {
113
+ if (!root) pure.add(e);
114
+ return [];
115
+ }
116
+ // A key evaluates once, outside the loops of the node. A loop that reads the origin is a part of the node, not a key.
117
+ if (!root && (r & (FOCUS | INTERNAL | OPAQUE | DEEP)) === 0) return [e];
118
+ switch (e.tag) {
119
+ case "app":
120
+ return all(e.args.map((x) => keysOf(x, top, outer, pure)));
121
+ case "rec":
122
+ return all(Object.values(e.fields).map((x) => keysOf(x, top, outer, pure)));
123
+ case "let": {
124
+ const inner = new Set([...outer, ...Object.keys(e.bind)]);
125
+ return all([...Object.values(e.bind).map((x) => keysOf(x, top, outer, pure)), keysOf(e.body, top, inner, pure)]);
126
+ }
127
+ case "each": {
128
+ const { base, tests } = parts(e.axis);
129
+ // The targets of a loop must not depend on the origin: a set of targets is not a value of a key. The address of
130
+ // `all` can fail, so it must not depend on the origin either.
131
+ if (base.t === "table" || ((base.t !== "all" || (e.at ?? []).length > 0) && addressReads(e.at, top) !== 0)) return undefined;
132
+ // The expressions of computed moves give the targets too, so they must read nothing.
133
+ if (addrExprs(e.at).some((x) => reads(x, outer, new Set(), top) !== 0)) return undefined;
134
+ return all([e.body, ...tests].map((x) => keysOf(x, false, outer, pure)));
135
+ }
136
+ // A leaf here reads the focus or a name of the node, so it is not a key, and the part cannot be in the memo. A
137
+ // missing case gives undefined too.
138
+ // Stryker disable StringLiteral,ConditionalExpression: see the comment above
139
+ case "lit":
140
+ case "ref":
141
+ case "var":
142
+ case "ext":
143
+ case "fold":
144
+ case "iterate":
145
+ return undefined;
146
+ // Stryker restore StringLiteral,ConditionalExpression
147
+ }
148
+ }
149
+
150
+ /** This function tells if an expression has a loop outside its keys and outside the parts that have a memo of their own. */
151
+ function loopOutside(e: Expr, keys: ReadonlySet<Expr>): boolean {
152
+ if (keys.has(e)) return false;
153
+ switch (e.tag) {
154
+ case "each":
155
+ case "fold":
156
+ case "iterate":
157
+ return true;
158
+ case "app":
159
+ return e.args.some((x) => loopOutside(x, keys));
160
+ case "rec":
161
+ return Object.values(e.fields).some((x) => loopOutside(x, keys));
162
+ case "let":
163
+ return [...Object.values(e.bind), e.body].some((x) => loopOutside(x, keys));
164
+ case "ref":
165
+ return addrExprs(e.at).some((x) => loopOutside(x, keys));
166
+ // A missing case gives undefined, which is false too.
167
+ // Stryker disable StringLiteral,ConditionalExpression: see the comment above
168
+ case "lit":
169
+ case "var":
170
+ case "ext":
171
+ return false;
172
+ // Stryker restore StringLiteral,ConditionalExpression
173
+ }
174
+ }
175
+
176
+ /** This function gives the `let` expressions above an `each`, and the `each`, or `undefined` for another expression. */
177
+ function eachUnderLets(e: Expr | undefined): { readonly lets: readonly Extract<Expr, { readonly tag: "let" }>[]; readonly each: Extract<Expr, { readonly tag: "each" }> } | undefined {
178
+ const lets: Extract<Expr, { readonly tag: "let" }>[] = [];
179
+ let x = e;
180
+ while (x?.tag === "let") {
181
+ lets.push(x);
182
+ x = x.body;
183
+ }
184
+ return x?.tag === "each" ? { lets, each: x } : undefined;
185
+ }
186
+
187
+ /**
188
+ * This function gives the nodes of `expr` that a program keeps in its memo, each with its keys. Each such node has a
189
+ * loop outside its keys. A node inside such a node can be in the memo too. Thus the first evaluation of the outer
190
+ * node evaluates the inner node once.
191
+ */
192
+ export function memoNodes(expr: Expr): ReadonlyMap<Expr, readonly Expr[]> {
193
+ const out = new Map<Expr, readonly Expr[]>();
194
+ const visit = (e: Expr): void => {
195
+ const pure = new Set<Expr>();
196
+ const keys = keysOf(e, true, new Set(), pure, true);
197
+ if (keys !== undefined && loopOutside(e, new Set([...keys, ...pure]))) out.set(e, keys);
198
+ if (e.tag === "app") {
199
+ // A list op over an `each` under `let` expressions is one loop, so that `each` and those `let` expressions have
200
+ // no value of their own. Their parts can be in the memo.
201
+ const [first, ...rest] = e.args;
202
+ const fused = isListOp(e.op) ? eachUnderLets(first) : undefined;
203
+ if (fused === undefined) {
204
+ if (first !== undefined) visit(first);
205
+ } else {
206
+ for (const l of fused.lets) Object.values(l.bind).forEach(visit);
207
+ [fused.each.body, ...parts(fused.each.axis).tests, ...addrExprs(fused.each.at)].forEach(visit);
208
+ }
209
+ rest.forEach(visit);
210
+ } else if (e.tag === "rec") {
211
+ Object.values(e.fields).forEach(visit);
212
+ } else if (e.tag === "let") {
213
+ Object.values(e.bind).forEach(visit);
214
+ visit(e.body);
215
+ } else if (e.tag === "each") {
216
+ [e.body, ...parts(e.axis).tests, ...addrExprs(e.at)].forEach(visit);
217
+ } else if (e.tag === "ref") {
218
+ addrExprs(e.at).forEach(visit);
219
+ }
220
+ };
221
+ visit(expr);
222
+ return out;
223
+ }