@mark1russell7/vex-compiler 0.11.0 → 0.11.2
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 +2 -0
- package/build/index.d.ts +37 -5
- package/build/index.d.ts.map +1 -1
- package/build/index.js +800 -85
- package/build/index.js.map +1 -1
- package/package.json +4 -4
- package/src/index.ts +1 -1
- package/src/js.ts +4 -2
- package/src/module.ts +655 -68
- package/src/runtime.ts +2 -7
- package/src/sheet-order.ts +123 -0
package/src/module.ts
CHANGED
|
@@ -15,21 +15,49 @@
|
|
|
15
15
|
* before the loop over the keys. A node of the memo is one function of its other keys, with a map of its values. The
|
|
16
16
|
* nodes with the same expression share the function.
|
|
17
17
|
*
|
|
18
|
-
* The printer takes a part of the language. It takes an array space of records, the fields and
|
|
19
|
-
* schema
|
|
20
|
-
*
|
|
18
|
+
* The printer takes a part of the language. It takes an array space or a tree space of records, and the fields and
|
|
19
|
+
* the variables of the schema. It takes the axes `all`, `others` and `window`. A tree space also has the move `parent` and the
|
|
20
|
+
* axes of a tree (COMPILE.MODULE.TREE). The kinds of each op site must decide its op. Another construct gives a
|
|
21
|
+
* reason, not code.
|
|
22
|
+
*
|
|
23
|
+
* `emitSheetModule` prints the formula columns of a sheet as one module (COMPILE.MODULE.SHEET). Each column is an array
|
|
24
|
+
* of results, and the run fills the arrays in the static order of `SheetRun.fill`. A read of a cell that is not finished
|
|
25
|
+
* starts the search of `SheetRun`. Thus each cell on a cycle gives the error of Vex.
|
|
21
26
|
*/
|
|
22
|
-
import { addrExprs, children, fromDocument, isDocument, isFieldName, lit, moveExpr, shapeError, type AnyDomain, type Axis, type Envelope, type Expr, type ExprOf, type Move, type Names, type PrimitiveKind } from "@mark1russell7/vex";
|
|
27
|
+
import { addrExprs, CELL_KIND, children, fromDocument, isDocument, isFieldName, lit, moveExpr, nestingOf, rec, shapeError, type AnyDomain, type Axis, type CellFormulas, type Envelope, type Expr, type ExprOf, type Move, type Names, type PrimitiveKind } from "@mark1russell7/vex";
|
|
23
28
|
import { factsOf, kindOfDomain, primitiveOf, type Facts, type Kind, type Schema } from "./facts.ts";
|
|
24
29
|
import { memoNodes } from "./memo.ts";
|
|
30
|
+
import { columnOrder, isCellRef, keyOrderOf, readsOf } from "./sheet-order.ts";
|
|
25
31
|
|
|
26
32
|
/** The options of a standalone module. */
|
|
27
33
|
export interface ModuleOptions {
|
|
28
34
|
readonly domains?: readonly AnyDomain[];
|
|
29
35
|
/** The kinds of the fields of the records and of the variables. A module reads only the names of its schema. */
|
|
30
36
|
readonly schema: Schema;
|
|
31
|
-
/**
|
|
37
|
+
/**
|
|
38
|
+
* The name of the function that the module exports. The default is `run`. A reserved word, a name that the module
|
|
39
|
+
* declares and a global that a module reads (`MODULE_GLOBALS`) are not names of the run (V-060).
|
|
40
|
+
*/
|
|
32
41
|
readonly name?: string;
|
|
42
|
+
/**
|
|
43
|
+
* The space of the records. In both spaces, the key of a record is the text of its position. The default `array`
|
|
44
|
+
* has no parents. A `tree` takes the parents as the third argument of the run (COMPILE.MODULE.TREE). Each entry
|
|
45
|
+
* is the position of the parent of its record, or -1 for a root.
|
|
46
|
+
*/
|
|
47
|
+
readonly space?: "array" | "tree";
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** The options of a module of a sheet (COMPILE.MODULE.SHEET): the options of a module, and the parts of a sheet. */
|
|
51
|
+
export interface SheetModuleOptions extends ModuleOptions {
|
|
52
|
+
/** The cells with their own formula (SHEET.CELL.FORMULA). The formula of a cell replaces the formula of its column at its key. */
|
|
53
|
+
readonly cells?: CellFormulas;
|
|
54
|
+
/**
|
|
55
|
+
* The kind of the values of each column. The printer prints each column after the columns that it reads. A column
|
|
56
|
+
* that a formula reads before its own formula prints needs its kind here, for example a column that reads itself.
|
|
57
|
+
*/
|
|
58
|
+
readonly kinds?: Readonly<Record<string, Kind>>;
|
|
59
|
+
/** The budget of the stack of the search of a run, in estimated frames, as in `SheetRun`. The default is 3000. */
|
|
60
|
+
readonly budget?: number;
|
|
33
61
|
}
|
|
34
62
|
|
|
35
63
|
/** The source of a standalone module, or the reason that the program cannot be one. */
|
|
@@ -89,6 +117,26 @@ interface Arg {
|
|
|
89
117
|
/** The levels of a constant of the run. */
|
|
90
118
|
const NO_DEPS: ReadonlySet<number> = new Set();
|
|
91
119
|
|
|
120
|
+
/**
|
|
121
|
+
* The level of a read of a cell (COMPILE.MODULE.SHEET). The results of the cells change in a run. Thus a value that reads
|
|
122
|
+
* a cell is not a constant or a column of the run. The level is far from the other levels.
|
|
123
|
+
*/
|
|
124
|
+
const CELLS = -1;
|
|
125
|
+
|
|
126
|
+
/** The name of the function of a run of a sheet that reads a cell: its column and its position. */
|
|
127
|
+
const READ_CELL = "RC";
|
|
128
|
+
|
|
129
|
+
/** This pattern finds a read of a cell in the code of a value: the read, or a printed function that can read a cell. */
|
|
130
|
+
const READS_IN_CODE = /\b(RC|fn\d+)\(/;
|
|
131
|
+
|
|
132
|
+
/** The columns of a sheet for the printer (COMPILE.MODULE.SHEET). */
|
|
133
|
+
interface SheetInfo {
|
|
134
|
+
/** The position of each column in the arrays of the run. */
|
|
135
|
+
readonly columns: ReadonlyMap<string, number>;
|
|
136
|
+
/** The kind of each column that the printer knows: a kind of the options, or the kind of a printed formula. */
|
|
137
|
+
readonly kinds: Map<string, Kind | undefined>;
|
|
138
|
+
}
|
|
139
|
+
|
|
92
140
|
/** This function gives the levels of some codes together. */
|
|
93
141
|
const depsOf = (...xs: readonly Code[]): ReadonlySet<number> => new Set(xs.flatMap((x) => [...x.v.deps]));
|
|
94
142
|
|
|
@@ -168,7 +216,13 @@ interface Spec {
|
|
|
168
216
|
}
|
|
169
217
|
|
|
170
218
|
/** The name of a helper of the generated code. */
|
|
171
|
-
type Helper = "F" | "C" | "T" | "L" | "Q" | "G" | "B" | "U" | "X" | "I" | "K" | "M" | "M1" | "S" | "V" | "SB" | "TK" | "NT";
|
|
219
|
+
type Helper = "F" | "C" | "T" | "L" | "Q" | "G" | "B" | "U" | "X" | "I" | "K" | "M" | "M1" | "S" | "V" | "SB" | "TK" | "NT" | TreeHelper | SheetHelper;
|
|
220
|
+
|
|
221
|
+
/** The helpers of a tree space (COMPILE.MODULE.TREE). */
|
|
222
|
+
type TreeHelper = "PT" | "CH" | "SG" | "PR" | "UP" | "SO" | "AN" | "BF";
|
|
223
|
+
|
|
224
|
+
/** The helpers of a sheet (COMPILE.MODULE.SHEET): the state of a run of a sheet, and the order of the keys of a tree. */
|
|
225
|
+
type SheetHelper = "SH" | "KO";
|
|
172
226
|
|
|
173
227
|
/** The helpers of the generated code. A module has only the helpers that it uses. */
|
|
174
228
|
const HELPERS: Readonly<Record<Exclude<Helper, "S">, string>> = {
|
|
@@ -201,6 +255,195 @@ const HELPERS: Readonly<Record<Exclude<Helper, "S">, string>> = {
|
|
|
201
255
|
].join("\n"),
|
|
202
256
|
TK: "function TK(l, n, s) { const o = V(l, s); return Number.isSafeInteger(n) && n >= 0 ? o.slice(0, n) : F(); }",
|
|
203
257
|
NT: "function NT(l, i, s) { const o = V(l, s); return Number.isSafeInteger(i) && i >= 0 && i < o.length ? o[i][1] : F(); }",
|
|
258
|
+
// The parents of a tree space: the position of the parent of each record, or -1 for a root. A walk up from each record
|
|
259
|
+
// marks its keys, so a walk that meets a key of the same walk finds a cycle. Each key is in one walk, so the check is linear.
|
|
260
|
+
PT: [
|
|
261
|
+
"function PT(p, n) {",
|
|
262
|
+
' if (!Array.isArray(p) || p.length !== n) C("the parents are not an array with one parent for each record");',
|
|
263
|
+
" const P = new Int32Array(n), s = new Uint8Array(n);",
|
|
264
|
+
" for (let i = 0; i < n; i++) {",
|
|
265
|
+
" const x = p[i];",
|
|
266
|
+
" if (x !== -1 && !(Number.isInteger(x) && x >= 0 && x < n)) C(`the parent of the record ${i} is not -1 or the position of a record`);",
|
|
267
|
+
" P[i] = x;",
|
|
268
|
+
" }",
|
|
269
|
+
" for (let i = 0; i < n; i++) {",
|
|
270
|
+
" let k = i;",
|
|
271
|
+
" while (k >= 0 && s[k] === 0) {",
|
|
272
|
+
" s[k] = 1;",
|
|
273
|
+
" k = P[k];",
|
|
274
|
+
" }",
|
|
275
|
+
" if (k >= 0 && s[k] === 1) C(`the parents of the record ${i} make a cycle`);",
|
|
276
|
+
" for (k = i; k >= 0 && s[k] === 1; k = P[k]) s[k] = 2;",
|
|
277
|
+
" }",
|
|
278
|
+
" return P;",
|
|
279
|
+
"}",
|
|
280
|
+
].join("\n"),
|
|
281
|
+
// The children of each record and the roots, in key order.
|
|
282
|
+
CH: [
|
|
283
|
+
"function CH(P, n) {",
|
|
284
|
+
" const h = [], r = [];",
|
|
285
|
+
" for (let i = 0; i < n; i++) h.push([]);",
|
|
286
|
+
" for (let i = 0; i < n; i++) (P[i] < 0 ? r : h[P[i]]).push(i);",
|
|
287
|
+
" return [h, r];",
|
|
288
|
+
"}",
|
|
289
|
+
].join("\n"),
|
|
290
|
+
// The siblings of each record with the record itself, and its position among them. The roots are the siblings of a root.
|
|
291
|
+
SG: [
|
|
292
|
+
"function SG(P, h, r, n) {",
|
|
293
|
+
" const g = [], s = new Int32Array(n);",
|
|
294
|
+
" for (let i = 0; i < n; i++) g.push(P[i] < 0 ? r : h[P[i]]);",
|
|
295
|
+
" for (const x of [r, ...h]) for (let q = 0; q < x.length; q++) s[x[q]] = q;",
|
|
296
|
+
" return [g, s];",
|
|
297
|
+
"}",
|
|
298
|
+
].join("\n"),
|
|
299
|
+
// The keys depth first, with each parent before its children, and the position and the size of the subtree of each
|
|
300
|
+
// record. Thus the descendants of a record are the keys after it, as many as its subtree has under it.
|
|
301
|
+
PR: [
|
|
302
|
+
"function PR(h, r, n) {",
|
|
303
|
+
" const o = [], at = new Int32Array(n), z = new Int32Array(n), st = [];",
|
|
304
|
+
" for (let q = r.length - 1; q >= 0; q--) st.push(r[q]);",
|
|
305
|
+
" while (st.length > 0) {",
|
|
306
|
+
" const k = st.pop();",
|
|
307
|
+
" at[k] = o.length;",
|
|
308
|
+
" o.push(k);",
|
|
309
|
+
" for (let q = h[k].length - 1; q >= 0; q--) st.push(h[k][q]);",
|
|
310
|
+
" }",
|
|
311
|
+
" for (let q = n - 1; q >= 0; q--) {",
|
|
312
|
+
" const k = o[q];",
|
|
313
|
+
" z[k] = 1;",
|
|
314
|
+
" for (const c of h[k]) z[k] += z[c];",
|
|
315
|
+
" }",
|
|
316
|
+
" return [o, at, z];",
|
|
317
|
+
"}",
|
|
318
|
+
].join("\n"),
|
|
319
|
+
UP: "function UP(P, k) { const p = P[k]; return p < 0 ? F() : p; }",
|
|
320
|
+
SO: "function SO(g, s, k, d) { const t = g[k][s[k] + d]; return t === undefined ? F() : t; }",
|
|
321
|
+
AN: "function AN(P, k) { const o = []; for (let p = P[k]; p >= 0; p = P[p]) o.push(p); return o; }",
|
|
322
|
+
// The record and the keys under it, in the order of a breadth-first search. A tree has no cycle, so no key comes twice.
|
|
323
|
+
BF: "function BF(h, k) { const o = [k]; for (let i = 0; i < o.length; i++) for (const c of h[o[i]]) o.push(c); return o; }",
|
|
324
|
+
// The state of a run of a sheet (COMPILE.MODULE.SHEET), as in SheetRun: the result of each finished cell, the search
|
|
325
|
+
// of Tarjan with its stack, and the budget of the stack. `r` reads a cell, `f` fills a cell, and `o` gives a column.
|
|
326
|
+
// A cell without a formula has the error sentinel from the start, as the error of its read.
|
|
327
|
+
SH: [
|
|
328
|
+
"function SH(n, cols, own, budget) {",
|
|
329
|
+
" const pg = (c, k) => {",
|
|
330
|
+
" const o = own[c];",
|
|
331
|
+
" const g = o === undefined ? undefined : o[k];",
|
|
332
|
+
" return g === undefined ? cols[c] : g;",
|
|
333
|
+
" };",
|
|
334
|
+
" const D = [];",
|
|
335
|
+
" for (let c = 0; c < cols.length; c++) {",
|
|
336
|
+
" const d = new Array(n);",
|
|
337
|
+
" for (let k = 0; k < n; k++) if (pg(c, k) === undefined) d[k] = E;",
|
|
338
|
+
" D.push(d);",
|
|
339
|
+
" }",
|
|
340
|
+
" const seen = new Map(), stack = [], FILL = {};",
|
|
341
|
+
" let top = FILL, missed = false, next = 0, used = 0;",
|
|
342
|
+
" const start = (c, k) => {",
|
|
343
|
+
" const i = next++;",
|
|
344
|
+
" const v = { id: c * n + k, c, k, i, low: i, re: false, r: E, p: false, need: undefined };",
|
|
345
|
+
" seen.set(v.id, v);",
|
|
346
|
+
" stack.push(v);",
|
|
347
|
+
" return v;",
|
|
348
|
+
" };",
|
|
349
|
+
" const ev = (v, g) => {",
|
|
350
|
+
" const caller = top;",
|
|
351
|
+
" v.p = false;",
|
|
352
|
+
" v.need = undefined;",
|
|
353
|
+
" top = v;",
|
|
354
|
+
" used += g[1];",
|
|
355
|
+
" const x = g[0](v.k);",
|
|
356
|
+
" used -= g[1];",
|
|
357
|
+
" top = caller;",
|
|
358
|
+
" if (!v.p) v.r = x;",
|
|
359
|
+
" };",
|
|
360
|
+
" const end = (v, caller) => {",
|
|
361
|
+
" if (v.low === v.i) {",
|
|
362
|
+
" const ms = stack.splice(stack.lastIndexOf(v));",
|
|
363
|
+
" const cycle = ms.length > 1 || v.re;",
|
|
364
|
+
" for (const m of ms) {",
|
|
365
|
+
" seen.delete(m.id);",
|
|
366
|
+
" D[m.c][m.k] = cycle ? E : m.r;",
|
|
367
|
+
" }",
|
|
368
|
+
" } else if (caller !== undefined) caller.low = Math.min(caller.low, v.low);",
|
|
369
|
+
" };",
|
|
370
|
+
" const r = (c, k) => {",
|
|
371
|
+
" const d = D[c][k];",
|
|
372
|
+
" if (d !== undefined) return d;",
|
|
373
|
+
" const caller = top;",
|
|
374
|
+
" if (caller === FILL) {",
|
|
375
|
+
" missed = true;",
|
|
376
|
+
" return E;",
|
|
377
|
+
" }",
|
|
378
|
+
" if (caller.p) return E;",
|
|
379
|
+
" const s = seen.get(c * n + k);",
|
|
380
|
+
" if (s !== undefined) {",
|
|
381
|
+
" caller.low = Math.min(caller.low, s.i);",
|
|
382
|
+
" s.re = true;",
|
|
383
|
+
" return E;",
|
|
384
|
+
" }",
|
|
385
|
+
" const g = pg(c, k);",
|
|
386
|
+
" const v = start(c, k);",
|
|
387
|
+
" if (used + g[1] > budget) {",
|
|
388
|
+
" caller.p = true;",
|
|
389
|
+
" caller.need = v;",
|
|
390
|
+
" return E;",
|
|
391
|
+
" }",
|
|
392
|
+
" ev(v, g);",
|
|
393
|
+
" if (v.p) {",
|
|
394
|
+
" caller.p = true;",
|
|
395
|
+
" caller.need = v;",
|
|
396
|
+
" return E;",
|
|
397
|
+
" }",
|
|
398
|
+
" end(v, caller);",
|
|
399
|
+
" const x = D[c][k];",
|
|
400
|
+
" return x === undefined ? E : x;",
|
|
401
|
+
" };",
|
|
402
|
+
" const drive = (c, k) => {",
|
|
403
|
+
" const work = [start(c, k)];",
|
|
404
|
+
" for (let v = work[0]; v !== undefined; v = work[work.length - 1]) {",
|
|
405
|
+
" ev(v, pg(v.c, v.k));",
|
|
406
|
+
" if (v.p) {",
|
|
407
|
+
" for (let q = v.need; q !== undefined; q = q.need) work.push(q);",
|
|
408
|
+
" continue;",
|
|
409
|
+
" }",
|
|
410
|
+
" work.pop();",
|
|
411
|
+
" end(v, work[work.length - 1]);",
|
|
412
|
+
" }",
|
|
413
|
+
" };",
|
|
414
|
+
" const f = (c, k) => {",
|
|
415
|
+
" if (D[c][k] !== undefined) return;",
|
|
416
|
+
" missed = false;",
|
|
417
|
+
" const x = pg(c, k)[0](k);",
|
|
418
|
+
" if (missed) drive(c, k);",
|
|
419
|
+
" else D[c][k] = x;",
|
|
420
|
+
" };",
|
|
421
|
+
" const o = (c) => {",
|
|
422
|
+
" const d = D[c], out = [];",
|
|
423
|
+
" for (let k = 0; k < n; k++) out.push(d[k] === E ? VEX_ERROR : d[k]);",
|
|
424
|
+
" return out;",
|
|
425
|
+
" };",
|
|
426
|
+
" return { r, f, o };",
|
|
427
|
+
"}",
|
|
428
|
+
].join("\n"),
|
|
429
|
+
// The keys of a tree in the order of a fill (SHEET.FILL): each parent before its children, or after them with `post`.
|
|
430
|
+
// `back` reverses the order of the siblings.
|
|
431
|
+
KO: [
|
|
432
|
+
"function KO(h, r, post, back) {",
|
|
433
|
+
" const o = [], st = [];",
|
|
434
|
+
" const push = (x) => {",
|
|
435
|
+
" if (back) for (let q = 0; q < x.length; q++) st.push(x[q]);",
|
|
436
|
+
" else for (let q = x.length - 1; q >= 0; q--) st.push(x[q]);",
|
|
437
|
+
" };",
|
|
438
|
+
" push(r);",
|
|
439
|
+
" while (st.length > 0) {",
|
|
440
|
+
" const k = st.pop();",
|
|
441
|
+
" o.push(k);",
|
|
442
|
+
" push(h[k]);",
|
|
443
|
+
" }",
|
|
444
|
+
" return post ? o.reverse() : o;",
|
|
445
|
+
"}",
|
|
446
|
+
].join("\n"),
|
|
204
447
|
// 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.
|
|
205
448
|
M1: [
|
|
206
449
|
"function M1(f) {",
|
|
@@ -240,6 +483,12 @@ const HELPERS: Readonly<Record<Exclude<Helper, "S">, string>> = {
|
|
|
240
483
|
].join("\n"),
|
|
241
484
|
};
|
|
242
485
|
|
|
486
|
+
/**
|
|
487
|
+
* This list has the globals of JavaScript that the code of a module reads. This code is the helpers, the run and the
|
|
488
|
+
* copies of the ops of the test domains. A test reads the text of the modules of the golden files and checks this list (V-060).
|
|
489
|
+
*/
|
|
490
|
+
export const MODULE_GLOBALS: ReadonlySet<string> = new Set("Array Error Int32Array Map Math Number Object Uint8Array undefined".split(" "));
|
|
491
|
+
|
|
243
492
|
/** A part of the helper S that only some nodes need (helperS). */
|
|
244
493
|
type Feature = "group" | "prefix" | "strict" | "ok" | "pre";
|
|
245
494
|
|
|
@@ -363,8 +612,44 @@ const NEEDS: Readonly<Record<Helper, readonly Helper[]>> = {
|
|
|
363
612
|
// Stryker disable next-line ArrayDeclaration: see the comment above
|
|
364
613
|
V: ["F"],
|
|
365
614
|
SB: ["V", "F"], TK: ["V", "F"], NT: ["V", "F"],
|
|
615
|
+
// Each module has C, and each move uses F (#move), so these needs only complete the list.
|
|
616
|
+
// Stryker disable next-line ArrayDeclaration: see the comment above
|
|
617
|
+
PT: ["C"], UP: ["F"], SO: ["F"],
|
|
618
|
+
CH: [], SG: [], PR: [], AN: [], BF: [],
|
|
619
|
+
SH: [], KO: [],
|
|
366
620
|
};
|
|
367
621
|
|
|
622
|
+
/** The parts of a tree that a run computes before the loop over its keys, if the program needs them. */
|
|
623
|
+
type TreePart = "children" | "siblings" | "order";
|
|
624
|
+
|
|
625
|
+
/** The statement of each part of a tree in a run, with the helper that computes it. */
|
|
626
|
+
const TREE_PARTS: Readonly<Record<TreePart, readonly [TreeHelper, string]>> = {
|
|
627
|
+
children: ["CH", "const [H, RT] = CH(P, n);"],
|
|
628
|
+
siblings: ["SG", "const [GP, SI] = SG(P, H, RT, n);"],
|
|
629
|
+
order: ["PR", "const [PO, PI, SZ] = PR(H, RT, n);"],
|
|
630
|
+
};
|
|
631
|
+
|
|
632
|
+
/** An axis whose targets in a tree space are a range of an array of positions: an axis of a tree, or a window. */
|
|
633
|
+
type TreeAxis = Extract<Axis, { readonly t: "children" | "ancestors" | "descendants" | "siblings" | "successors" | "predecessors" | "reachable" | "window" }>;
|
|
634
|
+
|
|
635
|
+
/** The axes of a tree space in a module, and the axes that a module of an array space does not have. */
|
|
636
|
+
const TREE_AXES: ReadonlySet<string> = new Set(["children", "ancestors", "descendants", "siblings", "successors", "predecessors", "reachable"]);
|
|
637
|
+
|
|
638
|
+
/** This function tells if an axis has its targets in a range of an array of positions in a tree space. */
|
|
639
|
+
const isTreeAxis = (a: Axis): a is TreeAxis => a.t === "window" || TREE_AXES.has(a.t);
|
|
640
|
+
|
|
641
|
+
/**
|
|
642
|
+
* The targets of an axis of a tree space: the statements before the loop, and the positions `a[q]` for `q` from `lo` up
|
|
643
|
+
* to `hi`. The loop skips the key `skip`.
|
|
644
|
+
*/
|
|
645
|
+
interface TreeRange {
|
|
646
|
+
readonly s: readonly string[];
|
|
647
|
+
readonly a: string;
|
|
648
|
+
readonly lo: string;
|
|
649
|
+
readonly hi: string;
|
|
650
|
+
readonly skip: string | undefined;
|
|
651
|
+
}
|
|
652
|
+
|
|
368
653
|
/** The list ops of a standalone module. */
|
|
369
654
|
const LIST_OPS: ReadonlySet<string> = new Set(["count", "sum", "mean", "min", "max", "any", "all", "none", "first"]);
|
|
370
655
|
const NUMBER_LIST_OPS: ReadonlySet<string> = new Set(["count", "sum", "mean", "min", "max"]);
|
|
@@ -372,6 +657,12 @@ const BOOLEAN_LIST_OPS: ReadonlySet<string> = new Set(["any", "all", "none"]);
|
|
|
372
657
|
/** The list ops that build a list from lists (LIST.BUILD), and `get` (LIST.GET). A module gives a reason for them. */
|
|
373
658
|
const BUILD_OPS: ReadonlySet<string> = new Set(["drop", "append", "flat", "without", "get"]);
|
|
374
659
|
|
|
660
|
+
/** This function tells if the step of a list op throws for a value of the kind `kind`, which is the wrong kind. */
|
|
661
|
+
const stepThrows = (op: string, kind: Kind | undefined): boolean => (NUMBER_STEPS.has(op) && kind !== "number") || (BOOLEAN_LIST_OPS.has(op) && kind !== "boolean");
|
|
662
|
+
|
|
663
|
+
/** The list ops whose step takes a number. */
|
|
664
|
+
const NUMBER_STEPS: ReadonlySet<string> = new Set(["sum", "mean", "min", "max"]);
|
|
665
|
+
|
|
375
666
|
/** This function gives the kind of the result of a list op: first gives the kind of its items. */
|
|
376
667
|
const listKind = (op: string, item: Kind | undefined): Kind | undefined => (NUMBER_LIST_OPS.has(op) ? "number" : BOOLEAN_LIST_OPS.has(op) ? "boolean" : item);
|
|
377
668
|
|
|
@@ -571,6 +862,23 @@ interface InlineForm {
|
|
|
571
862
|
readonly uses: readonly number[];
|
|
572
863
|
}
|
|
573
864
|
|
|
865
|
+
/**
|
|
866
|
+
* The tokens of the text between the names of an inline form: digits, spaces, operators and parentheses. The tokenizer
|
|
867
|
+
* takes the first token that matches at each position, as the tokenizer of JavaScript takes the longest operator. So
|
|
868
|
+
* `<<=`, `>>=` and `>>>=` leave a lone `=`, and an assignment stops the inline form (V-058).
|
|
869
|
+
*/
|
|
870
|
+
const TOKEN = /\d|\.\d|\s|===?|!==?|<<|>>>?|<=|>=|[+\-*/%<>!?:(),&|^~]/y;
|
|
871
|
+
|
|
872
|
+
/**
|
|
873
|
+
* This function tells if a text is a sequence of tokens. It takes one token at each step, so its time is linear in the
|
|
874
|
+
* length of the text. A repeated group of the tokens can split `!==` in two ways, and its time is exponential (V-057).
|
|
875
|
+
*/
|
|
876
|
+
function isTokens(t: string): boolean {
|
|
877
|
+
TOKEN.lastIndex = 0;
|
|
878
|
+
while (TOKEN.lastIndex < t.length) if (!TOKEN.test(t)) return false;
|
|
879
|
+
return true;
|
|
880
|
+
}
|
|
881
|
+
|
|
574
882
|
/**
|
|
575
883
|
* This function gives the inline form of the source of an arrow function. The body of the function must be an
|
|
576
884
|
* expression of operators, numbers, its parameters and the functions of `CALLS`. Such a body cannot throw for primitive
|
|
@@ -588,7 +896,7 @@ function inlineForm(src: string): InlineForm | undefined {
|
|
|
588
896
|
const split = (m[2] as string).split(/([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)?)/);
|
|
589
897
|
for (const [i, t] of split.entries()) {
|
|
590
898
|
if (i % 2 === 0) {
|
|
591
|
-
if (
|
|
899
|
+
if (!isTokens(t) || /\+\+|--|\)\s*\(/.test(t)) return undefined;
|
|
592
900
|
text += t;
|
|
593
901
|
} else if (CALLS.has(t)) text += t;
|
|
594
902
|
else {
|
|
@@ -606,6 +914,22 @@ function inlineForm(src: string): InlineForm | undefined {
|
|
|
606
914
|
/** This function gives the text of an inline form without spaces, with `#i` for the parameter `at(i)`. */
|
|
607
915
|
const patternOf = (form: InlineForm, at: (p: number) => number): string => form.parts.map((p) => (typeof p === "number" ? `#${at(p)}` : p.replaceAll(/\s/g, ""))).join("");
|
|
608
916
|
|
|
917
|
+
/** The reserved words of the strict code of a module, and the two names that strict code does not bind. */
|
|
918
|
+
const RESERVED: ReadonlySet<string> = new Set(
|
|
919
|
+
"await break case catch class const continue debugger default delete do else enum export extends false finally for function if implements import in instanceof interface let new null package private protected public return static super switch this throw true try typeof var void while with yield arguments eval".split(" "),
|
|
920
|
+
);
|
|
921
|
+
|
|
922
|
+
/**
|
|
923
|
+
* This function gives the reason that a name cannot be the name of the run, or `undefined` for a good name (V-060). A
|
|
924
|
+
* reserved word does not parse, and a second declaration of a name of the module does not parse. The function of the
|
|
925
|
+
* run with the name of a global of `MODULE_GLOBALS` hides that global from the code of the module.
|
|
926
|
+
*/
|
|
927
|
+
function nameReason(name: string, declared: ReadonlySet<string>): string | undefined {
|
|
928
|
+
if (RESERVED.has(name)) return `the name "${name}" is a reserved word of JavaScript`;
|
|
929
|
+
if (MODULE_GLOBALS.has(name)) return `the name "${name}" is a global that a module reads`;
|
|
930
|
+
return declared.has(name) ? `the name "${name}" is a name of the module` : undefined;
|
|
931
|
+
}
|
|
932
|
+
|
|
609
933
|
class Printer {
|
|
610
934
|
readonly #facts: Facts;
|
|
611
935
|
readonly #domains: readonly AnyDomain[];
|
|
@@ -622,6 +946,11 @@ class Printer {
|
|
|
622
946
|
memos = false;
|
|
623
947
|
/** The parts of the helper S that the nodes of the memo that keep their items need (helperS). */
|
|
624
948
|
readonly features = new Set<Feature>();
|
|
949
|
+
/** True for a tree space, and the parts of the tree that the program reads (COMPILE.MODULE.TREE). */
|
|
950
|
+
readonly #tree: boolean;
|
|
951
|
+
readonly treeParts = new Set<TreePart>();
|
|
952
|
+
/** The columns of a sheet, for a module of a sheet (COMPILE.MODULE.SHEET). */
|
|
953
|
+
readonly #sheet: SheetInfo | undefined;
|
|
625
954
|
#names = 0;
|
|
626
955
|
/** The number of the next bound function, and of the next printed function. */
|
|
627
956
|
#fnIds = 0;
|
|
@@ -658,11 +987,13 @@ class Printer {
|
|
|
658
987
|
/** The facts of the list of each function of the memo whose value is a list. */
|
|
659
988
|
readonly #lists = new Map<string, ListInfo | undefined>();
|
|
660
989
|
|
|
661
|
-
constructor(expr: Expr, options: ModuleOptions) {
|
|
990
|
+
constructor(expr: Expr, options: ModuleOptions, sheet?: SheetInfo) {
|
|
662
991
|
this.#domains = options.domains ?? [];
|
|
663
992
|
this.#facts = factsOf({ domains: this.#domains });
|
|
664
993
|
this.#schema = options.schema;
|
|
665
994
|
this.#memo = memoOf(expr);
|
|
995
|
+
this.#tree = options.space === "tree";
|
|
996
|
+
this.#sheet = sheet;
|
|
666
997
|
}
|
|
667
998
|
|
|
668
999
|
use(name: Helper): string {
|
|
@@ -670,18 +1001,27 @@ class Printer {
|
|
|
670
1001
|
return name;
|
|
671
1002
|
}
|
|
672
1003
|
|
|
1004
|
+
/** This method gives the name of a part of the tree, for example `H` for the children, and marks the part as read. */
|
|
1005
|
+
#part(part: TreePart, name: string): string {
|
|
1006
|
+
this.treeParts.add(part);
|
|
1007
|
+
return name;
|
|
1008
|
+
}
|
|
1009
|
+
|
|
673
1010
|
/**
|
|
674
1011
|
* This method gives the check of a result of a kind, or undefined for a result that needs no check. A number must be
|
|
675
1012
|
* finite, and the domain of the kind can check the value with valid. The law checker of the test kit checks the
|
|
676
1013
|
* declaration `returns` of each op (KIND.RETURNS), so the module trusts the kind itself.
|
|
677
1014
|
*/
|
|
678
1015
|
check(kind: Kind): string | undefined {
|
|
679
|
-
const
|
|
1016
|
+
const d = this.#facts.checkOf(kind);
|
|
1017
|
+
// The kind is primitive here. A static site on a value of a domain has no domain without a primitive type before it.
|
|
1018
|
+
if (d === undefined) throw new NotStandalone(`a domain without a primitive type comes before the domain of a ${kind}`);
|
|
1019
|
+
// The name of a domain can have each character. For a name that is not a JavaScript name, the check has the index
|
|
1020
|
+
// of its domain in its name (V-061).
|
|
1021
|
+
const plain = `k_${kind.replace(":", "_")}`;
|
|
1022
|
+
const name = /^[\w$]+$/.test(plain) ? plain : `k_d${String(d)}`;
|
|
680
1023
|
// Stryker disable next-line ConditionalExpression: a check of a kind is always the same, so the map only saves time
|
|
681
1024
|
if (!this.top.has(name)) {
|
|
682
|
-
const d = this.#facts.checkOf(kind);
|
|
683
|
-
// The kind is primitive here. A static site on a value of a domain has no domain without a primitive type before it.
|
|
684
|
-
if (d === undefined) throw new NotStandalone(`a domain without a primitive type comes before the domain of a ${kind}`);
|
|
685
1025
|
const domain = this.#domains[d];
|
|
686
1026
|
const valid = domain?.valid === undefined ? undefined : this.#valid(d, domain.name, kind, domain.valid);
|
|
687
1027
|
const conds = [...(kind === "number" ? ["Number.isFinite(x)"] : []), ...(valid === undefined ? [] : [`${valid}(x)`])];
|
|
@@ -832,8 +1172,9 @@ class Printer {
|
|
|
832
1172
|
* from outside is a constant of the run, so its code can be outside the loop.
|
|
833
1173
|
*/
|
|
834
1174
|
#columnar(e: Expr, c: Code, ctx: Ctx): boolean {
|
|
835
|
-
// A node of the memo has the level 1, so a column has a focus.
|
|
836
|
-
|
|
1175
|
+
// A node of the memo has the level 1, so a column has a focus. The results of the cells change in a run, so a part
|
|
1176
|
+
// that reads a cell is not a column.
|
|
1177
|
+
if (ctx.level < 2 || c.v.deps.has(CELLS) || !c.v.deps.has(ctx.level) || this.#work(e, ctx.fns) < COLUMN_WORK) return false;
|
|
837
1178
|
const scope = this.#callScope(c, ctx);
|
|
838
1179
|
if (c.v.deps.size !== 1 && scope === undefined) return false;
|
|
839
1180
|
// A node of the memo with keys keeps its costly part for each value of its keys already.
|
|
@@ -932,9 +1273,10 @@ class Printer {
|
|
|
932
1273
|
const names = Object.keys(e.fields);
|
|
933
1274
|
const raw = Object.values(e.fields).map((x) => this.expr(x, ctx));
|
|
934
1275
|
const deps = depsOf(...raw);
|
|
935
|
-
|
|
1276
|
+
// The interpreter evaluates each field, also after an error.
|
|
1277
|
+
const fields = this.#inOrder(this.#settle(raw, deps, Object.values(e.fields)), true);
|
|
936
1278
|
// A record of a module is a new object, so it needs no freeze.
|
|
937
|
-
const code = `({ ${fields.map((x, i) => `${JSON.stringify(names[i])}: ${x.v.code}`).join(", ")} })`;
|
|
1279
|
+
const code = `({ ${fields.map((x, i) => `${names[i] === "__proto__" ? '["__proto__"]' : JSON.stringify(names[i])}: ${x.v.code}`).join(", ")} })`;
|
|
938
1280
|
return { s: stmtsOf(...fields), v: { code, kind: undefined, safe: fields.every((x) => x.v.safe), deps } };
|
|
939
1281
|
}
|
|
940
1282
|
case "app":
|
|
@@ -946,10 +1288,57 @@ class Printer {
|
|
|
946
1288
|
case "iterate":
|
|
947
1289
|
return this.#iterate(e, ctx);
|
|
948
1290
|
case "ext":
|
|
949
|
-
|
|
1291
|
+
return this.#cell(e, ctx);
|
|
950
1292
|
}
|
|
951
1293
|
}
|
|
952
1294
|
|
|
1295
|
+
/**
|
|
1296
|
+
* This method gives the code of a read of a cell in a module of a sheet (COMPILE.MODULE.SHEET). The value is the result
|
|
1297
|
+
* of the cell, which can be the error sentinel, so the read throws its error. A read that is not a cell reference, or
|
|
1298
|
+
* of a column that the sheet does not have, gives an error, as in `SheetRun`.
|
|
1299
|
+
*/
|
|
1300
|
+
#cell(e: ExprOf<"ext">, ctx: Ctx): Code {
|
|
1301
|
+
const sheet = this.#sheet;
|
|
1302
|
+
if (sheet === undefined || e.kind !== CELL_KIND) throw new NotStandalone(`the extension "${e.kind}"`);
|
|
1303
|
+
const F = this.use("F");
|
|
1304
|
+
if (!isCellRef(e.data)) return bare({ code: `${F}()`, kind: undefined, safe: false, deps: new Set([CELLS]) });
|
|
1305
|
+
const { column, at } = e.data;
|
|
1306
|
+
const deps = new Set([...this.#addressDeps(at, ctx, []), CELLS]);
|
|
1307
|
+
const index = sheet.columns.get(column);
|
|
1308
|
+
// The read of a column that the sheet does not have is an error. A kind of the options lets an op take it.
|
|
1309
|
+
if (index === undefined) return bare({ code: `${F}()`, kind: sheet.kinds.get(column), safe: false, deps });
|
|
1310
|
+
if (!sheet.kinds.has(column)) throw new NotStandalone(`a formula reads the column "${column}" before its formula, so the column needs its kind in the option kinds`);
|
|
1311
|
+
const read = `${READ_CELL}(${String(index)}, ${this.#address(at, ctx, [])})`;
|
|
1312
|
+
const v = { code: `${this.use("G")}(${read})`, kind: sheet.kinds.get(column), safe: false, deps };
|
|
1313
|
+
// The read itself gives the result or the error sentinel. A move of the address can throw, so then the read is not
|
|
1314
|
+
// a value that holds the sentinel.
|
|
1315
|
+
return bare(at.every((m) => m.t === "origin") ? { ...v, held: read } : v);
|
|
1316
|
+
}
|
|
1317
|
+
|
|
1318
|
+
/**
|
|
1319
|
+
* This method gives the parts of a node in the order of the interpreter, when a part reads a cell (COMPILE.MODULE.SHEET).
|
|
1320
|
+
* A read of a cell can start the search of the run, and the search decides the cycles. So the module must read each
|
|
1321
|
+
* cell that the interpreter reads. With `all`, the interpreter evaluates each part also after an error, so each part
|
|
1322
|
+
* goes into a variable that can hold the error. Else the first error stops the parts, so each part goes into a
|
|
1323
|
+
* variable before the next part starts.
|
|
1324
|
+
*
|
|
1325
|
+
* The statements of the parts come before the code of their values. The last part that reads a cell keeps its place
|
|
1326
|
+
* only if no statement after it can throw. Also, with `all`, a value before it must not throw, or the code of its value
|
|
1327
|
+
* must read no cell.
|
|
1328
|
+
*/
|
|
1329
|
+
#inOrder(parts: readonly Code[], all: boolean): readonly Code[] {
|
|
1330
|
+
const last = parts.findLastIndex((x) => x.v.deps.has(CELLS));
|
|
1331
|
+
const after = parts.slice(last + 1).every((x) => x.s.length === 0 || x.v.safe);
|
|
1332
|
+
const before = !all || parts.slice(0, Math.max(last, 0)).every((x) => x.v.safe) || !READS_IN_CODE.test((parts[last] as Code).v.code);
|
|
1333
|
+
return parts.map((x, i) => {
|
|
1334
|
+
// A part after the last read of a cell cannot stop a read. A part that cannot throw and reads no cell cannot either.
|
|
1335
|
+
if (i > last || (x.v.safe && !x.v.deps.has(CELLS)) || (i === last && after && before)) return x;
|
|
1336
|
+
const b = this.fresh("b");
|
|
1337
|
+
if (all && !x.v.safe) return { s: this.#store(b, x), v: { ...x.v, code: `${this.use("G")}(${b})`, held: b, plain: false } };
|
|
1338
|
+
return { s: [...x.s, `const ${b} = ${x.v.code};`], v: { kind: x.v.kind, deps: x.v.deps, list: x.v.list, code: b, safe: true, plain: true } };
|
|
1339
|
+
});
|
|
1340
|
+
}
|
|
1341
|
+
|
|
953
1342
|
/**
|
|
954
1343
|
* This method gives the code of the index of an address from the focus. `values` has the code of the value of each
|
|
955
1344
|
* computed move, in order (NAV.COMPUTED).
|
|
@@ -958,11 +1347,12 @@ class Printer {
|
|
|
958
1347
|
let index = ctx.focus;
|
|
959
1348
|
let next = 0;
|
|
960
1349
|
// A move that can fail keeps its check when a later fixed key, index or origin replaces its index (V-052). The focus
|
|
961
|
-
// and the origin cannot fail, and the code of a move from an index has the code of that index in it.
|
|
1350
|
+
// and the origin cannot fail, and the code of a move from an index has the code of that index in it. In a tree,
|
|
1351
|
+
// the move parent is a move from an index.
|
|
962
1352
|
let fails = false;
|
|
963
1353
|
const checks: string[] = [];
|
|
964
1354
|
for (const m of at) {
|
|
965
|
-
if (fails && index !== undefined && m.t !== "offset" && m.t !== "other") checks.push(index);
|
|
1355
|
+
if (fails && index !== undefined && m.t !== "offset" && m.t !== "other" && (m.t !== "parent" || !this.#tree)) checks.push(index);
|
|
966
1356
|
index = moveExpr(m) === undefined ? this.#move(m, index, ctx.origin) : this.#computed(m, values[next++] as Code);
|
|
967
1357
|
fails = m.t !== "origin";
|
|
968
1358
|
}
|
|
@@ -997,6 +1387,8 @@ class Printer {
|
|
|
997
1387
|
/* v8 ignore next -- @preserve */
|
|
998
1388
|
if (focus === undefined) throw new NotStandalone("a node of the memo reads its focus");
|
|
999
1389
|
if (d === undefined || more.length > 0 || !Number.isInteger(d)) return `${F}()`;
|
|
1390
|
+
// In a tree space, an offset goes among the siblings (NAV.OFFSET.TREE).
|
|
1391
|
+
if (this.#tree) return `${this.use("SO")}(${this.#part("siblings", "GP")}, SI, ${focus}, ${d})`;
|
|
1000
1392
|
return `${this.use("X")}(${focus} + ${d}, n)`;
|
|
1001
1393
|
}
|
|
1002
1394
|
case "other":
|
|
@@ -1005,7 +1397,12 @@ class Printer {
|
|
|
1005
1397
|
if (focus === undefined) throw new NotStandalone("a node of the memo reads its focus");
|
|
1006
1398
|
return `(n === 2 ? 1 - ${focus} : ${F}())`;
|
|
1007
1399
|
case "parent":
|
|
1008
|
-
|
|
1400
|
+
// Only a tree space has parents (NAV.PARENT).
|
|
1401
|
+
if (!this.#tree) return `${F}()`;
|
|
1402
|
+
// Stryker disable next-line ConditionalExpression,StringLiteral: see #address
|
|
1403
|
+
/* v8 ignore next -- @preserve */
|
|
1404
|
+
if (focus === undefined) throw new NotStandalone("a node of the memo reads its focus");
|
|
1405
|
+
return `${this.use("UP")}(P, ${focus})`;
|
|
1009
1406
|
}
|
|
1010
1407
|
}
|
|
1011
1408
|
|
|
@@ -1018,7 +1415,8 @@ class Printer {
|
|
|
1018
1415
|
const safe = at.every((m) => m.t === "origin");
|
|
1019
1416
|
const values = this.#addressValues(at, ctx);
|
|
1020
1417
|
const deps = this.#addressDeps(at, ctx, values);
|
|
1021
|
-
|
|
1418
|
+
// The interpreter evaluates the expressions of the address before its moves, and the first error stops them.
|
|
1419
|
+
const parts = this.#inOrder(this.#settle(values, deps), false);
|
|
1022
1420
|
return { s: stmtsOf(...parts), v: { code: `R[${this.#address(at, ctx, parts)}][${JSON.stringify(field)}]`, kind, safe, deps } };
|
|
1023
1421
|
}
|
|
1024
1422
|
|
|
@@ -1042,7 +1440,8 @@ class Printer {
|
|
|
1042
1440
|
if (fails) for (const d of deps) kept.add(d);
|
|
1043
1441
|
if (moveExpr(m) !== undefined) deps = (values[next++] as Code).v.deps;
|
|
1044
1442
|
else if (m.t === "origin") deps = new Set([ctx.originLevel]);
|
|
1045
|
-
|
|
1443
|
+
// The parent of a key of a tree depends on the key. Outside a tree, the move fails at each key.
|
|
1444
|
+
else if (m.t === "key" || m.t === "index" || (m.t === "parent" && !this.#tree)) deps = NO_DEPS;
|
|
1046
1445
|
fails = m.t !== "origin";
|
|
1047
1446
|
}
|
|
1048
1447
|
return new Set([...deps, ...kept]);
|
|
@@ -1201,7 +1600,8 @@ class Printer {
|
|
|
1201
1600
|
if (head !== undefined && (LIST_OPS.has(op) || op === "nth") && this.#isList(head, ctx)) return this.#overList(op, head, args.slice(1), ctx);
|
|
1202
1601
|
const raw = args.map((x) => this.expr(x, ctx));
|
|
1203
1602
|
const deps = depsOf(...raw);
|
|
1204
|
-
|
|
1603
|
+
// The interpreter evaluates each argument, also after an error.
|
|
1604
|
+
const values = this.#inOrder(this.#settle(raw, deps, args), true);
|
|
1205
1605
|
const site = this.#facts.staticSite(op, values.map((x) => x.v.kind));
|
|
1206
1606
|
if (site?.t !== "fn") throw new NotStandalone(`the kinds of the values of "${op}" do not decide its op`);
|
|
1207
1607
|
if (site.bad) return { s: stmtsOf(...values), v: { code: `${this.use("F")}()`, kind: site.returns, safe: false, deps } };
|
|
@@ -1303,8 +1703,8 @@ class Printer {
|
|
|
1303
1703
|
*/
|
|
1304
1704
|
/**
|
|
1305
1705
|
* This method gives the loop over the targets of an axis: the statements before it, its bounds and the key that it
|
|
1306
|
-
* skips. `start` has the levels of the address, and `inner` is the position at a target. The axes all, others
|
|
1307
|
-
* window have a loop.
|
|
1706
|
+
* skips. `start` has the levels of the address, and `inner` is the position at a target. The axes all, others,
|
|
1707
|
+
* window and list have a loop. In a tree space, the axes of a tree have a loop too.
|
|
1308
1708
|
*/
|
|
1309
1709
|
#targetLoop(axis: Axis, at: readonly Move[], ctx: Ctx): {
|
|
1310
1710
|
readonly s: string[];
|
|
@@ -1350,21 +1750,64 @@ class Printer {
|
|
|
1350
1750
|
if (f !== undefined) {
|
|
1351
1751
|
const values = this.#addressValues(at, ctx);
|
|
1352
1752
|
start = this.#addressDeps(at, ctx, values);
|
|
1353
|
-
const parts = this.#settle(values, start);
|
|
1753
|
+
const parts = this.#inOrder(this.#settle(values, start), false);
|
|
1354
1754
|
s.push(...stmtsOf(...parts), `const ${f} = ${this.#address(at, ctx, parts)};`);
|
|
1355
1755
|
}
|
|
1756
|
+
const startSafe = at.every((m) => m.t === "origin");
|
|
1757
|
+
if (base.t === "window" && (!Number.isInteger(base.from) || !Number.isInteger(base.to))) throw new NotStandalone('the axis "window" with a bound that is not an integer');
|
|
1758
|
+
// In a tree space, the targets of a tree axis and of a window are a range of an array of positions.
|
|
1759
|
+
if (this.#tree && isTreeAxis(base)) {
|
|
1760
|
+
const range = this.#treeRange(base, f as string);
|
|
1761
|
+
const q = this.fresh("q");
|
|
1762
|
+
return { s: [...s, ...range.s], j, head: forHead(q, range.lo, range.hi, reverse), key: [`const ${j} = ${range.a}[${q}];`], check: [], skip: range.skip, fixed: false, start, startSafe, tests, inner };
|
|
1763
|
+
}
|
|
1356
1764
|
if (base.t === "others") skip = f;
|
|
1357
1765
|
else if (base.t === "window") {
|
|
1358
|
-
if (!Number.isInteger(base.from) || !Number.isInteger(base.to)) throw new NotStandalone('the axis "window" with a bound that is not an integer');
|
|
1359
1766
|
const h = this.fresh("h");
|
|
1360
1767
|
lo = `Math.max(0, ${f as string} + Math.max(${base.from}, -n))`;
|
|
1361
1768
|
s.push(`const ${h} = Math.min(n, ${f as string} + Math.min(${base.to}, n) + 1);`);
|
|
1362
1769
|
hi = h;
|
|
1363
1770
|
} else if (base.t !== "all") throw new NotStandalone(`the axis "${base.t}"`);
|
|
1364
|
-
const startSafe = at.every((m) => m.t === "origin");
|
|
1365
1771
|
return { s, j, head: forHead(j, lo, hi, reverse), key: [], check: [], skip, fixed: f === undefined, start, startSafe, tests, inner };
|
|
1366
1772
|
}
|
|
1367
1773
|
|
|
1774
|
+
/**
|
|
1775
|
+
* This method gives the targets of an axis of a tree space at the position `f`. They are the positions `a[q]` for `q`
|
|
1776
|
+
* from `lo` up to `hi`, without the key that the loop skips. The axes come from AXIS.TREE, AXIS.GRAPH and AXIS.WINDOW.
|
|
1777
|
+
*/
|
|
1778
|
+
#treeRange(base: TreeAxis, f: string): TreeRange {
|
|
1779
|
+
const a = this.fresh("A");
|
|
1780
|
+
const all = (code: string, lo = "0", skip?: string): TreeRange => ({ s: [`const ${a} = ${code};`], a, lo, hi: `${a}.length`, skip });
|
|
1781
|
+
switch (base.t) {
|
|
1782
|
+
// In a tree, the edges go from a parent to its children.
|
|
1783
|
+
case "children":
|
|
1784
|
+
case "successors":
|
|
1785
|
+
return all(`${this.#part("children", "H")}[${f}]`);
|
|
1786
|
+
case "siblings":
|
|
1787
|
+
return all(`${this.#part("siblings", "GP")}[${f}]`, "0", f);
|
|
1788
|
+
case "ancestors":
|
|
1789
|
+
return all(`${this.use("AN")}(P, ${f})`);
|
|
1790
|
+
case "predecessors":
|
|
1791
|
+
return all(`(P[${f}] < 0 ? [] : [P[${f}]])`);
|
|
1792
|
+
case "reachable":
|
|
1793
|
+
// The first key of the search is the focus, which is not a target.
|
|
1794
|
+
return all(`${this.use("BF")}(${this.#part("children", "H")}, ${f})`, "1");
|
|
1795
|
+
case "descendants": {
|
|
1796
|
+
// The descendants of a key are the keys after it in the order depth first, as many as its subtree has under it.
|
|
1797
|
+
const h = this.fresh("h");
|
|
1798
|
+
return { s: [`const ${a} = ${this.#part("order", "PI")}[${f}] + 1;`, `const ${h} = ${a} + SZ[${f}] - 1;`], a: "PO", lo: a, hi: h, skip: undefined };
|
|
1799
|
+
}
|
|
1800
|
+
case "window": {
|
|
1801
|
+
// The offsets among the siblings, from `from` to `to`. The bounds are integers (#targetLoop).
|
|
1802
|
+
const { from, to } = base;
|
|
1803
|
+
const l = this.fresh("h");
|
|
1804
|
+
const h = this.fresh("h");
|
|
1805
|
+
const s = [`const ${a} = ${this.#part("siblings", "GP")}[${f}];`, `const ${l} = Math.max(0, SI[${f}] + ${String(from)});`, `const ${h} = Math.min(${a}.length, SI[${f}] + ${String(to)} + 1);`];
|
|
1806
|
+
return { s, a, lo: l, hi: h, skip: undefined };
|
|
1807
|
+
}
|
|
1808
|
+
}
|
|
1809
|
+
}
|
|
1810
|
+
|
|
1368
1811
|
#list(op: string, target: ExprOf<"each">, rest: readonly Expr[], ctx: Ctx): Code {
|
|
1369
1812
|
const strict = this.#strict(op, rest);
|
|
1370
1813
|
const at = target.at ?? [];
|
|
@@ -1382,6 +1825,15 @@ class Printer {
|
|
|
1382
1825
|
const item = [...check, ...testCodes.flatMap((t) => [...t.s, `if (!${this.#boolean(t.v)}) continue;`]), ...body.s];
|
|
1383
1826
|
// An item whose tests and body cannot fail needs no try.
|
|
1384
1827
|
const safeItem = check.length === 0 && body.v.safe && testCodes.every((t) => this.#safeBoolean(t.v));
|
|
1828
|
+
// The interpreter evaluates each item before the list op (COMPILE.MODULE.SHEET). When an item reads a cell, an error
|
|
1829
|
+
// of an item or of a step must not stop the reads of the next items. So the items go into an array first.
|
|
1830
|
+
if ([body, ...testCodes].some((x) => x.v.deps.has(CELLS)) && (strict || stepThrows(op, body.v.kind))) {
|
|
1831
|
+
const list = this.fresh("L");
|
|
1832
|
+
const x = this.fresh("x");
|
|
1833
|
+
const all = [...key, ...(skip === undefined ? [] : [`if (${j} === ${skip}) continue;`]), `let ${x};`, "try {", ...ind(item), ` ${x} = ${body.v.code};`, "} catch {", ` ${x} = E;`, "}", `${list}.push(${x});`];
|
|
1834
|
+
const reduce = [`for (const ${v} of ${list}) {`, ` if (${v} === E) ${strict ? `${this.use("F")}();` : "continue;"}`, ` ${r.step}`, "}"];
|
|
1835
|
+
return { s: [...s, `const ${list} = [];`, head, ...ind(all), "}", ...reduce], v: { code: r.result, kind: listKind(op, body.v.kind), safe: false, deps } };
|
|
1836
|
+
}
|
|
1385
1837
|
const loop = [
|
|
1386
1838
|
...key,
|
|
1387
1839
|
...(skip === undefined ? [] : [`if (${j} === ${skip}) continue;`]),
|
|
@@ -1471,7 +1923,7 @@ class Printer {
|
|
|
1471
1923
|
const strict = this.#strict(op, rest.slice(exprs.length - 1));
|
|
1472
1924
|
const raw = [list, ...exprs.slice(1).map((x) => this.expr(x, ctx))];
|
|
1473
1925
|
const deps = depsOf(...raw);
|
|
1474
|
-
const parts = this.#settle(raw, deps, exprs);
|
|
1926
|
+
const parts = this.#inOrder(this.#settle(raw, deps, exprs), true);
|
|
1475
1927
|
const item = (list.v.list as ListInfo).item;
|
|
1476
1928
|
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 } } };
|
|
1477
1929
|
}
|
|
@@ -1484,7 +1936,7 @@ class Printer {
|
|
|
1484
1936
|
const strict = this.#strict(op, rest.slice(exprs.length - 1));
|
|
1485
1937
|
const raw = [list, ...exprs.slice(1).map((x) => this.expr(x, ctx))];
|
|
1486
1938
|
const deps = depsOf(...raw);
|
|
1487
|
-
const parts = this.#settle(raw, deps, exprs);
|
|
1939
|
+
const parts = this.#inOrder(this.#settle(raw, deps, exprs), true);
|
|
1488
1940
|
const [l] = parts as [Code];
|
|
1489
1941
|
const item = (list.v.list as ListInfo).item;
|
|
1490
1942
|
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 } };
|
|
@@ -1567,6 +2019,8 @@ class Printer {
|
|
|
1567
2019
|
const names = this.#loopNames(e.init, ctx, loop);
|
|
1568
2020
|
const t = this.#targetLoop(e.axis, e.at ?? [], ctx);
|
|
1569
2021
|
const tests = t.tests.map((x) => this.#hoist(this.expr(x, t.inner), hasLoop(x)));
|
|
2022
|
+
// The interpreter evaluates the tests at each target before the first step, so a module of a sheet does not have them.
|
|
2023
|
+
if (tests.some((x) => x.v.deps.has(CELLS))) throw new NotStandalone("a test of the axis of a fold reads a cell");
|
|
1570
2024
|
const step = this.#loopStep(e.step, { ...t.inner, env: names.env }, names.vars);
|
|
1571
2025
|
const result = this.expr(e.result, { ...ctx, env: names.env });
|
|
1572
2026
|
const body = [
|
|
@@ -1723,11 +2177,15 @@ class Printer {
|
|
|
1723
2177
|
}
|
|
1724
2178
|
|
|
1725
2179
|
/** This method gives the code of the program at the key of the run. A constant of the run evaluates once. */
|
|
2180
|
+
/** This method gives the code of a program at the key `o` of the run. A sheet has one program for each formula. */
|
|
1726
2181
|
root(expr: Expr): Code {
|
|
1727
|
-
|
|
2182
|
+
return this.#hoist(this.expr(expr, { origin: "o", focus: "o", level: 1, originLevel: 1, env: new Map(), fns: new Map(), keys: new Map() }));
|
|
2183
|
+
}
|
|
2184
|
+
|
|
2185
|
+
/** This method removes the declarations that no code reads, after the last program. */
|
|
2186
|
+
finish(): void {
|
|
1728
2187
|
// A function of an op with an inline form at each of its sites needs no declaration.
|
|
1729
2188
|
for (const [name, form] of this.#forms) if (form !== undefined && !this.#called.has(name)) this.top.delete(name);
|
|
1730
|
-
return c;
|
|
1731
2189
|
}
|
|
1732
2190
|
|
|
1733
2191
|
/**
|
|
@@ -1748,30 +2206,26 @@ class Printer {
|
|
|
1748
2206
|
}
|
|
1749
2207
|
}
|
|
1750
2208
|
|
|
2209
|
+
/** This function gives the name of the function of a module, and its space, or the reason that the options are not valid. */
|
|
2210
|
+
function runOf(options: ModuleOptions): { readonly name: string; readonly tree: boolean } | { readonly reason: string } {
|
|
2211
|
+
const name = options.name ?? "run";
|
|
2212
|
+
if (!/^[A-Za-z_$][\w$]*$/.test(name)) return { reason: `the name "${name}" is not a JavaScript name` };
|
|
2213
|
+
const tree = options.space === "tree";
|
|
2214
|
+
if (!tree && options.space !== undefined && options.space !== "array") return { reason: `the space "${String(options.space)}" is not "array" or "tree"` };
|
|
2215
|
+
return { name, tree };
|
|
2216
|
+
}
|
|
2217
|
+
|
|
2218
|
+
/** This function gives the reason of an error of the printer. Another exception is a defect, so it goes to the caller. */
|
|
2219
|
+
function reasonOf(thrown: unknown): Emitted {
|
|
2220
|
+
if (!(thrown instanceof NotStandalone)) throw thrown;
|
|
2221
|
+
return { ok: false, reason: thrown.message };
|
|
2222
|
+
}
|
|
2223
|
+
|
|
1751
2224
|
/**
|
|
1752
|
-
* This function
|
|
1753
|
-
*
|
|
1754
|
-
* The program can be an expression or a document (DOC.ENTRY).
|
|
2225
|
+
* This function gives the text of a module: the declarations, the helpers, and the function of the run. The run checks
|
|
2226
|
+
* its input, computes the parts of the tree and the constants of the run, and then gives the statements `body`.
|
|
1755
2227
|
*/
|
|
1756
|
-
|
|
1757
|
-
const name = options.name ?? "run";
|
|
1758
|
-
if (!/^[A-Za-z_$][\w$]*$/.test(name)) return { ok: false, reason: `the name "${name}" is not a JavaScript name` };
|
|
1759
|
-
// DOC.ENTRY: a document gives its expression first, or the reason that it is not valid.
|
|
1760
|
-
const read = isDocument(source) ? fromDocument(source, options.domains) : { ok: true as const, value: source };
|
|
1761
|
-
if (!read.ok) return { ok: false, reason: read.error.message };
|
|
1762
|
-
const expr = read.value;
|
|
1763
|
-
// EVAL.SHAPE: a module of an expression that is not valid has no use, so the printer gives the reason.
|
|
1764
|
-
const shape = shapeError(expr);
|
|
1765
|
-
if (shape !== undefined) return { ok: false, reason: shape };
|
|
1766
|
-
const p = new Printer(expr, options);
|
|
1767
|
-
let value: Code;
|
|
1768
|
-
try {
|
|
1769
|
-
value = p.root(expr);
|
|
1770
|
-
} catch (thrown) {
|
|
1771
|
-
// Each error of the printer is a NotStandalone. Another exception is a defect, so it goes to the caller.
|
|
1772
|
-
if (!(thrown instanceof NotStandalone)) throw thrown;
|
|
1773
|
-
return { ok: false, reason: thrown.message };
|
|
1774
|
-
}
|
|
2228
|
+
function printModule(p: Printer, options: ModuleOptions, run: { readonly name: string; readonly tree: boolean }, body: readonly string[]): Emitted {
|
|
1775
2229
|
p.use("C");
|
|
1776
2230
|
const helpers = new Set<Helper>();
|
|
1777
2231
|
// A helper comes after the helpers that it needs. A set keeps the first place of each helper.
|
|
@@ -1787,10 +2241,20 @@ export function emitModule(source: Expr | Envelope, options: ModuleOptions): Emi
|
|
|
1787
2241
|
fieldChecks = fields.map(([f, k]) => ` || ${p.against(k, `r[${JSON.stringify(f)}]`)}`).join("");
|
|
1788
2242
|
varChecks = vars.map(([v, k]) => ` || ${p.against(k, `vars[${JSON.stringify(v)}]`)}`).join("");
|
|
1789
2243
|
} catch (thrown) {
|
|
1790
|
-
|
|
1791
|
-
|
|
1792
|
-
}
|
|
2244
|
+
return reasonOf(thrown);
|
|
2245
|
+
}
|
|
2246
|
+
const { name, tree } = run;
|
|
2247
|
+
// A tree checks its parents, and it computes the parts that the program reads. The siblings and the order need the
|
|
2248
|
+
// children.
|
|
2249
|
+
if (tree) p.use("PT");
|
|
2250
|
+
if (p.treeParts.size > 0) p.treeParts.add("children");
|
|
2251
|
+
const parts = (["children", "siblings", "order"] as const).filter((x) => p.treeParts.has(x));
|
|
2252
|
+
for (const x of parts) p.use(TREE_PARTS[x][0]);
|
|
1793
2253
|
[...p.helpers].toSorted().forEach(add);
|
|
2254
|
+
// The names that this module declares at its top: the constants, the helpers and the declarations of the printer.
|
|
2255
|
+
const declared = new Set<string>(["VexContractError", "VEX_ERROR", "E", ...(p.memos ? ["Z"] : []), ...(helpers.has("S") ? ["N", "W"] : []), ...helpers, ...p.top.keys()]);
|
|
2256
|
+
const bad = nameReason(name, declared);
|
|
2257
|
+
if (bad !== undefined) return { ok: false, reason: bad };
|
|
1794
2258
|
const lines = [
|
|
1795
2259
|
"// Generated by @mark1russell7/vex-compiler from a Vex program. Do not edit.",
|
|
1796
2260
|
"/** The error of a run whose input does not keep the schema of the program. */",
|
|
@@ -1803,7 +2267,7 @@ export function emitModule(source: Expr | Envelope, options: ModuleOptions): Emi
|
|
|
1803
2267
|
...(helpers.has("S") ? ["const N = {}, W = {};"] : []),
|
|
1804
2268
|
...[...helpers].map((h) => (h === "S" ? helperS(p.features) : HELPERS[h])),
|
|
1805
2269
|
...p.top.values(),
|
|
1806
|
-
`export function ${name}(records, vars) {`,
|
|
2270
|
+
`export function ${name}(records, vars${tree ? ", parents" : ""}) {`,
|
|
1807
2271
|
' if (!Array.isArray(records)) C("the records are not an array");',
|
|
1808
2272
|
" const R = records;",
|
|
1809
2273
|
" const n = R.length;",
|
|
@@ -1812,20 +2276,143 @@ export function emitModule(source: Expr | Envelope, options: ModuleOptions): Emi
|
|
|
1812
2276
|
` if (typeof r !== "object" || r === null${fieldChecks}) C(\`the record \${i} does not keep the schema\`);`,
|
|
1813
2277
|
" }",
|
|
1814
2278
|
` if (typeof vars !== "object" || vars === null${varChecks}) C("the variables do not keep the schema");`,
|
|
2279
|
+
...(tree ? [" const P = PT(parents, n);", ...parts.map((x) => ` ${TREE_PARTS[x][1]}`)] : []),
|
|
1815
2280
|
...[...p.vars].map(([v, code]) => ` const ${code} = vars[${JSON.stringify(v)}];`),
|
|
1816
2281
|
...ind(p.run),
|
|
1817
|
-
|
|
1818
|
-
" for (let o = 0; o < n; o++) {",
|
|
1819
|
-
" try {",
|
|
1820
|
-
...ind(ind(ind(value.s))),
|
|
1821
|
-
` out.push(${value.v.code});`,
|
|
1822
|
-
" } catch {",
|
|
1823
|
-
" out.push(VEX_ERROR);",
|
|
1824
|
-
" }",
|
|
1825
|
-
" }",
|
|
1826
|
-
" return out;",
|
|
2282
|
+
...ind(body),
|
|
1827
2283
|
"}",
|
|
1828
2284
|
"",
|
|
1829
2285
|
];
|
|
1830
2286
|
return { ok: true, source: lines.join("\n") };
|
|
1831
2287
|
}
|
|
2288
|
+
|
|
2289
|
+
/**
|
|
2290
|
+
* This function prints a program as a standalone ES module. The module exports `VexContractError`, `VEX_ERROR` and a
|
|
2291
|
+
* function that takes the records and the variables and gives the value at each key. A module of a tree space takes
|
|
2292
|
+
* the parents too. The function is pure, so a build can use it. The program can be an expression or a document
|
|
2293
|
+
* (DOC.ENTRY).
|
|
2294
|
+
*/
|
|
2295
|
+
export function emitModule(source: Expr | Envelope, options: ModuleOptions): Emitted {
|
|
2296
|
+
const run = runOf(options);
|
|
2297
|
+
if ("reason" in run) return { ok: false, reason: run.reason };
|
|
2298
|
+
// DOC.ENTRY: a document gives its expression first, or the reason that it is not valid.
|
|
2299
|
+
const read = isDocument(source) ? fromDocument(source, options.domains) : { ok: true as const, value: source };
|
|
2300
|
+
if (!read.ok) return { ok: false, reason: read.error.message };
|
|
2301
|
+
const expr = read.value;
|
|
2302
|
+
// EVAL.SHAPE: a module of an expression that is not valid has no use, so the printer gives the reason.
|
|
2303
|
+
const shape = shapeError(expr);
|
|
2304
|
+
if (shape !== undefined) return { ok: false, reason: shape };
|
|
2305
|
+
const p = new Printer(expr, options);
|
|
2306
|
+
let value: Code;
|
|
2307
|
+
try {
|
|
2308
|
+
value = p.root(expr);
|
|
2309
|
+
p.finish();
|
|
2310
|
+
} catch (thrown) {
|
|
2311
|
+
return reasonOf(thrown);
|
|
2312
|
+
}
|
|
2313
|
+
const body = ["const out = [];", "for (let o = 0; o < n; o++) {", " try {", ...ind(ind(value.s)), ` out.push(${value.v.code});`, " } catch {", " out.push(VEX_ERROR);", " }", "}", "return out;"];
|
|
2314
|
+
return printModule(p, options, run, body);
|
|
2315
|
+
}
|
|
2316
|
+
|
|
2317
|
+
/** The budget of the stack of the search of a run of a sheet, as `STACK_BUDGET` of `SheetRun`. */
|
|
2318
|
+
const SHEET_BUDGET = 3000;
|
|
2319
|
+
|
|
2320
|
+
/** A formula of a sheet: its column, the position of its cell (undefined for the formula of the column) and its expression. */
|
|
2321
|
+
interface Formula {
|
|
2322
|
+
readonly column: string;
|
|
2323
|
+
readonly key: number | undefined;
|
|
2324
|
+
readonly expr: Expr;
|
|
2325
|
+
}
|
|
2326
|
+
|
|
2327
|
+
/** This function gives the words for a formula in a reason: the formula of a column, or of one cell. */
|
|
2328
|
+
const formulaText = (f: Formula): string => (f.key === undefined ? `the formula of the column "${f.column}"` : `the formula of the cell "${f.column}" at "${String(f.key)}"`);
|
|
2329
|
+
|
|
2330
|
+
/** This function gives the words for a kind in a reason. */
|
|
2331
|
+
const kindText = (k: Kind | undefined): string => k ?? "that the printer does not know";
|
|
2332
|
+
|
|
2333
|
+
/**
|
|
2334
|
+
* This function prints the formula columns of a sheet as a standalone ES module (COMPILE.MODULE.SHEET). The function of
|
|
2335
|
+
* the module takes the records and the variables, and the parents for a tree. It gives an object with an array for
|
|
2336
|
+
* each column: the result of the column at each key, or `VEX_ERROR`. The results are the results of `SheetRun`.
|
|
2337
|
+
*
|
|
2338
|
+
* The run fills the columns in the order of `SheetRun.fill`. A read of a finished cell is the read of an array. A read
|
|
2339
|
+
* of a cell that is not finished starts the search of `SheetRun`, with the same budget of the stack. Each cell on a
|
|
2340
|
+
* cycle of reads gives `VEX_ERROR`.
|
|
2341
|
+
*/
|
|
2342
|
+
export function emitSheetModule(columns: ReadonlyMap<string, Expr>, options: SheetModuleOptions): Emitted {
|
|
2343
|
+
const run = runOf(options);
|
|
2344
|
+
if ("reason" in run) return { ok: false, reason: run.reason };
|
|
2345
|
+
const budget = options.budget ?? SHEET_BUDGET;
|
|
2346
|
+
if (!Number.isSafeInteger(budget) || budget < 0) return { ok: false, reason: `the budget ${String(budget)} is not a whole number of 0 or more` };
|
|
2347
|
+
const cells: CellFormulas = options.cells ?? new Map();
|
|
2348
|
+
const names = [...new Set([...columns.keys(), ...cells.keys()])];
|
|
2349
|
+
const order = columnOrder(columns, cells);
|
|
2350
|
+
// The formulas in the order of the columns. A key of a cell that is not the text of a position is not a key of the
|
|
2351
|
+
// space, so no read finds its formula.
|
|
2352
|
+
const formulas: Formula[] = order.flatMap((column): Formula[] => {
|
|
2353
|
+
const own = [...(cells.get(column) ?? [])].filter(([k]) => /^(0|[1-9]\d*)$/.test(k) && Number.isSafeInteger(Number(k)));
|
|
2354
|
+
const formula = columns.get(column);
|
|
2355
|
+
return [...(formula === undefined ? [] : [{ column, key: undefined, expr: formula }]), ...own.map(([k, expr]) => ({ column, key: Number(k), expr }))];
|
|
2356
|
+
});
|
|
2357
|
+
for (const f of formulas) {
|
|
2358
|
+
// EVAL.SHAPE: the printer gives the reason for an expression that is not valid.
|
|
2359
|
+
const shape = shapeError(f.expr);
|
|
2360
|
+
if (shape !== undefined) return { ok: false, reason: `${formulaText(f)}: ${shape}` };
|
|
2361
|
+
}
|
|
2362
|
+
const kinds = new Map<string, Kind | undefined>(Object.entries(options.kinds ?? {}));
|
|
2363
|
+
const index = new Map(names.map((c, i) => [c, i]));
|
|
2364
|
+
// The memo of the printer covers each formula, so the formulas share their nodes of the memo.
|
|
2365
|
+
const p = new Printer(rec(Object.fromEntries(formulas.map((f, i) => [`f${String(i)}`, f.expr]))), options, { columns: index, kinds });
|
|
2366
|
+
const fns: string[] = [];
|
|
2367
|
+
const decls: string[] = [];
|
|
2368
|
+
try {
|
|
2369
|
+
for (const f of formulas) {
|
|
2370
|
+
const code = p.root(f.expr);
|
|
2371
|
+
const kind = code.v.kind;
|
|
2372
|
+
// The first formula of a column without a kind of the options gives the kind of the column.
|
|
2373
|
+
if (!kinds.has(f.column)) kinds.set(f.column, kind);
|
|
2374
|
+
else if (kinds.get(f.column) !== kind) throw new NotStandalone(`${formulaText(f)} gives a value of the kind ${kindText(kind)}, not of the kind ${kindText(kinds.get(f.column))} of its column`);
|
|
2375
|
+
const fn = p.fresh("cf");
|
|
2376
|
+
fns.push(fn);
|
|
2377
|
+
decls.push(...(code.v.safe && code.s.length === 0 ? [`const ${fn} = (o) => ${code.v.code};`] : [`const ${fn} = (o) => {`, " try {", ...ind(ind(code.s)), ` return ${code.v.code};`, " } catch {", " return E;", " }", "};"]));
|
|
2378
|
+
}
|
|
2379
|
+
p.finish();
|
|
2380
|
+
} catch (thrown) {
|
|
2381
|
+
return reasonOf(thrown);
|
|
2382
|
+
}
|
|
2383
|
+
// The program of each column, and of each cell with its own formula, with its cost in estimated frames, as in SheetRun.
|
|
2384
|
+
const entry = (i: number): string => `[${fns[i] as string}, ${String(3 * nestingOf((formulas[i] as Formula).expr) + 16)}]`;
|
|
2385
|
+
const own = names.map((c) => {
|
|
2386
|
+
const at = formulas.flatMap((f, i) => (f.column === c && f.key !== undefined ? [`${String(f.key)}: ${entry(i)}`] : []));
|
|
2387
|
+
return at.length === 0 ? "undefined" : `{ ${at.join(", ")} }`;
|
|
2388
|
+
});
|
|
2389
|
+
const cols = names.map((c) => {
|
|
2390
|
+
const i = formulas.findIndex((f) => f.column === c && f.key === undefined);
|
|
2391
|
+
return i < 0 ? "undefined" : entry(i);
|
|
2392
|
+
});
|
|
2393
|
+
p.use("SH");
|
|
2394
|
+
// A tree gives the keys in the order of a fill with the helper KO, once for each order.
|
|
2395
|
+
const orders = new Map<string, string>();
|
|
2396
|
+
const fill = order.map((c) => {
|
|
2397
|
+
const { reverse, post, back } = keyOrderOf(readsOf(columns, cells, c).directions);
|
|
2398
|
+
const at = String(index.get(c));
|
|
2399
|
+
if (!run.tree) return reverse ? `for (let o = n - 1; o >= 0; o--) SS.f(${at}, o);` : `for (let o = 0; o < n; o++) SS.f(${at}, o);`;
|
|
2400
|
+
const args = `${p.use("KO")}(H, RT, ${String(post)}, ${String(back)})`;
|
|
2401
|
+
let keys = orders.get(args);
|
|
2402
|
+
if (keys === undefined) {
|
|
2403
|
+
keys = p.fresh("K");
|
|
2404
|
+
orders.set(args, keys);
|
|
2405
|
+
}
|
|
2406
|
+
return `for (const o of ${keys}) SS.f(${at}, o);`;
|
|
2407
|
+
});
|
|
2408
|
+
if (run.tree) p.treeParts.add("children");
|
|
2409
|
+
const body = [
|
|
2410
|
+
...decls,
|
|
2411
|
+
`const SS = SH(n, [${cols.join(", ")}], [${own.join(", ")}], ${String(budget)});`,
|
|
2412
|
+
`const ${READ_CELL} = SS.r;`,
|
|
2413
|
+
...[...orders].map(([args, keys]) => `const ${keys} = ${args};`),
|
|
2414
|
+
...fill,
|
|
2415
|
+
`return { ${names.map((c, i) => `${JSON.stringify(c)}: SS.o(${String(i)})`).join(", ")} };`,
|
|
2416
|
+
];
|
|
2417
|
+
return printModule(p, options, run, body);
|
|
2418
|
+
}
|