@mark1russell7/vex-compiler 0.13.0 → 0.13.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/build/index.d.ts +4 -3
- package/build/index.d.ts.map +1 -1
- package/build/index.js +460 -66
- package/build/index.js.map +1 -1
- package/package.json +4 -4
- package/src/module.ts +407 -75
- package/src/runtime.ts +4 -0
- package/src/sheet-order.ts +56 -0
package/src/module.ts
CHANGED
|
@@ -15,19 +15,21 @@
|
|
|
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 or a
|
|
19
|
-
* the variables of the schema. It takes the axes `all`, `others` and `window`. A tree space also has the
|
|
20
|
-
* axes of a tree (COMPILE.MODULE.TREE).
|
|
21
|
-
*
|
|
18
|
+
* The printer takes a part of the language. It takes an array space, a tree space or a graph space of records, and
|
|
19
|
+
* the fields and the variables of the schema. It takes the axes `all`, `others` and `window`. A tree space also has the
|
|
20
|
+
* move `parent` and the axes of a tree (COMPILE.MODULE.TREE). A graph space has the axes of a graph
|
|
21
|
+
* (COMPILE.MODULE.GRAPH). A list is an array of pairs of a key and a value. The list ops, `reduce`, list literals and
|
|
22
|
+
* lists as names of loops are in a module (COMPILE.MODULE.LIST, COMPILE.MODULE.REDUCE). The kinds of each op site must
|
|
23
|
+
* decide its op. Another construct gives a reason, not code.
|
|
22
24
|
*
|
|
23
25
|
* `emitSheetModule` prints the formula columns of a sheet as one module (COMPILE.MODULE.SHEET). Each column is an array
|
|
24
26
|
* 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
27
|
* starts the search of `SheetRun`. Thus each cell on a cycle gives the error of Vex.
|
|
26
28
|
*/
|
|
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";
|
|
29
|
+
import { addrExprs, app, CELL_KIND, children, fromDocument, isDocument, isFieldName, isVexList, lit, moveExpr, nestingOf, rec, shapeError, type AnyDomain, type Axis, type CellFormulas, type Envelope, type Expr, type ExprOf, type Move, type Names, type PrimitiveKind, type VexList } from "@mark1russell7/vex";
|
|
28
30
|
import { factsOf, kindOfDomain, primitiveOf, type Facts, type Kind, type Schema } from "./facts.ts";
|
|
29
31
|
import { memoNodes } from "./memo.ts";
|
|
30
|
-
import { columnOrder, isCellRef, keyOrderOf, readsOf } from "./sheet-order.ts";
|
|
32
|
+
import { columnOrder, isCellRef, keyOrderOf, readsFinished, readsOf } from "./sheet-order.ts";
|
|
31
33
|
|
|
32
34
|
/** The options of a standalone module. */
|
|
33
35
|
export interface ModuleOptions {
|
|
@@ -40,11 +42,12 @@ export interface ModuleOptions {
|
|
|
40
42
|
*/
|
|
41
43
|
readonly name?: string;
|
|
42
44
|
/**
|
|
43
|
-
* The space of the records. In
|
|
45
|
+
* The space of the records. In each space, the key of a record is the text of its position. The default `array`
|
|
44
46
|
* 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.
|
|
47
|
+
* is the position of the parent of its record, or -1 for a root. A `graph` takes the edges as the third argument
|
|
48
|
+
* (COMPILE.MODULE.GRAPH). Each entry is an array of the positions of the ends of the edges from its record, in order.
|
|
46
49
|
*/
|
|
47
|
-
readonly space?: "array" | "tree";
|
|
50
|
+
readonly space?: "array" | "tree" | "graph";
|
|
48
51
|
}
|
|
49
52
|
|
|
50
53
|
/** The options of a module of a sheet (COMPILE.MODULE.SHEET): the options of a module, and the parts of a sheet. */
|
|
@@ -87,9 +90,24 @@ interface Value {
|
|
|
87
90
|
readonly list?: ListInfo | undefined;
|
|
88
91
|
}
|
|
89
92
|
|
|
90
|
-
/**
|
|
93
|
+
/**
|
|
94
|
+
* The facts of a list of the code: the kind of the values of its items, if the printer knows it. The key of an item is
|
|
95
|
+
* the position of its record, or the text of the key of a list literal (LIST.LITERAL).
|
|
96
|
+
*/
|
|
91
97
|
interface ListInfo {
|
|
92
98
|
readonly item: Kind | undefined;
|
|
99
|
+
/** For a list of lists (LIST.FLAT): the facts of each list that is the value of an item. Each item of such a list is an array. */
|
|
100
|
+
readonly inner?: ListInfo | undefined;
|
|
101
|
+
/** True when a key can be the text of a key of a literal. The focus of the axis list must be the position of a record. */
|
|
102
|
+
readonly texts?: boolean;
|
|
103
|
+
/** True for a list without items: the empty literal, and a list from it. Such a list fits each list. */
|
|
104
|
+
readonly empty?: boolean;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** The op of each step of `reduce` (COMPILE.MODULE.REDUCE): the name of the op, and the value of the option `domain`. */
|
|
108
|
+
interface Step {
|
|
109
|
+
readonly op: string;
|
|
110
|
+
readonly domain: unknown;
|
|
93
111
|
}
|
|
94
112
|
|
|
95
113
|
/** The code of a node: the statements before its value, and its value. `safe` covers the statements too. */
|
|
@@ -135,6 +153,8 @@ interface SheetInfo {
|
|
|
135
153
|
readonly columns: ReadonlyMap<string, number>;
|
|
136
154
|
/** The kind of each column that the printer knows: a kind of the options, or the kind of a printed formula. */
|
|
137
155
|
readonly kinds: Map<string, Kind | undefined>;
|
|
156
|
+
/** True when each read of a cell reads a finished cell, so a read starts no search (COMPILE.MODULE.SHEET.DIRECT). */
|
|
157
|
+
readonly direct: boolean;
|
|
138
158
|
}
|
|
139
159
|
|
|
140
160
|
/** This function gives the levels of some codes together. */
|
|
@@ -216,13 +236,19 @@ interface Spec {
|
|
|
216
236
|
}
|
|
217
237
|
|
|
218
238
|
/** The name of a helper of the generated code. */
|
|
219
|
-
type Helper = "F" | "C" | "T" | "L" | "Q" | "G" | "B" | "U" | "X" | "I" | "K" | "M" | "M1" | "S" | "V" | "SB" | "TK" | "NT" | TreeHelper | SheetHelper;
|
|
239
|
+
type Helper = "F" | "C" | "T" | "L" | "Q" | "G" | "B" | "U" | "X" | "I" | "K" | "M" | "M1" | "S" | "V" | "SB" | "TK" | "NT" | BuildHelper | TreeHelper | GraphHelper | SheetHelper;
|
|
240
|
+
|
|
241
|
+
/** The helpers of the list ops that build a list (LIST.BUILD), of `get` (LIST.GET) and of `indexOf` (LIST.INDEXOF). */
|
|
242
|
+
type BuildHelper = "DR" | "AP" | "WO" | "FL" | "GT" | "IX";
|
|
220
243
|
|
|
221
244
|
/** The helpers of a tree space (COMPILE.MODULE.TREE). */
|
|
222
245
|
type TreeHelper = "PT" | "CH" | "SG" | "PR" | "UP" | "SO" | "AN" | "BF";
|
|
223
246
|
|
|
247
|
+
/** The helpers of a graph space (COMPILE.MODULE.GRAPH). */
|
|
248
|
+
type GraphHelper = "GR" | "GI" | "RB";
|
|
249
|
+
|
|
224
250
|
/** 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";
|
|
251
|
+
type SheetHelper = "SH" | "KO" | "DO";
|
|
226
252
|
|
|
227
253
|
/** The helpers of the generated code. A module has only the helpers that it uses. */
|
|
228
254
|
const HELPERS: Readonly<Record<Exclude<Helper, "S">, string>> = {
|
|
@@ -255,6 +281,50 @@ const HELPERS: Readonly<Record<Exclude<Helper, "S">, string>> = {
|
|
|
255
281
|
].join("\n"),
|
|
256
282
|
TK: "function TK(l, n, s) { const o = V(l, s); return Number.isSafeInteger(n) && n >= 0 ? o.slice(0, n) : F(); }",
|
|
257
283
|
NT: "function NT(l, i, s) { const o = V(l, s); return Number.isSafeInteger(i) && i >= 0 && i < o.length ? o[i][1] : F(); }",
|
|
284
|
+
// The ops that build a list (LIST.BUILD) keep the key and the value of each item. A key is a position or a text, so
|
|
285
|
+
// `without` and `get` compare the text of each key. A list is an array that does not change after the op that makes it.
|
|
286
|
+
DR: "function DR(l, n, s) { const o = V(l, s); return Number.isSafeInteger(n) && n >= 0 ? o.slice(n) : F(); }",
|
|
287
|
+
AP: "function AP(l, o, s) { return V(l, s).concat(V(o, s)); }",
|
|
288
|
+
WO: [
|
|
289
|
+
"function WO(l, o, s) {",
|
|
290
|
+
" const a = V(l, s), g = new Map();",
|
|
291
|
+
" for (const [k] of V(o, s)) g.set(`${k}`, 1);",
|
|
292
|
+
" return a.filter((x) => !g.has(`${x[0]}`));",
|
|
293
|
+
"}",
|
|
294
|
+
].join("\n"),
|
|
295
|
+
FL: [
|
|
296
|
+
"function FL(l, s) {",
|
|
297
|
+
" const o = [];",
|
|
298
|
+
" for (const [, v] of V(l, s)) for (const x of V(v, s)) o.push(x);",
|
|
299
|
+
" return o;",
|
|
300
|
+
"}",
|
|
301
|
+
].join("\n"),
|
|
302
|
+
// The index of the keys of a list (LIST.GET): the value of the first item of each key. The array keeps its index, so a
|
|
303
|
+
// step that reads each key of a list of n items costs O(n). The key E marks an error item, for strict.
|
|
304
|
+
GT: [
|
|
305
|
+
"function GT(l, k, s) {",
|
|
306
|
+
" let x = l.ix;",
|
|
307
|
+
" if (x === undefined) {",
|
|
308
|
+
" x = new Map();",
|
|
309
|
+
" for (const [q, v] of l) {",
|
|
310
|
+
" const t = `${q}`;",
|
|
311
|
+
" if (v === E) x.set(E, E);",
|
|
312
|
+
" else if (!x.has(t)) x.set(t, v);",
|
|
313
|
+
" }",
|
|
314
|
+
" l.ix = x;",
|
|
315
|
+
" }",
|
|
316
|
+
' return (s && x.has(E)) || typeof k !== "string" || !x.has(k) ? F() : x.get(k);',
|
|
317
|
+
"}",
|
|
318
|
+
].join("\n"),
|
|
319
|
+
// The position of the first value among the items with a value (LIST.INDEXOF). `===` compares the values.
|
|
320
|
+
IX: [
|
|
321
|
+
"function IX(l, x, s) {",
|
|
322
|
+
" const o = V(l, s);",
|
|
323
|
+
' if (typeof x !== "number" && typeof x !== "string" && typeof x !== "boolean") F();',
|
|
324
|
+
" for (let i = 0; i < o.length; i++) if (o[i][1] === x) return i;",
|
|
325
|
+
" return F();",
|
|
326
|
+
"}",
|
|
327
|
+
].join("\n"),
|
|
258
328
|
// 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
329
|
// 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
330
|
PT: [
|
|
@@ -321,9 +391,37 @@ const HELPERS: Readonly<Record<Exclude<Helper, "S">, string>> = {
|
|
|
321
391
|
AN: "function AN(P, k) { const o = []; for (let p = P[k]; p >= 0; p = P[p]) o.push(p); return o; }",
|
|
322
392
|
// 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
393
|
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; }",
|
|
394
|
+
// The edges of a graph space: the positions of the ends of the edges from each record, in order. A second edge to the
|
|
395
|
+
// same end is the same edge, as in the interpreter. The mark of an end is the number of its record plus 1.
|
|
396
|
+
GR: [
|
|
397
|
+
"function GR(e, n) {",
|
|
398
|
+
' if (!Array.isArray(e) || e.length !== n) C("the edges are not an array with the ends of the edges of each record");',
|
|
399
|
+
" const O = [], s = new Int32Array(n);",
|
|
400
|
+
" for (let i = 0; i < n; i++) {",
|
|
401
|
+
" const x = e[i];",
|
|
402
|
+
" if (!Array.isArray(x)) C(`the edges of the record ${i} are not an array`);",
|
|
403
|
+
" const o = [];",
|
|
404
|
+
" for (const t of x) {",
|
|
405
|
+
" if (!(Number.isInteger(t) && t >= 0 && t < n)) C(`an edge of the record ${i} does not go to the position of a record`);",
|
|
406
|
+
" if (s[t] !== i + 1) {",
|
|
407
|
+
" s[t] = i + 1;",
|
|
408
|
+
" o.push(t);",
|
|
409
|
+
" }",
|
|
410
|
+
" }",
|
|
411
|
+
" O.push(o);",
|
|
412
|
+
" }",
|
|
413
|
+
" return O;",
|
|
414
|
+
"}",
|
|
415
|
+
].join("\n"),
|
|
416
|
+
// The predecessors of each record of a graph, in key order: the records in key order, and the ends of the edges of each record.
|
|
417
|
+
GI: "function GI(O, n) { const I = []; for (let i = 0; i < n; i++) I.push([]); for (let i = 0; i < n; i++) for (const t of O[i]) I[t].push(i); return I; }",
|
|
418
|
+
// The record and the keys that a path of edges reaches from it, once, in the order of a breadth-first search.
|
|
419
|
+
RB: "function RB(O, k, n) { const s = new Uint8Array(n), o = [k]; s[k] = 1; for (let i = 0; i < o.length; i++) for (const c of O[o[i]]) if (s[c] === 0) { s[c] = 1; o.push(c); } return o; }",
|
|
324
420
|
// The state of a run of a sheet (COMPILE.MODULE.SHEET), as in SheetRun: the result of each finished cell, the search
|
|
325
421
|
// 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
422
|
// A cell without a formula has the error sentinel from the start, as the error of its read.
|
|
423
|
+
// A column of a direct fill (COMPILE.MODULE.SHEET.DIRECT): the error sentinel of a cell changes to VEX_ERROR.
|
|
424
|
+
DO: "function DO(d) { for (let k = 0; k < d.length; k++) if (d[k] === E) d[k] = VEX_ERROR; return d; }",
|
|
327
425
|
SH: [
|
|
328
426
|
"function SH(n, cols, own, budget) {",
|
|
329
427
|
" const pg = (c, k) => {",
|
|
@@ -608,15 +706,17 @@ const STEPS: Readonly<Record<string, readonly [string, string]>> = {
|
|
|
608
706
|
/** The helpers that each helper uses. */
|
|
609
707
|
const NEEDS: Readonly<Record<Helper, readonly Helper[]>> = {
|
|
610
708
|
F: [], C: [], T: [], L: [], Q: [], G: ["F"], B: ["F"], U: ["F"], X: ["F"], I: ["F"], K: ["F"], M: ["G"], M1: ["G"], S: ["M1", "F"],
|
|
611
|
-
// Only
|
|
709
|
+
// Only the helpers of the list ops use V, and each of them needs F too, so the need of V only completes the list.
|
|
612
710
|
// Stryker disable next-line ArrayDeclaration: see the comment above
|
|
613
711
|
V: ["F"],
|
|
614
712
|
SB: ["V", "F"], TK: ["V", "F"], NT: ["V", "F"],
|
|
713
|
+
DR: ["V", "F"], AP: ["V"], WO: ["V"], FL: ["V"], GT: ["F"], IX: ["V", "F"],
|
|
615
714
|
// Each module has C, and each move uses F (#move), so these needs only complete the list.
|
|
616
715
|
// Stryker disable next-line ArrayDeclaration: see the comment above
|
|
617
|
-
PT: ["C"], UP: ["F"], SO: ["F"],
|
|
716
|
+
PT: ["C"], GR: ["C"], UP: ["F"], SO: ["F"],
|
|
618
717
|
CH: [], SG: [], PR: [], AN: [], BF: [],
|
|
619
|
-
|
|
718
|
+
GI: [], RB: [],
|
|
719
|
+
SH: [], KO: [], DO: [],
|
|
620
720
|
};
|
|
621
721
|
|
|
622
722
|
/** The parts of a tree that a run computes before the loop over its keys, if the program needs them. */
|
|
@@ -638,6 +738,9 @@ const TREE_AXES: ReadonlySet<string> = new Set(["children", "ancestors", "descen
|
|
|
638
738
|
/** This function tells if an axis has its targets in a range of an array of positions in a tree space. */
|
|
639
739
|
const isTreeAxis = (a: Axis): a is TreeAxis => a.t === "window" || TREE_AXES.has(a.t);
|
|
640
740
|
|
|
741
|
+
/** The axes of a graph space in a module (COMPILE.MODULE.GRAPH), other than the axes of each space. */
|
|
742
|
+
const GRAPH_AXES: ReadonlySet<string> = new Set(["successors", "predecessors", "reachable"]);
|
|
743
|
+
|
|
641
744
|
/**
|
|
642
745
|
* 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
746
|
* to `hi`. The loop skips the key `skip`.
|
|
@@ -652,13 +755,80 @@ interface TreeRange {
|
|
|
652
755
|
|
|
653
756
|
/** The list ops of a standalone module. */
|
|
654
757
|
const LIST_OPS: ReadonlySet<string> = new Set(["count", "sum", "mean", "min", "max", "any", "all", "none", "first"]);
|
|
758
|
+
/** The list ops with a running value in a module: the list ops above, and `reduce` with the op of a domain (COMPILE.MODULE.REDUCE). */
|
|
759
|
+
const FOLD_OPS: ReadonlySet<string> = new Set([...LIST_OPS, "reduce"]);
|
|
655
760
|
const NUMBER_LIST_OPS: ReadonlySet<string> = new Set(["count", "sum", "mean", "min", "max"]);
|
|
656
761
|
const BOOLEAN_LIST_OPS: ReadonlySet<string> = new Set(["any", "all", "none"]);
|
|
657
|
-
/** The list ops
|
|
658
|
-
const BUILD_OPS: ReadonlySet<string> = new Set(["
|
|
762
|
+
/** The list ops over lists of `#build`: append, without and flat (LIST.BUILD), get (LIST.GET) and indexOf (LIST.INDEXOF). */
|
|
763
|
+
const BUILD_OPS: ReadonlySet<string> = new Set(["append", "without", "flat", "get", "indexOf"]);
|
|
764
|
+
|
|
765
|
+
/** The helper of each op of `#build`. */
|
|
766
|
+
const BUILD_HELPERS: Readonly<Record<string, BuildHelper>> = { append: "AP", without: "WO", flat: "FL", get: "GT", indexOf: "IX" };
|
|
767
|
+
|
|
768
|
+
/** The list ops whose value is a list (LIST.SORT, LIST.TAKE and LIST.BUILD). */
|
|
769
|
+
const LIST_RESULTS: ReadonlySet<string> = new Set(["sortBy", "take", "drop", "append", "without", "flat"]);
|
|
770
|
+
|
|
771
|
+
/**
|
|
772
|
+
* This function tells if an expression gives a list. An each, a list literal and a list op of `LIST_RESULTS` give a
|
|
773
|
+
* list. A name of a list, and a let or a loop whose result is a list, give a list too. `isName` tells if a name outside the expression holds a list.
|
|
774
|
+
*/
|
|
775
|
+
function listy(e: Expr, isName: (name: string) => boolean): boolean {
|
|
776
|
+
switch (e.tag) {
|
|
777
|
+
case "each":
|
|
778
|
+
return true;
|
|
779
|
+
case "lit":
|
|
780
|
+
return isVexList(e.value);
|
|
781
|
+
case "app":
|
|
782
|
+
return LIST_RESULTS.has(e.op);
|
|
783
|
+
case "var":
|
|
784
|
+
return isName(e.name);
|
|
785
|
+
case "let":
|
|
786
|
+
return listy(e.body, namesIn(e.bind, isName));
|
|
787
|
+
case "fold":
|
|
788
|
+
case "iterate":
|
|
789
|
+
return listy(e.result, namesIn(e.init, isName));
|
|
790
|
+
case "call":
|
|
791
|
+
case "ext":
|
|
792
|
+
case "fn":
|
|
793
|
+
case "rec":
|
|
794
|
+
case "ref":
|
|
795
|
+
return false;
|
|
796
|
+
}
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
/** This function tells if a name holds a list in the scope of some bindings. A binding hides a name outside, and a function is not a list. */
|
|
800
|
+
function namesIn(bind: Readonly<Record<string, Expr>>, isName: (name: string) => boolean): (name: string) => boolean {
|
|
801
|
+
const lists = new Map(Object.entries(bind).map(([name, x]) => [name, x.tag !== "fn" && listy(x, isName)]));
|
|
802
|
+
return (name) => lists.get(name) ?? isName(name);
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
/** This function tells if an expression has a list literal with an item, so a key of the list can be a text (LIST.LITERAL). */
|
|
806
|
+
function hasKeyedLiteral(e: Expr): boolean {
|
|
807
|
+
return (e.tag === "lit" && isVexList(e.value) && e.value.items.length > 0) || children(e).some(hasKeyedLiteral);
|
|
808
|
+
}
|
|
809
|
+
|
|
810
|
+
/** This function gives the facts of the list of `append` from the facts of its two lists. An empty list fits each list. */
|
|
811
|
+
function joinLists(a: ListInfo, b: ListInfo): ListInfo {
|
|
812
|
+
if (a.empty === true) return b;
|
|
813
|
+
if (b.empty === true) return a;
|
|
814
|
+
if ((a.inner === undefined) !== (b.inner === undefined)) throw new NotStandalone('"append" of a list of lists and a list of values');
|
|
815
|
+
const texts = a.texts === true || b.texts === true;
|
|
816
|
+
return { item: join(a.item, b.item), inner: a.inner === undefined ? undefined : joinLists(a.inner, b.inner as ListInfo), texts };
|
|
817
|
+
}
|
|
818
|
+
|
|
819
|
+
/**
|
|
820
|
+
* This function tells if a list of a step fits the list of a name of a loop (LOOP.LIST). The items of the step have the
|
|
821
|
+
* kind of the items of the name, if the name has one. The name also has the text keys and the lists of lists of the step.
|
|
822
|
+
*/
|
|
823
|
+
function fits(name: ListInfo, step: ListInfo): boolean {
|
|
824
|
+
if (step.empty === true) return true;
|
|
825
|
+
if (name.item !== undefined && step.item !== name.item) return false;
|
|
826
|
+
if (step.texts === true && name.texts !== true) return false;
|
|
827
|
+
return name.inner === undefined ? step.inner === undefined : step.inner !== undefined && fits(name.inner, step.inner);
|
|
828
|
+
}
|
|
659
829
|
|
|
660
830
|
/** 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");
|
|
831
|
+
const stepThrows = (op: string, kind: Kind | undefined): boolean => op === "reduce" || (NUMBER_STEPS.has(op) && kind !== "number") || (BOOLEAN_LIST_OPS.has(op) && kind !== "boolean");
|
|
662
832
|
|
|
663
833
|
/** The list ops whose step takes a number. */
|
|
664
834
|
const NUMBER_STEPS: ReadonlySet<string> = new Set(["sum", "mean", "min", "max"]);
|
|
@@ -949,6 +1119,9 @@ class Printer {
|
|
|
949
1119
|
/** True for a tree space, and the parts of the tree that the program reads (COMPILE.MODULE.TREE). */
|
|
950
1120
|
readonly #tree: boolean;
|
|
951
1121
|
readonly treeParts = new Set<TreePart>();
|
|
1122
|
+
/** True for a graph space, and true when the program reads the predecessors of a graph (COMPILE.MODULE.GRAPH). */
|
|
1123
|
+
readonly #graph: boolean;
|
|
1124
|
+
into = false;
|
|
952
1125
|
/** The columns of a sheet, for a module of a sheet (COMPILE.MODULE.SHEET). */
|
|
953
1126
|
readonly #sheet: SheetInfo | undefined;
|
|
954
1127
|
#names = 0;
|
|
@@ -993,6 +1166,7 @@ class Printer {
|
|
|
993
1166
|
this.#schema = options.schema;
|
|
994
1167
|
this.#memo = memoOf(expr);
|
|
995
1168
|
this.#tree = options.space === "tree";
|
|
1169
|
+
this.#graph = options.space === "graph";
|
|
996
1170
|
this.#sheet = sheet;
|
|
997
1171
|
}
|
|
998
1172
|
|
|
@@ -1159,11 +1333,18 @@ class Printer {
|
|
|
1159
1333
|
return c;
|
|
1160
1334
|
}
|
|
1161
1335
|
|
|
1162
|
-
/** This method tells if an expression gives a list at a place that takes one
|
|
1336
|
+
/** This method tells if an expression gives a list at a place that takes one (`listy`). */
|
|
1163
1337
|
#isList(e: Expr, ctx: Ctx): boolean {
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1338
|
+
return listy(e, (name) => ctx.env.get(name)?.list !== undefined);
|
|
1339
|
+
}
|
|
1340
|
+
|
|
1341
|
+
/** This method prints a list literal (LIST.LITERAL) as an array of pairs of a key and a value. An error item holds the sentinel. */
|
|
1342
|
+
#listLiteral(l: VexList): Code {
|
|
1343
|
+
const values = l.items.map((it) => (it.result.ok ? literal(it.result.value) : undefined));
|
|
1344
|
+
const kinds = values.flatMap((x) => (x === undefined ? [] : [x.kind]));
|
|
1345
|
+
const code = `[${l.items.map((it, i) => `[${JSON.stringify(it.key)}, ${values[i]?.code ?? "E"}]`).join(", ")}]`;
|
|
1346
|
+
const has = l.items.length > 0;
|
|
1347
|
+
return bare({ code, kind: undefined, safe: true, deps: NO_DEPS, list: { item: kinds.reduce(join, kinds[0]), texts: has, empty: !has } });
|
|
1167
1348
|
}
|
|
1168
1349
|
|
|
1169
1350
|
/**
|
|
@@ -1256,7 +1437,7 @@ class Printer {
|
|
|
1256
1437
|
#node(e: Expr, ctx: Ctx): Code {
|
|
1257
1438
|
switch (e.tag) {
|
|
1258
1439
|
case "lit":
|
|
1259
|
-
return bare(literal(e.value));
|
|
1440
|
+
return isVexList(e.value) ? this.#listLiteral(e.value) : bare(literal(e.value));
|
|
1260
1441
|
case "ref":
|
|
1261
1442
|
return this.#ref(e, ctx);
|
|
1262
1443
|
case "var":
|
|
@@ -1327,6 +1508,8 @@ class Printer {
|
|
|
1327
1508
|
* must read no cell.
|
|
1328
1509
|
*/
|
|
1329
1510
|
#inOrder(parts: readonly Code[], all: boolean): readonly Code[] {
|
|
1511
|
+
// A read of a finished cell starts no search, so the order of the reads does not change a result.
|
|
1512
|
+
if (this.#sheet?.direct === true) return parts;
|
|
1330
1513
|
const last = parts.findLastIndex((x) => x.v.deps.has(CELLS));
|
|
1331
1514
|
const after = parts.slice(last + 1).every((x) => x.s.length === 0 || x.v.safe);
|
|
1332
1515
|
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);
|
|
@@ -1386,7 +1569,8 @@ class Printer {
|
|
|
1386
1569
|
// Stryker disable next-line ConditionalExpression,StringLiteral: see #address
|
|
1387
1570
|
/* v8 ignore next -- @preserve */
|
|
1388
1571
|
if (focus === undefined) throw new NotStandalone("a node of the memo reads its focus");
|
|
1389
|
-
|
|
1572
|
+
// A graph space has no offsets (NAV.OFFSET), so an offset fails at each key.
|
|
1573
|
+
if (this.#graph || d === undefined || more.length > 0 || !Number.isInteger(d)) return `${F}()`;
|
|
1390
1574
|
// In a tree space, an offset goes among the siblings (NAV.OFFSET.TREE).
|
|
1391
1575
|
if (this.#tree) return `${this.use("SO")}(${this.#part("siblings", "GP")}, SI, ${focus}, ${d})`;
|
|
1392
1576
|
return `${this.use("X")}(${focus} + ${d}, n)`;
|
|
@@ -1466,7 +1650,7 @@ class Printer {
|
|
|
1466
1650
|
* A binding is a variable. A binding with an error is an error only where the body reads its name, so the variable
|
|
1467
1651
|
* can hold the sentinel. A binding that is a constant of the run is the variable of that constant.
|
|
1468
1652
|
*/
|
|
1469
|
-
#let(e: ExprOf<"let">, ctx: Ctx): Code {
|
|
1653
|
+
#let(e: ExprOf<"let">, ctx: Ctx, wrap?: (body: Expr) => Expr): Code {
|
|
1470
1654
|
const env = new Map(ctx.env);
|
|
1471
1655
|
const fns = new Map(ctx.fns);
|
|
1472
1656
|
const s: string[] = [];
|
|
@@ -1501,8 +1685,12 @@ class Printer {
|
|
|
1501
1685
|
// The statements of the binding read its keys, so the let is not a constant of the run.
|
|
1502
1686
|
deps = new Set([...deps, ...c.v.deps]);
|
|
1503
1687
|
}
|
|
1504
|
-
|
|
1505
|
-
const
|
|
1688
|
+
// A list op over a let is the list op over its body, in the scope of its bindings (`#app`).
|
|
1689
|
+
const inner = wrap === undefined ? e.body : wrap(e.body);
|
|
1690
|
+
// A let at a place that takes a list gives its body there (LIST.VALUE).
|
|
1691
|
+
if (this.#wantList.has(e)) this.#wantList.add(inner);
|
|
1692
|
+
if (root !== undefined) root.root = inner;
|
|
1693
|
+
const body = this.expr(inner, { ...ctx, env, fns });
|
|
1506
1694
|
// A function that reads names of the place of the binding comes after them, before the body.
|
|
1507
1695
|
return { s: [...s, ...bound.flatMap((b) => b.decls), ...body.s], v: { ...body.v, deps: new Set([...deps, ...body.v.deps]) } };
|
|
1508
1696
|
}
|
|
@@ -1593,15 +1781,25 @@ class Printer {
|
|
|
1593
1781
|
if (op === "and" || op === "or") return this.#andOr(op === "and", args, ctx);
|
|
1594
1782
|
if (op === "ifError") return this.#ifError(args, ctx);
|
|
1595
1783
|
const [head] = args;
|
|
1596
|
-
|
|
1597
|
-
|
|
1598
|
-
|
|
1599
|
-
|
|
1600
|
-
|
|
1784
|
+
const rest = args.slice(1);
|
|
1785
|
+
// An each whose body is a list gives a list of lists (LIST.FLAT), so a list op over it goes over its array.
|
|
1786
|
+
if (FOLD_OPS.has(op) && head?.tag === "each" && !this.#isList(head.body, ctx)) return this.#list(op, head, rest, ctx);
|
|
1787
|
+
// A list op over a let with only literal options is the list op over the body of the let, so an each in the body
|
|
1788
|
+
// is one loop with a running value, not an array. A builder sheet prints such a let, for example `sum(let($0 = 0, each(…)))`.
|
|
1789
|
+
if (FOLD_OPS.has(op) && head?.tag === "let" && rest.every((x) => x.tag === "lit")) return this.#let(head, ctx, (body) => app(op, body, ...rest));
|
|
1790
|
+
// sortBy and take are list ops for each receiver. Each other list op needs a list, and a domain can have its name.
|
|
1791
|
+
if (head !== undefined && (op === "sortBy" || op === "take" || (op === "drop" && this.#isList(head, ctx)))) return this.#order(op, head, rest, ctx);
|
|
1792
|
+
if (head !== undefined && BUILD_OPS.has(op) && this.#isList(head, ctx)) return this.#build(op, head, rest, ctx);
|
|
1793
|
+
if (head !== undefined && (FOLD_OPS.has(op) || op === "nth") && this.#isList(head, ctx)) return this.#overList(op, head, rest, ctx);
|
|
1601
1794
|
const raw = args.map((x) => this.expr(x, ctx));
|
|
1602
1795
|
const deps = depsOf(...raw);
|
|
1603
1796
|
// The interpreter evaluates each argument, also after an error.
|
|
1604
1797
|
const values = this.#inOrder(this.#settle(raw, deps, args), true);
|
|
1798
|
+
return this.#opCall(op, values, deps);
|
|
1799
|
+
}
|
|
1800
|
+
|
|
1801
|
+
/** This method prints the call of the op of a domain on some values, from the static site of their kinds. */
|
|
1802
|
+
#opCall(op: string, values: readonly Code[], deps: ReadonlySet<number>): Code {
|
|
1605
1803
|
const site = this.#facts.staticSite(op, values.map((x) => x.v.kind));
|
|
1606
1804
|
if (site?.t !== "fn") throw new NotStandalone(`the kinds of the values of "${op}" do not decide its op`);
|
|
1607
1805
|
if (site.bad) return { s: stmtsOf(...values), v: { code: `${this.use("F")}()`, kind: site.returns, safe: false, deps } };
|
|
@@ -1688,15 +1886,28 @@ class Printer {
|
|
|
1688
1886
|
* This method gives the option strict of a list op. The options must be one literal with only strict. Only a literal
|
|
1689
1887
|
* has a value, so another expression gives the reason too.
|
|
1690
1888
|
*/
|
|
1691
|
-
#strict(op: string, rest: readonly Expr[]): boolean {
|
|
1889
|
+
#strict(op: string, rest: readonly Expr[], names: readonly string[] = ["strict"]): boolean {
|
|
1692
1890
|
const [options, ...more] = rest;
|
|
1693
1891
|
if (more.length > 0) throw new NotStandalone(`"${op}" with more than one option`);
|
|
1694
1892
|
if (options === undefined) return false;
|
|
1695
1893
|
const opts = (options as { readonly value?: unknown }).value;
|
|
1696
|
-
if (typeof opts !== "object" || opts === null || Object.keys(opts).some((k) => k
|
|
1894
|
+
if (typeof opts !== "object" || opts === null || Object.keys(opts).some((k) => !names.includes(k))) throw new NotStandalone(`the options of "${op}" are not a literal with ${names.join(" or ")}`);
|
|
1697
1895
|
return (opts as { readonly strict?: unknown }).strict === true;
|
|
1698
1896
|
}
|
|
1699
1897
|
|
|
1898
|
+
/**
|
|
1899
|
+
* This method gives the option strict of a list op. For `reduce`, it also gives the op of each step: the first
|
|
1900
|
+
* argument, a literal text, and the value of the option `domain` (COMPILE.MODULE.REDUCE).
|
|
1901
|
+
*/
|
|
1902
|
+
#foldOptions(op: string, rest: readonly Expr[]): { readonly strict: boolean; readonly step: Step | undefined } {
|
|
1903
|
+
if (op !== "reduce") return { strict: this.#strict(op, rest), step: undefined };
|
|
1904
|
+
const [name, ...options] = rest;
|
|
1905
|
+
const value = (name as { readonly value?: unknown } | undefined)?.value;
|
|
1906
|
+
if (name?.tag !== "lit" || typeof value !== "string") throw new NotStandalone('"reduce" without a literal text as its op');
|
|
1907
|
+
const strict = this.#strict(op, options, ["strict", "domain"]);
|
|
1908
|
+
return { strict, step: { op: value, domain: (options[0] as { readonly value?: { readonly domain?: unknown } } | undefined)?.value?.domain } };
|
|
1909
|
+
}
|
|
1910
|
+
|
|
1700
1911
|
/**
|
|
1701
1912
|
* A list op over an axis: one `for` loop with a running value. An item with an error is skipped, and with `strict` it
|
|
1702
1913
|
* is an error of the list op. A value of the wrong kind is an error of the list op, as in the interpreter.
|
|
@@ -1732,6 +1943,8 @@ class Printer {
|
|
|
1732
1943
|
if (base.t === "list") {
|
|
1733
1944
|
if (at.length > 0) throw new NotStandalone('the axis "list" with an address');
|
|
1734
1945
|
const list = this.#hoist(this.#listOf(base.list, ctx), hasLoop(base.list));
|
|
1946
|
+
// The focus of a target is the position of a record, so a list with the keys of a literal has no loop of a module.
|
|
1947
|
+
if ((list.v.list as ListInfo).texts === true) throw new NotStandalone('the axis "list" over a list with the keys of a literal');
|
|
1735
1948
|
const a = this.fresh("A");
|
|
1736
1949
|
const q = this.fresh("q");
|
|
1737
1950
|
const head = reverse ? `for (let ${q} = ${a}.length - 1; ${q} >= 0; ${q}--) {` : `for (let ${q} = 0; ${q} < ${a}.length; ${q}++) {`;
|
|
@@ -1761,6 +1974,13 @@ class Printer {
|
|
|
1761
1974
|
const q = this.fresh("q");
|
|
1762
1975
|
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
1976
|
}
|
|
1977
|
+
// In a graph space, the targets of an axis of a graph are an array of positions. A graph has no offsets and no tree.
|
|
1978
|
+
if (this.#graph && GRAPH_AXES.has(base.t)) {
|
|
1979
|
+
const range = this.#graphRange(base.t, f as string);
|
|
1980
|
+
const q = this.fresh("q");
|
|
1981
|
+
return { s: [...s, ...range.s], j, head: forHead(q, range.lo, range.hi, reverse), key: [`const ${j} = ${range.a}[${q}];`], check: [], skip: undefined, fixed: false, start, startSafe, tests, inner };
|
|
1982
|
+
}
|
|
1983
|
+
if (this.#graph && base.t === "window") throw new NotStandalone('the axis "window" in a graph space');
|
|
1764
1984
|
if (base.t === "others") skip = f;
|
|
1765
1985
|
else if (base.t === "window") {
|
|
1766
1986
|
const h = this.fresh("h");
|
|
@@ -1771,6 +1991,21 @@ class Printer {
|
|
|
1771
1991
|
return { s, j, head: forHead(j, lo, hi, reverse), key: [], check: [], skip, fixed: f === undefined, start, startSafe, tests, inner };
|
|
1772
1992
|
}
|
|
1773
1993
|
|
|
1994
|
+
/**
|
|
1995
|
+
* This method gives the targets of an axis of a graph space at the position `f` (AXIS.GRAPH). They are the positions
|
|
1996
|
+
* `a[q]` for `q` from `lo` up to `hi`. The first key of the search of `reachable` is the focus, which is not a target.
|
|
1997
|
+
*/
|
|
1998
|
+
#graphRange(t: string, f: string): TreeRange {
|
|
1999
|
+
const a = this.fresh("A");
|
|
2000
|
+
const range = (code: string, lo = "0"): TreeRange => ({ s: [`const ${a} = ${code};`], a, lo, hi: `${a}.length`, skip: undefined });
|
|
2001
|
+
if (t === "successors") return range(`GO[${f}]`);
|
|
2002
|
+
if (t === "predecessors") {
|
|
2003
|
+
this.into = true;
|
|
2004
|
+
return range(`GN[${f}]`);
|
|
2005
|
+
}
|
|
2006
|
+
return range(`${this.use("RB")}(GO, ${f}, n)`, "1");
|
|
2007
|
+
}
|
|
2008
|
+
|
|
1774
2009
|
/**
|
|
1775
2010
|
* 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
2011
|
* from `lo` up to `hi`, without the key that the loop skips. The axes come from AXIS.TREE, AXIS.GRAPH and AXIS.WINDOW.
|
|
@@ -1809,7 +2044,7 @@ class Printer {
|
|
|
1809
2044
|
}
|
|
1810
2045
|
|
|
1811
2046
|
#list(op: string, target: ExprOf<"each">, rest: readonly Expr[], ctx: Ctx): Code {
|
|
1812
|
-
const strict = this.#
|
|
2047
|
+
const { strict, step } = this.#foldOptions(op, rest);
|
|
1813
2048
|
const at = target.at ?? [];
|
|
1814
2049
|
const { s, j, head, key, check, skip, fixed, start, startSafe, tests, inner } = this.#targetLoop(target.axis, at, ctx);
|
|
1815
2050
|
const { level } = inner;
|
|
@@ -1821,7 +2056,7 @@ class Printer {
|
|
|
1821
2056
|
// itself gives `#CYCLE!`.
|
|
1822
2057
|
if (op === "count" && fixed && tests.length === 0 && body.v.safe && !body.v.deps.has(CELLS)) return bare(plainValue("n", "number"));
|
|
1823
2058
|
const deps = new Set([...start, ...[body, ...testCodes].flatMap((x) => [...x.v.deps])].filter((d) => d !== level));
|
|
1824
|
-
const r = this.#reduction(op, body.v.kind);
|
|
2059
|
+
const r = this.#reduction(op, body.v.kind, step);
|
|
1825
2060
|
const { v } = r;
|
|
1826
2061
|
s.push(r.init);
|
|
1827
2062
|
const item = [...check, ...testCodes.flatMap((t) => [...t.s, `if (!${this.#boolean(t.v)}) continue;`]), ...body.s];
|
|
@@ -1834,7 +2069,7 @@ class Printer {
|
|
|
1834
2069
|
const x = this.fresh("x");
|
|
1835
2070
|
const all = [...key, ...(skip === undefined ? [] : [`if (${j} === ${skip}) continue;`]), `let ${x};`, "try {", ...ind(item), ` ${x} = ${body.v.code};`, "} catch {", ` ${x} = E;`, "}", `${list}.push(${x});`];
|
|
1836
2071
|
const reduce = [`for (const ${v} of ${list}) {`, ` if (${v} === E) ${strict ? `${this.use("F")}();` : "continue;"}`, ` ${r.step}`, "}"];
|
|
1837
|
-
return { s: [...s, `const ${list} = [];`, head, ...ind(all), "}", ...reduce], v: { code: r.result, kind:
|
|
2072
|
+
return { s: [...s, `const ${list} = [];`, head, ...ind(all), "}", ...reduce], v: { code: r.result, kind: r.kind, safe: false, deps } };
|
|
1838
2073
|
}
|
|
1839
2074
|
const loop = [
|
|
1840
2075
|
...key,
|
|
@@ -1848,17 +2083,18 @@ class Printer {
|
|
|
1848
2083
|
// A count without strict, and any, all and none over booleans without strict, cannot fail. The address of the axis
|
|
1849
2084
|
// can fail, except at the focus or at the origin.
|
|
1850
2085
|
const safe = startSafe && !strict && (op === "count" || (BOOLEAN_LIST_OPS.has(op) && body.v.kind === "boolean"));
|
|
1851
|
-
return { s, v: { code: r.result, kind:
|
|
2086
|
+
return { s, v: { code: r.result, kind: r.kind, safe, deps } };
|
|
1852
2087
|
}
|
|
1853
2088
|
|
|
1854
2089
|
/**
|
|
1855
2090
|
* This method gives the parts of a list op that reduces the values of its items. The parts are the variable `v` of
|
|
1856
2091
|
* the value of an item, the first statement, the step and the result. A value of the wrong kind is an error of the op.
|
|
1857
2092
|
*/
|
|
1858
|
-
#reduction(op: string, kind: Kind | undefined): { readonly v: string; readonly init: string; readonly step: string; readonly result: string } {
|
|
2093
|
+
#reduction(op: string, kind: Kind | undefined, step?: Step): { readonly v: string; readonly init: string; readonly step: string; readonly result: string; readonly kind: Kind | undefined } {
|
|
1859
2094
|
const a = this.fresh("a");
|
|
1860
2095
|
const n = this.fresh("n");
|
|
1861
2096
|
const v = this.fresh("x");
|
|
2097
|
+
if (step !== undefined) return { v, init: `let ${a}, ${n} = 0;`, ...this.#reduceStep(step, kind, a, n, v) };
|
|
1862
2098
|
const num = kind === "number" ? v : `${this.use("U")}(${v})`;
|
|
1863
2099
|
const bool = kind === "boolean" ? v : `${this.use("B")}(${v})`;
|
|
1864
2100
|
const inits: Readonly<Record<string, string>> = {
|
|
@@ -1889,7 +2125,40 @@ class Printer {
|
|
|
1889
2125
|
all: a,
|
|
1890
2126
|
none: `!${a}`,
|
|
1891
2127
|
};
|
|
1892
|
-
return { v, init: inits[op] ?? `let ${a}, ${n} = 0;`, step: steps[op] as string, result: results[op] ?? `(${n} === 0 ? ${F}() : ${a})
|
|
2128
|
+
return { v, init: inits[op] ?? `let ${a}, ${n} = 0;`, step: steps[op] as string, result: results[op] ?? `(${n} === 0 ? ${F}() : ${a})`, kind: listKind(op, kind) };
|
|
2129
|
+
}
|
|
2130
|
+
|
|
2131
|
+
/**
|
|
2132
|
+
* This method gives the step and the result of `reduce` (COMPILE.MODULE.REDUCE), as in the interpreter. The first item
|
|
2133
|
+
* is the first running value. Each later item goes into the op of the domain of the running value. The kinds of the
|
|
2134
|
+
* items decide that op, and the op must give a value of the same kind. No items give the identity of the op.
|
|
2135
|
+
*/
|
|
2136
|
+
#reduceStep(step: Step, kind: Kind | undefined, a: string, n: string, v: string): { readonly step: string; readonly result: string; readonly kind: Kind | undefined } {
|
|
2137
|
+
const arg = (code: string): Code => bare({ code, kind, safe: true, deps: NO_DEPS, plain: true });
|
|
2138
|
+
const opCode = this.#opCall(step.op, [arg(a), arg(v)], NO_DEPS);
|
|
2139
|
+
if (opCode.v.kind !== kind) throw new NotStandalone(`the op "${step.op}" of "reduce" gives a value of the kind ${kindText(opCode.v.kind)}, not of the kind ${kindText(kind)} of the items`);
|
|
2140
|
+
const empty = this.#identity(step);
|
|
2141
|
+
// The identity of another domain is a value of another kind, so the kind of the result is not known.
|
|
2142
|
+
return { step: `${a} = ${n}++ === 0 ? ${v} : ${opCode.v.code};`, result: `(${n} === 0 ? ${empty.code} : ${a})`, kind: empty.kind === undefined || empty.kind === kind ? kind : undefined };
|
|
2143
|
+
}
|
|
2144
|
+
|
|
2145
|
+
/**
|
|
2146
|
+
* This method gives the code of `reduce` over no items, as in the interpreter. The code is the identity of the op in
|
|
2147
|
+
* the one domain that has one, or in the domain of the option `domain`. Another case is an error. The kind is the kind
|
|
2148
|
+
* of the domain.
|
|
2149
|
+
*/
|
|
2150
|
+
#identity(step: Step): { readonly code: string; readonly kind: Kind | undefined } {
|
|
2151
|
+
const { op, domain } = step;
|
|
2152
|
+
const fail = { code: `${this.use("F")}()`, kind: undefined };
|
|
2153
|
+
// A name of a domain that the program does not have leaves no domain, so it gives the error too.
|
|
2154
|
+
const found = [...this.#domains.entries()].filter(([, d]) => Object.hasOwn(d.ops, op) && (d.ops[op] as { readonly identity?: unknown }).identity !== undefined && (domain === undefined || d.name === domain));
|
|
2155
|
+
const [only, second] = found;
|
|
2156
|
+
if (only === undefined || second !== undefined) return fail;
|
|
2157
|
+
const [i, d] = only;
|
|
2158
|
+
const name = `id_${String(i)}_${String(this.#opIndex(op))}`;
|
|
2159
|
+
// Stryker disable next-line ConditionalExpression: the copy of an identity is always the same, so the test only saves time
|
|
2160
|
+
if (!this.top.has(name)) this.top.set(name, `const ${name} = ${copied((d.ops[op] as { readonly identity: () => unknown }).identity, [], `the identity of the op "${op}" of the domain ${d.name}`)};`);
|
|
2161
|
+
return { code: `${name}()`, kind: kindOfDomain(d) };
|
|
1893
2162
|
}
|
|
1894
2163
|
|
|
1895
2164
|
/**
|
|
@@ -1900,6 +2169,8 @@ class Printer {
|
|
|
1900
2169
|
const at = e.at ?? [];
|
|
1901
2170
|
const { s, j, head, key, check, skip, start, startSafe, tests, inner } = this.#targetLoop(e.axis, at, ctx);
|
|
1902
2171
|
const testCodes = tests.map((t) => this.#hoist(this.expr(t, inner), hasLoop(t)));
|
|
2172
|
+
// The value of an item can be a list, for flat (LIST.FLAT). The facts of the list tell it.
|
|
2173
|
+
if (this.#wantList.has(e)) this.#wantList.add(e.body);
|
|
1903
2174
|
const body = this.#hoist(this.expr(e.body, inner), hasLoop(e.body));
|
|
1904
2175
|
const deps = new Set([...start, ...[body, ...testCodes].flatMap((x) => [...x.v.deps])].filter((d) => d !== inner.level));
|
|
1905
2176
|
const list = this.fresh("L");
|
|
@@ -1911,23 +2182,54 @@ class Printer {
|
|
|
1911
2182
|
...(skip === undefined ? [] : [`if (${j} === ${skip}) continue;`]),
|
|
1912
2183
|
...(safeItem ? [...item, `${list}.push([${j}, ${body.v.code}]);`] : [`let ${v};`, "try {", ...ind(item), ` ${v} = ${body.v.code};`, "} catch {", ` ${v} = E;`, "}", `${list}.push([${j}, ${v}]);`]),
|
|
1913
2184
|
];
|
|
1914
|
-
return { s: [...s, `const ${list} = [];`, head, ...ind(loop), "}"], v: { code: list, kind: undefined, safe: startSafe, deps, list: { item: body.v.kind } } };
|
|
2185
|
+
return { s: [...s, `const ${list} = [];`, head, ...ind(loop), "}"], v: { code: list, kind: undefined, safe: startSafe, deps, list: { item: body.v.kind, inner: body.v.list } } };
|
|
1915
2186
|
}
|
|
1916
2187
|
|
|
1917
2188
|
/**
|
|
1918
|
-
* This method prints sortBy and
|
|
1919
|
-
* not in the new list, and with strict it is the error of the op.
|
|
2189
|
+
* This method prints sortBy, take and drop (LIST.SORT, LIST.TAKE, LIST.DROP): a new array from the array of a list. An
|
|
2190
|
+
* error item is not in the new list, and with strict it is the error of the op.
|
|
1920
2191
|
*/
|
|
1921
|
-
#order(op: "sortBy" | "take", head: Expr, rest: readonly Expr[], ctx: Ctx): Code {
|
|
2192
|
+
#order(op: "sortBy" | "take" | "drop", head: Expr, rest: readonly Expr[], ctx: Ctx): Code {
|
|
1922
2193
|
const list = this.#listOf(head, ctx);
|
|
1923
|
-
// A missing count is the literal null, which is not a whole number, so take
|
|
1924
|
-
const exprs = [head, ...(op === "
|
|
2194
|
+
// A missing count is the literal null, which is not a whole number, so take and drop give their error.
|
|
2195
|
+
const exprs = [head, ...(op === "sortBy" ? [] : [rest[0] ?? lit(null)])];
|
|
1925
2196
|
const strict = this.#strict(op, rest.slice(exprs.length - 1));
|
|
1926
2197
|
const raw = [list, ...exprs.slice(1).map((x) => this.expr(x, ctx))];
|
|
1927
2198
|
const deps = depsOf(...raw);
|
|
1928
2199
|
const parts = this.#inOrder(this.#settle(raw, deps, exprs), true);
|
|
1929
|
-
const
|
|
1930
|
-
|
|
2200
|
+
const helper = op === "sortBy" ? "SB" : op === "take" ? "TK" : "DR";
|
|
2201
|
+
// The new list has some items of the list, so it keeps the facts of the list.
|
|
2202
|
+
return { s: stmtsOf(...parts), v: { code: `${this.use(helper)}(${[...parts.map((x) => x.v.code), String(strict)].join(", ")})`, kind: undefined, safe: false, deps, list: list.v.list } };
|
|
2203
|
+
}
|
|
2204
|
+
|
|
2205
|
+
/**
|
|
2206
|
+
* This method prints append, without and flat (LIST.BUILD), get (LIST.GET) and indexOf (LIST.INDEXOF) over the array
|
|
2207
|
+
* of a list. Each list that the op reads follows LIST.LENIENT, as in the interpreter.
|
|
2208
|
+
*/
|
|
2209
|
+
#build(op: string, head: Expr, rest: readonly Expr[], ctx: Ctx): Code {
|
|
2210
|
+
const list = this.#listOf(head, ctx);
|
|
2211
|
+
const info = list.v.list as ListInfo;
|
|
2212
|
+
const two = op === "append" || op === "without";
|
|
2213
|
+
// A missing key of get, or value of indexOf, is the literal null. It is not a text or a value of indexOf, so the op
|
|
2214
|
+
// gives its error. A missing second list of append and without is not a list, so it gives a reason.
|
|
2215
|
+
const exprs = [head, ...(op === "flat" ? [] : [rest[0] ?? lit(null)])];
|
|
2216
|
+
const strict = this.#strict(op, rest.slice(exprs.length - 1));
|
|
2217
|
+
const raw = [list, ...exprs.slice(1).map((x) => (two ? this.#listOf(x, ctx) : this.expr(x, ctx)))];
|
|
2218
|
+
const deps = depsOf(...raw);
|
|
2219
|
+
const parts = this.#inOrder(this.#settle(raw, deps, exprs), true);
|
|
2220
|
+
const helper = BUILD_HELPERS[op] as BuildHelper;
|
|
2221
|
+
const value = (kind: Kind | undefined, facts: ListInfo | undefined): Code => ({
|
|
2222
|
+
s: stmtsOf(...parts),
|
|
2223
|
+
v: { code: `${this.use(helper)}(${[...parts.map((x) => x.v.code), String(strict)].join(", ")})`, kind, safe: false, deps, list: facts },
|
|
2224
|
+
});
|
|
2225
|
+
if (op === "get") return value(info.item, info.inner);
|
|
2226
|
+
if (op === "indexOf") return value("number", undefined);
|
|
2227
|
+
if (op === "without") return value(undefined, info);
|
|
2228
|
+
if (op === "append") return value(undefined, joinLists(info, (parts[1] as Code).v.list as ListInfo));
|
|
2229
|
+
// flat: the value of each item must be a list, so a list of values gives a reason. An empty list gives an empty list.
|
|
2230
|
+
if (info.empty === true) return value(undefined, info);
|
|
2231
|
+
if (info.inner === undefined) throw new NotStandalone('"flat" over a list whose items are not lists');
|
|
2232
|
+
return value(undefined, info.inner);
|
|
1931
2233
|
}
|
|
1932
2234
|
|
|
1933
2235
|
/** This method prints a list op over a list that is not an each: a loop over its array, and nth (LIST.NTH). */
|
|
@@ -1935,17 +2237,18 @@ class Printer {
|
|
|
1935
2237
|
const list = this.#listOf(head, ctx);
|
|
1936
2238
|
// A missing position is the literal null, which is not a whole number, so nth gives its error.
|
|
1937
2239
|
const exprs = [head, ...(op === "nth" ? [rest[0] ?? lit(null)] : [])];
|
|
1938
|
-
const strict = this.#
|
|
2240
|
+
const { strict, step } = this.#foldOptions(op, rest.slice(exprs.length - 1));
|
|
1939
2241
|
const raw = [list, ...exprs.slice(1).map((x) => this.expr(x, ctx))];
|
|
1940
2242
|
const deps = depsOf(...raw);
|
|
1941
2243
|
const parts = this.#inOrder(this.#settle(raw, deps, exprs), true);
|
|
1942
2244
|
const [l] = parts as [Code];
|
|
1943
|
-
const item =
|
|
1944
|
-
|
|
1945
|
-
|
|
2245
|
+
const { item, inner } = list.v.list as ListInfo;
|
|
2246
|
+
// The value of an item of a list of lists is a list, so nth and first give a list (LIST.FLAT).
|
|
2247
|
+
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, list: inner } };
|
|
2248
|
+
const r = this.#reduction(op, item, step);
|
|
1946
2249
|
const { v } = r;
|
|
1947
2250
|
const s = [...l.s, r.init, `for (const [, ${v}] of ${l.v.code}) {`, ` if (${v} === E) ${strict ? `${this.use("F")}();` : "continue;"}`, ` ${r.step}`, "}"];
|
|
1948
|
-
return { s, v: { code: r.result, kind:
|
|
2251
|
+
return { s, v: { code: r.result, kind: r.kind, safe: false, deps, list: op === "first" ? inner : undefined } };
|
|
1949
2252
|
}
|
|
1950
2253
|
|
|
1951
2254
|
/**
|
|
@@ -1953,17 +2256,23 @@ class Printer {
|
|
|
1953
2256
|
* node. Inside the loop, each name has the level `loop`. Thus a part that reads a name stays in the loop. A loop that
|
|
1954
2257
|
* reads no key of the run is a constant of the run.
|
|
1955
2258
|
*/
|
|
1956
|
-
#loopNames(init: Names, ctx: Ctx, loop: number): { readonly s: string[]; readonly env: Map<string, Name>; readonly vars: ReadonlyMap<string, Name>; readonly deps: Set<number> } {
|
|
2259
|
+
#loopNames(init: Names, step: Names, ctx: Ctx, loop: number): { readonly s: string[]; readonly env: Map<string, Name>; readonly vars: ReadonlyMap<string, Name>; readonly deps: Set<number> } {
|
|
1957
2260
|
const s: string[] = [];
|
|
1958
2261
|
const env = new Map(ctx.env);
|
|
1959
2262
|
const vars = new Map<string, Name>();
|
|
1960
2263
|
const deps = new Set<number>();
|
|
2264
|
+
// A step with a list literal can give a name the keys of the literal (LOOP.LIST).
|
|
2265
|
+
const keyed = Object.values(step).some(hasKeyedLiteral);
|
|
1961
2266
|
for (const [name, x] of Object.entries(init)) {
|
|
2267
|
+
// A name of a loop can hold a list (LOOP.LIST). Its first list fixes the kind of the items, if it has one.
|
|
2268
|
+
this.#wantList.add(x);
|
|
1962
2269
|
const c = this.expr(x, ctx);
|
|
1963
|
-
|
|
2270
|
+
const facts = c.v.list;
|
|
2271
|
+
if (c.v.kind === undefined && facts === undefined) throw new NotStandalone(`the first value of the name "${name}" of a loop has no kind`);
|
|
1964
2272
|
const v = this.fresh("l");
|
|
1965
2273
|
s.push(...c.s, `let ${v} = ${c.v.code};`);
|
|
1966
|
-
const
|
|
2274
|
+
const list = facts === undefined ? undefined : { item: facts.item, inner: facts.inner, texts: facts.texts === true || keyed };
|
|
2275
|
+
const read: Name = { code: v, kind: c.v.kind, lazy: false, deps: new Set([loop]), list };
|
|
1967
2276
|
env.set(name, read);
|
|
1968
2277
|
vars.set(name, read);
|
|
1969
2278
|
for (const d of c.v.deps) deps.add(d);
|
|
@@ -1977,9 +2286,11 @@ class Printer {
|
|
|
1977
2286
|
const sets: string[] = [];
|
|
1978
2287
|
const deps = new Set<number>();
|
|
1979
2288
|
for (const [name, x] of Object.entries(step)) {
|
|
2289
|
+
this.#wantList.add(x);
|
|
1980
2290
|
const c = this.#hoist(this.expr(x, inner), hasLoop(x));
|
|
1981
2291
|
const v = vars.get(name) as Name;
|
|
1982
|
-
if (c.v.kind !== v.kind) throw new NotStandalone(`a step of a loop changes the kind of the name "${name}"`);
|
|
2292
|
+
if (c.v.kind !== v.kind || (c.v.list === undefined) !== (v.list === undefined)) throw new NotStandalone(`a step of a loop changes the kind of the name "${name}"`);
|
|
2293
|
+
if (v.list !== undefined && !fits(v.list, c.v.list as ListInfo)) throw new NotStandalone(`a step of a loop gives the name "${name}" a list that does not fit its first list`);
|
|
1983
2294
|
const t = this.fresh("t");
|
|
1984
2295
|
s.push(...c.s, `const ${t} = ${c.v.code};`);
|
|
1985
2296
|
sets.push(`${v.code} = ${t};`);
|
|
@@ -1995,8 +2306,10 @@ class Printer {
|
|
|
1995
2306
|
#iterate(e: ExprOf<"iterate">, ctx: Ctx): Code {
|
|
1996
2307
|
// Stryker disable next-line UpdateOperator: a level of a loop is a name, so a count down gives other names, and the same code
|
|
1997
2308
|
const loop = this.#loops++;
|
|
1998
|
-
const names = this.#loopNames(e.init, ctx, loop);
|
|
2309
|
+
const names = this.#loopNames(e.init, e.step, ctx, loop);
|
|
1999
2310
|
const inner: Ctx = { ...ctx, env: names.env };
|
|
2311
|
+
// A loop at a place that takes a list gives its result there (LOOP.LIST).
|
|
2312
|
+
if (this.#wantList.has(e)) this.#wantList.add(e.result);
|
|
2000
2313
|
const until = e.until === undefined ? undefined : this.expr(e.until, inner);
|
|
2001
2314
|
const step = this.#loopStep(e.step, inner, names.vars);
|
|
2002
2315
|
const result = this.expr(e.result, inner);
|
|
@@ -2008,7 +2321,7 @@ class Printer {
|
|
|
2008
2321
|
];
|
|
2009
2322
|
const inside = [...(until?.v.deps ?? []), ...step.deps, ...result.v.deps].filter((d) => d !== loop);
|
|
2010
2323
|
const deps = new Set([...names.deps, ...inside]);
|
|
2011
|
-
return { s: [...names.s, `for (let ${k} = 0; ; ${k}++) {`, ...ind(body), "}", ...result.s], v: { code: result.v.code, kind: result.v.kind, safe: false, deps } };
|
|
2324
|
+
return { s: [...names.s, `for (let ${k} = 0; ; ${k}++) {`, ...ind(body), "}", ...result.s], v: { code: result.v.code, kind: result.v.kind, safe: false, deps, list: result.v.list } };
|
|
2012
2325
|
}
|
|
2013
2326
|
|
|
2014
2327
|
/**
|
|
@@ -2018,7 +2331,8 @@ class Printer {
|
|
|
2018
2331
|
#fold(e: ExprOf<"fold">, ctx: Ctx): Code {
|
|
2019
2332
|
// Stryker disable next-line UpdateOperator: a level of a loop is a name, so a count down gives other names, and the same code
|
|
2020
2333
|
const loop = this.#loops++;
|
|
2021
|
-
const names = this.#loopNames(e.init, ctx, loop);
|
|
2334
|
+
const names = this.#loopNames(e.init, e.step, ctx, loop);
|
|
2335
|
+
if (this.#wantList.has(e)) this.#wantList.add(e.result);
|
|
2022
2336
|
const t = this.#targetLoop(e.axis, e.at ?? [], ctx);
|
|
2023
2337
|
const tests = t.tests.map((x) => this.#hoist(this.expr(x, t.inner), hasLoop(x)));
|
|
2024
2338
|
// The interpreter evaluates the tests at each target before the first step, so a module of a sheet does not have them.
|
|
@@ -2034,7 +2348,7 @@ class Printer {
|
|
|
2034
2348
|
];
|
|
2035
2349
|
const inside = [...tests.flatMap((c) => [...c.v.deps]), ...step.deps].filter((d) => d !== loop && d !== t.inner.level);
|
|
2036
2350
|
const deps = new Set([...names.deps, ...t.start, ...inside, ...[...result.v.deps].filter((d) => d !== loop)]);
|
|
2037
|
-
return { s: [...names.s, ...t.s, t.head, ...ind(body), "}", ...result.s], v: { code: result.v.code, kind: result.v.kind, safe: false, deps } };
|
|
2351
|
+
return { s: [...names.s, ...t.s, t.head, ...ind(body), "}", ...result.s], v: { code: result.v.code, kind: result.v.kind, safe: false, deps, list: result.v.list } };
|
|
2038
2352
|
}
|
|
2039
2353
|
|
|
2040
2354
|
/**
|
|
@@ -2209,12 +2523,19 @@ class Printer {
|
|
|
2209
2523
|
}
|
|
2210
2524
|
|
|
2211
2525
|
/** This function gives the name of the function of a module, and its space, or the reason that the options are not valid. */
|
|
2212
|
-
function runOf(options: ModuleOptions):
|
|
2526
|
+
function runOf(options: ModuleOptions): Run | { readonly reason: string } {
|
|
2213
2527
|
const name = options.name ?? "run";
|
|
2214
2528
|
if (!/^[A-Za-z_$][\w$]*$/.test(name)) return { reason: `the name "${name}" is not a JavaScript name` };
|
|
2215
|
-
const
|
|
2216
|
-
if (
|
|
2217
|
-
return { name, tree };
|
|
2529
|
+
const space = options.space ?? "array";
|
|
2530
|
+
if (space !== "array" && space !== "tree" && space !== "graph") return { reason: `the space "${String(space)}" is not "array", "tree" or "graph"` };
|
|
2531
|
+
return { name, tree: space === "tree", graph: space === "graph" };
|
|
2532
|
+
}
|
|
2533
|
+
|
|
2534
|
+
/** The function of a module: its name, and its space. */
|
|
2535
|
+
interface Run {
|
|
2536
|
+
readonly name: string;
|
|
2537
|
+
readonly tree: boolean;
|
|
2538
|
+
readonly graph: boolean;
|
|
2218
2539
|
}
|
|
2219
2540
|
|
|
2220
2541
|
/** This function gives the reason of an error of the printer. Another exception is a defect, so it goes to the caller. */
|
|
@@ -2227,7 +2548,7 @@ function reasonOf(thrown: unknown): Emitted {
|
|
|
2227
2548
|
* This function gives the text of a module: the declarations, the helpers, and the function of the run. The run checks
|
|
2228
2549
|
* its input, computes the parts of the tree and the constants of the run, and then gives the statements `body`.
|
|
2229
2550
|
*/
|
|
2230
|
-
function printModule(p: Printer, options: ModuleOptions, run:
|
|
2551
|
+
function printModule(p: Printer, options: ModuleOptions, run: Run, body: readonly string[]): Emitted {
|
|
2231
2552
|
p.use("C");
|
|
2232
2553
|
const helpers = new Set<Helper>();
|
|
2233
2554
|
// A helper comes after the helpers that it needs. A set keeps the first place of each helper.
|
|
@@ -2245,13 +2566,16 @@ function printModule(p: Printer, options: ModuleOptions, run: { readonly name: s
|
|
|
2245
2566
|
} catch (thrown) {
|
|
2246
2567
|
return reasonOf(thrown);
|
|
2247
2568
|
}
|
|
2248
|
-
const { name, tree } = run;
|
|
2569
|
+
const { name, tree, graph } = run;
|
|
2249
2570
|
// A tree checks its parents, and it computes the parts that the program reads. The siblings and the order need the
|
|
2250
2571
|
// children.
|
|
2251
2572
|
if (tree) p.use("PT");
|
|
2252
2573
|
if (p.treeParts.size > 0) p.treeParts.add("children");
|
|
2253
2574
|
const parts = (["children", "siblings", "order"] as const).filter((x) => p.treeParts.has(x));
|
|
2254
2575
|
for (const x of parts) p.use(TREE_PARTS[x][0]);
|
|
2576
|
+
// A graph checks its edges, and it computes the predecessors if the program reads them.
|
|
2577
|
+
if (graph) p.use("GR");
|
|
2578
|
+
if (p.into) p.use("GI");
|
|
2255
2579
|
[...p.helpers].toSorted().forEach(add);
|
|
2256
2580
|
// The names that this module declares at its top: the constants, the helpers and the declarations of the printer.
|
|
2257
2581
|
const declared = new Set<string>(["VexContractError", "VEX_ERROR", "E", ...(p.memos ? ["Z"] : []), ...(helpers.has("S") ? ["N", "W"] : []), ...helpers, ...p.top.keys()]);
|
|
@@ -2269,7 +2593,7 @@ function printModule(p: Printer, options: ModuleOptions, run: { readonly name: s
|
|
|
2269
2593
|
...(helpers.has("S") ? ["const N = {}, W = {};"] : []),
|
|
2270
2594
|
...[...helpers].map((h) => (h === "S" ? helperS(p.features) : HELPERS[h])),
|
|
2271
2595
|
...p.top.values(),
|
|
2272
|
-
`export function ${name}(records, vars${tree ? ", parents" : ""}) {`,
|
|
2596
|
+
`export function ${name}(records, vars${tree ? ", parents" : graph ? ", edges" : ""}) {`,
|
|
2273
2597
|
' if (!Array.isArray(records)) C("the records are not an array");',
|
|
2274
2598
|
" const R = records;",
|
|
2275
2599
|
" const n = R.length;",
|
|
@@ -2279,6 +2603,7 @@ function printModule(p: Printer, options: ModuleOptions, run: { readonly name: s
|
|
|
2279
2603
|
" }",
|
|
2280
2604
|
` if (typeof vars !== "object" || vars === null${varChecks}) C("the variables do not keep the schema");`,
|
|
2281
2605
|
...(tree ? [" const P = PT(parents, n);", ...parts.map((x) => ` ${TREE_PARTS[x][1]}`)] : []),
|
|
2606
|
+
...(graph ? [" const GO = GR(edges, n);", ...(p.into ? [" const GN = GI(GO, n);"] : [])] : []),
|
|
2282
2607
|
...[...p.vars].map(([v, code]) => ` const ${code} = vars[${JSON.stringify(v)}];`),
|
|
2283
2608
|
...ind(p.run),
|
|
2284
2609
|
...ind(body),
|
|
@@ -2364,7 +2689,10 @@ export function emitSheetModule(columns: ReadonlyMap<string, Expr>, options: She
|
|
|
2364
2689
|
const kinds = new Map<string, Kind | undefined>(Object.entries(options.kinds ?? {}));
|
|
2365
2690
|
const index = new Map(names.map((c, i) => [c, i]));
|
|
2366
2691
|
// The memo of the printer covers each formula, so the formulas share their nodes of the memo.
|
|
2367
|
-
|
|
2692
|
+
// A sheet whose reads all read finished cells needs no search: each cell is the value of its formula
|
|
2693
|
+
// (COMPILE.MODULE.SHEET.DIRECT). A sheet with formulas of cells always has the search.
|
|
2694
|
+
const direct = formulas.every((f) => f.key === undefined) && order.every((c) => readsFinished(columns, order, c, run.tree));
|
|
2695
|
+
const p = new Printer(rec(Object.fromEntries(formulas.map((f, i) => [`f${String(i)}`, f.expr]))), options, { columns: index, kinds, direct });
|
|
2368
2696
|
const fns: string[] = [];
|
|
2369
2697
|
const decls: string[] = [];
|
|
2370
2698
|
try {
|
|
@@ -2392,29 +2720,33 @@ export function emitSheetModule(columns: ReadonlyMap<string, Expr>, options: She
|
|
|
2392
2720
|
const i = formulas.findIndex((f) => f.column === c && f.key === undefined);
|
|
2393
2721
|
return i < 0 ? "undefined" : entry(i);
|
|
2394
2722
|
});
|
|
2395
|
-
p.use("SH");
|
|
2723
|
+
p.use(direct ? "DO" : "SH");
|
|
2724
|
+
// The function of the formula of each column, for a direct fill. A direct fill has no formulas of cells.
|
|
2725
|
+
const fnOf = new Map(formulas.map((f, i) => [f.column, fns[i] as string]));
|
|
2726
|
+
const fillOf = (c: string, at: string): string => (direct ? `D[${at}][o] = ${fnOf.get(c) as string}(o);` : `SS.f(${at}, o);`);
|
|
2396
2727
|
// A tree gives the keys in the order of a fill with the helper KO, once for each order.
|
|
2397
2728
|
const orders = new Map<string, string>();
|
|
2398
2729
|
const fill = order.map((c) => {
|
|
2399
2730
|
const { reverse, post, back } = keyOrderOf(readsOf(columns, cells, c).directions);
|
|
2400
2731
|
const at = String(index.get(c));
|
|
2401
|
-
if (!run.tree) return reverse ? `for (let o = n - 1; o >= 0; o--)
|
|
2732
|
+
if (!run.tree) return reverse ? `for (let o = n - 1; o >= 0; o--) ${fillOf(c, at)}` : `for (let o = 0; o < n; o++) ${fillOf(c, at)}`;
|
|
2402
2733
|
const args = `${p.use("KO")}(H, RT, ${String(post)}, ${String(back)})`;
|
|
2403
2734
|
let keys = orders.get(args);
|
|
2404
2735
|
if (keys === undefined) {
|
|
2405
2736
|
keys = p.fresh("K");
|
|
2406
2737
|
orders.set(args, keys);
|
|
2407
2738
|
}
|
|
2408
|
-
return `for (const o of ${keys})
|
|
2739
|
+
return `for (const o of ${keys}) ${fillOf(c, at)}`;
|
|
2409
2740
|
});
|
|
2410
2741
|
if (run.tree) p.treeParts.add("children");
|
|
2411
2742
|
const body = [
|
|
2412
2743
|
...decls,
|
|
2413
|
-
|
|
2414
|
-
|
|
2744
|
+
...(direct
|
|
2745
|
+
? [`const D = [${names.map(() => "new Array(n)").join(", ")}];`, `const ${READ_CELL} = (c, k) => D[c][k];`]
|
|
2746
|
+
: [`const SS = SH(n, [${cols.join(", ")}], [${own.join(", ")}], ${String(budget)});`, `const ${READ_CELL} = SS.r;`]),
|
|
2415
2747
|
...[...orders].map(([args, keys]) => `const ${keys} = ${args};`),
|
|
2416
2748
|
...fill,
|
|
2417
|
-
`return { ${names.map((c, i) => `${JSON.stringify(c)}: SS.o(${String(i)})`).join(", ")} };`,
|
|
2749
|
+
`return { ${names.map((c, i) => `${JSON.stringify(c)}: ${direct ? `DO(D[${String(i)}])` : `SS.o(${String(i)})`}`).join(", ")} };`,
|
|
2418
2750
|
];
|
|
2419
2751
|
return printModule(p, options, run, body);
|
|
2420
2752
|
}
|