@mark1russell7/vex-compiler 0.17.2 → 0.19.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/README.md +35 -3
- package/build/facts-3ZtCfd0v.d.ts +37 -0
- package/build/facts-3ZtCfd0v.d.ts.map +1 -0
- package/build/index.d.ts +163 -97
- package/build/index.d.ts.map +1 -1
- package/build/index.js +1168 -4234
- package/build/index.js.map +1 -1
- package/build/memo-J-Km2qc0.js +577 -0
- package/build/memo-J-Km2qc0.js.map +1 -0
- package/build/module-entry.d.ts +105 -0
- package/build/module-entry.d.ts.map +1 -0
- package/build/module-entry.js +7005 -0
- package/build/module-entry.js.map +1 -0
- package/package.json +17 -6
- package/src/facts.ts +52 -41
- package/src/fn-text.ts +58 -0
- package/src/index.ts +2 -3
- package/src/js.ts +59 -33
- package/src/loop.ts +98 -10
- package/src/lower.ts +610 -128
- package/src/memo.ts +215 -94
- package/src/module-entry.ts +7 -0
- package/src/module-tidy.ts +502 -0
- package/src/module.ts +3166 -714
- package/src/runtime.ts +326 -36
- package/src/scope-key.ts +283 -0
- package/src/sheet-order.ts +13 -99
- package/src/tiers.ts +27 -12
- package/src/unshared.ts +125 -0
package/src/scope-key.ts
ADDED
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The key of an expression at a place of a module. Two expressions at their places have one key only if they have one
|
|
3
|
+
* value. A key holds what each read of the expression means at that place. A read of a name that the expression binds
|
|
4
|
+
* keeps its spelling, because the structure of the key holds its binder. Another read gives a token of its meaning.
|
|
5
|
+
* The root and `./module` of this package do not export this file.
|
|
6
|
+
*
|
|
7
|
+
* A table walks each expression once and keeps its form. A form holds the number of its structure with a hole at each
|
|
8
|
+
* read. It also holds the list of its reads in the order of the structure. So a key at a new place reads the list, and it
|
|
9
|
+
* does not walk the expression again. The lists have shared parts, so the forms of a chain use memory linear in the chain. The
|
|
10
|
+
* cost of a key at each place is linear in the reads and the binders of the expression. A key has a small text.
|
|
11
|
+
*
|
|
12
|
+
* A form depends on the nodes of the memo around it, so a table keeps the forms for each content of `keys`. The table has
|
|
13
|
+
* no copy of the other maps of a scope, because each key reads them as they stand. The table seals a map of `keys` at its
|
|
14
|
+
* first read. So a change of that map after a read is a refusal, and it does not give a wrong key.
|
|
15
|
+
*/
|
|
16
|
+
import type { Expr, ExprOf } from "@mark1russell7/vex";
|
|
17
|
+
|
|
18
|
+
/** The error of a construct that a standalone module does not have. */
|
|
19
|
+
export class NotStandalone extends Error {}
|
|
20
|
+
|
|
21
|
+
/** A variable of the code of a module. */
|
|
22
|
+
interface Variable {
|
|
23
|
+
readonly code: string;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** The place of an expression: what each name that the expression does not bind means there. */
|
|
27
|
+
export interface KeyScope {
|
|
28
|
+
/** The nodes of the memo around the place, with the variable of each. */
|
|
29
|
+
readonly keys: ReadonlyMap<Expr, Variable>;
|
|
30
|
+
/** The names around the place. A name that is not in this map is a variable of the run. */
|
|
31
|
+
readonly env: ReadonlyMap<string, Variable>;
|
|
32
|
+
/** The functions around the place, with the number of the binding of each. */
|
|
33
|
+
readonly fns: ReadonlyMap<string, { readonly id: number }>;
|
|
34
|
+
/** The columns of the `fix` forms around the place. */
|
|
35
|
+
readonly columns: ReadonlyMap<string, Variable>;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** A hole of a form: a read of a name, of a round or of a function. */
|
|
39
|
+
interface Read {
|
|
40
|
+
readonly hole: "var" | "last" | "call";
|
|
41
|
+
readonly name: string;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** The reads of a part of a form, with the names of a kind that a form binds around that part. */
|
|
45
|
+
interface Bound {
|
|
46
|
+
readonly kind: "names" | "rounds";
|
|
47
|
+
readonly names: readonly string[];
|
|
48
|
+
readonly parts: readonly Reads[];
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** The reads of an expression, in the order of its structure. A form above an expression shares this object. */
|
|
52
|
+
type Reads = Read | Bound;
|
|
53
|
+
|
|
54
|
+
/** The form of an expression: the key data of its structure, and its reads, if it has reads. */
|
|
55
|
+
interface Form {
|
|
56
|
+
readonly data: unknown;
|
|
57
|
+
readonly reads: Reads | undefined;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** The forms of one content of `keys`. */
|
|
61
|
+
interface Forms {
|
|
62
|
+
readonly table: KeyTable;
|
|
63
|
+
readonly keys: ReadonlyMap<Expr, Variable>;
|
|
64
|
+
readonly known: Map<Expr, Form>;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** A place in the walk of an expression: the forms, and the reads of the form that the walk makes. */
|
|
68
|
+
interface At {
|
|
69
|
+
readonly forms: Forms;
|
|
70
|
+
readonly reads: Reads[];
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** This function refuses a change of a map that a table read. */
|
|
74
|
+
function sealed(): never {
|
|
75
|
+
throw new NotStandalone("a map of the memo changed after a read of its keys");
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** The properties that seal a map. Each method that changes a map refuses. */
|
|
79
|
+
const SEAL: PropertyDescriptorMap = { set: { value: sealed, configurable: true }, delete: { value: sealed, configurable: true }, clear: { value: sealed, configurable: true } };
|
|
80
|
+
|
|
81
|
+
/** This class holds the number of each structure and the forms of each content of `keys`, for the keys of one printer. */
|
|
82
|
+
export class KeyTable {
|
|
83
|
+
readonly #numbers = new Map<string, number>();
|
|
84
|
+
readonly #nodes = new WeakMap<Expr, number>();
|
|
85
|
+
readonly #maps = new WeakMap<object, Forms>();
|
|
86
|
+
readonly #forms = new Map<string, Forms>();
|
|
87
|
+
|
|
88
|
+
/** This method gives the number of a structure. Two structures have one number only if they have one text. */
|
|
89
|
+
numberOf(text: string): number {
|
|
90
|
+
const known = this.#numbers.get(text);
|
|
91
|
+
if (known !== undefined) return known;
|
|
92
|
+
const fresh = this.#numbers.size;
|
|
93
|
+
this.#numbers.set(text, fresh);
|
|
94
|
+
return fresh;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** This method gives the number of a node of the program, the same object. */
|
|
98
|
+
#nodeId(e: Expr): number {
|
|
99
|
+
const known = this.#nodes.get(e);
|
|
100
|
+
if (known !== undefined) return known;
|
|
101
|
+
const fresh = this.numberOf(`node ${String(this.#numbers.size)}`);
|
|
102
|
+
this.#nodes.set(e, fresh);
|
|
103
|
+
return fresh;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** This method gives the forms of a map of `keys`, and seals the map. Two maps with one content have one record of forms. */
|
|
107
|
+
formsOf(keys: ReadonlyMap<Expr, Variable>): Forms {
|
|
108
|
+
const held = this.#maps.get(keys);
|
|
109
|
+
if (held !== undefined) return held;
|
|
110
|
+
const text = JSON.stringify([...keys].map(([e, value]) => [this.#nodeId(e), value.code]));
|
|
111
|
+
const forms = this.#forms.get(text) ?? { table: this, keys, known: new Map() };
|
|
112
|
+
this.#forms.set(text, forms);
|
|
113
|
+
this.#maps.set(keys, forms);
|
|
114
|
+
Object.defineProperties(keys, SEAL);
|
|
115
|
+
return forms;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** The text of -0 in a key. JSON gives 0 for -0, and -0 is not 0. */
|
|
120
|
+
const NEGATIVE_ZERO = { "-0": 0 };
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* This function gives a text that is the same for two expressions with the same structure. -0 is not 0. A part with a
|
|
124
|
+
* 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
|
|
125
|
+
* not, so a token is not the text of a literal.
|
|
126
|
+
*/
|
|
127
|
+
export function canonical(e: Expr, token: (x: unknown) => object | undefined): string {
|
|
128
|
+
return JSON.stringify(e, (_name, x: unknown) => token(x) ?? (Object.is(x, -0) ? NEGATIVE_ZERO : x));
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** The token function of a text with no tokens. */
|
|
132
|
+
const NO_TOKEN = (): undefined => undefined;
|
|
133
|
+
|
|
134
|
+
/** This function gives the text of a literal or of an extension. Only those parts hold data of the program, and a walk of that data finds each -0. */
|
|
135
|
+
function leafText(e: ExprOf<"lit"> | ExprOf<"ext">): string {
|
|
136
|
+
// Stryker disable next-line ConditionalExpression: a walk gives the same text as the plain form, so this test only saves the walk.
|
|
137
|
+
if (e.tag === "lit" && typeof e.value !== "object" && !Object.is(e.value, -0)) return JSON.stringify(e);
|
|
138
|
+
return canonical(e, NO_TOKEN);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** This function gives the result of a part that sees more names of a kind, and keeps the reads of that part with those names. */
|
|
142
|
+
function within<T>(at: At, kind: Bound["kind"], names: readonly string[], part: (inner: At) => T): T {
|
|
143
|
+
const inner: At = { forms: at.forms, reads: [] };
|
|
144
|
+
const result = part(inner);
|
|
145
|
+
if (inner.reads.length > 0) at.reads.push({ kind, names, parts: inner.reads });
|
|
146
|
+
return result;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** This function gives the key data of an object that is not an expression, for example an axis or a record of names. */
|
|
150
|
+
function record(x: object, at: At): unknown {
|
|
151
|
+
// A copy keeps each own property, also a property with the name `__proto__`.
|
|
152
|
+
const out: Record<string, unknown> = { ...x };
|
|
153
|
+
for (const name of Object.keys(out)) out[name] = data(out[name], at);
|
|
154
|
+
return out;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** This function gives the key data of a part of an expression. An array or a record keeps its form, and an expression gets its key data. */
|
|
158
|
+
function data(x: unknown, at: At): unknown {
|
|
159
|
+
if (Array.isArray(x)) return x.map((part) => data(part, at));
|
|
160
|
+
if (typeof x !== "object" || x === null) return Object.is(x, -0) ? NEGATIVE_ZERO : x;
|
|
161
|
+
return typeof (x as { tag?: unknown }).tag === "string" ? node(x as Expr, at) : record(x, at);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** This function gives the key data of a hole, and adds the read to the reads of the form. */
|
|
165
|
+
function hole(kind: Read["hole"], name: string, at: At): unknown {
|
|
166
|
+
at.reads.push({ hole: kind, name });
|
|
167
|
+
return { "?": kind };
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** This function gives the key data of a loop over names: each part sees the names that its form gives it (LOOP.NAMES). */
|
|
171
|
+
function loop(e: ExprOf<"fold"> | ExprOf<"iterate">, at: At): unknown {
|
|
172
|
+
const outer = e.tag === "fold" ? { axis: data(e.axis, at), at: data(e.at, at) } : { limit: data(e.limit, at) };
|
|
173
|
+
const init = record(e.init, at);
|
|
174
|
+
const items = e.tag === "fold" ? (e.as ?? []) : [];
|
|
175
|
+
const inner = within(at, "names", Object.keys(e.init), (x) => ({
|
|
176
|
+
...(e.tag === "iterate" ? { until: data(e.until, x) } : {}),
|
|
177
|
+
step: within(x, "names", items, (y) => record(e.step, y)),
|
|
178
|
+
result: node(e.result, x),
|
|
179
|
+
}));
|
|
180
|
+
return { ...e, ...outer, init, ...inner };
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* This function gives the key data of the parts of an expression. The scope of each form is the scope of the interpreter.
|
|
185
|
+
* Each number of an expression goes through `data`, so the plain text of this result keeps each -0.
|
|
186
|
+
*/
|
|
187
|
+
function parts(e: Exclude<Expr, ExprOf<"lit"> | ExprOf<"ext">>, at: At): unknown {
|
|
188
|
+
switch (e.tag) {
|
|
189
|
+
case "var":
|
|
190
|
+
case "last":
|
|
191
|
+
return hole(e.tag, e.name, at);
|
|
192
|
+
case "call":
|
|
193
|
+
return { ...e, fn: hole("call", e.fn, at), args: data(e.args, at) };
|
|
194
|
+
case "fn":
|
|
195
|
+
return { ...e, body: within(at, "names", e.params, (x) => node(e.body, x)) };
|
|
196
|
+
case "let":
|
|
197
|
+
// Each binding sees the outer names, so a binding does not see the other bindings (FN.BIND).
|
|
198
|
+
return { ...e, bind: record(e.bind, at), body: within(at, "names", Object.keys(e.bind), (x) => node(e.body, x)) };
|
|
199
|
+
case "each":
|
|
200
|
+
return { ...e, axis: data(e.axis, at), at: data(e.at, at), body: within(at, "names", e.as ?? [], (x) => node(e.body, x)) };
|
|
201
|
+
case "fold":
|
|
202
|
+
case "iterate":
|
|
203
|
+
return loop(e, at);
|
|
204
|
+
case "fix":
|
|
205
|
+
return { ...e, init: node(e.init, at), step: within(at, "rounds", [e.name], (x) => node(e.step, x)) };
|
|
206
|
+
case "ref":
|
|
207
|
+
case "app":
|
|
208
|
+
case "rec":
|
|
209
|
+
return record(e, at);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** This function gives the form of an expression from its walk. */
|
|
214
|
+
function formOf(e: Expr, forms: Forms): Form {
|
|
215
|
+
const own: At = { forms, reads: [] };
|
|
216
|
+
const structure = { "#": forms.table.numberOf(e.tag === "lit" || e.tag === "ext" ? leafText(e) : JSON.stringify(parts(e, own))) };
|
|
217
|
+
const [first, ...more] = own.reads;
|
|
218
|
+
return { data: structure, reads: more.length === 0 ? first : { kind: "names", names: [], parts: own.reads } };
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** This function gives the key data of an expression: the number of its form, or the token of a node of the memo. */
|
|
222
|
+
function node(e: Expr, at: At): unknown {
|
|
223
|
+
const key = at.forms.keys.get(e);
|
|
224
|
+
if (key !== undefined) return { "@": key.code };
|
|
225
|
+
let form = at.forms.known.get(e);
|
|
226
|
+
if (form === undefined) {
|
|
227
|
+
form = formOf(e, at.forms);
|
|
228
|
+
at.forms.known.set(e, form);
|
|
229
|
+
}
|
|
230
|
+
if (form.reads !== undefined) at.reads.push(form.reads);
|
|
231
|
+
return form.data;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** The names of each kind that a walk of the reads binds at this time. */
|
|
235
|
+
interface Binders {
|
|
236
|
+
readonly names: Set<string>;
|
|
237
|
+
readonly rounds: Set<string>;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/** This function gives the meaning of a read. A name of the run and a name of the code are two tokens, so one text in both does not give one key. */
|
|
241
|
+
function meaning(x: Read, scope: KeyScope, bound: Binders): unknown {
|
|
242
|
+
switch (x.hole) {
|
|
243
|
+
case "var": {
|
|
244
|
+
if (bound.names.has(x.name)) return { "=": x.name };
|
|
245
|
+
const name = scope.env.get(x.name);
|
|
246
|
+
return name === undefined ? { $$: x.name } : { $: name.code };
|
|
247
|
+
}
|
|
248
|
+
case "last":
|
|
249
|
+
return bound.rounds.has(x.name) ? { "=": x.name } : { "^": scope.columns.get(x.name)?.code };
|
|
250
|
+
case "call":
|
|
251
|
+
// A call of a function around the place gives the number of its binding, so two functions with one name give two keys.
|
|
252
|
+
return bound.names.has(x.name) ? { "=": x.name } : { "()": x.name, of: scope.fns.get(x.name)?.id };
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/** This function adds the meaning of each read to a list, in the order of the structure. */
|
|
257
|
+
function meanings(reads: readonly Reads[], scope: KeyScope, bound: Binders, out: unknown[]): void {
|
|
258
|
+
for (const x of reads) {
|
|
259
|
+
if ("hole" in x) {
|
|
260
|
+
out.push(meaning(x, scope, bound));
|
|
261
|
+
continue;
|
|
262
|
+
}
|
|
263
|
+
const set = bound[x.kind];
|
|
264
|
+
const fresh = x.names.filter((name) => !set.has(name));
|
|
265
|
+
for (const name of fresh) set.add(name);
|
|
266
|
+
meanings(x.parts, scope, bound, out);
|
|
267
|
+
for (const name of fresh) set.delete(name);
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/**
|
|
272
|
+
* This function gives the key of an expression at a place. Two keys of one table are equal only if the two expressions at
|
|
273
|
+
* their places have one value. Two expressions with one value can have two keys, for example with two spellings of a
|
|
274
|
+
* name that they bind.
|
|
275
|
+
*/
|
|
276
|
+
export function keyText(e: Expr, scope: KeyScope, table: KeyTable): string {
|
|
277
|
+
const at: At = { forms: table.formsOf(scope.keys), reads: [] };
|
|
278
|
+
const structure = node(e, at);
|
|
279
|
+
if (at.reads.length === 0) return JSON.stringify(structure);
|
|
280
|
+
const reads: unknown[] = [];
|
|
281
|
+
meanings(at.reads, scope, { names: new Set(), rounds: new Set() }, reads);
|
|
282
|
+
return JSON.stringify({ "#": table.numberOf(JSON.stringify([structure, reads])) });
|
|
283
|
+
}
|
package/src/sheet-order.ts
CHANGED
|
@@ -1,105 +1,15 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* The static order of the cells of a sheet in a module (COMPILE.MODULE.SHEET). It is the order of `SheetRun.fill` in
|
|
3
|
-
* `packages/core/src/sheet.ts` (SHEET.FILL)
|
|
3
|
+
* `packages/core/src/sheet.ts` (SHEET.FILL), and it uses `readsOf` and `isCellRef` of that file. The keys of a column
|
|
4
4
|
* follow its reads from itself. The order changes only the speed, not a result (SHEET.ORDER).
|
|
5
5
|
*/
|
|
6
|
-
import { addrExprs, CELL_KIND, children,
|
|
6
|
+
import { addrExprs, CELL_KIND, children, isCellRef, listOf, readsOf, shapeError, splitLimit, type Axis, type Direction, type Expr } from "@mark1russell7/vex";
|
|
7
7
|
|
|
8
|
-
/**
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
/** This function tells if the data of an extension is a cell reference: a column, and an address of fixed moves. */
|
|
12
|
-
export const isCellRef = (u: unknown): u is CellRef =>
|
|
13
|
-
typeof u === "object" &&
|
|
14
|
-
u !== null &&
|
|
15
|
-
typeof (u as { column?: unknown }).column === "string" &&
|
|
16
|
-
Array.isArray((u as { at?: unknown }).at) &&
|
|
17
|
-
(u as { at: readonly unknown[] }).at.every((m) => isMove(m) && moveExpr(m) === undefined);
|
|
18
|
-
|
|
19
|
-
/** This function adds the direction of one move or one axis of a read of a column from itself. */
|
|
20
|
-
function addDirection(d: Set<Direction>, m: Move | Axis): void {
|
|
21
|
-
// The reverse order reads the same keys as its axis.
|
|
22
|
-
if (m.t === "reverse") {
|
|
23
|
-
addDirection(d, m.axis);
|
|
24
|
-
return;
|
|
25
|
-
}
|
|
26
|
-
if (m.t === "offset" || m.t === "window") {
|
|
27
|
-
// An offset moves by its first step that is not 0. A window reads the keys from `from` to `to`.
|
|
28
|
-
const steps = m.t === "offset" ? [m.d.find((x) => x !== 0) ?? 0] : [m.from, m.to];
|
|
29
|
-
// A step of 0 reads the cell itself, which is a cycle in each order.
|
|
30
|
-
// Stryker disable next-line EqualityOperator: see the comment above
|
|
31
|
-
if (steps.some((x) => x < 0)) d.add("before");
|
|
32
|
-
// Stryker disable next-line EqualityOperator: see the comment above
|
|
33
|
-
if (steps.some((x) => x > 0)) d.add("after");
|
|
34
|
-
} else if (m.t === "children" || m.t === "descendants") d.add("down");
|
|
35
|
-
// The items of a list can be at each key, so the axis list gives no direction, and the other reads decide the order.
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
/** This function gives the base axis of an axis, and the tests of its `where` axes. */
|
|
39
|
-
function partsOf(axis: Axis): { readonly base: Axis; readonly tests: readonly Expr[] } {
|
|
8
|
+
/** This function gives the tests of the `where` axes of an axis. */
|
|
9
|
+
function testsOf(axis: Axis): readonly Expr[] {
|
|
40
10
|
const tests: Expr[] = [];
|
|
41
|
-
let
|
|
42
|
-
|
|
43
|
-
tests.push(base.test);
|
|
44
|
-
base = base.axis;
|
|
45
|
-
}
|
|
46
|
-
return { base, tests };
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
/**
|
|
50
|
-
* This function gives the columns that the formulas of the column `self` read with a cell reference: its formula and
|
|
51
|
-
* the formulas of its cells. It also gives the directions of their reads of the column itself. A read in the body or
|
|
52
|
-
* in a test of an axis also has the direction of that axis.
|
|
53
|
-
*/
|
|
54
|
-
export function readsOf(columns: ReadonlyMap<string, Expr>, cells: CellFormulas, self: string): { readonly columns: ReadonlySet<string>; readonly directions: ReadonlySet<Direction> } {
|
|
55
|
-
const read = new Set<string>();
|
|
56
|
-
const directions = new Set<Direction>();
|
|
57
|
-
const formula = columns.get(self);
|
|
58
|
-
// An expression that is not valid reads no column. A module gives the reason for it.
|
|
59
|
-
const todo: [Expr, Axis | undefined][] = [...(formula === undefined ? [] : [formula]), ...(cells.get(self)?.values() ?? [])].filter((e) => shapeError(e) === undefined).map((e) => [e, undefined]);
|
|
60
|
-
for (let item = todo.pop(); item !== undefined; item = todo.pop()) {
|
|
61
|
-
const [e, axis] = item;
|
|
62
|
-
if (e.tag === "each" || e.tag === "fold") {
|
|
63
|
-
const { base, tests } = partsOf(e.axis);
|
|
64
|
-
for (const x of [...(e.tag === "each" ? [e.body] : Object.values(e.step)), ...tests]) todo.push([x, base]);
|
|
65
|
-
// The values of init, the result of a fold, the list of the axis list and the expressions of the address evaluate
|
|
66
|
-
// at the node, so they keep the outer direction.
|
|
67
|
-
const list = listOf(e.axis);
|
|
68
|
-
for (const x of [...(e.tag === "fold" ? [...Object.values(e.init), e.result] : []), ...addrExprs(e.at), ...(list === undefined ? [] : [list])]) todo.push([x, axis]);
|
|
69
|
-
} else if (e.tag !== "ext") {
|
|
70
|
-
for (const child of children(e)) todo.push([child, axis]);
|
|
71
|
-
// The data of an extension of another kind can look like a cell reference. It only changes the order of a fill.
|
|
72
|
-
// Stryker disable next-line ConditionalExpression,LogicalOperator: see the comment above
|
|
73
|
-
} else if (e.kind === CELL_KIND && isCellRef(e.data)) {
|
|
74
|
-
read.add(e.data.column);
|
|
75
|
-
// The directions of the reads of another column only change the order, because that column comes first.
|
|
76
|
-
// Stryker disable next-line ConditionalExpression: see the comment above
|
|
77
|
-
if (e.data.column === self) for (const m of [...(axis === undefined ? [] : [axis]), ...e.data.at]) addDirection(directions, m);
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
return { columns: read, directions };
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
/**
|
|
84
|
-
* This function gives the columns of a sheet in an order where each column comes after the columns that it reads. The
|
|
85
|
-
* columns of a cycle keep their order. The columns with formulas of cells only come last.
|
|
86
|
-
*/
|
|
87
|
-
export function columnOrder(columns: ReadonlyMap<string, Expr>, cells: CellFormulas): readonly string[] {
|
|
88
|
-
const names = new Set([...columns.keys(), ...cells.keys()]);
|
|
89
|
-
let left = [...names].map((c) => ({ c, needs: [...readsOf(columns, cells, c).columns].filter((x) => x !== c && names.has(x)) }));
|
|
90
|
-
const order: string[] = [];
|
|
91
|
-
const placed = new Set<string>();
|
|
92
|
-
// Each pass places each column whose reads are placed. A pass that places no column leaves a cycle, so it places
|
|
93
|
-
// the first column that is left.
|
|
94
|
-
while (left.length > 0) {
|
|
95
|
-
const ready = left.filter((x) => x.needs.every((n) => placed.has(n)));
|
|
96
|
-
for (const x of ready.length > 0 ? ready : left.slice(0, 1)) {
|
|
97
|
-
order.push(x.c);
|
|
98
|
-
placed.add(x.c);
|
|
99
|
-
}
|
|
100
|
-
left = left.filter((x) => !placed.has(x.c));
|
|
101
|
-
}
|
|
102
|
-
return order;
|
|
11
|
+
for (let x = axis; x.t === "where"; x = x.axis) tests.push(x.test);
|
|
12
|
+
return tests;
|
|
103
13
|
}
|
|
104
14
|
|
|
105
15
|
/**
|
|
@@ -158,13 +68,17 @@ export function readsFinished(columns: ReadonlyMap<string, Expr>, order: readonl
|
|
|
158
68
|
const todo: [Expr, ReadPlace][] = [[formula, "key"]];
|
|
159
69
|
for (let item = todo.pop(); item !== undefined; item = todo.pop()) {
|
|
160
70
|
const [e, place] = item;
|
|
161
|
-
|
|
71
|
+
// A test of the axis of a data limit reads at each target, as the test of an `each` does.
|
|
72
|
+
const split = e.tag === "iterate" ? splitLimit(e) : undefined;
|
|
73
|
+
if (split !== undefined) for (const x of split) todo.push([x, place]);
|
|
74
|
+
else if (e.tag === "each" || e.tag === "fold") {
|
|
162
75
|
const inner: ReadPlace = place === "key" && (e.at === undefined || e.at.length === 0) && baseOf(e.axis).t === "children" ? "children" : "unknown";
|
|
163
|
-
const
|
|
164
|
-
for (const x of [...(e.tag === "each" ? [e.body] : Object.values(e.step)), ...tests]) todo.push([x, inner]);
|
|
76
|
+
for (const x of [...(e.tag === "each" ? [e.body] : Object.values(e.step)), ...testsOf(e.axis)]) todo.push([x, inner]);
|
|
165
77
|
const list = listOf(e.axis);
|
|
166
78
|
for (const x of [...(e.tag === "fold" ? [...Object.values(e.init), e.result] : []), ...addrExprs(e.at), ...(list === undefined ? [] : [list])]) todo.push([x, place]);
|
|
167
79
|
} else if (e.tag === "fn") todo.push([e.body, "unknown"]);
|
|
80
|
+
// The parts of a column evaluate at each row, so a read in them has no place (FIX.ROUNDS).
|
|
81
|
+
else if (e.tag === "fix") todo.push([e.init, "unknown"], [e.step, "unknown"]);
|
|
168
82
|
else if (e.tag !== "ext") for (const child of children(e)) todo.push([child, place]);
|
|
169
83
|
else if (e.kind === CELL_KIND && isCellRef(e.data)) {
|
|
170
84
|
const { column, at } = e.data;
|
package/src/tiers.ts
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* The tiers (docs/COMPILER.md §2.1). Tier 2 is generated JavaScript
|
|
3
|
-
* gives each result that tier 2 cannot give. Thus a tiered program gives
|
|
2
|
+
* The tiers (docs/COMPILER.md §2.1). Tier 2 is generated JavaScript, and it gives its values and its error results. Tier
|
|
3
|
+
* 1 is the closure compiler of the core, and it gives each result that tier 2 cannot give. Thus a tiered program gives
|
|
4
|
+
* the results of the interpreter.
|
|
4
5
|
*/
|
|
5
|
-
import { compile, fromDocument, isDocument, ok, type CompileOptions, type Envelope, type Expr, type Program, type Space } from "@mark1russell7/vex";
|
|
6
|
+
import { compile, fail, fromDocument, isDocument, monotoneError, ok, sizeError, stepError, type CompileOptions, type Envelope, type Expr, type Program, type Space, type VexError } from "@mark1russell7/vex";
|
|
6
7
|
import { factsOf, type Schema } from "./facts.ts";
|
|
7
8
|
|
|
8
9
|
/** The options of the compiler: the options of `compile`, and the schema of the host (docs/COMPILER.md §3.2). */
|
|
@@ -20,9 +21,12 @@ export type Generated =
|
|
|
20
21
|
| { readonly ok: true; readonly program: LoopProgram; readonly source: string; readonly options: GenerateOptions }
|
|
21
22
|
| { readonly ok: false; readonly reason: string };
|
|
22
23
|
|
|
23
|
-
/** A function of tier 2. It gives the value of the program, or `FALLBACK
|
|
24
|
+
/** A function of tier 2. It gives the value of the program, or `FALLBACK` for each other result. */
|
|
24
25
|
export type Tier2 = (space: Space, origin: string, vars: Readonly<Record<string, unknown>> | undefined, tables: Readonly<Record<string, Space>> | undefined) => unknown;
|
|
25
26
|
|
|
27
|
+
/** This function gives the reason that tier 1 refuses a program with a good shape, or `undefined`. */
|
|
28
|
+
const refusal = (e: Expr, options: GenerateOptions): string | undefined => sizeError(e, options) ?? stepError(e, options) ?? monotoneError(e, options);
|
|
29
|
+
|
|
26
30
|
/**
|
|
27
31
|
* This function lowers an expression or a document and prints its source for the options (DOC.ENTRY). The op tables of
|
|
28
32
|
* the domains give the fast path of each op site. It is pure, so a build can use it.
|
|
@@ -34,6 +38,9 @@ export function generate(source: Expr | Envelope, options: GenerateOptions = {})
|
|
|
34
38
|
try {
|
|
35
39
|
const facts = factsOf(options);
|
|
36
40
|
const program = lower(read.value, facts, options.schema);
|
|
41
|
+
// LOOP.SIZE, STEP.MAX: tier 2 refuses the programs that tier 1 refuses. The lowering checks the shape and the nesting first.
|
|
42
|
+
const size = refusal(read.value, options);
|
|
43
|
+
if (size !== undefined) return { ok: false, reason: size };
|
|
37
44
|
return { ok: true, program, source: printJs(program, facts), options };
|
|
38
45
|
} catch (thrown) {
|
|
39
46
|
// A stack overflow in the lowering of a deep expression also goes to tier 1.
|
|
@@ -46,16 +53,22 @@ export function generate(source: Expr | Envelope, options: GenerateOptions = {})
|
|
|
46
53
|
* that does not permit `new Function`.
|
|
47
54
|
*/
|
|
48
55
|
export function load(generated: Extract<Generated, { readonly ok: true }>): Tier2 {
|
|
56
|
+
return link(generated).run;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** This function loads a program, with the function that gives the error of a run that gave `FALLBACK`. */
|
|
60
|
+
function link(generated: Extract<Generated, { readonly ok: true }>): { readonly run: Tier2; readonly take: () => VexError | undefined } {
|
|
61
|
+
const runtime = createRuntime(generated.options);
|
|
49
62
|
// oxlint-disable-next-line typescript/no-implied-eval -- the source comes from printJs, and it reads each name and literal from K (§5).
|
|
50
63
|
const make = new Function("K", "R", generated.source) as (k: readonly unknown[], r: ReturnType<typeof createRuntime>) => Tier2;
|
|
51
|
-
return make(generated.program.constants,
|
|
64
|
+
return { run: make(generated.program.constants, runtime), take: () => runtime.take() };
|
|
52
65
|
}
|
|
53
66
|
|
|
54
67
|
/** The counts of the runs of a tiered program. */
|
|
55
68
|
export interface TierStats {
|
|
56
69
|
/** The number of runs. */
|
|
57
70
|
readonly runs: number;
|
|
58
|
-
/** The number of runs where tier 2 gave
|
|
71
|
+
/** The number of runs where tier 2 gave no result, so tier 1 gave it. A run that tier 2 ends with an error is no fallback. */
|
|
59
72
|
readonly fallbacks: number;
|
|
60
73
|
}
|
|
61
74
|
|
|
@@ -69,20 +82,20 @@ export interface TieredProgram extends Program {
|
|
|
69
82
|
}
|
|
70
83
|
|
|
71
84
|
/**
|
|
72
|
-
* This function compiles an expression or a document into tier 2 if it can, and else into tier 1 (DOC.ENTRY).
|
|
73
|
-
*
|
|
74
|
-
* tier 2 makes no trace.
|
|
85
|
+
* This function compiles an expression or a document into tier 2 if it can, and else into tier 1 (DOC.ENTRY). Tier 2
|
|
86
|
+
* gives a value or an error. When it gives no result, tier 1 does that evaluation again. A run with a trace and
|
|
87
|
+
* `explain` always use tier 1, because tier 2 makes no trace.
|
|
75
88
|
*/
|
|
76
89
|
export function tiered(source: Expr | Envelope, options: GenerateOptions = {}): TieredProgram {
|
|
77
90
|
const slow = compile(source, options);
|
|
78
91
|
// The program of tier 1 has the expression of a document, so tier 2 does not read the document again.
|
|
79
92
|
const { expr } = slow;
|
|
80
93
|
const generated = generate(expr, options);
|
|
81
|
-
let fast:
|
|
94
|
+
let fast: ReturnType<typeof link> | undefined;
|
|
82
95
|
let reason: string | undefined;
|
|
83
96
|
if (generated.ok) {
|
|
84
97
|
try {
|
|
85
|
-
fast =
|
|
98
|
+
fast = link(generated);
|
|
86
99
|
} catch {
|
|
87
100
|
reason = "the page does not permit new Function";
|
|
88
101
|
}
|
|
@@ -98,8 +111,10 @@ export function tiered(source: Expr | Envelope, options: GenerateOptions = {}):
|
|
|
98
111
|
run(r) {
|
|
99
112
|
stats.runs++;
|
|
100
113
|
if (fast === undefined || r.trace !== undefined) return slow.run(r);
|
|
101
|
-
const value = fast(r.space, r.origin, r.vars, r.tables);
|
|
114
|
+
const value = fast.run(r.space, r.origin, r.vars, r.tables);
|
|
102
115
|
if (value !== FALLBACK) return ok(value);
|
|
116
|
+
const error = fast.take();
|
|
117
|
+
if (error !== undefined) return fail(error);
|
|
103
118
|
stats.fallbacks++;
|
|
104
119
|
return slow.run(r);
|
|
105
120
|
},
|
package/src/unshared.ts
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A program can use one object at two places, and a name can have two meanings at those places. The printer and the
|
|
3
|
+
* lowering hold facts of a place by the object of its node. Thus this file first gives each place an object of its own.
|
|
4
|
+
* A program from JSON is a tree, so it stays the same objects. The root and `./module` of this package do not export this file.
|
|
5
|
+
*/
|
|
6
|
+
import { children, type Expr, MAX_NESTING, nestingOf } from "@mark1russell7/vex";
|
|
7
|
+
|
|
8
|
+
/** The original of each copy that `unsharedAll` made. */
|
|
9
|
+
const ORIGINALS = new WeakMap<Expr, Expr>();
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* The most places that a program can have for a compile (COMPILE.PLACES). A place is a node at one position of the tree
|
|
13
|
+
* of the program, so a shared object counts once for each place. The compile takes time at each place.
|
|
14
|
+
*
|
|
15
|
+
* The rule: the largest program of each doubling shape under this limit stays under 1,024 MB, half of a heap of 2,048 MB.
|
|
16
|
+
* At 4 times the places, at least one shape goes over that line. The workflow `places-gate.yml` holds this rule.
|
|
17
|
+
*
|
|
18
|
+
* The worst of 5 fresh processes in tier 2 at the limit is 560 MB (plain), 566 MB (constant) and 489 MB (loop).
|
|
19
|
+
* At 4 times the places it is 1,661 MB, 1,699 MB and 1,469 MB. The limit is 15 times the largest module of `ireko`.
|
|
20
|
+
* `docs/COMPILER.md` has the measures.
|
|
21
|
+
*/
|
|
22
|
+
export const MAX_PLACES: number = 1 << 15;
|
|
23
|
+
|
|
24
|
+
/** This function gives the parts of a node. A node that is not valid has no parts here, and the check of the shape gives its reason. */
|
|
25
|
+
function partsOf(x: Expr): readonly Expr[] {
|
|
26
|
+
try {
|
|
27
|
+
return children(x).filter((part) => typeof part === "object" && (part as unknown) !== null);
|
|
28
|
+
} catch {
|
|
29
|
+
return [];
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** This function gives the count of the objects of the expressions when each object has one place. Otherwise it gives `undefined`. */
|
|
34
|
+
function treeSize(exprs: readonly Expr[]): number | undefined {
|
|
35
|
+
const seen = new Set<Expr>();
|
|
36
|
+
const todo = [...exprs];
|
|
37
|
+
for (let x = todo.pop(); x !== undefined; x = todo.pop()) {
|
|
38
|
+
if (seen.has(x)) return undefined;
|
|
39
|
+
seen.add(x);
|
|
40
|
+
todo.push(...partsOf(x));
|
|
41
|
+
}
|
|
42
|
+
return seen.size;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* This function gives the number of places of expressions with a shared object, with a walk that visits each object once.
|
|
47
|
+
* So it takes the time of the objects, not of the places. An object that holds itself has no end, and its count is infinite.
|
|
48
|
+
*/
|
|
49
|
+
function sharedPlaces(exprs: readonly Expr[]): number {
|
|
50
|
+
const counts = new Map<Expr, number>();
|
|
51
|
+
const open = new Map<Expr, readonly Expr[]>();
|
|
52
|
+
const todo = [...exprs];
|
|
53
|
+
for (let x = todo.at(-1); x !== undefined; x = todo.at(-1)) {
|
|
54
|
+
const parts = open.get(x);
|
|
55
|
+
if (counts.has(x)) {
|
|
56
|
+
todo.pop();
|
|
57
|
+
} else if (parts !== undefined) {
|
|
58
|
+
todo.pop();
|
|
59
|
+
counts.set(x, parts.reduce((sum, part) => sum + (counts.get(part) ?? Infinity), 1));
|
|
60
|
+
} else {
|
|
61
|
+
const own = partsOf(x);
|
|
62
|
+
open.set(x, own);
|
|
63
|
+
todo.push(...own.filter((part) => !counts.has(part)));
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
return exprs.reduce((sum, e) => sum + (counts.get(e) as number), 0);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** This function gives the number of places of the expressions. */
|
|
70
|
+
export const placesOf = (exprs: readonly Expr[]): number => treeSize(exprs) ?? sharedPlaces(exprs);
|
|
71
|
+
|
|
72
|
+
/** The result of one walk of a program: the reason that a compile refuses it (COMPILE.PLACES), and if two places hold one object. */
|
|
73
|
+
export interface PlacesRead {
|
|
74
|
+
readonly error: string | undefined;
|
|
75
|
+
readonly shares: boolean;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** This function gives the result of one walk of the expressions. So a program with no shared object needs no second walk. */
|
|
79
|
+
export function placesRead(exprs: readonly Expr[]): PlacesRead {
|
|
80
|
+
const size = treeSize(exprs);
|
|
81
|
+
const places = size ?? sharedPlaces(exprs);
|
|
82
|
+
return {
|
|
83
|
+
error: places > MAX_PLACES ? `COMPILE.PLACES: the program has ${String(places)} places, and the limit is ${String(MAX_PLACES)}` : undefined,
|
|
84
|
+
shares: size === undefined,
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** This function gives the reason that a compile refuses the expressions, or `undefined` (COMPILE.PLACES). */
|
|
89
|
+
export const placesError = (exprs: readonly Expr[]): string | undefined => placesRead(exprs).error;
|
|
90
|
+
|
|
91
|
+
/** This function gives a copy of a part of an expression, with a new object for each place. A value of a literal and the data of an extension are not nodes, so they stay. */
|
|
92
|
+
function copied(x: unknown): unknown {
|
|
93
|
+
if (Array.isArray(x)) return x.map(copied);
|
|
94
|
+
if (typeof x !== "object" || x === null) return x;
|
|
95
|
+
// A copy keeps each own property, also a property with the name `__proto__`.
|
|
96
|
+
const out: Record<string, unknown> = { ...x };
|
|
97
|
+
const tag = out["tag"];
|
|
98
|
+
if (tag === "lit" || tag === "ext") return noted(out, x);
|
|
99
|
+
for (const name of Object.keys(out)) {
|
|
100
|
+
const part = out[name];
|
|
101
|
+
if (typeof part === "object") out[name] = copied(part);
|
|
102
|
+
}
|
|
103
|
+
return typeof tag === "string" ? noted(out, x) : out;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** This function notes the original of a copy of a node, and gives the copy. */
|
|
107
|
+
function noted(copy: unknown, original: unknown): unknown {
|
|
108
|
+
ORIGINALS.set(copy as Expr, original as Expr);
|
|
109
|
+
return copy;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* This function gives the expressions with one object at each place. Expressions without a shared object stay the same
|
|
114
|
+
* objects. So does an expression that is nested too deep: the printer and the lowering refuse it. A caller with the
|
|
115
|
+
* result of `placesRead` gives its `shares`, and this function makes no walk.
|
|
116
|
+
*/
|
|
117
|
+
export function unsharedAll(exprs: readonly Expr[], shares: boolean = treeSize(exprs) === undefined): readonly Expr[] {
|
|
118
|
+
return !shares || exprs.some((e) => nestingOf(e) > MAX_NESTING) ? exprs : (exprs.map(copied) as readonly Expr[]);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** This function gives the expression with one object at each place, as `unsharedAll` does. */
|
|
122
|
+
export const unshared = (e: Expr, shares?: boolean): Expr => unsharedAll([e], shares)[0] as Expr;
|
|
123
|
+
|
|
124
|
+
/** This function gives the original of a copy, and an expression that is not a copy gives itself. */
|
|
125
|
+
export const originalOf = (e: Expr): Expr => ORIGINALS.get(e) ?? e;
|