@mark1russell7/vex-compiler 0.13.3 → 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 +11 -19
- package/build/index.d.ts.map +1 -1
- package/build/index.js +364 -85
- package/build/index.js.map +1 -1
- package/package.json +4 -4
- package/src/facts.ts +37 -10
- package/src/module.ts +333 -78
package/src/module.ts
CHANGED
|
@@ -20,7 +20,10 @@
|
|
|
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
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).
|
|
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.
|
|
24
27
|
* Another construct gives a reason, not code.
|
|
25
28
|
*
|
|
26
29
|
* `emitSheetModule` prints the formula columns of a sheet as one module (COMPILE.MODULE.SHEET). Each column is an array
|
|
@@ -28,8 +31,8 @@
|
|
|
28
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
|
|
29
32
|
* formula reads it with the list ops (COMPILE.MODULE.SHEET.LIST).
|
|
30
33
|
*/
|
|
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";
|
|
32
|
-
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";
|
|
33
36
|
import { memoNodes } from "./memo.ts";
|
|
34
37
|
import { columnOrder, isCellRef, keyOrderOf, readsFinished, readsOf } from "./sheet-order.ts";
|
|
35
38
|
|
|
@@ -66,14 +69,7 @@ export interface SheetModuleOptions extends ModuleOptions {
|
|
|
66
69
|
readonly budget?: number;
|
|
67
70
|
}
|
|
68
71
|
|
|
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
|
-
}
|
|
72
|
+
export type { ListKind } from "./facts.ts";
|
|
77
73
|
|
|
78
74
|
/** The source of a standalone module, or the reason that the program cannot be one. */
|
|
79
75
|
export type Emitted = { readonly ok: true; readonly source: string } | { readonly ok: false; readonly reason: string };
|
|
@@ -104,13 +100,13 @@ interface Value {
|
|
|
104
100
|
|
|
105
101
|
/**
|
|
106
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
|
|
107
|
-
* 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`.
|
|
108
104
|
*/
|
|
109
105
|
interface ListInfo {
|
|
110
106
|
readonly item: Kind | undefined;
|
|
111
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. */
|
|
112
108
|
readonly inner?: ListInfo | undefined;
|
|
113
|
-
/** 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. */
|
|
114
110
|
readonly texts?: boolean;
|
|
115
111
|
/** True for a list without items: the empty literal, and a list from it. Such a list fits each list. */
|
|
116
112
|
readonly empty?: boolean;
|
|
@@ -137,11 +133,12 @@ interface Name {
|
|
|
137
133
|
readonly list?: ListInfo | undefined;
|
|
138
134
|
}
|
|
139
135
|
|
|
140
|
-
/** 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). */
|
|
141
137
|
interface Arg {
|
|
142
138
|
readonly code: string;
|
|
143
139
|
readonly kind: Kind | undefined;
|
|
144
140
|
readonly deps: ReadonlySet<number>;
|
|
141
|
+
readonly list: ListInfo | undefined;
|
|
145
142
|
}
|
|
146
143
|
|
|
147
144
|
/** The levels of a constant of the run. */
|
|
@@ -240,6 +237,8 @@ interface CallScope {
|
|
|
240
237
|
interface Spec {
|
|
241
238
|
readonly name: string;
|
|
242
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;
|
|
243
242
|
readonly safe: boolean;
|
|
244
243
|
readonly deps: ReadonlySet<number>;
|
|
245
244
|
readonly origin: number;
|
|
@@ -250,7 +249,7 @@ interface Spec {
|
|
|
250
249
|
}
|
|
251
250
|
|
|
252
251
|
/** The name of a helper of the generated code. */
|
|
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;
|
|
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;
|
|
254
253
|
|
|
255
254
|
/** The helpers of the list ops that build a list (LIST.BUILD), of `get` (LIST.GET) and of `indexOf` (LIST.INDEXOF). */
|
|
256
255
|
type BuildHelper = "DR" | "AP" | "WO" | "FL" | "GT" | "IX";
|
|
@@ -262,7 +261,7 @@ type TreeHelper = "PT" | "CH" | "SG" | "PR" | "UP" | "SO" | "AN" | "BF";
|
|
|
262
261
|
type GraphHelper = "GR" | "GI" | "RB";
|
|
263
262
|
|
|
264
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. */
|
|
265
|
-
type SheetHelper = "SH" | "KO" | "DO" | "LO" | "LC";
|
|
264
|
+
type SheetHelper = "SH" | "KO" | "DO" | "LO" | "LC" | "LV";
|
|
266
265
|
|
|
267
266
|
/** The helpers of the generated code. A module has only the helpers that it uses. */
|
|
268
267
|
const HELPERS: Readonly<Record<Exclude<Helper, "S">, string>> = {
|
|
@@ -293,8 +292,63 @@ const HELPERS: Readonly<Record<Exclude<Helper, "S">, string>> = {
|
|
|
293
292
|
" return o.sort((a, b) => (a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0));",
|
|
294
293
|
"}",
|
|
295
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"),
|
|
296
304
|
TK: "function TK(l, n, s) { const o = V(l, s); return Number.isSafeInteger(n) && n >= 0 ? o.slice(0, n) : F(); }",
|
|
297
|
-
|
|
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"),
|
|
298
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
|
|
299
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.
|
|
300
354
|
DR: "function DR(l, n, s) { const o = V(l, s); return Number.isSafeInteger(n) && n >= 0 ? o.slice(n) : F(); }",
|
|
@@ -439,6 +493,18 @@ const HELPERS: Readonly<Record<Exclude<Helper, "S">, string>> = {
|
|
|
439
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
|
|
440
494
|
// error VEX_ERROR. The depth `h` is the number of the levels of lists in the items.
|
|
441
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"),
|
|
442
508
|
// A column of lists (COMPILE.MODULE.SHEET.LIST): each cell with a list gives a `vex.list`.
|
|
443
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; }",
|
|
444
510
|
SH: [
|
|
@@ -728,14 +794,14 @@ const NEEDS: Readonly<Record<Helper, readonly Helper[]>> = {
|
|
|
728
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.
|
|
729
795
|
// Stryker disable next-line ArrayDeclaration: see the comment above
|
|
730
796
|
V: ["F"],
|
|
731
|
-
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: [],
|
|
732
798
|
DR: ["V", "F"], AP: ["V"], WO: ["V"], FL: ["V"], GT: ["F"], IX: ["V", "F"],
|
|
733
799
|
// Each module has C, and each move uses F (#move), so these needs only complete the list.
|
|
734
800
|
// Stryker disable next-line ArrayDeclaration: see the comment above
|
|
735
801
|
PT: ["C"], GR: ["C"], UP: ["F"], SO: ["F"],
|
|
736
802
|
CH: [], SG: [], PR: [], AN: [], BF: [],
|
|
737
803
|
GI: [], RB: [],
|
|
738
|
-
SH: [], KO: [], DO: [], LO: [], LC: ["LO"],
|
|
804
|
+
SH: [], KO: [], DO: [], LO: [], LC: ["LO"], LV: [],
|
|
739
805
|
};
|
|
740
806
|
|
|
741
807
|
/** The parts of a tree that a run computes before the loop over its keys, if the program needs them. */
|
|
@@ -784,14 +850,35 @@ const BUILD_OPS: ReadonlySet<string> = new Set(["append", "without", "flat", "ge
|
|
|
784
850
|
/** The helper of each op of `#build`. */
|
|
785
851
|
const BUILD_HELPERS: Readonly<Record<string, BuildHelper>> = { append: "AP", without: "WO", flat: "FL", get: "GT", indexOf: "IX" };
|
|
786
852
|
|
|
787
|
-
/**
|
|
788
|
-
|
|
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
|
+
}
|
|
789
875
|
|
|
790
876
|
/**
|
|
791
877
|
* This function tells if an expression gives a list. An each, a list literal and a list op of `LIST_RESULTS` give a
|
|
792
|
-
* 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.
|
|
793
880
|
*/
|
|
794
|
-
function listy(e: Expr,
|
|
881
|
+
function listy(e: Expr, scope: ListScope): boolean {
|
|
795
882
|
switch (e.tag) {
|
|
796
883
|
case "each":
|
|
797
884
|
return true;
|
|
@@ -799,33 +886,59 @@ function listy(e: Expr, isName: (name: string) => boolean, isCell: (e: ExprOf<"e
|
|
|
799
886
|
return isVexList(e.value);
|
|
800
887
|
case "app":
|
|
801
888
|
// 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,
|
|
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)));
|
|
803
890
|
case "var":
|
|
804
|
-
return
|
|
891
|
+
return scope.name(e.name);
|
|
805
892
|
case "let":
|
|
806
|
-
return listy(e.body,
|
|
893
|
+
return listy(e.body, scopeIn(e.bind, scope));
|
|
807
894
|
case "fold":
|
|
808
895
|
case "iterate":
|
|
809
|
-
return listy(e.result,
|
|
896
|
+
return listy(e.result, scopeIn(e.init, scope));
|
|
810
897
|
case "ext":
|
|
811
|
-
return
|
|
812
|
-
case "
|
|
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
|
+
}
|
|
813
907
|
case "fn":
|
|
814
908
|
case "rec":
|
|
815
|
-
case "ref":
|
|
816
909
|
return false;
|
|
817
910
|
}
|
|
818
911
|
}
|
|
819
912
|
|
|
820
|
-
/**
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
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) };
|
|
925
|
+
}
|
|
926
|
+
|
|
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) };
|
|
824
934
|
}
|
|
825
935
|
|
|
826
|
-
/**
|
|
827
|
-
function
|
|
828
|
-
|
|
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);
|
|
829
942
|
}
|
|
830
943
|
|
|
831
944
|
/**
|
|
@@ -1139,6 +1252,8 @@ class Printer {
|
|
|
1139
1252
|
readonly helpers = new Set<Helper>();
|
|
1140
1253
|
/** The declarations at the top of the module: the functions of the domains and the checks of the results. */
|
|
1141
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>();
|
|
1142
1257
|
/** The statements at the start of a run: the constants of the run and the functions of the memo. */
|
|
1143
1258
|
readonly run: string[] = [];
|
|
1144
1259
|
/** The variables of the schema that the program reads. */
|
|
@@ -1267,7 +1382,23 @@ class Printer {
|
|
|
1267
1382
|
*/
|
|
1268
1383
|
against(kind: Kind, input: string): string {
|
|
1269
1384
|
const primitive = primitiveOf(kind);
|
|
1270
|
-
|
|
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 {
|
|
1271
1402
|
const d = this.#domains.findIndex((x) => kindOfDomain(x) === kind);
|
|
1272
1403
|
const domain = this.#domains[d];
|
|
1273
1404
|
if (domain === undefined) throw new NotStandalone(`the schema has the kind ${kind}, and no domain has it`);
|
|
@@ -1276,7 +1407,7 @@ class Printer {
|
|
|
1276
1407
|
const src = copied(domain.is, [[...SAMPLES.number, ...SAMPLES.string, ...SAMPLES.boolean, null, {}, [], ...this.#samples(kind)]], `the test "is" of the domain ${domain.name}`);
|
|
1277
1408
|
this.top.set(name, `const ${name} = ${src};`);
|
|
1278
1409
|
}
|
|
1279
|
-
return
|
|
1410
|
+
return name;
|
|
1280
1411
|
}
|
|
1281
1412
|
|
|
1282
1413
|
/** This method gives a new name for the code. */
|
|
@@ -1351,7 +1482,8 @@ class Printer {
|
|
|
1351
1482
|
this.#keyOf.set(c, this.#constKey(e, ctx));
|
|
1352
1483
|
this.#constant.add(e);
|
|
1353
1484
|
}
|
|
1354
|
-
// 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.
|
|
1355
1487
|
if (c.v.list !== undefined && !this.#wantList.has(e)) throw new NotStandalone("a list is a value of the program");
|
|
1356
1488
|
return this.#columnar(e, c, ctx) ? this.#column(e, c, ctx) : c;
|
|
1357
1489
|
}
|
|
@@ -1366,7 +1498,23 @@ class Printer {
|
|
|
1366
1498
|
|
|
1367
1499
|
/** This method tells if an expression gives a list at a place that takes one (`listy`). */
|
|
1368
1500
|
#isList(e: Expr, ctx: Ctx): boolean {
|
|
1369
|
-
|
|
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
|
+
};
|
|
1370
1518
|
}
|
|
1371
1519
|
|
|
1372
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. */
|
|
@@ -1488,12 +1636,15 @@ class Printer {
|
|
|
1488
1636
|
return this.#call(e, ctx);
|
|
1489
1637
|
case "rec": {
|
|
1490
1638
|
const names = Object.keys(e.fields);
|
|
1491
|
-
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));
|
|
1492
1643
|
const deps = depsOf(...raw);
|
|
1493
1644
|
// The interpreter evaluates each field, also after an error.
|
|
1494
|
-
const fields = this.#inOrder(this.#settle(raw, deps,
|
|
1645
|
+
const fields = this.#inOrder(this.#settle(raw, deps, exprs), true);
|
|
1495
1646
|
// A record of a module is a new object, so it needs no freeze.
|
|
1496
|
-
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(", ")} })`;
|
|
1497
1648
|
return { s: stmtsOf(...fields), v: { code, kind: undefined, safe: fields.every((x) => x.v.safe), deps } };
|
|
1498
1649
|
}
|
|
1499
1650
|
case "app":
|
|
@@ -1633,6 +1784,8 @@ class Printer {
|
|
|
1633
1784
|
const [field, ...more] = e.path;
|
|
1634
1785
|
const kind = field === undefined ? undefined : this.#schema.fields?.[field];
|
|
1635
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;
|
|
1636
1789
|
// A move to the origin cannot fail, and the schema has the field in each record.
|
|
1637
1790
|
const at = e.at ?? [];
|
|
1638
1791
|
const safe = at.every((m) => m.t === "origin");
|
|
@@ -1640,7 +1793,18 @@ class Printer {
|
|
|
1640
1793
|
const deps = this.#addressDeps(at, ctx, values);
|
|
1641
1794
|
// The interpreter evaluates the expressions of the address before its moves, and the first error stops them.
|
|
1642
1795
|
const parts = this.#inOrder(this.#settle(values, deps), false);
|
|
1643
|
-
|
|
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;
|
|
1644
1808
|
}
|
|
1645
1809
|
|
|
1646
1810
|
/** This method gives the code of the expressions of the computed moves of an address. They evaluate at the node. */
|
|
@@ -1744,27 +1908,31 @@ class Printer {
|
|
|
1744
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)}`);
|
|
1745
1909
|
const s: string[] = [];
|
|
1746
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);
|
|
1747
1913
|
const c = this.#hoist(this.expr(x, ctx), hasLoop(x));
|
|
1914
|
+
const { kind, deps, list } = c.v;
|
|
1748
1915
|
// A value that cannot throw is the argument itself. A read of a name that can hold the error passes the name.
|
|
1749
1916
|
if (c.v.safe) {
|
|
1750
1917
|
s.push(...c.s);
|
|
1751
|
-
return { code: c.v.code, kind
|
|
1918
|
+
return { code: c.v.code, kind, deps, list };
|
|
1752
1919
|
}
|
|
1753
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
|
|
1754
|
-
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 };
|
|
1755
1922
|
const b = this.fresh("b");
|
|
1756
1923
|
s.push(...this.#store(b, c));
|
|
1757
|
-
return { code: b, kind
|
|
1924
|
+
return { code: b, kind, deps, list };
|
|
1758
1925
|
});
|
|
1759
|
-
// Each parameter can hold the error of its argument, so one function serves the arguments of one kind.
|
|
1760
|
-
|
|
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 })));
|
|
1761
1929
|
const spec = bound.specs.get(sig) ?? this.#printFn(bound, args, sig);
|
|
1762
1930
|
// Each marker becomes the levels at the call. The levels of the arguments count for each call, because their
|
|
1763
1931
|
// statements read their keys, so the marker of the parameters gives no level.
|
|
1764
1932
|
const levels = (d: number): readonly number[] => (d === spec.origin ? [ctx.originLevel] : d === spec.focus ? [ctx.level] : d === spec.param ? [] : [d]);
|
|
1765
1933
|
const deps = new Set([...args.flatMap((a) => [...a.deps]), ...[...spec.deps].flatMap(levels)]);
|
|
1766
1934
|
const position = spec.deps.has(spec.origin) ? [ctx.focus, ctx.origin] : spec.deps.has(spec.focus) ? [ctx.focus] : [];
|
|
1767
|
-
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 } };
|
|
1768
1936
|
}
|
|
1769
1937
|
|
|
1770
1938
|
/**
|
|
@@ -1784,9 +1952,12 @@ class Printer {
|
|
|
1784
1952
|
const o = this.fresh("o");
|
|
1785
1953
|
const env = new Map(bound.ctx.env);
|
|
1786
1954
|
// A parameter hides a function of its name, because a read looks at the values first.
|
|
1787
|
-
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 }));
|
|
1788
1956
|
const scope: CallScope = { param, focus, repeats: nestsLoops(bound.fn.body), names: new Set(names), decls: [], root: bound.fn.body };
|
|
1789
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);
|
|
1790
1961
|
const body = this.expr(bound.fn.body, { origin: o, focus: k, level: focus, originLevel: origin, env, fns: bound.ctx.fns, keys: new Map() });
|
|
1791
1962
|
this.#scopes.pop();
|
|
1792
1963
|
const markers = new Set([origin, focus, param]);
|
|
@@ -1800,7 +1971,7 @@ class Printer {
|
|
|
1800
1971
|
const decl = s.length === 0 ? [`${head} ${body.v.code};`] : [`${head} {`, ...ind(s), ` return ${body.v.code};`, "};"];
|
|
1801
1972
|
(global ? this.run : bound.decls).push(...decl);
|
|
1802
1973
|
if (!global) bound.local = true;
|
|
1803
|
-
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 };
|
|
1804
1975
|
bound.specs.set(sig, spec);
|
|
1805
1976
|
return spec;
|
|
1806
1977
|
}
|
|
@@ -1832,16 +2003,49 @@ class Printer {
|
|
|
1832
2003
|
if (head !== undefined && (op === "sortBy" || op === "take" || (op === "drop" && this.#isList(head, ctx)))) return this.#order(op, head, rest, ctx);
|
|
1833
2004
|
if (head !== undefined && BUILD_OPS.has(op) && this.#isList(head, ctx)) return this.#build(op, head, rest, ctx);
|
|
1834
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);
|
|
1835
2008
|
const raw = args.map((x) => this.expr(x, ctx));
|
|
1836
2009
|
const deps = depsOf(...raw);
|
|
1837
2010
|
// The interpreter evaluates each argument, also after an error.
|
|
1838
2011
|
const values = this.#inOrder(this.#settle(raw, deps, args), true);
|
|
2012
|
+
if (op === "fill" && this.#facts.own(op)) return this.#fill(values, deps);
|
|
1839
2013
|
return this.#opCall(op, values, deps);
|
|
1840
2014
|
}
|
|
1841
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
|
+
|
|
1842
2043
|
/** This method prints the call of the op of a domain on some values, from the static site of their kinds. */
|
|
1843
2044
|
#opCall(op: string, values: readonly Code[], deps: ReadonlySet<number>): Code {
|
|
1844
|
-
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);
|
|
1845
2049
|
if (site?.t !== "fn") throw new NotStandalone(`the kinds of the values of "${op}" do not decide its op`);
|
|
1846
2050
|
if (site.bad) return { s: stmtsOf(...values), v: { code: `${this.use("F")}()`, kind: site.returns, safe: false, deps } };
|
|
1847
2051
|
if (site.returns === undefined) throw new NotStandalone(`the op "${op}" does not declare the kind of its result`);
|
|
@@ -1852,14 +2056,15 @@ class Printer {
|
|
|
1852
2056
|
// A static site of a domain has the function of the op of that domain.
|
|
1853
2057
|
const fn = (d.ops[op] as { fn: (...a: never[]) => unknown }).fn;
|
|
1854
2058
|
const kinds = values.map((x) => x.v.kind).filter((k): k is Kind => k !== undefined);
|
|
1855
|
-
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}`);
|
|
1856
2061
|
// An inline form cannot throw for primitive values only.
|
|
1857
|
-
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);
|
|
1858
2063
|
this.top.set(name, `const ${name} = ${src};`);
|
|
1859
2064
|
}
|
|
1860
2065
|
const form = this.#forms.get(name);
|
|
1861
2066
|
// An inline form takes each argument once, or a plain argument more often, so each argument evaluates once.
|
|
1862
|
-
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));
|
|
1863
2068
|
if (inline) {
|
|
1864
2069
|
const text = form.parts.map((x) => (typeof x === "number" ? `(${(values[x] as Code).v.code})` : x)).join("");
|
|
1865
2070
|
const checked = this.check(site.returns);
|
|
@@ -1868,7 +2073,7 @@ class Printer {
|
|
|
1868
2073
|
}
|
|
1869
2074
|
this.#called.add(name);
|
|
1870
2075
|
// An exception of the op is an error of Vex: the boundary around the op catches it.
|
|
1871
|
-
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(", ")})`);
|
|
1872
2077
|
return { s: stmtsOf(...values), v: { code, kind: site.returns, safe: false, deps } };
|
|
1873
2078
|
}
|
|
1874
2079
|
|
|
@@ -1972,6 +2177,8 @@ class Printer {
|
|
|
1972
2177
|
readonly startSafe: boolean;
|
|
1973
2178
|
readonly tests: readonly Expr[];
|
|
1974
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;
|
|
1975
2182
|
} {
|
|
1976
2183
|
const { base: outer, tests } = testsOf(axis);
|
|
1977
2184
|
// The reverse order of an axis is a loop from its end (AXIS.REVERSE). The validation keeps a base axis inside.
|
|
@@ -1984,14 +2191,14 @@ class Printer {
|
|
|
1984
2191
|
if (base.t === "list") {
|
|
1985
2192
|
if (at.length > 0) throw new NotStandalone('the axis "list" with an address');
|
|
1986
2193
|
const list = this.#hoist(this.#listOf(base.list, ctx), hasLoop(base.list));
|
|
1987
|
-
//
|
|
1988
|
-
|
|
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;
|
|
1989
2196
|
const a = this.fresh("A");
|
|
1990
2197
|
const q = this.fresh("q");
|
|
1991
2198
|
const head = reverse ? `for (let ${q} = ${a}.length - 1; ${q} >= 0; ${q}--) {` : `for (let ${q} = 0; ${q} < ${a}.length; ${q}++) {`;
|
|
1992
2199
|
const key = [`const ${j} = ${a}[${q}][0];`];
|
|
1993
2200
|
const check = [`if (${a}[${q}][1] === E) ${this.use("F")}();`];
|
|
1994
|
-
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 };
|
|
1995
2202
|
}
|
|
1996
2203
|
const s: string[] = [];
|
|
1997
2204
|
let lo = "0";
|
|
@@ -2013,13 +2220,13 @@ class Printer {
|
|
|
2013
2220
|
if (this.#tree && isTreeAxis(base)) {
|
|
2014
2221
|
const range = this.#treeRange(base, f as string);
|
|
2015
2222
|
const q = this.fresh("q");
|
|
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 };
|
|
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 };
|
|
2017
2224
|
}
|
|
2018
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.
|
|
2019
2226
|
if (this.#graph && GRAPH_AXES.has(base.t)) {
|
|
2020
2227
|
const range = this.#graphRange(base.t, f as string);
|
|
2021
2228
|
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 };
|
|
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 };
|
|
2023
2230
|
}
|
|
2024
2231
|
if (this.#graph && base.t === "window") throw new NotStandalone('the axis "window" in a graph space');
|
|
2025
2232
|
if (base.t === "others") skip = f;
|
|
@@ -2029,7 +2236,15 @@ class Printer {
|
|
|
2029
2236
|
s.push(`const ${h} = Math.min(n, ${f as string} + Math.min(${base.to}, n) + 1);`);
|
|
2030
2237
|
hi = h;
|
|
2031
2238
|
} else if (base.t !== "all") throw new NotStandalone(`the axis "${base.t}"`);
|
|
2032
|
-
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"');
|
|
2033
2248
|
}
|
|
2034
2249
|
|
|
2035
2250
|
/**
|
|
@@ -2087,11 +2302,12 @@ class Printer {
|
|
|
2087
2302
|
#list(op: string, target: ExprOf<"each">, rest: readonly Expr[], ctx: Ctx): Code {
|
|
2088
2303
|
const { strict, step } = this.#foldOptions(op, rest);
|
|
2089
2304
|
const at = target.at ?? [];
|
|
2090
|
-
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);
|
|
2091
2306
|
const { level } = inner;
|
|
2092
2307
|
// Inside the loop, a constant of the run evaluates once, before the loop over the keys of the run.
|
|
2093
2308
|
const testCodes = tests.map((t) => this.#hoist(this.expr(t, inner), hasLoop(t)));
|
|
2094
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));
|
|
2095
2311
|
// A count of all the items, whose body cannot fail, is the count of the records. A safe body covers its statements.
|
|
2096
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
|
|
2097
2313
|
// itself gives `#CYCLE!`.
|
|
@@ -2208,11 +2424,12 @@ class Printer {
|
|
|
2208
2424
|
*/
|
|
2209
2425
|
#eachList(e: ExprOf<"each">, ctx: Ctx): Code {
|
|
2210
2426
|
const at = e.at ?? [];
|
|
2211
|
-
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);
|
|
2212
2428
|
const testCodes = tests.map((t) => this.#hoist(this.expr(t, inner), hasLoop(t)));
|
|
2213
2429
|
// The value of an item can be a list, for flat (LIST.FLAT). The facts of the list tell it.
|
|
2214
2430
|
if (this.#wantList.has(e)) this.#wantList.add(e.body);
|
|
2215
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));
|
|
2216
2433
|
const deps = new Set([...start, ...[body, ...testCodes].flatMap((x) => [...x.v.deps])].filter((d) => d !== inner.level));
|
|
2217
2434
|
const list = this.fresh("L");
|
|
2218
2435
|
const v = this.fresh("x");
|
|
@@ -2223,7 +2440,7 @@ class Printer {
|
|
|
2223
2440
|
...(skip === undefined ? [] : [`if (${j} === ${skip}) continue;`]),
|
|
2224
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}]);`]),
|
|
2225
2442
|
];
|
|
2226
|
-
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 } } };
|
|
2227
2444
|
}
|
|
2228
2445
|
|
|
2229
2446
|
/**
|
|
@@ -2234,13 +2451,31 @@ class Printer {
|
|
|
2234
2451
|
const list = this.#listOf(head, ctx);
|
|
2235
2452
|
// A missing count is the literal null, which is not a whole number, so take and drop give their error.
|
|
2236
2453
|
const exprs = [head, ...(op === "sortBy" ? [] : [rest[0] ?? lit(null)])];
|
|
2237
|
-
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;
|
|
2238
2457
|
const raw = [list, ...exprs.slice(1).map((x) => this.expr(x, ctx))];
|
|
2239
2458
|
const deps = depsOf(...raw);
|
|
2240
2459
|
const parts = this.#inOrder(this.#settle(raw, deps, exprs), true);
|
|
2241
|
-
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])];
|
|
2242
2462
|
// The new list has some items of the list, so it keeps the facts of the list.
|
|
2243
|
-
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})`;
|
|
2244
2479
|
}
|
|
2245
2480
|
|
|
2246
2481
|
/**
|
|
@@ -2302,8 +2537,8 @@ class Printer {
|
|
|
2302
2537
|
const env = new Map(ctx.env);
|
|
2303
2538
|
const vars = new Map<string, Name>();
|
|
2304
2539
|
const deps = new Set<number>();
|
|
2305
|
-
// A step with a list literal can give a name the keys of the literal (LOOP.LIST).
|
|
2306
|
-
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);
|
|
2307
2542
|
for (const [name, x] of Object.entries(init)) {
|
|
2308
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.
|
|
2309
2544
|
this.#wantList.add(x);
|
|
@@ -2379,6 +2614,7 @@ class Printer {
|
|
|
2379
2614
|
// The interpreter evaluates the tests at each target before the first step, so a module of a sheet does not have them.
|
|
2380
2615
|
if (tests.some((x) => x.v.deps.has(CELLS))) throw new NotStandalone("a test of the axis of a fold reads a cell");
|
|
2381
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]);
|
|
2382
2618
|
const result = this.expr(e.result, { ...ctx, env: names.env });
|
|
2383
2619
|
const body = [
|
|
2384
2620
|
...t.key,
|
|
@@ -2398,6 +2634,8 @@ class Printer {
|
|
|
2398
2634
|
* is a constant of the run itself.
|
|
2399
2635
|
*/
|
|
2400
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);
|
|
2401
2639
|
const values = keys.map((k) => this.#hoist(this.expr(k, ctx)));
|
|
2402
2640
|
const varying = keys.filter((_k, i) => (values[i] as Code).v.deps.size > 0);
|
|
2403
2641
|
const params = varying.map(() => this.fresh("q"));
|
|
@@ -2405,7 +2643,7 @@ class Printer {
|
|
|
2405
2643
|
keys.map((k, i): [Expr, Name] => {
|
|
2406
2644
|
const x = (values[i] as Code).v;
|
|
2407
2645
|
const p = varying.indexOf(k);
|
|
2408
|
-
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 }];
|
|
2409
2647
|
}),
|
|
2410
2648
|
);
|
|
2411
2649
|
const outer = this.#inside;
|
|
@@ -2418,7 +2656,7 @@ class Printer {
|
|
|
2418
2656
|
}
|
|
2419
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
|
|
2420
2658
|
// can hold the error sentinel, so the nodes with a safe key and the nodes without one share it.
|
|
2421
|
-
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 }]));
|
|
2422
2660
|
const structure = canonical(e, (x) => tokens.get(x as Expr));
|
|
2423
2661
|
let fn = this.#structures.get(structure);
|
|
2424
2662
|
if (fn === undefined) {
|
|
@@ -2587,6 +2825,19 @@ function reasonOf(thrown: unknown): Emitted {
|
|
|
2587
2825
|
return { ok: false, reason: thrown.message };
|
|
2588
2826
|
}
|
|
2589
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
|
+
|
|
2590
2841
|
/**
|
|
2591
2842
|
* This function gives the text of a module: the declarations, the helpers, and the function of the run. The run checks
|
|
2592
2843
|
* its input, computes the parts of the tree and the constants of the run, and then gives the statements `body`.
|
|
@@ -2604,7 +2855,7 @@ function printModule(p: Printer, options: ModuleOptions, run: Run, body: readonl
|
|
|
2604
2855
|
let fieldChecks: string;
|
|
2605
2856
|
let varChecks: string;
|
|
2606
2857
|
try {
|
|
2607
|
-
fieldChecks = fields.map(([f, k]) => ` || ${p
|
|
2858
|
+
fieldChecks = fields.map(([f, k]) => ` || ${fieldCheck(p, f, k)}`).join("");
|
|
2608
2859
|
varChecks = vars.map(([v, k]) => ` || ${p.against(k, `vars[${JSON.stringify(v)}]`)}`).join("");
|
|
2609
2860
|
} catch (thrown) {
|
|
2610
2861
|
return reasonOf(thrown);
|
|
@@ -2640,6 +2891,7 @@ function printModule(p: Printer, options: ModuleOptions, run: Run, body: readonl
|
|
|
2640
2891
|
' if (!Array.isArray(records)) C("the records are not an array");',
|
|
2641
2892
|
" const R = records;",
|
|
2642
2893
|
" const n = R.length;",
|
|
2894
|
+
...[...p.inputs.values()].map((x) => ` const ${x} = [];`),
|
|
2643
2895
|
" for (let i = 0; i < n; i++) {",
|
|
2644
2896
|
" const r = R[i];",
|
|
2645
2897
|
` if (typeof r !== "object" || r === null${fieldChecks}) C(\`the record \${i} does not keep the schema\`);`,
|
|
@@ -2706,11 +2958,14 @@ const kindText = (k: Kind | undefined, l?: ListInfo): string => (l === undefined
|
|
|
2706
2958
|
const depthOf = (l: ListInfo): number => (l.inner === undefined ? 0 : 1 + depthOf(l.inner));
|
|
2707
2959
|
|
|
2708
2960
|
/** 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 };
|
|
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 };
|
|
2712
2964
|
};
|
|
2713
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
|
+
|
|
2714
2969
|
/**
|
|
2715
2970
|
* This function gives the facts of the lists of a column from the list of its first formula. The other cells of the
|
|
2716
2971
|
* column can have other formulas. Thus a list without items does not tell that each list of the column is empty.
|