@mark1russell7/vex-compiler 0.13.1 → 0.13.3
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 +15 -5
- package/build/index.d.ts.map +1 -1
- package/build/index.js +376 -72
- package/build/index.js.map +1 -1
- package/package.json +4 -4
- package/src/index.ts +1 -1
- package/src/module.ts +326 -84
- package/src/runtime.ts +4 -0
- package/src/sheet-order.ts +63 -0
package/src/module.ts
CHANGED
|
@@ -15,20 +15,23 @@
|
|
|
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). A
|
|
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 value of a program can be a
|
|
23
|
+
* list, and the run gives it as a `vex.list` (COMPILE.MODULE.LIST.RESULT). The kinds of each op site must decide its op.
|
|
22
24
|
* Another construct gives a reason, not code.
|
|
23
25
|
*
|
|
24
26
|
* `emitSheetModule` prints the formula columns of a sheet as one module (COMPILE.MODULE.SHEET). Each column is an array
|
|
25
27
|
* of results, and the run fills the arrays in the static order of `SheetRun.fill`. A read of a cell that is not finished
|
|
26
|
-
* starts the search of `SheetRun`. Thus each cell on a cycle gives the error of Vex.
|
|
28
|
+
* starts the search of `SheetRun`. Thus each cell on a cycle gives the error of Vex. A cell can hold a list, and a
|
|
29
|
+
* formula reads it with the list ops (COMPILE.MODULE.SHEET.LIST).
|
|
27
30
|
*/
|
|
28
31
|
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";
|
|
29
32
|
import { factsOf, kindOfDomain, primitiveOf, type Facts, type Kind, type Schema } from "./facts.ts";
|
|
30
33
|
import { memoNodes } from "./memo.ts";
|
|
31
|
-
import { columnOrder, isCellRef, keyOrderOf, readsOf } from "./sheet-order.ts";
|
|
34
|
+
import { columnOrder, isCellRef, keyOrderOf, readsFinished, readsOf } from "./sheet-order.ts";
|
|
32
35
|
|
|
33
36
|
/** The options of a standalone module. */
|
|
34
37
|
export interface ModuleOptions {
|
|
@@ -41,11 +44,12 @@ export interface ModuleOptions {
|
|
|
41
44
|
*/
|
|
42
45
|
readonly name?: string;
|
|
43
46
|
/**
|
|
44
|
-
* The space of the records. In
|
|
47
|
+
* The space of the records. In each space, the key of a record is the text of its position. The default `array`
|
|
45
48
|
* has no parents. A `tree` takes the parents as the third argument of the run (COMPILE.MODULE.TREE). Each entry
|
|
46
|
-
* is the position of the parent of its record, or -1 for a root.
|
|
49
|
+
* is the position of the parent of its record, or -1 for a root. A `graph` takes the edges as the third argument
|
|
50
|
+
* (COMPILE.MODULE.GRAPH). Each entry is an array of the positions of the ends of the edges from its record, in order.
|
|
47
51
|
*/
|
|
48
|
-
readonly space?: "array" | "tree";
|
|
52
|
+
readonly space?: "array" | "tree" | "graph";
|
|
49
53
|
}
|
|
50
54
|
|
|
51
55
|
/** The options of a module of a sheet (COMPILE.MODULE.SHEET): the options of a module, and the parts of a sheet. */
|
|
@@ -55,12 +59,22 @@ export interface SheetModuleOptions extends ModuleOptions {
|
|
|
55
59
|
/**
|
|
56
60
|
* The kind of the values of each column. The printer prints each column after the columns that it reads. A column
|
|
57
61
|
* that a formula reads before its own formula prints needs its kind here, for example a column that reads itself.
|
|
62
|
+
* A column of lists has a `ListKind` (COMPILE.MODULE.SHEET.LIST).
|
|
58
63
|
*/
|
|
59
|
-
readonly kinds?: Readonly<Record<string, Kind>>;
|
|
64
|
+
readonly kinds?: Readonly<Record<string, Kind | ListKind>>;
|
|
60
65
|
/** The budget of the stack of the search of a run, in estimated frames, as in `SheetRun`. The default is 3000. */
|
|
61
66
|
readonly budget?: number;
|
|
62
67
|
}
|
|
63
68
|
|
|
69
|
+
/**
|
|
70
|
+
* The kind of a column of lists in a module of a sheet (COMPILE.MODULE.SHEET.LIST): the kind of the items, which can be
|
|
71
|
+
* a list too. With `texts`, a key of an item can be the text of a key of a list literal.
|
|
72
|
+
*/
|
|
73
|
+
export interface ListKind {
|
|
74
|
+
readonly list: Kind | ListKind;
|
|
75
|
+
readonly texts?: boolean;
|
|
76
|
+
}
|
|
77
|
+
|
|
64
78
|
/** The source of a standalone module, or the reason that the program cannot be one. */
|
|
65
79
|
export type Emitted = { readonly ok: true; readonly source: string } | { readonly ok: false; readonly reason: string };
|
|
66
80
|
|
|
@@ -102,6 +116,12 @@ interface ListInfo {
|
|
|
102
116
|
readonly empty?: boolean;
|
|
103
117
|
}
|
|
104
118
|
|
|
119
|
+
/** The op of each step of `reduce` (COMPILE.MODULE.REDUCE): the name of the op, and the value of the option `domain`. */
|
|
120
|
+
interface Step {
|
|
121
|
+
readonly op: string;
|
|
122
|
+
readonly domain: unknown;
|
|
123
|
+
}
|
|
124
|
+
|
|
105
125
|
/** The code of a node: the statements before its value, and its value. `safe` covers the statements too. */
|
|
106
126
|
interface Code {
|
|
107
127
|
readonly s: readonly string[];
|
|
@@ -145,6 +165,10 @@ interface SheetInfo {
|
|
|
145
165
|
readonly columns: ReadonlyMap<string, number>;
|
|
146
166
|
/** The kind of each column that the printer knows: a kind of the options, or the kind of a printed formula. */
|
|
147
167
|
readonly kinds: Map<string, Kind | undefined>;
|
|
168
|
+
/** The facts of the lists of each column of lists that the printer knows (COMPILE.MODULE.SHEET.LIST). */
|
|
169
|
+
readonly lists: Map<string, ListInfo>;
|
|
170
|
+
/** True when each read of a cell reads a finished cell, so a read starts no search (COMPILE.MODULE.SHEET.DIRECT). */
|
|
171
|
+
readonly direct: boolean;
|
|
148
172
|
}
|
|
149
173
|
|
|
150
174
|
/** This function gives the levels of some codes together. */
|
|
@@ -226,7 +250,7 @@ interface Spec {
|
|
|
226
250
|
}
|
|
227
251
|
|
|
228
252
|
/** The name of a helper of the generated code. */
|
|
229
|
-
type Helper = "F" | "C" | "T" | "L" | "Q" | "G" | "B" | "U" | "X" | "I" | "K" | "M" | "M1" | "S" | "V" | "SB" | "TK" | "NT" | BuildHelper | TreeHelper | SheetHelper;
|
|
253
|
+
type Helper = "F" | "C" | "T" | "L" | "Q" | "G" | "B" | "U" | "X" | "I" | "K" | "M" | "M1" | "S" | "V" | "SB" | "TK" | "NT" | BuildHelper | TreeHelper | GraphHelper | SheetHelper;
|
|
230
254
|
|
|
231
255
|
/** The helpers of the list ops that build a list (LIST.BUILD), of `get` (LIST.GET) and of `indexOf` (LIST.INDEXOF). */
|
|
232
256
|
type BuildHelper = "DR" | "AP" | "WO" | "FL" | "GT" | "IX";
|
|
@@ -234,8 +258,11 @@ type BuildHelper = "DR" | "AP" | "WO" | "FL" | "GT" | "IX";
|
|
|
234
258
|
/** The helpers of a tree space (COMPILE.MODULE.TREE). */
|
|
235
259
|
type TreeHelper = "PT" | "CH" | "SG" | "PR" | "UP" | "SO" | "AN" | "BF";
|
|
236
260
|
|
|
261
|
+
/** The helpers of a graph space (COMPILE.MODULE.GRAPH). */
|
|
262
|
+
type GraphHelper = "GR" | "GI" | "RB";
|
|
263
|
+
|
|
237
264
|
/** 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. */
|
|
238
|
-
type SheetHelper = "SH" | "KO";
|
|
265
|
+
type SheetHelper = "SH" | "KO" | "DO" | "LO" | "LC";
|
|
239
266
|
|
|
240
267
|
/** The helpers of the generated code. A module has only the helpers that it uses. */
|
|
241
268
|
const HELPERS: Readonly<Record<Exclude<Helper, "S">, string>> = {
|
|
@@ -378,9 +405,42 @@ const HELPERS: Readonly<Record<Exclude<Helper, "S">, string>> = {
|
|
|
378
405
|
AN: "function AN(P, k) { const o = []; for (let p = P[k]; p >= 0; p = P[p]) o.push(p); return o; }",
|
|
379
406
|
// 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.
|
|
380
407
|
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; }",
|
|
408
|
+
// The edges of a graph space: the positions of the ends of the edges from each record, in order. A second edge to the
|
|
409
|
+
// same end is the same edge, as in the interpreter. The mark of an end is the number of its record plus 1.
|
|
410
|
+
GR: [
|
|
411
|
+
"function GR(e, n) {",
|
|
412
|
+
' if (!Array.isArray(e) || e.length !== n) C("the edges are not an array with the ends of the edges of each record");',
|
|
413
|
+
" const O = [], s = new Int32Array(n);",
|
|
414
|
+
" for (let i = 0; i < n; i++) {",
|
|
415
|
+
" const x = e[i];",
|
|
416
|
+
" if (!Array.isArray(x)) C(`the edges of the record ${i} are not an array`);",
|
|
417
|
+
" const o = [];",
|
|
418
|
+
" for (const t of x) {",
|
|
419
|
+
" if (!(Number.isInteger(t) && t >= 0 && t < n)) C(`an edge of the record ${i} does not go to the position of a record`);",
|
|
420
|
+
" if (s[t] !== i + 1) {",
|
|
421
|
+
" s[t] = i + 1;",
|
|
422
|
+
" o.push(t);",
|
|
423
|
+
" }",
|
|
424
|
+
" }",
|
|
425
|
+
" O.push(o);",
|
|
426
|
+
" }",
|
|
427
|
+
" return O;",
|
|
428
|
+
"}",
|
|
429
|
+
].join("\n"),
|
|
430
|
+
// 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.
|
|
431
|
+
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; }",
|
|
432
|
+
// The record and the keys that a path of edges reaches from it, once, in the order of a breadth-first search.
|
|
433
|
+
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; }",
|
|
381
434
|
// The state of a run of a sheet (COMPILE.MODULE.SHEET), as in SheetRun: the result of each finished cell, the search
|
|
382
435
|
// of Tarjan with its stack, and the budget of the stack. `r` reads a cell, `f` fills a cell, and `o` gives a column.
|
|
383
436
|
// A cell without a formula has the error sentinel from the start, as the error of its read.
|
|
437
|
+
// A column of a direct fill (COMPILE.MODULE.SHEET.DIRECT): the error sentinel of a cell changes to VEX_ERROR.
|
|
438
|
+
DO: "function DO(d) { for (let k = 0; k < d.length; k++) if (d[k] === E) d[k] = VEX_ERROR; return d; }",
|
|
439
|
+
// A list of a result (COMPILE.MODULE.LIST.RESULT): a `vex.list` with a text key for each item. An error item has the
|
|
440
|
+
// error VEX_ERROR. The depth `h` is the number of the levels of lists in the items.
|
|
441
|
+
LO: 'function LO(l, h) { return { kind: "vex.list", items: l.map(([k, v]) => ({ key: `${k}`, result: v === E ? { ok: false, error: VEX_ERROR } : { ok: true, value: h > 0 ? LO(v, h - 1) : v } })) }; }',
|
|
442
|
+
// A column of lists (COMPILE.MODULE.SHEET.LIST): each cell with a list gives a `vex.list`.
|
|
443
|
+
LC: "function LC(d, h) { for (let k = 0; k < d.length; k++) if (d[k] !== VEX_ERROR) d[k] = LO(d[k], h); return d; }",
|
|
384
444
|
SH: [
|
|
385
445
|
"function SH(n, cols, own, budget) {",
|
|
386
446
|
" const pg = (c, k) => {",
|
|
@@ -672,9 +732,10 @@ const NEEDS: Readonly<Record<Helper, readonly Helper[]>> = {
|
|
|
672
732
|
DR: ["V", "F"], AP: ["V"], WO: ["V"], FL: ["V"], GT: ["F"], IX: ["V", "F"],
|
|
673
733
|
// Each module has C, and each move uses F (#move), so these needs only complete the list.
|
|
674
734
|
// Stryker disable next-line ArrayDeclaration: see the comment above
|
|
675
|
-
PT: ["C"], UP: ["F"], SO: ["F"],
|
|
735
|
+
PT: ["C"], GR: ["C"], UP: ["F"], SO: ["F"],
|
|
676
736
|
CH: [], SG: [], PR: [], AN: [], BF: [],
|
|
677
|
-
|
|
737
|
+
GI: [], RB: [],
|
|
738
|
+
SH: [], KO: [], DO: [], LO: [], LC: ["LO"],
|
|
678
739
|
};
|
|
679
740
|
|
|
680
741
|
/** The parts of a tree that a run computes before the loop over its keys, if the program needs them. */
|
|
@@ -696,6 +757,9 @@ const TREE_AXES: ReadonlySet<string> = new Set(["children", "ancestors", "descen
|
|
|
696
757
|
/** This function tells if an axis has its targets in a range of an array of positions in a tree space. */
|
|
697
758
|
const isTreeAxis = (a: Axis): a is TreeAxis => a.t === "window" || TREE_AXES.has(a.t);
|
|
698
759
|
|
|
760
|
+
/** The axes of a graph space in a module (COMPILE.MODULE.GRAPH), other than the axes of each space. */
|
|
761
|
+
const GRAPH_AXES: ReadonlySet<string> = new Set(["successors", "predecessors", "reachable"]);
|
|
762
|
+
|
|
699
763
|
/**
|
|
700
764
|
* The targets of an axis of a tree space: the statements before the loop, and the positions `a[q]` for `q` from `lo` up
|
|
701
765
|
* to `hi`. The loop skips the key `skip`.
|
|
@@ -710,6 +774,8 @@ interface TreeRange {
|
|
|
710
774
|
|
|
711
775
|
/** The list ops of a standalone module. */
|
|
712
776
|
const LIST_OPS: ReadonlySet<string> = new Set(["count", "sum", "mean", "min", "max", "any", "all", "none", "first"]);
|
|
777
|
+
/** 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). */
|
|
778
|
+
const FOLD_OPS: ReadonlySet<string> = new Set([...LIST_OPS, "reduce"]);
|
|
713
779
|
const NUMBER_LIST_OPS: ReadonlySet<string> = new Set(["count", "sum", "mean", "min", "max"]);
|
|
714
780
|
const BOOLEAN_LIST_OPS: ReadonlySet<string> = new Set(["any", "all", "none"]);
|
|
715
781
|
/** The list ops over lists of `#build`: append, without and flat (LIST.BUILD), get (LIST.GET) and indexOf (LIST.INDEXOF). */
|
|
@@ -725,23 +791,25 @@ const LIST_RESULTS: ReadonlySet<string> = new Set(["sortBy", "take", "drop", "ap
|
|
|
725
791
|
* This function tells if an expression gives a list. An each, a list literal and a list op of `LIST_RESULTS` give a
|
|
726
792
|
* 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.
|
|
727
793
|
*/
|
|
728
|
-
function listy(e: Expr, isName: (name: string) => boolean): boolean {
|
|
794
|
+
function listy(e: Expr, isName: (name: string) => boolean, isCell: (e: ExprOf<"ext">) => boolean): boolean {
|
|
729
795
|
switch (e.tag) {
|
|
730
796
|
case "each":
|
|
731
797
|
return true;
|
|
732
798
|
case "lit":
|
|
733
799
|
return isVexList(e.value);
|
|
734
800
|
case "app":
|
|
735
|
-
|
|
801
|
+
// A branch of if and ifError can be a list (COMPILE.MODULE.LIST.RESULT).
|
|
802
|
+
return LIST_RESULTS.has(e.op) || ((e.op === "if" || e.op === "ifError") && e.args.slice(e.op === "if" ? 1 : 0).some((x) => listy(x, isName, isCell)));
|
|
736
803
|
case "var":
|
|
737
804
|
return isName(e.name);
|
|
738
805
|
case "let":
|
|
739
|
-
return listy(e.body, namesIn(e.bind, isName));
|
|
806
|
+
return listy(e.body, namesIn(e.bind, isName, isCell), isCell);
|
|
740
807
|
case "fold":
|
|
741
808
|
case "iterate":
|
|
742
|
-
return listy(e.result, namesIn(e.init, isName));
|
|
743
|
-
case "call":
|
|
809
|
+
return listy(e.result, namesIn(e.init, isName, isCell), isCell);
|
|
744
810
|
case "ext":
|
|
811
|
+
return isCell(e);
|
|
812
|
+
case "call":
|
|
745
813
|
case "fn":
|
|
746
814
|
case "rec":
|
|
747
815
|
case "ref":
|
|
@@ -750,8 +818,8 @@ function listy(e: Expr, isName: (name: string) => boolean): boolean {
|
|
|
750
818
|
}
|
|
751
819
|
|
|
752
820
|
/** 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. */
|
|
753
|
-
function namesIn(bind: Readonly<Record<string, Expr>>, isName: (name: string) => boolean): (name: string) => boolean {
|
|
754
|
-
const lists = new Map(Object.entries(bind).map(([name, x]) => [name, x.tag !== "fn" && listy(x, isName)]));
|
|
821
|
+
function namesIn(bind: Readonly<Record<string, Expr>>, isName: (name: string) => boolean, isCell: (e: ExprOf<"ext">) => boolean): (name: string) => boolean {
|
|
822
|
+
const lists = new Map(Object.entries(bind).map(([name, x]) => [name, x.tag !== "fn" && listy(x, isName, isCell)]));
|
|
755
823
|
return (name) => lists.get(name) ?? isName(name);
|
|
756
824
|
}
|
|
757
825
|
|
|
@@ -760,13 +828,23 @@ function hasKeyedLiteral(e: Expr): boolean {
|
|
|
760
828
|
return (e.tag === "lit" && isVexList(e.value) && e.value.items.length > 0) || children(e).some(hasKeyedLiteral);
|
|
761
829
|
}
|
|
762
830
|
|
|
763
|
-
/**
|
|
764
|
-
function
|
|
831
|
+
/**
|
|
832
|
+
* This function gives the facts of the list of `append` from the facts of its two lists. It also gives the list of
|
|
833
|
+
* `if` from its two branches. An empty list fits each list. The op `op` names the op in the reason.
|
|
834
|
+
*/
|
|
835
|
+
function joinLists(a: ListInfo, b: ListInfo, op: string): ListInfo {
|
|
765
836
|
if (a.empty === true) return b;
|
|
766
837
|
if (b.empty === true) return a;
|
|
767
|
-
if ((a.inner === undefined) !== (b.inner === undefined)) throw new NotStandalone(
|
|
838
|
+
if ((a.inner === undefined) !== (b.inner === undefined)) throw new NotStandalone(`"${op}" of a list of lists and a list of values`);
|
|
768
839
|
const texts = a.texts === true || b.texts === true;
|
|
769
|
-
return { item: join(a.item, b.item), inner: a.inner === undefined ? undefined : joinLists(a.inner, b.inner as ListInfo), texts };
|
|
840
|
+
return { item: join(a.item, b.item), inner: a.inner === undefined ? undefined : joinLists(a.inner, b.inner as ListInfo, op), texts };
|
|
841
|
+
}
|
|
842
|
+
|
|
843
|
+
/** This function gives the facts of the list of `if` or `ifError` from its two branches. Two values that are not lists give undefined. */
|
|
844
|
+
function branchLists(op: string, a: ListInfo | undefined, b: ListInfo | undefined): ListInfo | undefined {
|
|
845
|
+
if (a === undefined && b === undefined) return undefined;
|
|
846
|
+
if (a === undefined || b === undefined) throw new NotStandalone(`"${op}" of a list and a value that is not a list`);
|
|
847
|
+
return joinLists(a, b, op);
|
|
770
848
|
}
|
|
771
849
|
|
|
772
850
|
/**
|
|
@@ -781,7 +859,7 @@ function fits(name: ListInfo, step: ListInfo): boolean {
|
|
|
781
859
|
}
|
|
782
860
|
|
|
783
861
|
/** This function tells if the step of a list op throws for a value of the kind `kind`, which is the wrong kind. */
|
|
784
|
-
const stepThrows = (op: string, kind: Kind | undefined): boolean => (NUMBER_STEPS.has(op) && kind !== "number") || (BOOLEAN_LIST_OPS.has(op) && kind !== "boolean");
|
|
862
|
+
const stepThrows = (op: string, kind: Kind | undefined): boolean => op === "reduce" || (NUMBER_STEPS.has(op) && kind !== "number") || (BOOLEAN_LIST_OPS.has(op) && kind !== "boolean");
|
|
785
863
|
|
|
786
864
|
/** The list ops whose step takes a number. */
|
|
787
865
|
const NUMBER_STEPS: ReadonlySet<string> = new Set(["sum", "mean", "min", "max"]);
|
|
@@ -1072,6 +1150,9 @@ class Printer {
|
|
|
1072
1150
|
/** True for a tree space, and the parts of the tree that the program reads (COMPILE.MODULE.TREE). */
|
|
1073
1151
|
readonly #tree: boolean;
|
|
1074
1152
|
readonly treeParts = new Set<TreePart>();
|
|
1153
|
+
/** True for a graph space, and true when the program reads the predecessors of a graph (COMPILE.MODULE.GRAPH). */
|
|
1154
|
+
readonly #graph: boolean;
|
|
1155
|
+
into = false;
|
|
1075
1156
|
/** The columns of a sheet, for a module of a sheet (COMPILE.MODULE.SHEET). */
|
|
1076
1157
|
readonly #sheet: SheetInfo | undefined;
|
|
1077
1158
|
#names = 0;
|
|
@@ -1116,6 +1197,7 @@ class Printer {
|
|
|
1116
1197
|
this.#schema = options.schema;
|
|
1117
1198
|
this.#memo = memoOf(expr);
|
|
1118
1199
|
this.#tree = options.space === "tree";
|
|
1200
|
+
this.#graph = options.space === "graph";
|
|
1119
1201
|
this.#sheet = sheet;
|
|
1120
1202
|
}
|
|
1121
1203
|
|
|
@@ -1284,7 +1366,12 @@ class Printer {
|
|
|
1284
1366
|
|
|
1285
1367
|
/** This method tells if an expression gives a list at a place that takes one (`listy`). */
|
|
1286
1368
|
#isList(e: Expr, ctx: Ctx): boolean {
|
|
1287
|
-
return listy(e, (name) => ctx.env.get(name)?.list !== undefined);
|
|
1369
|
+
return listy(e, (name) => ctx.env.get(name)?.list !== undefined, (x) => this.#cellList(x) !== undefined);
|
|
1370
|
+
}
|
|
1371
|
+
|
|
1372
|
+
/** This method gives the facts of the list of a read of a cell. A read of a column that holds no list gives undefined. */
|
|
1373
|
+
#cellList(e: ExprOf<"ext">): ListInfo | undefined {
|
|
1374
|
+
return e.kind === CELL_KIND && isCellRef(e.data) ? this.#sheet?.lists.get(e.data.column) : undefined;
|
|
1288
1375
|
}
|
|
1289
1376
|
|
|
1290
1377
|
/** 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. */
|
|
@@ -1436,10 +1523,13 @@ class Printer {
|
|
|
1436
1523
|
const deps = new Set([...this.#addressDeps(at, ctx, []), CELLS]);
|
|
1437
1524
|
const index = sheet.columns.get(column);
|
|
1438
1525
|
// The read of a column that the sheet does not have is an error. A kind of the options lets an op take it.
|
|
1439
|
-
|
|
1526
|
+
const list = sheet.lists.get(column);
|
|
1527
|
+
if (index === undefined) return bare({ code: `${F}()`, kind: sheet.kinds.get(column), safe: false, deps, list });
|
|
1440
1528
|
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`);
|
|
1441
|
-
|
|
1442
|
-
const
|
|
1529
|
+
// A direct fill reads the array of the column. The search reads the cell with the function of its state.
|
|
1530
|
+
const address = this.#address(at, ctx, []);
|
|
1531
|
+
const read = sheet.direct ? `D[${String(index)}][${address}]` : `${READ_CELL}(${String(index)}, ${address})`;
|
|
1532
|
+
const v = { code: `${this.use("G")}(${read})`, kind: sheet.kinds.get(column), safe: false, deps, list };
|
|
1443
1533
|
// The read itself gives the result or the error sentinel. A move of the address can throw, so then the read is not
|
|
1444
1534
|
// a value that holds the sentinel.
|
|
1445
1535
|
return bare(at.every((m) => m.t === "origin") ? { ...v, held: read } : v);
|
|
@@ -1457,6 +1547,8 @@ class Printer {
|
|
|
1457
1547
|
* must read no cell.
|
|
1458
1548
|
*/
|
|
1459
1549
|
#inOrder(parts: readonly Code[], all: boolean): readonly Code[] {
|
|
1550
|
+
// A read of a finished cell starts no search, so the order of the reads does not change a result.
|
|
1551
|
+
if (this.#sheet?.direct === true) return parts;
|
|
1460
1552
|
const last = parts.findLastIndex((x) => x.v.deps.has(CELLS));
|
|
1461
1553
|
const after = parts.slice(last + 1).every((x) => x.s.length === 0 || x.v.safe);
|
|
1462
1554
|
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);
|
|
@@ -1516,7 +1608,8 @@ class Printer {
|
|
|
1516
1608
|
// Stryker disable next-line ConditionalExpression,StringLiteral: see #address
|
|
1517
1609
|
/* v8 ignore next -- @preserve */
|
|
1518
1610
|
if (focus === undefined) throw new NotStandalone("a node of the memo reads its focus");
|
|
1519
|
-
|
|
1611
|
+
// A graph space has no offsets (NAV.OFFSET), so an offset fails at each key.
|
|
1612
|
+
if (this.#graph || d === undefined || more.length > 0 || !Number.isInteger(d)) return `${F}()`;
|
|
1520
1613
|
// In a tree space, an offset goes among the siblings (NAV.OFFSET.TREE).
|
|
1521
1614
|
if (this.#tree) return `${this.use("SO")}(${this.#part("siblings", "GP")}, SI, ${focus}, ${d})`;
|
|
1522
1615
|
return `${this.use("X")}(${focus} + ${d}, n)`;
|
|
@@ -1723,24 +1816,31 @@ class Printer {
|
|
|
1723
1816
|
|
|
1724
1817
|
#app(e: ExprOf<"app">, ctx: Ctx): Code {
|
|
1725
1818
|
const { op, args } = e;
|
|
1819
|
+
// A branch of if and of ifError is at a place that takes a list when the node is.
|
|
1820
|
+
if ((op === "if" || op === "ifError") && this.#wantList.has(e)) for (const x of args.slice(op === "if" ? 1 : 0)) this.#wantList.add(x);
|
|
1726
1821
|
if (op === "if") return this.#if(args, ctx);
|
|
1727
1822
|
if (op === "and" || op === "or") return this.#andOr(op === "and", args, ctx);
|
|
1728
1823
|
if (op === "ifError") return this.#ifError(args, ctx);
|
|
1729
1824
|
const [head] = args;
|
|
1730
1825
|
const rest = args.slice(1);
|
|
1731
1826
|
// An each whose body is a list gives a list of lists (LIST.FLAT), so a list op over it goes over its array.
|
|
1732
|
-
if (
|
|
1827
|
+
if (FOLD_OPS.has(op) && head?.tag === "each" && !this.#isList(head.body, ctx)) return this.#list(op, head, rest, ctx);
|
|
1733
1828
|
// 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
|
|
1734
1829
|
// is one loop with a running value, not an array. A builder sheet prints such a let, for example `sum(let($0 = 0, each(…)))`.
|
|
1735
|
-
if (
|
|
1830
|
+
if (FOLD_OPS.has(op) && head?.tag === "let" && rest.every((x) => x.tag === "lit")) return this.#let(head, ctx, (body) => app(op, body, ...rest));
|
|
1736
1831
|
// sortBy and take are list ops for each receiver. Each other list op needs a list, and a domain can have its name.
|
|
1737
1832
|
if (head !== undefined && (op === "sortBy" || op === "take" || (op === "drop" && this.#isList(head, ctx)))) return this.#order(op, head, rest, ctx);
|
|
1738
1833
|
if (head !== undefined && BUILD_OPS.has(op) && this.#isList(head, ctx)) return this.#build(op, head, rest, ctx);
|
|
1739
|
-
if (head !== undefined && (
|
|
1834
|
+
if (head !== undefined && (FOLD_OPS.has(op) || op === "nth") && this.#isList(head, ctx)) return this.#overList(op, head, rest, ctx);
|
|
1740
1835
|
const raw = args.map((x) => this.expr(x, ctx));
|
|
1741
1836
|
const deps = depsOf(...raw);
|
|
1742
1837
|
// The interpreter evaluates each argument, also after an error.
|
|
1743
1838
|
const values = this.#inOrder(this.#settle(raw, deps, args), true);
|
|
1839
|
+
return this.#opCall(op, values, deps);
|
|
1840
|
+
}
|
|
1841
|
+
|
|
1842
|
+
/** This method prints the call of the op of a domain on some values, from the static site of their kinds. */
|
|
1843
|
+
#opCall(op: string, values: readonly Code[], deps: ReadonlySet<number>): Code {
|
|
1744
1844
|
const site = this.#facts.staticSite(op, values.map((x) => x.v.kind));
|
|
1745
1845
|
if (site?.t !== "fn") throw new NotStandalone(`the kinds of the values of "${op}" do not decide its op`);
|
|
1746
1846
|
if (site.bad) return { s: stmtsOf(...values), v: { code: `${this.use("F")}()`, kind: site.returns, safe: false, deps } };
|
|
@@ -1779,7 +1879,7 @@ class Printer {
|
|
|
1779
1879
|
const raw = [this.expr(c, ctx), this.expr(a, ctx), this.expr(b, ctx)];
|
|
1780
1880
|
const deps = depsOf(...raw);
|
|
1781
1881
|
const [cond, yes, no] = this.#settle(raw, deps, [c, a, b]) as [Code, Code, Code];
|
|
1782
|
-
const v = { kind: join(yes.v.kind, no.v.kind), safe: this.#safeBoolean(cond.v) && yes.v.safe && no.v.safe, deps };
|
|
1882
|
+
const v = { kind: join(yes.v.kind, no.v.kind), safe: this.#safeBoolean(cond.v) && yes.v.safe && no.v.safe, deps, list: branchLists("if", yes.v.list, no.v.list) };
|
|
1783
1883
|
if (yes.s.length === 0 && no.s.length === 0) return { s: cond.s, v: { ...v, code: `(${this.#boolean(cond.v)} ? ${yes.v.code} : ${no.v.code})` } };
|
|
1784
1884
|
const t = this.fresh("t");
|
|
1785
1885
|
const s = [...cond.s, `let ${t};`, `if (${this.#boolean(cond.v)}) {`, ...ind(yes.s), ` ${t} = ${yes.v.code};`, "} else {", ...ind(no.s), ` ${t} = ${no.v.code};`, "}"];
|
|
@@ -1811,7 +1911,7 @@ class Printer {
|
|
|
1811
1911
|
if (first.v.safe) return first;
|
|
1812
1912
|
const t = this.fresh("t");
|
|
1813
1913
|
const s = [`let ${t};`, "try {", ...ind(first.s), ` ${t} = ${first.v.code};`, "} catch {", ...ind(second.s), ` ${t} = ${second.v.code};`, "}"];
|
|
1814
|
-
return { s, v: { code: t, kind: join(first.v.kind, second.v.kind), safe: second.v.safe, deps } };
|
|
1914
|
+
return { s, v: { code: t, kind: join(first.v.kind, second.v.kind), safe: second.v.safe, deps, list: branchLists("ifError", first.v.list, second.v.list) } };
|
|
1815
1915
|
}
|
|
1816
1916
|
|
|
1817
1917
|
#opIndex(op: string): number {
|
|
@@ -1827,15 +1927,28 @@ class Printer {
|
|
|
1827
1927
|
* This method gives the option strict of a list op. The options must be one literal with only strict. Only a literal
|
|
1828
1928
|
* has a value, so another expression gives the reason too.
|
|
1829
1929
|
*/
|
|
1830
|
-
#strict(op: string, rest: readonly Expr[]): boolean {
|
|
1930
|
+
#strict(op: string, rest: readonly Expr[], names: readonly string[] = ["strict"]): boolean {
|
|
1831
1931
|
const [options, ...more] = rest;
|
|
1832
1932
|
if (more.length > 0) throw new NotStandalone(`"${op}" with more than one option`);
|
|
1833
1933
|
if (options === undefined) return false;
|
|
1834
1934
|
const opts = (options as { readonly value?: unknown }).value;
|
|
1835
|
-
if (typeof opts !== "object" || opts === null || Object.keys(opts).some((k) => k
|
|
1935
|
+
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 ")}`);
|
|
1836
1936
|
return (opts as { readonly strict?: unknown }).strict === true;
|
|
1837
1937
|
}
|
|
1838
1938
|
|
|
1939
|
+
/**
|
|
1940
|
+
* This method gives the option strict of a list op. For `reduce`, it also gives the op of each step: the first
|
|
1941
|
+
* argument, a literal text, and the value of the option `domain` (COMPILE.MODULE.REDUCE).
|
|
1942
|
+
*/
|
|
1943
|
+
#foldOptions(op: string, rest: readonly Expr[]): { readonly strict: boolean; readonly step: Step | undefined } {
|
|
1944
|
+
if (op !== "reduce") return { strict: this.#strict(op, rest), step: undefined };
|
|
1945
|
+
const [name, ...options] = rest;
|
|
1946
|
+
const value = (name as { readonly value?: unknown } | undefined)?.value;
|
|
1947
|
+
if (name?.tag !== "lit" || typeof value !== "string") throw new NotStandalone('"reduce" without a literal text as its op');
|
|
1948
|
+
const strict = this.#strict(op, options, ["strict", "domain"]);
|
|
1949
|
+
return { strict, step: { op: value, domain: (options[0] as { readonly value?: { readonly domain?: unknown } } | undefined)?.value?.domain } };
|
|
1950
|
+
}
|
|
1951
|
+
|
|
1839
1952
|
/**
|
|
1840
1953
|
* A list op over an axis: one `for` loop with a running value. An item with an error is skipped, and with `strict` it
|
|
1841
1954
|
* is an error of the list op. A value of the wrong kind is an error of the list op, as in the interpreter.
|
|
@@ -1902,6 +2015,13 @@ class Printer {
|
|
|
1902
2015
|
const q = this.fresh("q");
|
|
1903
2016
|
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 };
|
|
1904
2017
|
}
|
|
2018
|
+
// 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.
|
|
2019
|
+
if (this.#graph && GRAPH_AXES.has(base.t)) {
|
|
2020
|
+
const range = this.#graphRange(base.t, f as string);
|
|
2021
|
+
const q = this.fresh("q");
|
|
2022
|
+
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 };
|
|
2023
|
+
}
|
|
2024
|
+
if (this.#graph && base.t === "window") throw new NotStandalone('the axis "window" in a graph space');
|
|
1905
2025
|
if (base.t === "others") skip = f;
|
|
1906
2026
|
else if (base.t === "window") {
|
|
1907
2027
|
const h = this.fresh("h");
|
|
@@ -1912,6 +2032,21 @@ class Printer {
|
|
|
1912
2032
|
return { s, j, head: forHead(j, lo, hi, reverse), key: [], check: [], skip, fixed: f === undefined, start, startSafe, tests, inner };
|
|
1913
2033
|
}
|
|
1914
2034
|
|
|
2035
|
+
/**
|
|
2036
|
+
* This method gives the targets of an axis of a graph space at the position `f` (AXIS.GRAPH). They are the positions
|
|
2037
|
+
* `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.
|
|
2038
|
+
*/
|
|
2039
|
+
#graphRange(t: string, f: string): TreeRange {
|
|
2040
|
+
const a = this.fresh("A");
|
|
2041
|
+
const range = (code: string, lo = "0"): TreeRange => ({ s: [`const ${a} = ${code};`], a, lo, hi: `${a}.length`, skip: undefined });
|
|
2042
|
+
if (t === "successors") return range(`GO[${f}]`);
|
|
2043
|
+
if (t === "predecessors") {
|
|
2044
|
+
this.into = true;
|
|
2045
|
+
return range(`GN[${f}]`);
|
|
2046
|
+
}
|
|
2047
|
+
return range(`${this.use("RB")}(GO, ${f}, n)`, "1");
|
|
2048
|
+
}
|
|
2049
|
+
|
|
1915
2050
|
/**
|
|
1916
2051
|
* This method gives the targets of an axis of a tree space at the position `f`. They are the positions `a[q]` for `q`
|
|
1917
2052
|
* from `lo` up to `hi`, without the key that the loop skips. The axes come from AXIS.TREE, AXIS.GRAPH and AXIS.WINDOW.
|
|
@@ -1950,7 +2085,7 @@ class Printer {
|
|
|
1950
2085
|
}
|
|
1951
2086
|
|
|
1952
2087
|
#list(op: string, target: ExprOf<"each">, rest: readonly Expr[], ctx: Ctx): Code {
|
|
1953
|
-
const strict = this.#
|
|
2088
|
+
const { strict, step } = this.#foldOptions(op, rest);
|
|
1954
2089
|
const at = target.at ?? [];
|
|
1955
2090
|
const { s, j, head, key, check, skip, fixed, start, startSafe, tests, inner } = this.#targetLoop(target.axis, at, ctx);
|
|
1956
2091
|
const { level } = inner;
|
|
@@ -1962,7 +2097,7 @@ class Printer {
|
|
|
1962
2097
|
// itself gives `#CYCLE!`.
|
|
1963
2098
|
if (op === "count" && fixed && tests.length === 0 && body.v.safe && !body.v.deps.has(CELLS)) return bare(plainValue("n", "number"));
|
|
1964
2099
|
const deps = new Set([...start, ...[body, ...testCodes].flatMap((x) => [...x.v.deps])].filter((d) => d !== level));
|
|
1965
|
-
const r = this.#reduction(op, body.v.kind);
|
|
2100
|
+
const r = this.#reduction(op, body.v.kind, step);
|
|
1966
2101
|
const { v } = r;
|
|
1967
2102
|
s.push(r.init);
|
|
1968
2103
|
const item = [...check, ...testCodes.flatMap((t) => [...t.s, `if (!${this.#boolean(t.v)}) continue;`]), ...body.s];
|
|
@@ -1975,7 +2110,7 @@ class Printer {
|
|
|
1975
2110
|
const x = this.fresh("x");
|
|
1976
2111
|
const all = [...key, ...(skip === undefined ? [] : [`if (${j} === ${skip}) continue;`]), `let ${x};`, "try {", ...ind(item), ` ${x} = ${body.v.code};`, "} catch {", ` ${x} = E;`, "}", `${list}.push(${x});`];
|
|
1977
2112
|
const reduce = [`for (const ${v} of ${list}) {`, ` if (${v} === E) ${strict ? `${this.use("F")}();` : "continue;"}`, ` ${r.step}`, "}"];
|
|
1978
|
-
return { s: [...s, `const ${list} = [];`, head, ...ind(all), "}", ...reduce], v: { code: r.result, kind:
|
|
2113
|
+
return { s: [...s, `const ${list} = [];`, head, ...ind(all), "}", ...reduce], v: { code: r.result, kind: r.kind, safe: false, deps } };
|
|
1979
2114
|
}
|
|
1980
2115
|
const loop = [
|
|
1981
2116
|
...key,
|
|
@@ -1989,17 +2124,18 @@ class Printer {
|
|
|
1989
2124
|
// A count without strict, and any, all and none over booleans without strict, cannot fail. The address of the axis
|
|
1990
2125
|
// can fail, except at the focus or at the origin.
|
|
1991
2126
|
const safe = startSafe && !strict && (op === "count" || (BOOLEAN_LIST_OPS.has(op) && body.v.kind === "boolean"));
|
|
1992
|
-
return { s, v: { code: r.result, kind:
|
|
2127
|
+
return { s, v: { code: r.result, kind: r.kind, safe, deps } };
|
|
1993
2128
|
}
|
|
1994
2129
|
|
|
1995
2130
|
/**
|
|
1996
2131
|
* This method gives the parts of a list op that reduces the values of its items. The parts are the variable `v` of
|
|
1997
2132
|
* 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.
|
|
1998
2133
|
*/
|
|
1999
|
-
#reduction(op: string, kind: Kind | undefined): { readonly v: string; readonly init: string; readonly step: string; readonly result: string } {
|
|
2134
|
+
#reduction(op: string, kind: Kind | undefined, step?: Step): { readonly v: string; readonly init: string; readonly step: string; readonly result: string; readonly kind: Kind | undefined } {
|
|
2000
2135
|
const a = this.fresh("a");
|
|
2001
2136
|
const n = this.fresh("n");
|
|
2002
2137
|
const v = this.fresh("x");
|
|
2138
|
+
if (step !== undefined) return { v, init: `let ${a}, ${n} = 0;`, ...this.#reduceStep(step, kind, a, n, v) };
|
|
2003
2139
|
const num = kind === "number" ? v : `${this.use("U")}(${v})`;
|
|
2004
2140
|
const bool = kind === "boolean" ? v : `${this.use("B")}(${v})`;
|
|
2005
2141
|
const inits: Readonly<Record<string, string>> = {
|
|
@@ -2030,7 +2166,40 @@ class Printer {
|
|
|
2030
2166
|
all: a,
|
|
2031
2167
|
none: `!${a}`,
|
|
2032
2168
|
};
|
|
2033
|
-
return { v, init: inits[op] ?? `let ${a}, ${n} = 0;`, step: steps[op] as string, result: results[op] ?? `(${n} === 0 ? ${F}() : ${a})
|
|
2169
|
+
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) };
|
|
2170
|
+
}
|
|
2171
|
+
|
|
2172
|
+
/**
|
|
2173
|
+
* This method gives the step and the result of `reduce` (COMPILE.MODULE.REDUCE), as in the interpreter. The first item
|
|
2174
|
+
* is the first running value. Each later item goes into the op of the domain of the running value. The kinds of the
|
|
2175
|
+
* items decide that op, and the op must give a value of the same kind. No items give the identity of the op.
|
|
2176
|
+
*/
|
|
2177
|
+
#reduceStep(step: Step, kind: Kind | undefined, a: string, n: string, v: string): { readonly step: string; readonly result: string; readonly kind: Kind | undefined } {
|
|
2178
|
+
const arg = (code: string): Code => bare({ code, kind, safe: true, deps: NO_DEPS, plain: true });
|
|
2179
|
+
const opCode = this.#opCall(step.op, [arg(a), arg(v)], NO_DEPS);
|
|
2180
|
+
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`);
|
|
2181
|
+
const empty = this.#identity(step);
|
|
2182
|
+
// The identity of another domain is a value of another kind, so the kind of the result is not known.
|
|
2183
|
+
return { step: `${a} = ${n}++ === 0 ? ${v} : ${opCode.v.code};`, result: `(${n} === 0 ? ${empty.code} : ${a})`, kind: empty.kind === undefined || empty.kind === kind ? kind : undefined };
|
|
2184
|
+
}
|
|
2185
|
+
|
|
2186
|
+
/**
|
|
2187
|
+
* This method gives the code of `reduce` over no items, as in the interpreter. The code is the identity of the op in
|
|
2188
|
+
* the one domain that has one, or in the domain of the option `domain`. Another case is an error. The kind is the kind
|
|
2189
|
+
* of the domain.
|
|
2190
|
+
*/
|
|
2191
|
+
#identity(step: Step): { readonly code: string; readonly kind: Kind | undefined } {
|
|
2192
|
+
const { op, domain } = step;
|
|
2193
|
+
const fail = { code: `${this.use("F")}()`, kind: undefined };
|
|
2194
|
+
// A name of a domain that the program does not have leaves no domain, so it gives the error too.
|
|
2195
|
+
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));
|
|
2196
|
+
const [only, second] = found;
|
|
2197
|
+
if (only === undefined || second !== undefined) return fail;
|
|
2198
|
+
const [i, d] = only;
|
|
2199
|
+
const name = `id_${String(i)}_${String(this.#opIndex(op))}`;
|
|
2200
|
+
// Stryker disable next-line ConditionalExpression: the copy of an identity is always the same, so the test only saves time
|
|
2201
|
+
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}`)};`);
|
|
2202
|
+
return { code: `${name}()`, kind: kindOfDomain(d) };
|
|
2034
2203
|
}
|
|
2035
2204
|
|
|
2036
2205
|
/**
|
|
@@ -2097,7 +2266,7 @@ class Printer {
|
|
|
2097
2266
|
if (op === "get") return value(info.item, info.inner);
|
|
2098
2267
|
if (op === "indexOf") return value("number", undefined);
|
|
2099
2268
|
if (op === "without") return value(undefined, info);
|
|
2100
|
-
if (op === "append") return value(undefined, joinLists(info, (parts[1] as Code).v.list as ListInfo));
|
|
2269
|
+
if (op === "append") return value(undefined, joinLists(info, (parts[1] as Code).v.list as ListInfo, op));
|
|
2101
2270
|
// 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.
|
|
2102
2271
|
if (info.empty === true) return value(undefined, info);
|
|
2103
2272
|
if (info.inner === undefined) throw new NotStandalone('"flat" over a list whose items are not lists');
|
|
@@ -2109,7 +2278,7 @@ class Printer {
|
|
|
2109
2278
|
const list = this.#listOf(head, ctx);
|
|
2110
2279
|
// A missing position is the literal null, which is not a whole number, so nth gives its error.
|
|
2111
2280
|
const exprs = [head, ...(op === "nth" ? [rest[0] ?? lit(null)] : [])];
|
|
2112
|
-
const strict = this.#
|
|
2281
|
+
const { strict, step } = this.#foldOptions(op, rest.slice(exprs.length - 1));
|
|
2113
2282
|
const raw = [list, ...exprs.slice(1).map((x) => this.expr(x, ctx))];
|
|
2114
2283
|
const deps = depsOf(...raw);
|
|
2115
2284
|
const parts = this.#inOrder(this.#settle(raw, deps, exprs), true);
|
|
@@ -2117,10 +2286,10 @@ class Printer {
|
|
|
2117
2286
|
const { item, inner } = list.v.list as ListInfo;
|
|
2118
2287
|
// The value of an item of a list of lists is a list, so nth and first give a list (LIST.FLAT).
|
|
2119
2288
|
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 } };
|
|
2120
|
-
const r = this.#reduction(op, item);
|
|
2289
|
+
const r = this.#reduction(op, item, step);
|
|
2121
2290
|
const { v } = r;
|
|
2122
2291
|
const s = [...l.s, r.init, `for (const [, ${v}] of ${l.v.code}) {`, ` if (${v} === E) ${strict ? `${this.use("F")}();` : "continue;"}`, ` ${r.step}`, "}"];
|
|
2123
|
-
return { s, v: { code: r.result, kind:
|
|
2292
|
+
return { s, v: { code: r.result, kind: r.kind, safe: false, deps, list: op === "first" ? inner : undefined } };
|
|
2124
2293
|
}
|
|
2125
2294
|
|
|
2126
2295
|
/**
|
|
@@ -2367,6 +2536,8 @@ class Printer {
|
|
|
2367
2536
|
/** This method gives the code of the program at the key of the run. A constant of the run evaluates once. */
|
|
2368
2537
|
/** This method gives the code of a program at the key `o` of the run. A sheet has one program for each formula. */
|
|
2369
2538
|
root(expr: Expr): Code {
|
|
2539
|
+
// The value of a program and of a cell can be a list (COMPILE.MODULE.LIST.RESULT).
|
|
2540
|
+
this.#wantList.add(expr);
|
|
2370
2541
|
return this.#hoist(this.expr(expr, { origin: "o", focus: "o", level: 1, originLevel: 1, env: new Map(), fns: new Map(), keys: new Map() }));
|
|
2371
2542
|
}
|
|
2372
2543
|
|
|
@@ -2395,12 +2566,19 @@ class Printer {
|
|
|
2395
2566
|
}
|
|
2396
2567
|
|
|
2397
2568
|
/** This function gives the name of the function of a module, and its space, or the reason that the options are not valid. */
|
|
2398
|
-
function runOf(options: ModuleOptions):
|
|
2569
|
+
function runOf(options: ModuleOptions): Run | { readonly reason: string } {
|
|
2399
2570
|
const name = options.name ?? "run";
|
|
2400
2571
|
if (!/^[A-Za-z_$][\w$]*$/.test(name)) return { reason: `the name "${name}" is not a JavaScript name` };
|
|
2401
|
-
const
|
|
2402
|
-
if (
|
|
2403
|
-
return { name, tree };
|
|
2572
|
+
const space = options.space ?? "array";
|
|
2573
|
+
if (space !== "array" && space !== "tree" && space !== "graph") return { reason: `the space "${String(space)}" is not "array", "tree" or "graph"` };
|
|
2574
|
+
return { name, tree: space === "tree", graph: space === "graph" };
|
|
2575
|
+
}
|
|
2576
|
+
|
|
2577
|
+
/** The function of a module: its name, and its space. */
|
|
2578
|
+
interface Run {
|
|
2579
|
+
readonly name: string;
|
|
2580
|
+
readonly tree: boolean;
|
|
2581
|
+
readonly graph: boolean;
|
|
2404
2582
|
}
|
|
2405
2583
|
|
|
2406
2584
|
/** This function gives the reason of an error of the printer. Another exception is a defect, so it goes to the caller. */
|
|
@@ -2413,7 +2591,7 @@ function reasonOf(thrown: unknown): Emitted {
|
|
|
2413
2591
|
* This function gives the text of a module: the declarations, the helpers, and the function of the run. The run checks
|
|
2414
2592
|
* its input, computes the parts of the tree and the constants of the run, and then gives the statements `body`.
|
|
2415
2593
|
*/
|
|
2416
|
-
function printModule(p: Printer, options: ModuleOptions, run:
|
|
2594
|
+
function printModule(p: Printer, options: ModuleOptions, run: Run, body: readonly string[]): Emitted {
|
|
2417
2595
|
p.use("C");
|
|
2418
2596
|
const helpers = new Set<Helper>();
|
|
2419
2597
|
// A helper comes after the helpers that it needs. A set keeps the first place of each helper.
|
|
@@ -2431,13 +2609,16 @@ function printModule(p: Printer, options: ModuleOptions, run: { readonly name: s
|
|
|
2431
2609
|
} catch (thrown) {
|
|
2432
2610
|
return reasonOf(thrown);
|
|
2433
2611
|
}
|
|
2434
|
-
const { name, tree } = run;
|
|
2612
|
+
const { name, tree, graph } = run;
|
|
2435
2613
|
// A tree checks its parents, and it computes the parts that the program reads. The siblings and the order need the
|
|
2436
2614
|
// children.
|
|
2437
2615
|
if (tree) p.use("PT");
|
|
2438
2616
|
if (p.treeParts.size > 0) p.treeParts.add("children");
|
|
2439
2617
|
const parts = (["children", "siblings", "order"] as const).filter((x) => p.treeParts.has(x));
|
|
2440
2618
|
for (const x of parts) p.use(TREE_PARTS[x][0]);
|
|
2619
|
+
// A graph checks its edges, and it computes the predecessors if the program reads them.
|
|
2620
|
+
if (graph) p.use("GR");
|
|
2621
|
+
if (p.into) p.use("GI");
|
|
2441
2622
|
[...p.helpers].toSorted().forEach(add);
|
|
2442
2623
|
// The names that this module declares at its top: the constants, the helpers and the declarations of the printer.
|
|
2443
2624
|
const declared = new Set<string>(["VexContractError", "VEX_ERROR", "E", ...(p.memos ? ["Z"] : []), ...(helpers.has("S") ? ["N", "W"] : []), ...helpers, ...p.top.keys()]);
|
|
@@ -2455,7 +2636,7 @@ function printModule(p: Printer, options: ModuleOptions, run: { readonly name: s
|
|
|
2455
2636
|
...(helpers.has("S") ? ["const N = {}, W = {};"] : []),
|
|
2456
2637
|
...[...helpers].map((h) => (h === "S" ? helperS(p.features) : HELPERS[h])),
|
|
2457
2638
|
...p.top.values(),
|
|
2458
|
-
`export function ${name}(records, vars${tree ? ", parents" : ""}) {`,
|
|
2639
|
+
`export function ${name}(records, vars${tree ? ", parents" : graph ? ", edges" : ""}) {`,
|
|
2459
2640
|
' if (!Array.isArray(records)) C("the records are not an array");',
|
|
2460
2641
|
" const R = records;",
|
|
2461
2642
|
" const n = R.length;",
|
|
@@ -2465,6 +2646,7 @@ function printModule(p: Printer, options: ModuleOptions, run: { readonly name: s
|
|
|
2465
2646
|
" }",
|
|
2466
2647
|
` if (typeof vars !== "object" || vars === null${varChecks}) C("the variables do not keep the schema");`,
|
|
2467
2648
|
...(tree ? [" const P = PT(parents, n);", ...parts.map((x) => ` ${TREE_PARTS[x][1]}`)] : []),
|
|
2649
|
+
...(graph ? [" const GO = GR(edges, n);", ...(p.into ? [" const GN = GI(GO, n);"] : [])] : []),
|
|
2468
2650
|
...[...p.vars].map(([v, code]) => ` const ${code} = vars[${JSON.stringify(v)}];`),
|
|
2469
2651
|
...ind(p.run),
|
|
2470
2652
|
...ind(body),
|
|
@@ -2498,7 +2680,9 @@ export function emitModule(source: Expr | Envelope, options: ModuleOptions): Emi
|
|
|
2498
2680
|
} catch (thrown) {
|
|
2499
2681
|
return reasonOf(thrown);
|
|
2500
2682
|
}
|
|
2501
|
-
|
|
2683
|
+
// A list gives a vex.list (COMPILE.MODULE.LIST.RESULT).
|
|
2684
|
+
const result = value.v.list === undefined ? value.v.code : `${p.use("LO")}(${value.v.code}, ${String(depthOf(value.v.list))})`;
|
|
2685
|
+
const body = ["const out = [];", "for (let o = 0; o < n; o++) {", " try {", ...ind(ind(value.s)), ` out.push(${result});`, " } catch {", " out.push(VEX_ERROR);", " }", "}", "return out;"];
|
|
2502
2686
|
return printModule(p, options, run, body);
|
|
2503
2687
|
}
|
|
2504
2688
|
|
|
@@ -2515,8 +2699,23 @@ interface Formula {
|
|
|
2515
2699
|
/** This function gives the words for a formula in a reason: the formula of a column, or of one cell. */
|
|
2516
2700
|
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)}"`);
|
|
2517
2701
|
|
|
2518
|
-
/** This function gives the words for a kind in a reason. */
|
|
2519
|
-
const kindText = (k: Kind | undefined): string => k ?? "that the printer does not know";
|
|
2702
|
+
/** This function gives the words for a kind in a reason. A list gives the kind of its items. */
|
|
2703
|
+
const kindText = (k: Kind | undefined, l?: ListInfo): string => (l === undefined ? (k ?? "that the printer does not know") : `list of ${l.inner === undefined ? kindText(l.item) : kindText(undefined, l.inner)}`);
|
|
2704
|
+
|
|
2705
|
+
/** This function gives the number of the levels of lists in the items of a list: 0 for a list of values. */
|
|
2706
|
+
const depthOf = (l: ListInfo): number => (l.inner === undefined ? 0 : 1 + depthOf(l.inner));
|
|
2707
|
+
|
|
2708
|
+
/** This function gives the facts of the lists of a column from the kind of the option `kinds` (COMPILE.MODULE.SHEET.LIST). */
|
|
2709
|
+
const listOfKind = (k: ListKind): ListInfo => {
|
|
2710
|
+
const texts = k.texts === true;
|
|
2711
|
+
return typeof k.list === "object" ? { item: undefined, inner: listOfKind(k.list), texts } : { item: k.list, texts };
|
|
2712
|
+
};
|
|
2713
|
+
|
|
2714
|
+
/**
|
|
2715
|
+
* This function gives the facts of the lists of a column from the list of its first formula. The other cells of the
|
|
2716
|
+
* column can have other formulas. Thus a list without items does not tell that each list of the column is empty.
|
|
2717
|
+
*/
|
|
2718
|
+
const columnList = (l: ListInfo): ListInfo => ({ item: l.item, inner: l.inner === undefined ? undefined : columnList(l.inner), texts: l.texts === true });
|
|
2520
2719
|
|
|
2521
2720
|
/**
|
|
2522
2721
|
* This function prints the formula columns of a sheet as a standalone ES module (COMPILE.MODULE.SHEET). The function of
|
|
@@ -2547,19 +2746,43 @@ export function emitSheetModule(columns: ReadonlyMap<string, Expr>, options: She
|
|
|
2547
2746
|
const shape = shapeError(f.expr);
|
|
2548
2747
|
if (shape !== undefined) return { ok: false, reason: `${formulaText(f)}: ${shape}` };
|
|
2549
2748
|
}
|
|
2550
|
-
const kinds = new Map<string, Kind | undefined>(
|
|
2749
|
+
const kinds = new Map<string, Kind | undefined>();
|
|
2750
|
+
const lists = new Map<string, ListInfo>();
|
|
2751
|
+
for (const [c, k] of Object.entries(options.kinds ?? {})) {
|
|
2752
|
+
kinds.set(c, typeof k === "object" ? undefined : k);
|
|
2753
|
+
if (typeof k === "object") lists.set(c, listOfKind(k));
|
|
2754
|
+
}
|
|
2551
2755
|
const index = new Map(names.map((c, i) => [c, i]));
|
|
2552
2756
|
// The memo of the printer covers each formula, so the formulas share their nodes of the memo.
|
|
2553
|
-
|
|
2757
|
+
// A sheet whose reads all read finished cells needs no search: each cell is the value of its formula
|
|
2758
|
+
// (COMPILE.MODULE.SHEET.DIRECT). A sheet with formulas of cells always has the search.
|
|
2759
|
+
const direct = formulas.every((f) => f.key === undefined) && order.every((c) => readsFinished(columns, order, c, run.tree));
|
|
2760
|
+
const p = new Printer(rec(Object.fromEntries(formulas.map((f, i) => [`f${String(i)}`, f.expr]))), options, { columns: index, kinds, lists, direct });
|
|
2554
2761
|
const fns: string[] = [];
|
|
2555
2762
|
const decls: string[] = [];
|
|
2763
|
+
// The statements that put the value of each formula into the array of its column at the key `o`, for a direct fill.
|
|
2764
|
+
const blocks = new Map<string, readonly string[]>();
|
|
2556
2765
|
try {
|
|
2557
2766
|
for (const f of formulas) {
|
|
2558
2767
|
const code = p.root(f.expr);
|
|
2559
|
-
const kind = code.v
|
|
2560
|
-
// The first formula of a column without a kind of the options gives the kind of the column.
|
|
2561
|
-
|
|
2562
|
-
|
|
2768
|
+
const { kind, list } = code.v;
|
|
2769
|
+
// The first formula of a column without a kind of the options gives the kind of the column. Each other formula
|
|
2770
|
+
// must give a value of that kind, or a list that fits the lists of the column (COMPILE.MODULE.SHEET.LIST).
|
|
2771
|
+
if (!kinds.has(f.column)) {
|
|
2772
|
+
kinds.set(f.column, kind);
|
|
2773
|
+
if (list !== undefined) lists.set(f.column, columnList(list));
|
|
2774
|
+
} else {
|
|
2775
|
+
const known = lists.get(f.column);
|
|
2776
|
+
if (kinds.get(f.column) !== kind || (known === undefined) !== (list === undefined) || (known !== undefined && !fits(known, list as ListInfo))) {
|
|
2777
|
+
throw new NotStandalone(`${formulaText(f)} gives a value of the kind ${kindText(kind, list)}, not of the kind ${kindText(kinds.get(f.column), known)} of its column`);
|
|
2778
|
+
}
|
|
2779
|
+
}
|
|
2780
|
+
// COMPILE.MODULE.ONCE: a direct fill has the code of each formula in its loop over the keys, with no function.
|
|
2781
|
+
if (direct) {
|
|
2782
|
+
const at = `D[${String(index.get(f.column))}][o]`;
|
|
2783
|
+
blocks.set(f.column, code.v.safe && code.s.length === 0 ? [`${at} = ${code.v.code};`] : ["try {", ...ind(code.s), ` ${at} = ${code.v.code};`, "} catch {", ` ${at} = E;`, "}"]);
|
|
2784
|
+
continue;
|
|
2785
|
+
}
|
|
2563
2786
|
const fn = p.fresh("cf");
|
|
2564
2787
|
fns.push(fn);
|
|
2565
2788
|
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;", " }", "};"]));
|
|
@@ -2568,39 +2791,58 @@ export function emitSheetModule(columns: ReadonlyMap<string, Expr>, options: She
|
|
|
2568
2791
|
} catch (thrown) {
|
|
2569
2792
|
return reasonOf(thrown);
|
|
2570
2793
|
}
|
|
2571
|
-
|
|
2572
|
-
const entry = (i: number): string => `[${fns[i] as string}, ${String(3 * nestingOf((formulas[i] as Formula).expr) + 16)}]`;
|
|
2573
|
-
const own = names.map((c) => {
|
|
2574
|
-
const at = formulas.flatMap((f, i) => (f.column === c && f.key !== undefined ? [`${String(f.key)}: ${entry(i)}`] : []));
|
|
2575
|
-
return at.length === 0 ? "undefined" : `{ ${at.join(", ")} }`;
|
|
2576
|
-
});
|
|
2577
|
-
const cols = names.map((c) => {
|
|
2578
|
-
const i = formulas.findIndex((f) => f.column === c && f.key === undefined);
|
|
2579
|
-
return i < 0 ? "undefined" : entry(i);
|
|
2580
|
-
});
|
|
2581
|
-
p.use("SH");
|
|
2794
|
+
p.use(direct ? "DO" : "SH");
|
|
2582
2795
|
// A tree gives the keys in the order of a fill with the helper KO, once for each order.
|
|
2583
2796
|
const orders = new Map<string, string>();
|
|
2584
|
-
const
|
|
2797
|
+
const headOf = (c: string): string => {
|
|
2585
2798
|
const { reverse, post, back } = keyOrderOf(readsOf(columns, cells, c).directions);
|
|
2586
|
-
|
|
2587
|
-
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);`;
|
|
2799
|
+
if (!run.tree) return reverse ? "for (let o = n - 1; o >= 0; o--)" : "for (let o = 0; o < n; o++)";
|
|
2588
2800
|
const args = `${p.use("KO")}(H, RT, ${String(post)}, ${String(back)})`;
|
|
2589
2801
|
let keys = orders.get(args);
|
|
2590
2802
|
if (keys === undefined) {
|
|
2591
2803
|
keys = p.fresh("K");
|
|
2592
2804
|
orders.set(args, keys);
|
|
2593
2805
|
}
|
|
2594
|
-
return `for (const o of ${keys})
|
|
2595
|
-
}
|
|
2806
|
+
return `for (const o of ${keys})`;
|
|
2807
|
+
};
|
|
2808
|
+
let fill: string[];
|
|
2809
|
+
if (direct) {
|
|
2810
|
+
// COMPILE.MODULE.ONCE: the columns that follow each other in the order share one loop over the keys when they have
|
|
2811
|
+
// the same order of the keys, and each read of a column of the loop reads a finished cell.
|
|
2812
|
+
const loops: { head: string; columns: string[] }[] = [];
|
|
2813
|
+
for (const c of order) {
|
|
2814
|
+
const head = headOf(c);
|
|
2815
|
+
const last = loops.at(-1);
|
|
2816
|
+
if (last?.head === head && readsFinished(columns, order, c, run.tree, new Set(last.columns))) last.columns.push(c);
|
|
2817
|
+
else loops.push({ head, columns: [c] });
|
|
2818
|
+
}
|
|
2819
|
+
fill = [];
|
|
2820
|
+
for (const { head, columns: cs } of loops) fill.push(`${head} {`, ...cs.flatMap((c) => ind(blocks.get(c) as readonly string[])), "}");
|
|
2821
|
+
} else {
|
|
2822
|
+
// The program of each column, and of each cell with its own formula, with its cost in estimated frames, as in SheetRun.
|
|
2823
|
+
const entry = (i: number): string => `[${fns[i] as string}, ${String(3 * nestingOf((formulas[i] as Formula).expr) + 16)}]`;
|
|
2824
|
+
const own = names.map((c) => {
|
|
2825
|
+
const at = formulas.flatMap((f, i) => (f.column === c && f.key !== undefined ? [`${String(f.key)}: ${entry(i)}`] : []));
|
|
2826
|
+
return at.length === 0 ? "undefined" : `{ ${at.join(", ")} }`;
|
|
2827
|
+
});
|
|
2828
|
+
const cols = names.map((c) => {
|
|
2829
|
+
const i = formulas.findIndex((f) => f.column === c && f.key === undefined);
|
|
2830
|
+
return i < 0 ? "undefined" : entry(i);
|
|
2831
|
+
});
|
|
2832
|
+
decls.push(`const SS = SH(n, [${cols.join(", ")}], [${own.join(", ")}], ${String(budget)});`, `const ${READ_CELL} = SS.r;`);
|
|
2833
|
+
fill = order.map((c) => `${headOf(c)} SS.f(${String(index.get(c))}, o);`);
|
|
2834
|
+
}
|
|
2596
2835
|
if (run.tree) p.treeParts.add("children");
|
|
2836
|
+
// A column of lists gives a vex.list in each cell with a list (COMPILE.MODULE.LIST.RESULT).
|
|
2837
|
+
const resultOf = (c: string, read: string): string => {
|
|
2838
|
+
const l = lists.get(c);
|
|
2839
|
+
return l === undefined ? read : `${p.use("LC")}(${read}, ${String(depthOf(l))})`;
|
|
2840
|
+
};
|
|
2597
2841
|
const body = [
|
|
2598
|
-
...decls,
|
|
2599
|
-
`const SS = SH(n, [${cols.join(", ")}], [${own.join(", ")}], ${String(budget)});`,
|
|
2600
|
-
`const ${READ_CELL} = SS.r;`,
|
|
2842
|
+
...(direct ? [`const D = [${names.map(() => "new Array(n)").join(", ")}];`] : decls),
|
|
2601
2843
|
...[...orders].map(([args, keys]) => `const ${keys} = ${args};`),
|
|
2602
2844
|
...fill,
|
|
2603
|
-
`return { ${names.map((c, i) => `${JSON.stringify(c)}: SS.o(${String(i)})`).join(", ")} };`,
|
|
2845
|
+
`return { ${names.map((c, i) => `${JSON.stringify(c)}: ${resultOf(c, direct ? `DO(D[${String(i)}])` : `SS.o(${String(i)})`)}`).join(", ")} };`,
|
|
2604
2846
|
];
|
|
2605
2847
|
return printModule(p, options, run, body);
|
|
2606
2848
|
}
|