@mark1russell7/vex-compiler 0.13.2 → 0.13.4
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 +14 -13
- package/build/index.d.ts.map +1 -1
- package/build/index.js +499 -123
- package/build/index.js.map +1 -1
- package/package.json +4 -4
- package/src/facts.ts +37 -10
- package/src/index.ts +1 -1
- package/src/module.ts +462 -111
- package/src/sheet-order.ts +11 -4
package/src/module.ts
CHANGED
|
@@ -19,15 +19,20 @@
|
|
|
19
19
|
* the fields and the variables of the schema. It takes the axes `all`, `others` and `window`. A tree space also has the
|
|
20
20
|
* move `parent` and the axes of a tree (COMPILE.MODULE.TREE). A graph space has the axes of a graph
|
|
21
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
|
|
23
|
-
*
|
|
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). An op and a record get each list of an
|
|
24
|
+
* argument or a field as a `vex.list` too (COMPILE.MODULE.LIST.ARG, COMPILE.MODULE.LIST.FIELD). The value of a call
|
|
25
|
+
* can be a list (COMPILE.MODULE.LIST.CALL). A field of the schema can have a list kind, and the record then holds a
|
|
26
|
+
* `vex.list` (COMPILE.MODULE.LIST.INPUT). The kinds of each op site must decide its op.
|
|
27
|
+
* Another construct gives a reason, not code.
|
|
24
28
|
*
|
|
25
29
|
* `emitSheetModule` prints the formula columns of a sheet as one module (COMPILE.MODULE.SHEET). Each column is an array
|
|
26
30
|
* of results, and the run fills the arrays in the static order of `SheetRun.fill`. A read of a cell that is not finished
|
|
27
|
-
* starts the search of `SheetRun`. Thus each cell on a cycle gives the error of Vex.
|
|
31
|
+
* starts the search of `SheetRun`. Thus each cell on a cycle gives the error of Vex. A cell can hold a list, and a
|
|
32
|
+
* formula reads it with the list ops (COMPILE.MODULE.SHEET.LIST).
|
|
28
33
|
*/
|
|
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";
|
|
30
|
-
import { factsOf, kindOfDomain, primitiveOf, type Facts, type Kind, type Schema } from "./facts.ts";
|
|
34
|
+
import { addrExprs, app, CELL_KIND, children, fromDocument, isDocument, isFieldName, isListOp, isVexList, lit, moveExpr, nestingOf, rec, shapeError, vexList, type AnyDomain, type Axis, type CellFormulas, type Envelope, type Expr, type ExprOf, type Move, type Names, type PrimitiveKind, type VexList } from "@mark1russell7/vex";
|
|
35
|
+
import { factsOf, kindOfDomain, primitiveOf, type Facts, type Kind, type ListKind, type Schema } from "./facts.ts";
|
|
31
36
|
import { memoNodes } from "./memo.ts";
|
|
32
37
|
import { columnOrder, isCellRef, keyOrderOf, readsFinished, readsOf } from "./sheet-order.ts";
|
|
33
38
|
|
|
@@ -57,12 +62,15 @@ export interface SheetModuleOptions extends ModuleOptions {
|
|
|
57
62
|
/**
|
|
58
63
|
* The kind of the values of each column. The printer prints each column after the columns that it reads. A column
|
|
59
64
|
* that a formula reads before its own formula prints needs its kind here, for example a column that reads itself.
|
|
65
|
+
* A column of lists has a `ListKind` (COMPILE.MODULE.SHEET.LIST).
|
|
60
66
|
*/
|
|
61
|
-
readonly kinds?: Readonly<Record<string, Kind>>;
|
|
67
|
+
readonly kinds?: Readonly<Record<string, Kind | ListKind>>;
|
|
62
68
|
/** The budget of the stack of the search of a run, in estimated frames, as in `SheetRun`. The default is 3000. */
|
|
63
69
|
readonly budget?: number;
|
|
64
70
|
}
|
|
65
71
|
|
|
72
|
+
export type { ListKind } from "./facts.ts";
|
|
73
|
+
|
|
66
74
|
/** The source of a standalone module, or the reason that the program cannot be one. */
|
|
67
75
|
export type Emitted = { readonly ok: true; readonly source: string } | { readonly ok: false; readonly reason: string };
|
|
68
76
|
|
|
@@ -92,13 +100,13 @@ interface Value {
|
|
|
92
100
|
|
|
93
101
|
/**
|
|
94
102
|
* 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
|
|
103
|
+
* the position of its record or the text of the key of a list literal (LIST.LITERAL). It can also be a position of `fill`.
|
|
96
104
|
*/
|
|
97
105
|
interface ListInfo {
|
|
98
106
|
readonly item: Kind | undefined;
|
|
99
107
|
/** 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
108
|
readonly inner?: ListInfo | undefined;
|
|
101
|
-
/** True when a key can be
|
|
109
|
+
/** True when a key can be a key of a literal or of `fill`. The axis list cannot read a record at such a key. */
|
|
102
110
|
readonly texts?: boolean;
|
|
103
111
|
/** True for a list without items: the empty literal, and a list from it. Such a list fits each list. */
|
|
104
112
|
readonly empty?: boolean;
|
|
@@ -125,11 +133,12 @@ interface Name {
|
|
|
125
133
|
readonly list?: ListInfo | undefined;
|
|
126
134
|
}
|
|
127
135
|
|
|
128
|
-
/** An argument of a call: its code, its kind and its
|
|
136
|
+
/** An argument of a call: its code, its kind, its levels and the facts of its list (COMPILE.MODULE.LIST.ARG). */
|
|
129
137
|
interface Arg {
|
|
130
138
|
readonly code: string;
|
|
131
139
|
readonly kind: Kind | undefined;
|
|
132
140
|
readonly deps: ReadonlySet<number>;
|
|
141
|
+
readonly list: ListInfo | undefined;
|
|
133
142
|
}
|
|
134
143
|
|
|
135
144
|
/** The levels of a constant of the run. */
|
|
@@ -153,6 +162,8 @@ interface SheetInfo {
|
|
|
153
162
|
readonly columns: ReadonlyMap<string, number>;
|
|
154
163
|
/** The kind of each column that the printer knows: a kind of the options, or the kind of a printed formula. */
|
|
155
164
|
readonly kinds: Map<string, Kind | undefined>;
|
|
165
|
+
/** The facts of the lists of each column of lists that the printer knows (COMPILE.MODULE.SHEET.LIST). */
|
|
166
|
+
readonly lists: Map<string, ListInfo>;
|
|
156
167
|
/** True when each read of a cell reads a finished cell, so a read starts no search (COMPILE.MODULE.SHEET.DIRECT). */
|
|
157
168
|
readonly direct: boolean;
|
|
158
169
|
}
|
|
@@ -226,6 +237,8 @@ interface CallScope {
|
|
|
226
237
|
interface Spec {
|
|
227
238
|
readonly name: string;
|
|
228
239
|
readonly kind: Kind | undefined;
|
|
240
|
+
/** The facts of the list of the body, for a function whose value is a list (COMPILE.MODULE.LIST.CALL). */
|
|
241
|
+
readonly list: ListInfo | undefined;
|
|
229
242
|
readonly safe: boolean;
|
|
230
243
|
readonly deps: ReadonlySet<number>;
|
|
231
244
|
readonly origin: number;
|
|
@@ -236,7 +249,7 @@ interface Spec {
|
|
|
236
249
|
}
|
|
237
250
|
|
|
238
251
|
/** The name of a helper of the generated code. */
|
|
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;
|
|
252
|
+
type Helper = "F" | "C" | "T" | "L" | "Q" | "G" | "B" | "U" | "X" | "I" | "K" | "M" | "M1" | "S" | "V" | "SB" | "SK" | "TK" | "NT" | "FI" | "LI" | BuildHelper | TreeHelper | GraphHelper | SheetHelper;
|
|
240
253
|
|
|
241
254
|
/** The helpers of the list ops that build a list (LIST.BUILD), of `get` (LIST.GET) and of `indexOf` (LIST.INDEXOF). */
|
|
242
255
|
type BuildHelper = "DR" | "AP" | "WO" | "FL" | "GT" | "IX";
|
|
@@ -248,7 +261,7 @@ type TreeHelper = "PT" | "CH" | "SG" | "PR" | "UP" | "SO" | "AN" | "BF";
|
|
|
248
261
|
type GraphHelper = "GR" | "GI" | "RB";
|
|
249
262
|
|
|
250
263
|
/** 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. */
|
|
251
|
-
type SheetHelper = "SH" | "KO" | "DO";
|
|
264
|
+
type SheetHelper = "SH" | "KO" | "DO" | "LO" | "LC" | "LV";
|
|
252
265
|
|
|
253
266
|
/** The helpers of the generated code. A module has only the helpers that it uses. */
|
|
254
267
|
const HELPERS: Readonly<Record<Exclude<Helper, "S">, string>> = {
|
|
@@ -279,8 +292,63 @@ const HELPERS: Readonly<Record<Exclude<Helper, "S">, string>> = {
|
|
|
279
292
|
" return o.sort((a, b) => (a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0));",
|
|
280
293
|
"}",
|
|
281
294
|
].join("\n"),
|
|
295
|
+
// The option by of sortBy (LIST.SORT.BY): the function f gives the sort value of each item with a value, in order.
|
|
296
|
+
SK: [
|
|
297
|
+
"function SK(l, s, f) {",
|
|
298
|
+
" const o = V(l, s).map((x) => [x, f(x[1])]);",
|
|
299
|
+
" const t = o.length > 0 ? typeof o[0][1] : \"number\";",
|
|
300
|
+
" for (const [, v] of o) if (typeof v !== t || (t !== \"number\" && t !== \"string\") || v !== v) F();",
|
|
301
|
+
" return o.sort((a, b) => (a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0)).map((x) => x[0]);",
|
|
302
|
+
"}",
|
|
303
|
+
].join("\n"),
|
|
282
304
|
TK: "function TK(l, n, s) { const o = V(l, s); return Number.isSafeInteger(n) && n >= 0 ? o.slice(0, n) : F(); }",
|
|
283
|
-
|
|
305
|
+
// nth keeps the items with values on the array, as GT keeps its index. Thus a loop that reads each item of a list of n
|
|
306
|
+
// items costs O(n), not O(n squared) (COMPILE.MODULE.NTH.INDEX).
|
|
307
|
+
NT: [
|
|
308
|
+
"function NT(l, i, s) {",
|
|
309
|
+
" let o = l.vw;",
|
|
310
|
+
" if (o === undefined) {",
|
|
311
|
+
" o = l.filter((x) => x[1] !== E);",
|
|
312
|
+
" l.vw = o;",
|
|
313
|
+
" }",
|
|
314
|
+
" if (s && o.length < l.length) F();",
|
|
315
|
+
" return Number.isSafeInteger(i) && i >= 0 && i < o.length ? o[i][1] : F();",
|
|
316
|
+
"}",
|
|
317
|
+
].join("\n"),
|
|
318
|
+
// fill (LIST.FILL, COMPILE.MODULE.FILL): n items with the value v, and the keys 0 to n - 1. A count that is not a whole
|
|
319
|
+
// number from 0 to 100000, or a missing value, is the error of the interpreter. Each item can share the array of a list.
|
|
320
|
+
FI: [
|
|
321
|
+
"function FI(n, v) {",
|
|
322
|
+
" if (!(Number.isSafeInteger(n) && n >= 0 && n <= 100000 && v !== undefined)) F();",
|
|
323
|
+
" const o = [];",
|
|
324
|
+
" for (let i = 0; i < n; i++) o.push([i, v]);",
|
|
325
|
+
" return o;",
|
|
326
|
+
"}",
|
|
327
|
+
].join("\n"),
|
|
328
|
+
// A list of a field of the input (COMPILE.MODULE.LIST.INPUT): the array of a `vex.list` whose items have lists to the
|
|
329
|
+
// depth `h`, and values that pass the test `t`. The shape is the shape of `isVexList`. An error item holds the sentinel.
|
|
330
|
+
// An input that is not such a list, or an error item of `#DEPTH!`, gives undefined, so the check of the run fails.
|
|
331
|
+
LI: [
|
|
332
|
+
"function LI(x, h, t) {",
|
|
333
|
+
" if (typeof x !== \"object\" || x === null || x.kind !== \"vex.list\" || !Array.isArray(x.items)) return undefined;",
|
|
334
|
+
" const o = [];",
|
|
335
|
+
" for (let i = 0; i < x.items.length; i++) {",
|
|
336
|
+
" const it = x.items[i];",
|
|
337
|
+
" const r = typeof it === \"object\" && it !== null ? it.result : undefined;",
|
|
338
|
+
" if (typeof r !== \"object\" || r === null || typeof it.key !== \"string\") return undefined;",
|
|
339
|
+
" if (r.ok === true) {",
|
|
340
|
+
" const v = h > 0 ? LI(r.value, h - 1, t) : r.value !== undefined && t(r.value) ? r.value : undefined;",
|
|
341
|
+
" if (v === undefined) return undefined;",
|
|
342
|
+
" o.push([it.key, v]);",
|
|
343
|
+
" } else {",
|
|
344
|
+
" const e = r.error;",
|
|
345
|
+
" if (r.ok !== false || typeof e !== \"object\" || e === null || typeof e.code !== \"string\" || typeof e.kind !== \"string\" || typeof e.message !== \"string\" || !Array.isArray(e.path) || e.kind === \"depth\") return undefined;",
|
|
346
|
+
" o.push([it.key, E]);",
|
|
347
|
+
" }",
|
|
348
|
+
" }",
|
|
349
|
+
" return o;",
|
|
350
|
+
"}",
|
|
351
|
+
].join("\n"),
|
|
284
352
|
// 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
353
|
// `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
354
|
DR: "function DR(l, n, s) { const o = V(l, s); return Number.isSafeInteger(n) && n >= 0 ? o.slice(n) : F(); }",
|
|
@@ -422,6 +490,23 @@ const HELPERS: Readonly<Record<Exclude<Helper, "S">, string>> = {
|
|
|
422
490
|
// A cell without a formula has the error sentinel from the start, as the error of its read.
|
|
423
491
|
// A column of a direct fill (COMPILE.MODULE.SHEET.DIRECT): the error sentinel of a cell changes to VEX_ERROR.
|
|
424
492
|
DO: "function DO(d) { for (let k = 0; k < d.length; k++) if (d[k] === E) d[k] = VEX_ERROR; return d; }",
|
|
493
|
+
// A list of a result (COMPILE.MODULE.LIST.RESULT): a `vex.list` with a text key for each item. An error item has the
|
|
494
|
+
// error VEX_ERROR. The depth `h` is the number of the levels of lists in the items.
|
|
495
|
+
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 } })) }; }',
|
|
496
|
+
// A list in an argument of an op or in a field of a record (COMPILE.MODULE.LIST.ARG, COMPILE.MODULE.LIST.FIELD): a frozen
|
|
497
|
+
// `vex.list`, as the interpreter gives. The array keeps it, so each later read of the list gives the same object.
|
|
498
|
+
LV: [
|
|
499
|
+
"function LV(l, h) {",
|
|
500
|
+
" let o = l.vl;",
|
|
501
|
+
" if (o === undefined) {",
|
|
502
|
+
' o = Object.freeze({ kind: "vex.list", items: Object.freeze(l.map(([k, v]) => ({ key: `${k}`, result: v === E ? { ok: false, error: VEX_ERROR } : { ok: true, value: h > 0 ? LV(v, h - 1) : v } }))) });',
|
|
503
|
+
" l.vl = o;",
|
|
504
|
+
" }",
|
|
505
|
+
" return o;",
|
|
506
|
+
"}",
|
|
507
|
+
].join("\n"),
|
|
508
|
+
// A column of lists (COMPILE.MODULE.SHEET.LIST): each cell with a list gives a `vex.list`.
|
|
509
|
+
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; }",
|
|
425
510
|
SH: [
|
|
426
511
|
"function SH(n, cols, own, budget) {",
|
|
427
512
|
" const pg = (c, k) => {",
|
|
@@ -709,14 +794,14 @@ const NEEDS: Readonly<Record<Helper, readonly Helper[]>> = {
|
|
|
709
794
|
// 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.
|
|
710
795
|
// Stryker disable next-line ArrayDeclaration: see the comment above
|
|
711
796
|
V: ["F"],
|
|
712
|
-
SB: ["V", "F"], TK: ["V", "F"], NT: ["V", "F"],
|
|
797
|
+
SB: ["V", "F"], SK: ["V", "F"], TK: ["V", "F"], NT: ["V", "F"], FI: ["F"], LI: [],
|
|
713
798
|
DR: ["V", "F"], AP: ["V"], WO: ["V"], FL: ["V"], GT: ["F"], IX: ["V", "F"],
|
|
714
799
|
// Each module has C, and each move uses F (#move), so these needs only complete the list.
|
|
715
800
|
// Stryker disable next-line ArrayDeclaration: see the comment above
|
|
716
801
|
PT: ["C"], GR: ["C"], UP: ["F"], SO: ["F"],
|
|
717
802
|
CH: [], SG: [], PR: [], AN: [], BF: [],
|
|
718
803
|
GI: [], RB: [],
|
|
719
|
-
SH: [], KO: [], DO: [],
|
|
804
|
+
SH: [], KO: [], DO: [], LO: [], LC: ["LO"], LV: [],
|
|
720
805
|
};
|
|
721
806
|
|
|
722
807
|
/** The parts of a tree that a run computes before the loop over its keys, if the program needs them. */
|
|
@@ -765,55 +850,114 @@ const BUILD_OPS: ReadonlySet<string> = new Set(["append", "without", "flat", "ge
|
|
|
765
850
|
/** The helper of each op of `#build`. */
|
|
766
851
|
const BUILD_HELPERS: Readonly<Record<string, BuildHelper>> = { append: "AP", without: "WO", flat: "FL", get: "GT", indexOf: "IX" };
|
|
767
852
|
|
|
768
|
-
/**
|
|
769
|
-
|
|
853
|
+
/**
|
|
854
|
+
* The ops whose value is a list: the list ops of LIST.SORT, LIST.TAKE and LIST.BUILD, and `fill` (LIST.FILL). A domain
|
|
855
|
+
* can have the op `fill`. Then the op of the domain gives no list, and the place of a list gives a reason.
|
|
856
|
+
*/
|
|
857
|
+
const LIST_RESULTS: ReadonlySet<string> = new Set(["sortBy", "take", "drop", "append", "without", "flat", "fill"]);
|
|
858
|
+
|
|
859
|
+
/**
|
|
860
|
+
* The scope of `listy`. `name` tells if a name holds a list, and `fn` gives the bound function of a name. `cell` tells
|
|
861
|
+
* if a read of a cell gives a list, and `field` tells if a read of a field gives a list (COMPILE.MODULE.LIST.INPUT).
|
|
862
|
+
*/
|
|
863
|
+
interface ListScope {
|
|
864
|
+
readonly name: (name: string) => boolean;
|
|
865
|
+
readonly fn: (name: string) => ListFn | undefined;
|
|
866
|
+
readonly cell: (e: ExprOf<"ext">) => boolean;
|
|
867
|
+
readonly field: (e: ExprOf<"ref">) => boolean;
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
/** A bound function for `listy`: its node, and the scope of its binding (FN.BIND). */
|
|
871
|
+
interface ListFn {
|
|
872
|
+
readonly fn: ExprOf<"fn">;
|
|
873
|
+
readonly scope: ListScope;
|
|
874
|
+
}
|
|
770
875
|
|
|
771
876
|
/**
|
|
772
877
|
* 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.
|
|
878
|
+
* list. A name of a list, and a let or a loop whose result is a list, give a list too. A call gives a list when the
|
|
879
|
+
* body of its function gives one (COMPILE.MODULE.LIST.CALL). The scope tells the names and the functions outside the expression.
|
|
774
880
|
*/
|
|
775
|
-
function listy(e: Expr,
|
|
881
|
+
function listy(e: Expr, scope: ListScope): boolean {
|
|
776
882
|
switch (e.tag) {
|
|
777
883
|
case "each":
|
|
778
884
|
return true;
|
|
779
885
|
case "lit":
|
|
780
886
|
return isVexList(e.value);
|
|
781
887
|
case "app":
|
|
782
|
-
|
|
888
|
+
// A branch of if and ifError can be a list (COMPILE.MODULE.LIST.RESULT).
|
|
889
|
+
return LIST_RESULTS.has(e.op) || ((e.op === "if" || e.op === "ifError") && e.args.slice(e.op === "if" ? 1 : 0).some((x) => listy(x, scope)));
|
|
783
890
|
case "var":
|
|
784
|
-
return
|
|
891
|
+
return scope.name(e.name);
|
|
785
892
|
case "let":
|
|
786
|
-
return listy(e.body,
|
|
893
|
+
return listy(e.body, scopeIn(e.bind, scope));
|
|
787
894
|
case "fold":
|
|
788
895
|
case "iterate":
|
|
789
|
-
return listy(e.result,
|
|
790
|
-
case "call":
|
|
896
|
+
return listy(e.result, scopeIn(e.init, scope));
|
|
791
897
|
case "ext":
|
|
898
|
+
return scope.cell(e);
|
|
899
|
+
case "ref":
|
|
900
|
+
return scope.field(e);
|
|
901
|
+
case "call": {
|
|
902
|
+
// A call of no function gives a reason in the printer. A value or a parameter with the name of a function makes
|
|
903
|
+
// the printer give that reason too, so the scope does not hide the function.
|
|
904
|
+
const f = scope.fn(e.fn);
|
|
905
|
+
return f !== undefined && listy(f.fn.body, paramsIn(f, e.args, scope));
|
|
906
|
+
}
|
|
792
907
|
case "fn":
|
|
793
908
|
case "rec":
|
|
794
|
-
case "ref":
|
|
795
909
|
return false;
|
|
796
910
|
}
|
|
797
911
|
}
|
|
798
912
|
|
|
799
|
-
/**
|
|
800
|
-
function
|
|
801
|
-
|
|
802
|
-
|
|
913
|
+
/**
|
|
914
|
+
* This function gives the scope of some bindings. A value hides a name outside, and a function is not a list. A
|
|
915
|
+
* function sees the scope outside the bindings, so it cannot call itself.
|
|
916
|
+
*/
|
|
917
|
+
function scopeIn(bind: Readonly<Record<string, Expr>>, scope: ListScope): ListScope {
|
|
918
|
+
const lists = new Map<string, boolean>();
|
|
919
|
+
const fns = new Map<string, ListFn>();
|
|
920
|
+
for (const [name, x] of Object.entries(bind)) {
|
|
921
|
+
if (x.tag === "fn") fns.set(name, { fn: x, scope });
|
|
922
|
+
lists.set(name, listy(x, scope));
|
|
923
|
+
}
|
|
924
|
+
return { ...scope, name: (name) => lists.get(name) ?? scope.name(name), fn: (name) => fns.get(name) ?? scope.fn(name) };
|
|
803
925
|
}
|
|
804
926
|
|
|
805
|
-
/**
|
|
806
|
-
function
|
|
807
|
-
|
|
927
|
+
/**
|
|
928
|
+
* This function gives the scope of the body of a function at a call. The body sees the scope of the binding of the
|
|
929
|
+
* function, and each parameter holds a list when its argument does.
|
|
930
|
+
*/
|
|
931
|
+
function paramsIn(f: ListFn, args: readonly Expr[], scope: ListScope): ListScope {
|
|
932
|
+
const lists = new Map(args.map((x, i) => [f.fn.params[i], listy(x, scope)]));
|
|
933
|
+
return { ...f.scope, name: (name) => lists.get(name) ?? f.scope.name(name) };
|
|
808
934
|
}
|
|
809
935
|
|
|
810
|
-
/**
|
|
811
|
-
function
|
|
936
|
+
/**
|
|
937
|
+
* This function tells if an expression has a list literal with an item (LIST.LITERAL), or `fill` (LIST.FILL). Then a key
|
|
938
|
+
* of a list of the expression can be a key that is not the position of a record.
|
|
939
|
+
*/
|
|
940
|
+
function hasTextKeys(e: Expr): boolean {
|
|
941
|
+
return (e.tag === "lit" && isVexList(e.value) && e.value.items.length > 0) || (e.tag === "app" && e.op === "fill") || children(e).some(hasTextKeys);
|
|
942
|
+
}
|
|
943
|
+
|
|
944
|
+
/**
|
|
945
|
+
* This function gives the facts of the list of `append` from the facts of its two lists. It also gives the list of
|
|
946
|
+
* `if` from its two branches. An empty list fits each list. The op `op` names the op in the reason.
|
|
947
|
+
*/
|
|
948
|
+
function joinLists(a: ListInfo, b: ListInfo, op: string): ListInfo {
|
|
812
949
|
if (a.empty === true) return b;
|
|
813
950
|
if (b.empty === true) return a;
|
|
814
|
-
if ((a.inner === undefined) !== (b.inner === undefined)) throw new NotStandalone(
|
|
951
|
+
if ((a.inner === undefined) !== (b.inner === undefined)) throw new NotStandalone(`"${op}" of a list of lists and a list of values`);
|
|
815
952
|
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 };
|
|
953
|
+
return { item: join(a.item, b.item), inner: a.inner === undefined ? undefined : joinLists(a.inner, b.inner as ListInfo, op), texts };
|
|
954
|
+
}
|
|
955
|
+
|
|
956
|
+
/** This function gives the facts of the list of `if` or `ifError` from its two branches. Two values that are not lists give undefined. */
|
|
957
|
+
function branchLists(op: string, a: ListInfo | undefined, b: ListInfo | undefined): ListInfo | undefined {
|
|
958
|
+
if (a === undefined && b === undefined) return undefined;
|
|
959
|
+
if (a === undefined || b === undefined) throw new NotStandalone(`"${op}" of a list and a value that is not a list`);
|
|
960
|
+
return joinLists(a, b, op);
|
|
817
961
|
}
|
|
818
962
|
|
|
819
963
|
/**
|
|
@@ -1108,6 +1252,8 @@ class Printer {
|
|
|
1108
1252
|
readonly helpers = new Set<Helper>();
|
|
1109
1253
|
/** The declarations at the top of the module: the functions of the domains and the checks of the results. */
|
|
1110
1254
|
readonly top = new Map<string, string>();
|
|
1255
|
+
/** The array of the lists of each field of the input that the program reads (COMPILE.MODULE.LIST.INPUT). */
|
|
1256
|
+
readonly inputs = new Map<string, string>();
|
|
1111
1257
|
/** The statements at the start of a run: the constants of the run and the functions of the memo. */
|
|
1112
1258
|
readonly run: string[] = [];
|
|
1113
1259
|
/** The variables of the schema that the program reads. */
|
|
@@ -1236,7 +1382,23 @@ class Printer {
|
|
|
1236
1382
|
*/
|
|
1237
1383
|
against(kind: Kind, input: string): string {
|
|
1238
1384
|
const primitive = primitiveOf(kind);
|
|
1239
|
-
|
|
1385
|
+
return primitive === undefined ? `!${this.#isOf(kind)}(${input})` : `typeof ${input} !== "${primitive}"`;
|
|
1386
|
+
}
|
|
1387
|
+
|
|
1388
|
+
/**
|
|
1389
|
+
* This method gives the name of a test of the kind of an item of a list of the input (COMPILE.MODULE.LIST.INPUT). The
|
|
1390
|
+
* test of a primitive type checks the JavaScript type, and the test of a domain is the copy of its `is`.
|
|
1391
|
+
*/
|
|
1392
|
+
test(kind: Kind): string {
|
|
1393
|
+
const primitive = primitiveOf(kind);
|
|
1394
|
+
if (primitive === undefined) return this.#isOf(kind);
|
|
1395
|
+
const name = `is_${primitive}`;
|
|
1396
|
+
this.top.set(name, `const ${name} = (x) => typeof x === "${primitive}";`);
|
|
1397
|
+
return name;
|
|
1398
|
+
}
|
|
1399
|
+
|
|
1400
|
+
/** This method gives the name of the copy of the test `is` of the domain of a kind. */
|
|
1401
|
+
#isOf(kind: Kind): string {
|
|
1240
1402
|
const d = this.#domains.findIndex((x) => kindOfDomain(x) === kind);
|
|
1241
1403
|
const domain = this.#domains[d];
|
|
1242
1404
|
if (domain === undefined) throw new NotStandalone(`the schema has the kind ${kind}, and no domain has it`);
|
|
@@ -1245,7 +1407,7 @@ class Printer {
|
|
|
1245
1407
|
const src = copied(domain.is, [[...SAMPLES.number, ...SAMPLES.string, ...SAMPLES.boolean, null, {}, [], ...this.#samples(kind)]], `the test "is" of the domain ${domain.name}`);
|
|
1246
1408
|
this.top.set(name, `const ${name} = ${src};`);
|
|
1247
1409
|
}
|
|
1248
|
-
return
|
|
1410
|
+
return name;
|
|
1249
1411
|
}
|
|
1250
1412
|
|
|
1251
1413
|
/** This method gives a new name for the code. */
|
|
@@ -1320,7 +1482,8 @@ class Printer {
|
|
|
1320
1482
|
this.#keyOf.set(c, this.#constKey(e, ctx));
|
|
1321
1483
|
this.#constant.add(e);
|
|
1322
1484
|
}
|
|
1323
|
-
// A list is a value only at a place that takes a list
|
|
1485
|
+
// A list is a value only at a place that takes a list: a result, a binding, an argument, a field and the body of a
|
|
1486
|
+
// function take one. A condition, an argument of and or of or, and a key of get take no list.
|
|
1324
1487
|
if (c.v.list !== undefined && !this.#wantList.has(e)) throw new NotStandalone("a list is a value of the program");
|
|
1325
1488
|
return this.#columnar(e, c, ctx) ? this.#column(e, c, ctx) : c;
|
|
1326
1489
|
}
|
|
@@ -1335,7 +1498,28 @@ class Printer {
|
|
|
1335
1498
|
|
|
1336
1499
|
/** This method tells if an expression gives a list at a place that takes one (`listy`). */
|
|
1337
1500
|
#isList(e: Expr, ctx: Ctx): boolean {
|
|
1338
|
-
|
|
1501
|
+
// A key of a node of the memo is a name of its function, and the name keeps the facts of a list.
|
|
1502
|
+
const key = ctx.keys.get(e);
|
|
1503
|
+
if (key !== undefined) return key.list !== undefined;
|
|
1504
|
+
return listy(e, this.#scopeOf(ctx));
|
|
1505
|
+
}
|
|
1506
|
+
|
|
1507
|
+
/** This method gives the scope of `listy` at a node: the names and the bound functions of its context. */
|
|
1508
|
+
#scopeOf(ctx: Ctx): ListScope {
|
|
1509
|
+
return {
|
|
1510
|
+
name: (name) => ctx.env.get(name)?.list !== undefined,
|
|
1511
|
+
fn: (name) => {
|
|
1512
|
+
const bound = ctx.fns.get(name);
|
|
1513
|
+
return bound === undefined ? undefined : { fn: bound.fn, scope: this.#scopeOf(bound.ctx) };
|
|
1514
|
+
},
|
|
1515
|
+
cell: (x) => this.#cellList(x) !== undefined,
|
|
1516
|
+
field: (x) => typeof this.#schema.fields?.[x.path.join(".")] === "object",
|
|
1517
|
+
};
|
|
1518
|
+
}
|
|
1519
|
+
|
|
1520
|
+
/** 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. */
|
|
1521
|
+
#cellList(e: ExprOf<"ext">): ListInfo | undefined {
|
|
1522
|
+
return e.kind === CELL_KIND && isCellRef(e.data) ? this.#sheet?.lists.get(e.data.column) : undefined;
|
|
1339
1523
|
}
|
|
1340
1524
|
|
|
1341
1525
|
/** 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. */
|
|
@@ -1452,12 +1636,15 @@ class Printer {
|
|
|
1452
1636
|
return this.#call(e, ctx);
|
|
1453
1637
|
case "rec": {
|
|
1454
1638
|
const names = Object.keys(e.fields);
|
|
1455
|
-
const
|
|
1639
|
+
const exprs = Object.values(e.fields);
|
|
1640
|
+
// A field can hold a list (COMPILE.MODULE.LIST.FIELD).
|
|
1641
|
+
for (const x of exprs) this.#wantList.add(x);
|
|
1642
|
+
const raw = exprs.map((x) => this.expr(x, ctx));
|
|
1456
1643
|
const deps = depsOf(...raw);
|
|
1457
1644
|
// The interpreter evaluates each field, also after an error.
|
|
1458
|
-
const fields = this.#inOrder(this.#settle(raw, deps,
|
|
1645
|
+
const fields = this.#inOrder(this.#settle(raw, deps, exprs), true);
|
|
1459
1646
|
// A record of a module is a new object, so it needs no freeze.
|
|
1460
|
-
const code = `({ ${fields.map((x, i) => `${names[i] === "__proto__" ? '["__proto__"]' : JSON.stringify(names[i])}: ${x.v
|
|
1647
|
+
const code = `({ ${fields.map((x, i) => `${names[i] === "__proto__" ? '["__proto__"]' : JSON.stringify(names[i])}: ${this.#plain(x.v)}`).join(", ")} })`;
|
|
1461
1648
|
return { s: stmtsOf(...fields), v: { code, kind: undefined, safe: fields.every((x) => x.v.safe), deps } };
|
|
1462
1649
|
}
|
|
1463
1650
|
case "app":
|
|
@@ -1487,10 +1674,13 @@ class Printer {
|
|
|
1487
1674
|
const deps = new Set([...this.#addressDeps(at, ctx, []), CELLS]);
|
|
1488
1675
|
const index = sheet.columns.get(column);
|
|
1489
1676
|
// The read of a column that the sheet does not have is an error. A kind of the options lets an op take it.
|
|
1490
|
-
|
|
1677
|
+
const list = sheet.lists.get(column);
|
|
1678
|
+
if (index === undefined) return bare({ code: `${F}()`, kind: sheet.kinds.get(column), safe: false, deps, list });
|
|
1491
1679
|
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`);
|
|
1492
|
-
|
|
1493
|
-
const
|
|
1680
|
+
// A direct fill reads the array of the column. The search reads the cell with the function of its state.
|
|
1681
|
+
const address = this.#address(at, ctx, []);
|
|
1682
|
+
const read = sheet.direct ? `D[${String(index)}][${address}]` : `${READ_CELL}(${String(index)}, ${address})`;
|
|
1683
|
+
const v = { code: `${this.use("G")}(${read})`, kind: sheet.kinds.get(column), safe: false, deps, list };
|
|
1494
1684
|
// The read itself gives the result or the error sentinel. A move of the address can throw, so then the read is not
|
|
1495
1685
|
// a value that holds the sentinel.
|
|
1496
1686
|
return bare(at.every((m) => m.t === "origin") ? { ...v, held: read } : v);
|
|
@@ -1594,6 +1784,8 @@ class Printer {
|
|
|
1594
1784
|
const [field, ...more] = e.path;
|
|
1595
1785
|
const kind = field === undefined ? undefined : this.#schema.fields?.[field];
|
|
1596
1786
|
if (field === undefined || more.length > 0 || !isFieldName(field) || kind === undefined) throw new NotStandalone(`a read of a field that is not in the schema: "${e.path.join(".")}"`);
|
|
1787
|
+
// The check of the run keeps the array of each list of the input (COMPILE.MODULE.LIST.INPUT).
|
|
1788
|
+
const input = typeof kind === "object" ? this.#input(field) : undefined;
|
|
1597
1789
|
// A move to the origin cannot fail, and the schema has the field in each record.
|
|
1598
1790
|
const at = e.at ?? [];
|
|
1599
1791
|
const safe = at.every((m) => m.t === "origin");
|
|
@@ -1601,7 +1793,18 @@ class Printer {
|
|
|
1601
1793
|
const deps = this.#addressDeps(at, ctx, values);
|
|
1602
1794
|
// The interpreter evaluates the expressions of the address before its moves, and the first error stops them.
|
|
1603
1795
|
const parts = this.#inOrder(this.#settle(values, deps), false);
|
|
1604
|
-
|
|
1796
|
+
const address = this.#address(at, ctx, parts);
|
|
1797
|
+
if (typeof kind === "object") return { s: stmtsOf(...parts), v: { code: `${input as string}[${address}]`, kind: undefined, safe, deps, list: listOfKind(kind, true) } };
|
|
1798
|
+
return { s: stmtsOf(...parts), v: { code: `R[${address}][${JSON.stringify(field)}]`, kind, safe, deps } };
|
|
1799
|
+
}
|
|
1800
|
+
|
|
1801
|
+
/** This method gives the name of the array of the lists of a field of the input. */
|
|
1802
|
+
#input(field: string): string {
|
|
1803
|
+
const known = this.inputs.get(field);
|
|
1804
|
+
if (known !== undefined) return known;
|
|
1805
|
+
const name = this.fresh("LF");
|
|
1806
|
+
this.inputs.set(field, name);
|
|
1807
|
+
return name;
|
|
1605
1808
|
}
|
|
1606
1809
|
|
|
1607
1810
|
/** This method gives the code of the expressions of the computed moves of an address. They evaluate at the node. */
|
|
@@ -1705,27 +1908,31 @@ class Printer {
|
|
|
1705
1908
|
if (bound.fn.params.length !== e.args.length) throw new NotStandalone(`a call of "${e.fn}" with ${String(e.args.length)} arguments, not ${String(bound.fn.params.length)}`);
|
|
1706
1909
|
const s: string[] = [];
|
|
1707
1910
|
const args = e.args.map((x): Arg => {
|
|
1911
|
+
// An argument can be a list, as a binding of a let can (COMPILE.MODULE.LIST.ARG).
|
|
1912
|
+
this.#wantList.add(x);
|
|
1708
1913
|
const c = this.#hoist(this.expr(x, ctx), hasLoop(x));
|
|
1914
|
+
const { kind, deps, list } = c.v;
|
|
1709
1915
|
// A value that cannot throw is the argument itself. A read of a name that can hold the error passes the name.
|
|
1710
1916
|
if (c.v.safe) {
|
|
1711
1917
|
s.push(...c.s);
|
|
1712
|
-
return { code: c.v.code, kind
|
|
1918
|
+
return { code: c.v.code, kind, deps, list };
|
|
1713
1919
|
}
|
|
1714
1920
|
// Stryker disable next-line ConditionalExpression: the statements with a read of a name bind other names and do not throw, so the read alone has the same value
|
|
1715
|
-
if (c.s.length === 0 && c.v.held !== undefined) return { code: c.v.held, kind
|
|
1921
|
+
if (c.s.length === 0 && c.v.held !== undefined) return { code: c.v.held, kind, deps, list };
|
|
1716
1922
|
const b = this.fresh("b");
|
|
1717
1923
|
s.push(...this.#store(b, c));
|
|
1718
|
-
return { code: b, kind
|
|
1924
|
+
return { code: b, kind, deps, list };
|
|
1719
1925
|
});
|
|
1720
|
-
// Each parameter can hold the error of its argument, so one function serves the arguments of one kind.
|
|
1721
|
-
|
|
1926
|
+
// Each parameter can hold the error of its argument, so one function serves the arguments of one kind. The facts of
|
|
1927
|
+
// a list are a part of its kind.
|
|
1928
|
+
const sig = JSON.stringify(args.map((a) => (a.list === undefined ? (a.kind ?? null) : { list: a.list })));
|
|
1722
1929
|
const spec = bound.specs.get(sig) ?? this.#printFn(bound, args, sig);
|
|
1723
1930
|
// Each marker becomes the levels at the call. The levels of the arguments count for each call, because their
|
|
1724
1931
|
// statements read their keys, so the marker of the parameters gives no level.
|
|
1725
1932
|
const levels = (d: number): readonly number[] => (d === spec.origin ? [ctx.originLevel] : d === spec.focus ? [ctx.level] : d === spec.param ? [] : [d]);
|
|
1726
1933
|
const deps = new Set([...args.flatMap((a) => [...a.deps]), ...[...spec.deps].flatMap(levels)]);
|
|
1727
1934
|
const position = spec.deps.has(spec.origin) ? [ctx.focus, ctx.origin] : spec.deps.has(spec.focus) ? [ctx.focus] : [];
|
|
1728
|
-
return { s, v: { code: `${spec.name}(${[...args.map((a) => a.code), ...position].join(", ")})`, kind: spec.kind, safe: spec.safe, deps } };
|
|
1935
|
+
return { s, v: { code: `${spec.name}(${[...args.map((a) => a.code), ...position].join(", ")})`, kind: spec.kind, safe: spec.safe, deps, list: spec.list } };
|
|
1729
1936
|
}
|
|
1730
1937
|
|
|
1731
1938
|
/**
|
|
@@ -1745,9 +1952,12 @@ class Printer {
|
|
|
1745
1952
|
const o = this.fresh("o");
|
|
1746
1953
|
const env = new Map(bound.ctx.env);
|
|
1747
1954
|
// A parameter hides a function of its name, because a read looks at the values first.
|
|
1748
|
-
bound.fn.params.forEach((p, i) => env.set(p, { code: names[i] as string, kind: (args[i] as Arg).kind, lazy: true, deps: new Set([param]) }));
|
|
1955
|
+
bound.fn.params.forEach((p, i) => env.set(p, { code: names[i] as string, kind: (args[i] as Arg).kind, lazy: true, deps: new Set([param]), list: (args[i] as Arg).list }));
|
|
1749
1956
|
const scope: CallScope = { param, focus, repeats: nestsLoops(bound.fn.body), names: new Set(names), decls: [], root: bound.fn.body };
|
|
1750
1957
|
this.#scopes.push(scope);
|
|
1958
|
+
// The value of a call can be a list, as the value of a let can (COMPILE.MODULE.LIST.CALL). The call is at a place
|
|
1959
|
+
// that takes a list, or it gives the reason.
|
|
1960
|
+
this.#wantList.add(bound.fn.body);
|
|
1751
1961
|
const body = this.expr(bound.fn.body, { origin: o, focus: k, level: focus, originLevel: origin, env, fns: bound.ctx.fns, keys: new Map() });
|
|
1752
1962
|
this.#scopes.pop();
|
|
1753
1963
|
const markers = new Set([origin, focus, param]);
|
|
@@ -1761,7 +1971,7 @@ class Printer {
|
|
|
1761
1971
|
const decl = s.length === 0 ? [`${head} ${body.v.code};`] : [`${head} {`, ...ind(s), ` return ${body.v.code};`, "};"];
|
|
1762
1972
|
(global ? this.run : bound.decls).push(...decl);
|
|
1763
1973
|
if (!global) bound.local = true;
|
|
1764
|
-
const spec: Spec = { name, kind: body.v.kind, safe: body.v.safe, deps: body.v.deps, origin, focus, param, global };
|
|
1974
|
+
const spec: Spec = { name, kind: body.v.kind, list: body.v.list, safe: body.v.safe, deps: body.v.deps, origin, focus, param, global };
|
|
1765
1975
|
bound.specs.set(sig, spec);
|
|
1766
1976
|
return spec;
|
|
1767
1977
|
}
|
|
@@ -1777,6 +1987,8 @@ class Printer {
|
|
|
1777
1987
|
|
|
1778
1988
|
#app(e: ExprOf<"app">, ctx: Ctx): Code {
|
|
1779
1989
|
const { op, args } = e;
|
|
1990
|
+
// A branch of if and of ifError is at a place that takes a list when the node is.
|
|
1991
|
+
if ((op === "if" || op === "ifError") && this.#wantList.has(e)) for (const x of args.slice(op === "if" ? 1 : 0)) this.#wantList.add(x);
|
|
1780
1992
|
if (op === "if") return this.#if(args, ctx);
|
|
1781
1993
|
if (op === "and" || op === "or") return this.#andOr(op === "and", args, ctx);
|
|
1782
1994
|
if (op === "ifError") return this.#ifError(args, ctx);
|
|
@@ -1791,16 +2003,49 @@ class Printer {
|
|
|
1791
2003
|
if (head !== undefined && (op === "sortBy" || op === "take" || (op === "drop" && this.#isList(head, ctx)))) return this.#order(op, head, rest, ctx);
|
|
1792
2004
|
if (head !== undefined && BUILD_OPS.has(op) && this.#isList(head, ctx)) return this.#build(op, head, rest, ctx);
|
|
1793
2005
|
if (head !== undefined && (FOLD_OPS.has(op) || op === "nth") && this.#isList(head, ctx)) return this.#overList(op, head, rest, ctx);
|
|
2006
|
+
// An argument can be a list (COMPILE.MODULE.LIST.ARG).
|
|
2007
|
+
for (const x of args) this.#wantList.add(x);
|
|
1794
2008
|
const raw = args.map((x) => this.expr(x, ctx));
|
|
1795
2009
|
const deps = depsOf(...raw);
|
|
1796
2010
|
// The interpreter evaluates each argument, also after an error.
|
|
1797
2011
|
const values = this.#inOrder(this.#settle(raw, deps, args), true);
|
|
2012
|
+
if (op === "fill" && this.#facts.own(op)) return this.#fill(values, deps);
|
|
1798
2013
|
return this.#opCall(op, values, deps);
|
|
1799
2014
|
}
|
|
1800
2015
|
|
|
2016
|
+
/**
|
|
2017
|
+
* This method prints `fill(n, value)` without a domain with the op (LIST.FILL, COMPILE.MODULE.FILL). The helper `FI`
|
|
2018
|
+
* gets each value, so an error of an argument after the value is the error of the op. The keys are not the positions
|
|
2019
|
+
* of records, so the axis `list` over the list cannot read a record at its keys.
|
|
2020
|
+
*/
|
|
2021
|
+
#fill(values: readonly Code[], deps: ReadonlySet<number>): Code {
|
|
2022
|
+
const value = values[1]?.v;
|
|
2023
|
+
const list: ListInfo = { item: value?.kind, inner: value?.list, texts: true };
|
|
2024
|
+
return { s: stmtsOf(...values), v: { code: `${this.use("FI")}(${values.map((x) => x.v.code).join(", ")})`, kind: undefined, safe: false, deps, list } };
|
|
2025
|
+
}
|
|
2026
|
+
|
|
2027
|
+
/**
|
|
2028
|
+
* This method gives the code of a value outside the list ops: a list is a `vex.list`, as in the interpreter
|
|
2029
|
+
* (COMPILE.MODULE.LIST.ARG, COMPILE.MODULE.LIST.FIELD). An error item has the error `VEX_ERROR`.
|
|
2030
|
+
*/
|
|
2031
|
+
#plain(v: Value): string {
|
|
2032
|
+
return v.list === undefined ? v.code : `${this.use("LV")}(${v.code}, ${String(depthOf(v.list))})`;
|
|
2033
|
+
}
|
|
2034
|
+
|
|
2035
|
+
/** This method gives the samples of a list of the facts `l`: no items, items with values, and an error item. */
|
|
2036
|
+
#listSamples(l: ListInfo): readonly unknown[] {
|
|
2037
|
+
const values = l.inner !== undefined ? [vexList([])] : l.item === undefined ? SAMPLES.number : this.#samples(l.item);
|
|
2038
|
+
const items = values.map((value, i) => ({ key: String(i), result: { ok: true as const, value } }));
|
|
2039
|
+
// An error item of a module has the error VEX_ERROR, which is not an error value of the interpreter.
|
|
2040
|
+
return [vexList([]), vexList(items), vexList([{ key: "0", result: { ok: false, error: { vexError: true } as never } }])];
|
|
2041
|
+
}
|
|
2042
|
+
|
|
1801
2043
|
/** This method prints the call of the op of a domain on some values, from the static site of their kinds. */
|
|
1802
2044
|
#opCall(op: string, values: readonly Code[], deps: ReadonlySet<number>): Code {
|
|
1803
|
-
const
|
|
2045
|
+
const lists = new Set(values.flatMap((x, i) => (x.v.list === undefined ? [] : [i])));
|
|
2046
|
+
// A list op of the interpreter that a module does not have, and an op of a domain, cannot take a list as the receiver.
|
|
2047
|
+
if (lists.has(0)) throw new NotStandalone(isListOp(op) ? `the list op "${op}"` : `a list as the receiver of the op "${op}"`);
|
|
2048
|
+
const site = this.#facts.staticSite(op, values.map((x) => x.v.kind), lists);
|
|
1804
2049
|
if (site?.t !== "fn") throw new NotStandalone(`the kinds of the values of "${op}" do not decide its op`);
|
|
1805
2050
|
if (site.bad) return { s: stmtsOf(...values), v: { code: `${this.use("F")}()`, kind: site.returns, safe: false, deps } };
|
|
1806
2051
|
if (site.returns === undefined) throw new NotStandalone(`the op "${op}" does not declare the kind of its result`);
|
|
@@ -1811,14 +2056,15 @@ class Printer {
|
|
|
1811
2056
|
// A static site of a domain has the function of the op of that domain.
|
|
1812
2057
|
const fn = (d.ops[op] as { fn: (...a: never[]) => unknown }).fn;
|
|
1813
2058
|
const kinds = values.map((x) => x.v.kind).filter((k): k is Kind => k !== undefined);
|
|
1814
|
-
const
|
|
2059
|
+
const each = values.flatMap((x) => (x.v.list !== undefined ? [this.#listSamples(x.v.list)] : x.v.kind === undefined ? [] : [this.#samples(x.v.kind)]));
|
|
2060
|
+
const src = copied(fn, each, `the op "${op}" of the domain ${d.name}`);
|
|
1815
2061
|
// An inline form cannot throw for primitive values only.
|
|
1816
|
-
this.#forms.set(name, kinds.every((k) => primitiveOf(k) !== undefined) ? inlineForm(src) : undefined);
|
|
2062
|
+
this.#forms.set(name, lists.size === 0 && kinds.every((k) => primitiveOf(k) !== undefined) ? inlineForm(src) : undefined);
|
|
1817
2063
|
this.top.set(name, `const ${name} = ${src};`);
|
|
1818
2064
|
}
|
|
1819
2065
|
const form = this.#forms.get(name);
|
|
1820
2066
|
// An inline form takes each argument once, or a plain argument more often, so each argument evaluates once.
|
|
1821
|
-
const inline = form !== undefined && form.params.length === values.length && values.every((x, i) => form.uses[i] === 1 || (x.v.plain === true && x.v.safe && (form.uses[i] as number) > 0));
|
|
2067
|
+
const inline = form !== undefined && lists.size === 0 && form.params.length === values.length && values.every((x, i) => form.uses[i] === 1 || (x.v.plain === true && x.v.safe && (form.uses[i] as number) > 0));
|
|
1822
2068
|
if (inline) {
|
|
1823
2069
|
const text = form.parts.map((x) => (typeof x === "number" ? `(${(values[x] as Code).v.code})` : x)).join("");
|
|
1824
2070
|
const checked = this.check(site.returns);
|
|
@@ -1827,7 +2073,7 @@ class Printer {
|
|
|
1827
2073
|
}
|
|
1828
2074
|
this.#called.add(name);
|
|
1829
2075
|
// An exception of the op is an error of Vex: the boundary around the op catches it.
|
|
1830
|
-
const code = this.#checked(site.returns, `${name}(${values.map((x) => x.v
|
|
2076
|
+
const code = this.#checked(site.returns, `${name}(${values.map((x) => this.#plain(x.v)).join(", ")})`);
|
|
1831
2077
|
return { s: stmtsOf(...values), v: { code, kind: site.returns, safe: false, deps } };
|
|
1832
2078
|
}
|
|
1833
2079
|
|
|
@@ -1838,7 +2084,7 @@ class Printer {
|
|
|
1838
2084
|
const raw = [this.expr(c, ctx), this.expr(a, ctx), this.expr(b, ctx)];
|
|
1839
2085
|
const deps = depsOf(...raw);
|
|
1840
2086
|
const [cond, yes, no] = this.#settle(raw, deps, [c, a, b]) as [Code, Code, Code];
|
|
1841
|
-
const v = { kind: join(yes.v.kind, no.v.kind), safe: this.#safeBoolean(cond.v) && yes.v.safe && no.v.safe, deps };
|
|
2087
|
+
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) };
|
|
1842
2088
|
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})` } };
|
|
1843
2089
|
const t = this.fresh("t");
|
|
1844
2090
|
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};`, "}"];
|
|
@@ -1870,7 +2116,7 @@ class Printer {
|
|
|
1870
2116
|
if (first.v.safe) return first;
|
|
1871
2117
|
const t = this.fresh("t");
|
|
1872
2118
|
const s = [`let ${t};`, "try {", ...ind(first.s), ` ${t} = ${first.v.code};`, "} catch {", ...ind(second.s), ` ${t} = ${second.v.code};`, "}"];
|
|
1873
|
-
return { s, v: { code: t, kind: join(first.v.kind, second.v.kind), safe: second.v.safe, deps } };
|
|
2119
|
+
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) } };
|
|
1874
2120
|
}
|
|
1875
2121
|
|
|
1876
2122
|
#opIndex(op: string): number {
|
|
@@ -1931,6 +2177,8 @@ class Printer {
|
|
|
1931
2177
|
readonly startSafe: boolean;
|
|
1932
2178
|
readonly tests: readonly Expr[];
|
|
1933
2179
|
readonly inner: Ctx;
|
|
2180
|
+
/** True when a target can be a key that is not the position of a record: a key of a literal or of `fill`. */
|
|
2181
|
+
readonly texts: boolean;
|
|
1934
2182
|
} {
|
|
1935
2183
|
const { base: outer, tests } = testsOf(axis);
|
|
1936
2184
|
// The reverse order of an axis is a loop from its end (AXIS.REVERSE). The validation keeps a base axis inside.
|
|
@@ -1943,14 +2191,14 @@ class Printer {
|
|
|
1943
2191
|
if (base.t === "list") {
|
|
1944
2192
|
if (at.length > 0) throw new NotStandalone('the axis "list" with an address');
|
|
1945
2193
|
const list = this.#hoist(this.#listOf(base.list, ctx), hasLoop(base.list));
|
|
1946
|
-
//
|
|
1947
|
-
|
|
2194
|
+
// A key of a literal or of fill is not the position of a record. Such a focus is a key of a list of the code only.
|
|
2195
|
+
const texts = (list.v.list as ListInfo).texts === true;
|
|
1948
2196
|
const a = this.fresh("A");
|
|
1949
2197
|
const q = this.fresh("q");
|
|
1950
2198
|
const head = reverse ? `for (let ${q} = ${a}.length - 1; ${q} >= 0; ${q}--) {` : `for (let ${q} = 0; ${q} < ${a}.length; ${q}++) {`;
|
|
1951
2199
|
const key = [`const ${j} = ${a}[${q}][0];`];
|
|
1952
2200
|
const check = [`if (${a}[${q}][1] === E) ${this.use("F")}();`];
|
|
1953
|
-
return { s: [...list.s, `const ${a} = ${list.v.code};`], j, head, key, check, skip: undefined, fixed: false, start: list.v.deps, startSafe: list.v.safe, tests, inner };
|
|
2201
|
+
return { s: [...list.s, `const ${a} = ${list.v.code};`], j, head, key, check, skip: undefined, fixed: false, start: list.v.deps, startSafe: list.v.safe, tests, inner, texts };
|
|
1954
2202
|
}
|
|
1955
2203
|
const s: string[] = [];
|
|
1956
2204
|
let lo = "0";
|
|
@@ -1972,13 +2220,13 @@ class Printer {
|
|
|
1972
2220
|
if (this.#tree && isTreeAxis(base)) {
|
|
1973
2221
|
const range = this.#treeRange(base, f as string);
|
|
1974
2222
|
const q = this.fresh("q");
|
|
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 };
|
|
2223
|
+
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, texts: false };
|
|
1976
2224
|
}
|
|
1977
2225
|
// 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
2226
|
if (this.#graph && GRAPH_AXES.has(base.t)) {
|
|
1979
2227
|
const range = this.#graphRange(base.t, f as string);
|
|
1980
2228
|
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 };
|
|
2229
|
+
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, texts: false };
|
|
1982
2230
|
}
|
|
1983
2231
|
if (this.#graph && base.t === "window") throw new NotStandalone('the axis "window" in a graph space');
|
|
1984
2232
|
if (base.t === "others") skip = f;
|
|
@@ -1988,7 +2236,15 @@ class Printer {
|
|
|
1988
2236
|
s.push(`const ${h} = Math.min(n, ${f as string} + Math.min(${base.to}, n) + 1);`);
|
|
1989
2237
|
hi = h;
|
|
1990
2238
|
} else if (base.t !== "all") throw new NotStandalone(`the axis "${base.t}"`);
|
|
1991
|
-
return { s, j, head: forHead(j, lo, hi, reverse), key: [], check: [], skip, fixed: f === undefined, start, startSafe, tests, inner };
|
|
2239
|
+
return { s, j, head: forHead(j, lo, hi, reverse), key: [], check: [], skip, fixed: f === undefined, start, startSafe, tests, inner, texts: false };
|
|
2240
|
+
}
|
|
2241
|
+
|
|
2242
|
+
/**
|
|
2243
|
+
* This method gives a reason when a part of a loop of the axis `list` reads at a target that is not a record. The
|
|
2244
|
+
* interpreter reads the record of such a key, and a module has no record for it.
|
|
2245
|
+
*/
|
|
2246
|
+
#readsNoTarget(texts: boolean, level: number, deps: readonly ReadonlySet<number>[]): void {
|
|
2247
|
+
if (texts && deps.some((d) => d.has(level))) throw new NotStandalone('the axis "list" reads a record at a key of a literal or of "fill"');
|
|
1992
2248
|
}
|
|
1993
2249
|
|
|
1994
2250
|
/**
|
|
@@ -2046,11 +2302,12 @@ class Printer {
|
|
|
2046
2302
|
#list(op: string, target: ExprOf<"each">, rest: readonly Expr[], ctx: Ctx): Code {
|
|
2047
2303
|
const { strict, step } = this.#foldOptions(op, rest);
|
|
2048
2304
|
const at = target.at ?? [];
|
|
2049
|
-
const { s, j, head, key, check, skip, fixed, start, startSafe, tests, inner } = this.#targetLoop(target.axis, at, ctx);
|
|
2305
|
+
const { s, j, head, key, check, skip, fixed, start, startSafe, tests, inner, texts } = this.#targetLoop(target.axis, at, ctx);
|
|
2050
2306
|
const { level } = inner;
|
|
2051
2307
|
// Inside the loop, a constant of the run evaluates once, before the loop over the keys of the run.
|
|
2052
2308
|
const testCodes = tests.map((t) => this.#hoist(this.expr(t, inner), hasLoop(t)));
|
|
2053
2309
|
const body = this.#hoist(this.expr(target.body, inner), hasLoop(target.body));
|
|
2310
|
+
this.#readsNoTarget(texts, level, [body, ...testCodes].map((x) => x.v.deps));
|
|
2054
2311
|
// A count of all the items, whose body cannot fail, is the count of the records. A safe body covers its statements.
|
|
2055
2312
|
// V-063: a body that reads a cell keeps its loop. The search of the run must see each read, so a cell that reads
|
|
2056
2313
|
// itself gives `#CYCLE!`.
|
|
@@ -2167,11 +2424,12 @@ class Printer {
|
|
|
2167
2424
|
*/
|
|
2168
2425
|
#eachList(e: ExprOf<"each">, ctx: Ctx): Code {
|
|
2169
2426
|
const at = e.at ?? [];
|
|
2170
|
-
const { s, j, head, key, check, skip, start, startSafe, tests, inner } = this.#targetLoop(e.axis, at, ctx);
|
|
2427
|
+
const { s, j, head, key, check, skip, start, startSafe, tests, inner, texts } = this.#targetLoop(e.axis, at, ctx);
|
|
2171
2428
|
const testCodes = tests.map((t) => this.#hoist(this.expr(t, inner), hasLoop(t)));
|
|
2172
2429
|
// The value of an item can be a list, for flat (LIST.FLAT). The facts of the list tell it.
|
|
2173
2430
|
if (this.#wantList.has(e)) this.#wantList.add(e.body);
|
|
2174
2431
|
const body = this.#hoist(this.expr(e.body, inner), hasLoop(e.body));
|
|
2432
|
+
this.#readsNoTarget(texts, inner.level, [body, ...testCodes].map((x) => x.v.deps));
|
|
2175
2433
|
const deps = new Set([...start, ...[body, ...testCodes].flatMap((x) => [...x.v.deps])].filter((d) => d !== inner.level));
|
|
2176
2434
|
const list = this.fresh("L");
|
|
2177
2435
|
const v = this.fresh("x");
|
|
@@ -2182,7 +2440,7 @@ class Printer {
|
|
|
2182
2440
|
...(skip === undefined ? [] : [`if (${j} === ${skip}) continue;`]),
|
|
2183
2441
|
...(safeItem ? [...item, `${list}.push([${j}, ${body.v.code}]);`] : [`let ${v};`, "try {", ...ind(item), ` ${v} = ${body.v.code};`, "} catch {", ` ${v} = E;`, "}", `${list}.push([${j}, ${v}]);`]),
|
|
2184
2442
|
];
|
|
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 } } };
|
|
2443
|
+
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, texts } } };
|
|
2186
2444
|
}
|
|
2187
2445
|
|
|
2188
2446
|
/**
|
|
@@ -2193,13 +2451,31 @@ class Printer {
|
|
|
2193
2451
|
const list = this.#listOf(head, ctx);
|
|
2194
2452
|
// A missing count is the literal null, which is not a whole number, so take and drop give their error.
|
|
2195
2453
|
const exprs = [head, ...(op === "sortBy" ? [] : [rest[0] ?? lit(null)])];
|
|
2196
|
-
const
|
|
2454
|
+
const options = rest.slice(exprs.length - 1);
|
|
2455
|
+
const strict = this.#strict(op, options, op === "sortBy" ? ["strict", "by"] : ["strict"]);
|
|
2456
|
+
const by = op === "sortBy" ? this.#sortValue(options, list.v.list as ListInfo) : undefined;
|
|
2197
2457
|
const raw = [list, ...exprs.slice(1).map((x) => this.expr(x, ctx))];
|
|
2198
2458
|
const deps = depsOf(...raw);
|
|
2199
2459
|
const parts = this.#inOrder(this.#settle(raw, deps, exprs), true);
|
|
2200
|
-
const helper = op === "sortBy" ? "SB" : op === "take" ? "TK" : "DR";
|
|
2460
|
+
const helper = by !== undefined ? "SK" : op === "sortBy" ? "SB" : op === "take" ? "TK" : "DR";
|
|
2461
|
+
const args = [...parts.map((x) => x.v.code), String(strict), ...(by === undefined ? [] : [by])];
|
|
2201
2462
|
// 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)}(${
|
|
2463
|
+
return { s: stmtsOf(...parts), v: { code: `${this.use(helper)}(${args.join(", ")})`, kind: undefined, safe: false, deps, list: list.v.list } };
|
|
2464
|
+
}
|
|
2465
|
+
|
|
2466
|
+
/**
|
|
2467
|
+
* This method gives the function of the option `by` of `sortBy` (COMPILE.MODULE.SORT.BY), or undefined without the
|
|
2468
|
+
* option. The function applies the op of the static site of the kind of the items. An empty list applies no op.
|
|
2469
|
+
*/
|
|
2470
|
+
#sortValue(options: readonly Expr[], info: ListInfo): string | undefined {
|
|
2471
|
+
const by = (options[0] as { readonly value?: { readonly by?: unknown } } | undefined)?.value?.by;
|
|
2472
|
+
if (by === undefined) return undefined;
|
|
2473
|
+
if (typeof by !== "string") throw new NotStandalone('the option "by" of "sortBy" is not a literal text');
|
|
2474
|
+
if (info.empty === true) return undefined;
|
|
2475
|
+
if (info.item === undefined) throw new NotStandalone(`the kinds of the items of "sortBy" do not decide the op "${by}" of the option by`);
|
|
2476
|
+
const x = this.fresh("x");
|
|
2477
|
+
const value = this.#opCall(by, [bare({ code: x, kind: info.item, safe: true, deps: NO_DEPS, plain: true })], NO_DEPS);
|
|
2478
|
+
return `((${x}) => ${value.v.code})`;
|
|
2203
2479
|
}
|
|
2204
2480
|
|
|
2205
2481
|
/**
|
|
@@ -2225,7 +2501,7 @@ class Printer {
|
|
|
2225
2501
|
if (op === "get") return value(info.item, info.inner);
|
|
2226
2502
|
if (op === "indexOf") return value("number", undefined);
|
|
2227
2503
|
if (op === "without") return value(undefined, info);
|
|
2228
|
-
if (op === "append") return value(undefined, joinLists(info, (parts[1] as Code).v.list as ListInfo));
|
|
2504
|
+
if (op === "append") return value(undefined, joinLists(info, (parts[1] as Code).v.list as ListInfo, op));
|
|
2229
2505
|
// 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
2506
|
if (info.empty === true) return value(undefined, info);
|
|
2231
2507
|
if (info.inner === undefined) throw new NotStandalone('"flat" over a list whose items are not lists');
|
|
@@ -2261,8 +2537,8 @@ class Printer {
|
|
|
2261
2537
|
const env = new Map(ctx.env);
|
|
2262
2538
|
const vars = new Map<string, Name>();
|
|
2263
2539
|
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(
|
|
2540
|
+
// A step with a list literal or fill can give a name the keys of the literal or of fill (LOOP.LIST).
|
|
2541
|
+
const keyed = Object.values(step).some(hasTextKeys);
|
|
2266
2542
|
for (const [name, x] of Object.entries(init)) {
|
|
2267
2543
|
// 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
2544
|
this.#wantList.add(x);
|
|
@@ -2338,6 +2614,7 @@ class Printer {
|
|
|
2338
2614
|
// The interpreter evaluates the tests at each target before the first step, so a module of a sheet does not have them.
|
|
2339
2615
|
if (tests.some((x) => x.v.deps.has(CELLS))) throw new NotStandalone("a test of the axis of a fold reads a cell");
|
|
2340
2616
|
const step = this.#loopStep(e.step, { ...t.inner, env: names.env }, names.vars);
|
|
2617
|
+
this.#readsNoTarget(t.texts, t.inner.level, [...tests.map((x) => x.v.deps), step.deps]);
|
|
2341
2618
|
const result = this.expr(e.result, { ...ctx, env: names.env });
|
|
2342
2619
|
const body = [
|
|
2343
2620
|
...t.key,
|
|
@@ -2357,6 +2634,8 @@ class Printer {
|
|
|
2357
2634
|
* is a constant of the run itself.
|
|
2358
2635
|
*/
|
|
2359
2636
|
#memoized(e: Expr, keys: readonly Expr[], ctx: Ctx): Code {
|
|
2637
|
+
// A key can be a list, for example the list of a let that nth reads in the node (COMPILE.MODULE.NTH.INDEX).
|
|
2638
|
+
for (const k of keys) this.#wantList.add(k);
|
|
2360
2639
|
const values = keys.map((k) => this.#hoist(this.expr(k, ctx)));
|
|
2361
2640
|
const varying = keys.filter((_k, i) => (values[i] as Code).v.deps.size > 0);
|
|
2362
2641
|
const params = varying.map(() => this.fresh("q"));
|
|
@@ -2364,7 +2643,7 @@ class Printer {
|
|
|
2364
2643
|
keys.map((k, i): [Expr, Name] => {
|
|
2365
2644
|
const x = (values[i] as Code).v;
|
|
2366
2645
|
const p = varying.indexOf(k);
|
|
2367
|
-
return [k, p < 0 ? this.#nameOf(x) : { code: params[p] as string, kind: x.kind, lazy: true, deps: new Set([1]) }];
|
|
2646
|
+
return [k, p < 0 ? this.#nameOf(x) : { code: params[p] as string, kind: x.kind, lazy: true, deps: new Set([1]), list: x.list }];
|
|
2368
2647
|
}),
|
|
2369
2648
|
);
|
|
2370
2649
|
const outer = this.#inside;
|
|
@@ -2377,7 +2656,7 @@ class Printer {
|
|
|
2377
2656
|
}
|
|
2378
2657
|
// The kinds of the keys decide the ops in the node, so they are a part of the structure. Each key of the function
|
|
2379
2658
|
// can hold the error sentinel, so the nodes with a safe key and the nodes without one share it.
|
|
2380
|
-
const tokens = new Map(keys.map((k, i): [Expr, object] => [k, varying.includes(k) ? { "#": varying.indexOf(k), kind: (values[i] as Code).v.kind } : { "@": (names.get(k) as Name).code }]));
|
|
2659
|
+
const tokens = new Map(keys.map((k, i): [Expr, object] => [k, varying.includes(k) ? { "#": varying.indexOf(k), kind: (values[i] as Code).v.kind, list: (values[i] as Code).v.list } : { "@": (names.get(k) as Name).code }]));
|
|
2381
2660
|
const structure = canonical(e, (x) => tokens.get(x as Expr));
|
|
2382
2661
|
let fn = this.#structures.get(structure);
|
|
2383
2662
|
if (fn === undefined) {
|
|
@@ -2495,6 +2774,8 @@ class Printer {
|
|
|
2495
2774
|
/** This method gives the code of the program at the key of the run. A constant of the run evaluates once. */
|
|
2496
2775
|
/** This method gives the code of a program at the key `o` of the run. A sheet has one program for each formula. */
|
|
2497
2776
|
root(expr: Expr): Code {
|
|
2777
|
+
// The value of a program and of a cell can be a list (COMPILE.MODULE.LIST.RESULT).
|
|
2778
|
+
this.#wantList.add(expr);
|
|
2498
2779
|
return this.#hoist(this.expr(expr, { origin: "o", focus: "o", level: 1, originLevel: 1, env: new Map(), fns: new Map(), keys: new Map() }));
|
|
2499
2780
|
}
|
|
2500
2781
|
|
|
@@ -2544,6 +2825,19 @@ function reasonOf(thrown: unknown): Emitted {
|
|
|
2544
2825
|
return { ok: false, reason: thrown.message };
|
|
2545
2826
|
}
|
|
2546
2827
|
|
|
2828
|
+
/**
|
|
2829
|
+
* This function gives the code of the check of a field of a record `r` at the position `i`. The check of a list keeps
|
|
2830
|
+
* the array of the list when the program reads the field (COMPILE.MODULE.LIST.INPUT). The code is true for a field
|
|
2831
|
+
* against the schema.
|
|
2832
|
+
*/
|
|
2833
|
+
function fieldCheck(p: Printer, field: string, kind: Kind | ListKind): string {
|
|
2834
|
+
const input = `r[${JSON.stringify(field)}]`;
|
|
2835
|
+
if (typeof kind !== "object") return p.against(kind, input);
|
|
2836
|
+
const read = `${p.use("LI")}(${input}, ${String(depthOf(listOfKind(kind)))}, ${p.test(leafOf(kind))})`;
|
|
2837
|
+
const keep = p.inputs.get(field);
|
|
2838
|
+
return `${keep === undefined ? read : `(${keep}[i] = ${read})`} === undefined`;
|
|
2839
|
+
}
|
|
2840
|
+
|
|
2547
2841
|
/**
|
|
2548
2842
|
* This function gives the text of a module: the declarations, the helpers, and the function of the run. The run checks
|
|
2549
2843
|
* its input, computes the parts of the tree and the constants of the run, and then gives the statements `body`.
|
|
@@ -2561,7 +2855,7 @@ function printModule(p: Printer, options: ModuleOptions, run: Run, body: readonl
|
|
|
2561
2855
|
let fieldChecks: string;
|
|
2562
2856
|
let varChecks: string;
|
|
2563
2857
|
try {
|
|
2564
|
-
fieldChecks = fields.map(([f, k]) => ` || ${p
|
|
2858
|
+
fieldChecks = fields.map(([f, k]) => ` || ${fieldCheck(p, f, k)}`).join("");
|
|
2565
2859
|
varChecks = vars.map(([v, k]) => ` || ${p.against(k, `vars[${JSON.stringify(v)}]`)}`).join("");
|
|
2566
2860
|
} catch (thrown) {
|
|
2567
2861
|
return reasonOf(thrown);
|
|
@@ -2597,6 +2891,7 @@ function printModule(p: Printer, options: ModuleOptions, run: Run, body: readonl
|
|
|
2597
2891
|
' if (!Array.isArray(records)) C("the records are not an array");',
|
|
2598
2892
|
" const R = records;",
|
|
2599
2893
|
" const n = R.length;",
|
|
2894
|
+
...[...p.inputs.values()].map((x) => ` const ${x} = [];`),
|
|
2600
2895
|
" for (let i = 0; i < n; i++) {",
|
|
2601
2896
|
" const r = R[i];",
|
|
2602
2897
|
` if (typeof r !== "object" || r === null${fieldChecks}) C(\`the record \${i} does not keep the schema\`);`,
|
|
@@ -2637,7 +2932,9 @@ export function emitModule(source: Expr | Envelope, options: ModuleOptions): Emi
|
|
|
2637
2932
|
} catch (thrown) {
|
|
2638
2933
|
return reasonOf(thrown);
|
|
2639
2934
|
}
|
|
2640
|
-
|
|
2935
|
+
// A list gives a vex.list (COMPILE.MODULE.LIST.RESULT).
|
|
2936
|
+
const result = value.v.list === undefined ? value.v.code : `${p.use("LO")}(${value.v.code}, ${String(depthOf(value.v.list))})`;
|
|
2937
|
+
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;"];
|
|
2641
2938
|
return printModule(p, options, run, body);
|
|
2642
2939
|
}
|
|
2643
2940
|
|
|
@@ -2654,8 +2951,26 @@ interface Formula {
|
|
|
2654
2951
|
/** This function gives the words for a formula in a reason: the formula of a column, or of one cell. */
|
|
2655
2952
|
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)}"`);
|
|
2656
2953
|
|
|
2657
|
-
/** This function gives the words for a kind in a reason. */
|
|
2658
|
-
const kindText = (k: Kind | undefined): string => k ?? "that the printer does not know";
|
|
2954
|
+
/** This function gives the words for a kind in a reason. A list gives the kind of its items. */
|
|
2955
|
+
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)}`);
|
|
2956
|
+
|
|
2957
|
+
/** This function gives the number of the levels of lists in the items of a list: 0 for a list of values. */
|
|
2958
|
+
const depthOf = (l: ListInfo): number => (l.inner === undefined ? 0 : 1 + depthOf(l.inner));
|
|
2959
|
+
|
|
2960
|
+
/** This function gives the facts of the lists of a column from the kind of the option `kinds` (COMPILE.MODULE.SHEET.LIST). */
|
|
2961
|
+
const listOfKind = (k: ListKind, all = false): ListInfo => {
|
|
2962
|
+
const texts = all || k.texts === true;
|
|
2963
|
+
return typeof k.list === "object" ? { item: undefined, inner: listOfKind(k.list, all), texts } : { item: k.list, texts };
|
|
2964
|
+
};
|
|
2965
|
+
|
|
2966
|
+
/** This function gives the kind of the items at the bottom of a list kind. */
|
|
2967
|
+
const leafOf = (k: ListKind): Kind => (typeof k.list === "object" ? leafOf(k.list) : k.list);
|
|
2968
|
+
|
|
2969
|
+
/**
|
|
2970
|
+
* This function gives the facts of the lists of a column from the list of its first formula. The other cells of the
|
|
2971
|
+
* column can have other formulas. Thus a list without items does not tell that each list of the column is empty.
|
|
2972
|
+
*/
|
|
2973
|
+
const columnList = (l: ListInfo): ListInfo => ({ item: l.item, inner: l.inner === undefined ? undefined : columnList(l.inner), texts: l.texts === true });
|
|
2659
2974
|
|
|
2660
2975
|
/**
|
|
2661
2976
|
* This function prints the formula columns of a sheet as a standalone ES module (COMPILE.MODULE.SHEET). The function of
|
|
@@ -2686,22 +3001,43 @@ export function emitSheetModule(columns: ReadonlyMap<string, Expr>, options: She
|
|
|
2686
3001
|
const shape = shapeError(f.expr);
|
|
2687
3002
|
if (shape !== undefined) return { ok: false, reason: `${formulaText(f)}: ${shape}` };
|
|
2688
3003
|
}
|
|
2689
|
-
const kinds = new Map<string, Kind | undefined>(
|
|
3004
|
+
const kinds = new Map<string, Kind | undefined>();
|
|
3005
|
+
const lists = new Map<string, ListInfo>();
|
|
3006
|
+
for (const [c, k] of Object.entries(options.kinds ?? {})) {
|
|
3007
|
+
kinds.set(c, typeof k === "object" ? undefined : k);
|
|
3008
|
+
if (typeof k === "object") lists.set(c, listOfKind(k));
|
|
3009
|
+
}
|
|
2690
3010
|
const index = new Map(names.map((c, i) => [c, i]));
|
|
2691
3011
|
// The memo of the printer covers each formula, so the formulas share their nodes of the memo.
|
|
2692
3012
|
// A sheet whose reads all read finished cells needs no search: each cell is the value of its formula
|
|
2693
3013
|
// (COMPILE.MODULE.SHEET.DIRECT). A sheet with formulas of cells always has the search.
|
|
2694
3014
|
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 });
|
|
3015
|
+
const p = new Printer(rec(Object.fromEntries(formulas.map((f, i) => [`f${String(i)}`, f.expr]))), options, { columns: index, kinds, lists, direct });
|
|
2696
3016
|
const fns: string[] = [];
|
|
2697
3017
|
const decls: string[] = [];
|
|
3018
|
+
// The statements that put the value of each formula into the array of its column at the key `o`, for a direct fill.
|
|
3019
|
+
const blocks = new Map<string, readonly string[]>();
|
|
2698
3020
|
try {
|
|
2699
3021
|
for (const f of formulas) {
|
|
2700
3022
|
const code = p.root(f.expr);
|
|
2701
|
-
const kind = code.v
|
|
2702
|
-
// The first formula of a column without a kind of the options gives the kind of the column.
|
|
2703
|
-
|
|
2704
|
-
|
|
3023
|
+
const { kind, list } = code.v;
|
|
3024
|
+
// The first formula of a column without a kind of the options gives the kind of the column. Each other formula
|
|
3025
|
+
// must give a value of that kind, or a list that fits the lists of the column (COMPILE.MODULE.SHEET.LIST).
|
|
3026
|
+
if (!kinds.has(f.column)) {
|
|
3027
|
+
kinds.set(f.column, kind);
|
|
3028
|
+
if (list !== undefined) lists.set(f.column, columnList(list));
|
|
3029
|
+
} else {
|
|
3030
|
+
const known = lists.get(f.column);
|
|
3031
|
+
if (kinds.get(f.column) !== kind || (known === undefined) !== (list === undefined) || (known !== undefined && !fits(known, list as ListInfo))) {
|
|
3032
|
+
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`);
|
|
3033
|
+
}
|
|
3034
|
+
}
|
|
3035
|
+
// COMPILE.MODULE.ONCE: a direct fill has the code of each formula in its loop over the keys, with no function.
|
|
3036
|
+
if (direct) {
|
|
3037
|
+
const at = `D[${String(index.get(f.column))}][o]`;
|
|
3038
|
+
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;`, "}"]);
|
|
3039
|
+
continue;
|
|
3040
|
+
}
|
|
2705
3041
|
const fn = p.fresh("cf");
|
|
2706
3042
|
fns.push(fn);
|
|
2707
3043
|
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;", " }", "};"]));
|
|
@@ -2710,43 +3046,58 @@ export function emitSheetModule(columns: ReadonlyMap<string, Expr>, options: She
|
|
|
2710
3046
|
} catch (thrown) {
|
|
2711
3047
|
return reasonOf(thrown);
|
|
2712
3048
|
}
|
|
2713
|
-
// The program of each column, and of each cell with its own formula, with its cost in estimated frames, as in SheetRun.
|
|
2714
|
-
const entry = (i: number): string => `[${fns[i] as string}, ${String(3 * nestingOf((formulas[i] as Formula).expr) + 16)}]`;
|
|
2715
|
-
const own = names.map((c) => {
|
|
2716
|
-
const at = formulas.flatMap((f, i) => (f.column === c && f.key !== undefined ? [`${String(f.key)}: ${entry(i)}`] : []));
|
|
2717
|
-
return at.length === 0 ? "undefined" : `{ ${at.join(", ")} }`;
|
|
2718
|
-
});
|
|
2719
|
-
const cols = names.map((c) => {
|
|
2720
|
-
const i = formulas.findIndex((f) => f.column === c && f.key === undefined);
|
|
2721
|
-
return i < 0 ? "undefined" : entry(i);
|
|
2722
|
-
});
|
|
2723
3049
|
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);`);
|
|
2727
3050
|
// A tree gives the keys in the order of a fill with the helper KO, once for each order.
|
|
2728
3051
|
const orders = new Map<string, string>();
|
|
2729
|
-
const
|
|
3052
|
+
const headOf = (c: string): string => {
|
|
2730
3053
|
const { reverse, post, back } = keyOrderOf(readsOf(columns, cells, c).directions);
|
|
2731
|
-
|
|
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)}`;
|
|
3054
|
+
if (!run.tree) return reverse ? "for (let o = n - 1; o >= 0; o--)" : "for (let o = 0; o < n; o++)";
|
|
2733
3055
|
const args = `${p.use("KO")}(H, RT, ${String(post)}, ${String(back)})`;
|
|
2734
3056
|
let keys = orders.get(args);
|
|
2735
3057
|
if (keys === undefined) {
|
|
2736
3058
|
keys = p.fresh("K");
|
|
2737
3059
|
orders.set(args, keys);
|
|
2738
3060
|
}
|
|
2739
|
-
return `for (const o of ${keys})
|
|
2740
|
-
}
|
|
3061
|
+
return `for (const o of ${keys})`;
|
|
3062
|
+
};
|
|
3063
|
+
let fill: string[];
|
|
3064
|
+
if (direct) {
|
|
3065
|
+
// COMPILE.MODULE.ONCE: the columns that follow each other in the order share one loop over the keys when they have
|
|
3066
|
+
// the same order of the keys, and each read of a column of the loop reads a finished cell.
|
|
3067
|
+
const loops: { head: string; columns: string[] }[] = [];
|
|
3068
|
+
for (const c of order) {
|
|
3069
|
+
const head = headOf(c);
|
|
3070
|
+
const last = loops.at(-1);
|
|
3071
|
+
if (last?.head === head && readsFinished(columns, order, c, run.tree, new Set(last.columns))) last.columns.push(c);
|
|
3072
|
+
else loops.push({ head, columns: [c] });
|
|
3073
|
+
}
|
|
3074
|
+
fill = [];
|
|
3075
|
+
for (const { head, columns: cs } of loops) fill.push(`${head} {`, ...cs.flatMap((c) => ind(blocks.get(c) as readonly string[])), "}");
|
|
3076
|
+
} else {
|
|
3077
|
+
// The program of each column, and of each cell with its own formula, with its cost in estimated frames, as in SheetRun.
|
|
3078
|
+
const entry = (i: number): string => `[${fns[i] as string}, ${String(3 * nestingOf((formulas[i] as Formula).expr) + 16)}]`;
|
|
3079
|
+
const own = names.map((c) => {
|
|
3080
|
+
const at = formulas.flatMap((f, i) => (f.column === c && f.key !== undefined ? [`${String(f.key)}: ${entry(i)}`] : []));
|
|
3081
|
+
return at.length === 0 ? "undefined" : `{ ${at.join(", ")} }`;
|
|
3082
|
+
});
|
|
3083
|
+
const cols = names.map((c) => {
|
|
3084
|
+
const i = formulas.findIndex((f) => f.column === c && f.key === undefined);
|
|
3085
|
+
return i < 0 ? "undefined" : entry(i);
|
|
3086
|
+
});
|
|
3087
|
+
decls.push(`const SS = SH(n, [${cols.join(", ")}], [${own.join(", ")}], ${String(budget)});`, `const ${READ_CELL} = SS.r;`);
|
|
3088
|
+
fill = order.map((c) => `${headOf(c)} SS.f(${String(index.get(c))}, o);`);
|
|
3089
|
+
}
|
|
2741
3090
|
if (run.tree) p.treeParts.add("children");
|
|
3091
|
+
// A column of lists gives a vex.list in each cell with a list (COMPILE.MODULE.LIST.RESULT).
|
|
3092
|
+
const resultOf = (c: string, read: string): string => {
|
|
3093
|
+
const l = lists.get(c);
|
|
3094
|
+
return l === undefined ? read : `${p.use("LC")}(${read}, ${String(depthOf(l))})`;
|
|
3095
|
+
};
|
|
2742
3096
|
const body = [
|
|
2743
|
-
...decls,
|
|
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;`]),
|
|
3097
|
+
...(direct ? [`const D = [${names.map(() => "new Array(n)").join(", ")}];`] : decls),
|
|
2747
3098
|
...[...orders].map(([args, keys]) => `const ${keys} = ${args};`),
|
|
2748
3099
|
...fill,
|
|
2749
|
-
`return { ${names.map((c, i) => `${JSON.stringify(c)}: ${direct ? `DO(D[${String(i)}])` : `SS.o(${String(i)})`}`).join(", ")} };`,
|
|
3100
|
+
`return { ${names.map((c, i) => `${JSON.stringify(c)}: ${resultOf(c, direct ? `DO(D[${String(i)}])` : `SS.o(${String(i)})`)}`).join(", ")} };`,
|
|
2750
3101
|
];
|
|
2751
3102
|
return printModule(p, options, run, body);
|
|
2752
3103
|
}
|