@mark1russell7/vex-compiler 0.13.3 → 0.14.0
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 +554 -104
- package/build/index.js.map +1 -1
- package/package.json +4 -4
- package/src/facts.ts +37 -10
- package/src/module.ts +496 -103
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 ItemNames, 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,16 +133,23 @@ 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. */
|
|
148
145
|
const NO_DEPS: ReadonlySet<number> = new Set();
|
|
149
146
|
|
|
147
|
+
/** The names of the items of a loop without `as` (COMPILE.MODULE.LIST.ITEM). */
|
|
148
|
+
const NO_NAMES: ReadonlyMap<string, Name> = new Map();
|
|
149
|
+
|
|
150
|
+
/** This function gives the names of a body or of a step: the names `as` of the items hide the names outside (AXIS.LIST.SCOPE). */
|
|
151
|
+
const withNames = (env: ReadonlyMap<string, Name>, items: ReadonlyMap<string, Name>): ReadonlyMap<string, Name> => new Map([...env, ...items]);
|
|
152
|
+
|
|
150
153
|
/**
|
|
151
154
|
* The level of a read of a cell (COMPILE.MODULE.SHEET). The results of the cells change in a run. Thus a value that reads
|
|
152
155
|
* a cell is not a constant or a column of the run. The level is far from the other levels.
|
|
@@ -197,6 +200,16 @@ interface Ctx {
|
|
|
197
200
|
readonly fns: ReadonlyMap<string, BoundFn>;
|
|
198
201
|
}
|
|
199
202
|
|
|
203
|
+
/**
|
|
204
|
+
* A name of a loop whose step appends to its own list (COMPILE.MODULE.APPEND.OWN). It has the name, its read in the
|
|
205
|
+
* loop and the variable of the array of its last append. The printer makes the variable at the first append that uses it.
|
|
206
|
+
*/
|
|
207
|
+
interface Owner {
|
|
208
|
+
readonly name: string;
|
|
209
|
+
readonly read: Name;
|
|
210
|
+
w: string | undefined;
|
|
211
|
+
}
|
|
212
|
+
|
|
200
213
|
/**
|
|
201
214
|
* A bound function of the printer (FN.BIND): its node and the context of its binding. It also has one printed
|
|
202
215
|
* JavaScript function for each signature of the arguments of its calls.
|
|
@@ -240,6 +253,8 @@ interface CallScope {
|
|
|
240
253
|
interface Spec {
|
|
241
254
|
readonly name: string;
|
|
242
255
|
readonly kind: Kind | undefined;
|
|
256
|
+
/** The facts of the list of the body, for a function whose value is a list (COMPILE.MODULE.LIST.CALL). */
|
|
257
|
+
readonly list: ListInfo | undefined;
|
|
243
258
|
readonly safe: boolean;
|
|
244
259
|
readonly deps: ReadonlySet<number>;
|
|
245
260
|
readonly origin: number;
|
|
@@ -250,10 +265,10 @@ interface Spec {
|
|
|
250
265
|
}
|
|
251
266
|
|
|
252
267
|
/** 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;
|
|
268
|
+
type Helper = "F" | "C" | "T" | "L" | "Q" | "G" | "B" | "U" | "X" | "I" | "K" | "M" | "M1" | "S" | "V" | "SB" | "SK" | "TK" | "VW" | "NT" | "CT" | "FS" | "FI" | "LI" | BuildHelper | TreeHelper | GraphHelper | SheetHelper;
|
|
254
269
|
|
|
255
270
|
/** The helpers of the list ops that build a list (LIST.BUILD), of `get` (LIST.GET) and of `indexOf` (LIST.INDEXOF). */
|
|
256
|
-
type BuildHelper = "DR" | "AP" | "WO" | "FL" | "GT" | "IX";
|
|
271
|
+
type BuildHelper = "DR" | "AP" | "AO" | "WO" | "FL" | "GT" | "IX";
|
|
257
272
|
|
|
258
273
|
/** The helpers of a tree space (COMPILE.MODULE.TREE). */
|
|
259
274
|
type TreeHelper = "PT" | "CH" | "SG" | "PR" | "UP" | "SO" | "AN" | "BF";
|
|
@@ -262,7 +277,7 @@ type TreeHelper = "PT" | "CH" | "SG" | "PR" | "UP" | "SO" | "AN" | "BF";
|
|
|
262
277
|
type GraphHelper = "GR" | "GI" | "RB";
|
|
263
278
|
|
|
264
279
|
/** 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";
|
|
280
|
+
type SheetHelper = "SH" | "KO" | "DO" | "LO" | "LC" | "LV";
|
|
266
281
|
|
|
267
282
|
/** The helpers of the generated code. A module has only the helpers that it uses. */
|
|
268
283
|
const HELPERS: Readonly<Record<Exclude<Helper, "S">, string>> = {
|
|
@@ -293,12 +308,81 @@ const HELPERS: Readonly<Record<Exclude<Helper, "S">, string>> = {
|
|
|
293
308
|
" return o.sort((a, b) => (a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0));",
|
|
294
309
|
"}",
|
|
295
310
|
].join("\n"),
|
|
311
|
+
// The option by of sortBy (LIST.SORT.BY): the function f gives the sort value of each item with a value, in order.
|
|
312
|
+
SK: [
|
|
313
|
+
"function SK(l, s, f) {",
|
|
314
|
+
" const o = V(l, s).map((x) => [x, f(x[1])]);",
|
|
315
|
+
" const t = o.length > 0 ? typeof o[0][1] : \"number\";",
|
|
316
|
+
" for (const [, v] of o) if (typeof v !== t || (t !== \"number\" && t !== \"string\") || v !== v) F();",
|
|
317
|
+
" return o.sort((a, b) => (a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0)).map((x) => x[0]);",
|
|
318
|
+
"}",
|
|
319
|
+
].join("\n"),
|
|
296
320
|
TK: "function TK(l, n, s) { const o = V(l, s); return Number.isSafeInteger(n) && n >= 0 ? o.slice(0, n) : F(); }",
|
|
297
|
-
|
|
321
|
+
// The items with values of a list stay on its array, as GT keeps its index. Thus a loop that reads each item of a list
|
|
322
|
+
// of n items with nth costs O(n), not O(n squared). count and first read them too (COMPILE.MODULE.NTH.INDEX).
|
|
323
|
+
VW: [
|
|
324
|
+
"function VW(l) {",
|
|
325
|
+
" let o = l.vw;",
|
|
326
|
+
" if (o === undefined) {",
|
|
327
|
+
" o = l.filter((x) => x[1] !== E);",
|
|
328
|
+
" l.vw = o;",
|
|
329
|
+
" }",
|
|
330
|
+
" return o;",
|
|
331
|
+
"}",
|
|
332
|
+
].join("\n"),
|
|
333
|
+
NT: [
|
|
334
|
+
"function NT(l, i, s) {",
|
|
335
|
+
" const o = VW(l);",
|
|
336
|
+
" if (s && o.length < l.length) F();",
|
|
337
|
+
" return Number.isSafeInteger(i) && i >= 0 && i < o.length ? o[i][1] : F();",
|
|
338
|
+
"}",
|
|
339
|
+
].join("\n"),
|
|
340
|
+
// count and first of a list that is not an each. With strict, an error item is the error of the op.
|
|
341
|
+
CT: "function CT(l, s) { const o = VW(l); return s && o.length < l.length ? F() : o.length; }",
|
|
342
|
+
FS: "function FS(l, s) { const o = VW(l); return (s && o.length < l.length) || o.length === 0 ? F() : o[0][1]; }",
|
|
343
|
+
// 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
|
|
344
|
+
// number from 0 to 100000, or a missing value, is the error of the interpreter. Each item can share the array of a list.
|
|
345
|
+
FI: [
|
|
346
|
+
"function FI(n, v) {",
|
|
347
|
+
" if (!(Number.isSafeInteger(n) && n >= 0 && n <= 100000 && v !== undefined)) F();",
|
|
348
|
+
" const o = [];",
|
|
349
|
+
" for (let i = 0; i < n; i++) o.push([i, v]);",
|
|
350
|
+
" return o;",
|
|
351
|
+
"}",
|
|
352
|
+
].join("\n"),
|
|
353
|
+
// A list of a field of the input (COMPILE.MODULE.LIST.INPUT): the array of a `vex.list` whose items have lists to the
|
|
354
|
+
// depth `h`, and values that pass the test `t`. The shape is the shape of `isVexList`. An error item holds the sentinel.
|
|
355
|
+
// An input that is not such a list, or an error item of `#DEPTH!`, gives undefined, so the check of the run fails.
|
|
356
|
+
LI: [
|
|
357
|
+
"function LI(x, h, t) {",
|
|
358
|
+
" if (typeof x !== \"object\" || x === null || x.kind !== \"vex.list\" || !Array.isArray(x.items)) return undefined;",
|
|
359
|
+
" const o = [];",
|
|
360
|
+
" for (let i = 0; i < x.items.length; i++) {",
|
|
361
|
+
" const it = x.items[i];",
|
|
362
|
+
" const r = typeof it === \"object\" && it !== null ? it.result : undefined;",
|
|
363
|
+
" if (typeof r !== \"object\" || r === null || typeof it.key !== \"string\") return undefined;",
|
|
364
|
+
" if (r.ok === true) {",
|
|
365
|
+
" const v = h > 0 ? LI(r.value, h - 1, t) : r.value !== undefined && t(r.value) ? r.value : undefined;",
|
|
366
|
+
" if (v === undefined) return undefined;",
|
|
367
|
+
" o.push([it.key, v]);",
|
|
368
|
+
" } else {",
|
|
369
|
+
" const e = r.error;",
|
|
370
|
+
" 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;",
|
|
371
|
+
" o.push([it.key, E]);",
|
|
372
|
+
" }",
|
|
373
|
+
" }",
|
|
374
|
+
" return o;",
|
|
375
|
+
"}",
|
|
376
|
+
].join("\n"),
|
|
298
377
|
// 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
378
|
// `without` and `get` compare the text of each key. A list is an array that does not change after the op that makes it.
|
|
379
|
+
// The one exception is the array of AO during its loop, which no other part reads (COMPILE.MODULE.APPEND.OWN).
|
|
300
380
|
DR: "function DR(l, n, s) { const o = V(l, s); return Number.isSafeInteger(n) && n >= 0 ? o.slice(n) : F(); }",
|
|
301
381
|
AP: "function AP(l, o, s) { return V(l, s).concat(V(o, s)); }",
|
|
382
|
+
// append into the list of a name of a loop (COMPILE.MODULE.APPEND.OWN). w is the array of the last append of the name
|
|
383
|
+
// in this run of the loop, and no other part reads it. Such an array has no error items, so V(l, s) is a copy of l.
|
|
384
|
+
// Each other list gets the copy of AP. V(o, s) throws before the first push, so an error does not change l.
|
|
385
|
+
AO: "function AO(l, o, s, w) { if (l !== w) return AP(l, o, s); for (const x of V(o, s)) l.push(x); return l; }",
|
|
302
386
|
WO: [
|
|
303
387
|
"function WO(l, o, s) {",
|
|
304
388
|
" const a = V(l, s), g = new Map();",
|
|
@@ -439,6 +523,18 @@ const HELPERS: Readonly<Record<Exclude<Helper, "S">, string>> = {
|
|
|
439
523
|
// 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
524
|
// error VEX_ERROR. The depth `h` is the number of the levels of lists in the items.
|
|
441
525
|
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 } })) }; }',
|
|
526
|
+
// 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
|
|
527
|
+
// `vex.list`, as the interpreter gives. The array keeps it, so each later read of the list gives the same object.
|
|
528
|
+
LV: [
|
|
529
|
+
"function LV(l, h) {",
|
|
530
|
+
" let o = l.vl;",
|
|
531
|
+
" if (o === undefined) {",
|
|
532
|
+
' 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 } }))) });',
|
|
533
|
+
" l.vl = o;",
|
|
534
|
+
" }",
|
|
535
|
+
" return o;",
|
|
536
|
+
"}",
|
|
537
|
+
].join("\n"),
|
|
442
538
|
// A column of lists (COMPILE.MODULE.SHEET.LIST): each cell with a list gives a `vex.list`.
|
|
443
539
|
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
540
|
SH: [
|
|
@@ -728,14 +824,14 @@ const NEEDS: Readonly<Record<Helper, readonly Helper[]>> = {
|
|
|
728
824
|
// 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
825
|
// Stryker disable next-line ArrayDeclaration: see the comment above
|
|
730
826
|
V: ["F"],
|
|
731
|
-
SB: ["V", "F"], TK: ["V", "F"], NT: ["
|
|
732
|
-
DR: ["V", "F"], AP: ["V"], WO: ["V"], FL: ["V"], GT: ["F"], IX: ["V", "F"],
|
|
827
|
+
SB: ["V", "F"], SK: ["V", "F"], TK: ["V", "F"], VW: [], NT: ["VW", "F"], CT: ["VW", "F"], FS: ["VW", "F"], FI: ["F"], LI: [],
|
|
828
|
+
DR: ["V", "F"], AP: ["V"], AO: ["AP", "V"], WO: ["V"], FL: ["V"], GT: ["F"], IX: ["V", "F"],
|
|
733
829
|
// Each module has C, and each move uses F (#move), so these needs only complete the list.
|
|
734
830
|
// Stryker disable next-line ArrayDeclaration: see the comment above
|
|
735
831
|
PT: ["C"], GR: ["C"], UP: ["F"], SO: ["F"],
|
|
736
832
|
CH: [], SG: [], PR: [], AN: [], BF: [],
|
|
737
833
|
GI: [], RB: [],
|
|
738
|
-
SH: [], KO: [], DO: [], LO: [], LC: ["LO"],
|
|
834
|
+
SH: [], KO: [], DO: [], LO: [], LC: ["LO"], LV: [],
|
|
739
835
|
};
|
|
740
836
|
|
|
741
837
|
/** The parts of a tree that a run computes before the loop over its keys, if the program needs them. */
|
|
@@ -784,14 +880,35 @@ const BUILD_OPS: ReadonlySet<string> = new Set(["append", "without", "flat", "ge
|
|
|
784
880
|
/** The helper of each op of `#build`. */
|
|
785
881
|
const BUILD_HELPERS: Readonly<Record<string, BuildHelper>> = { append: "AP", without: "WO", flat: "FL", get: "GT", indexOf: "IX" };
|
|
786
882
|
|
|
787
|
-
/**
|
|
788
|
-
|
|
883
|
+
/**
|
|
884
|
+
* The ops whose value is a list: the list ops of LIST.SORT, LIST.TAKE and LIST.BUILD, and `fill` (LIST.FILL). A domain
|
|
885
|
+
* can have the op `fill`. Then the op of the domain gives no list, and the place of a list gives a reason.
|
|
886
|
+
*/
|
|
887
|
+
const LIST_RESULTS: ReadonlySet<string> = new Set(["sortBy", "take", "drop", "append", "without", "flat", "fill"]);
|
|
888
|
+
|
|
889
|
+
/**
|
|
890
|
+
* The scope of `listy`. `name` tells if a name holds a list, and `fn` gives the bound function of a name. `cell` tells
|
|
891
|
+
* 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).
|
|
892
|
+
*/
|
|
893
|
+
interface ListScope {
|
|
894
|
+
readonly name: (name: string) => boolean;
|
|
895
|
+
readonly fn: (name: string) => ListFn | undefined;
|
|
896
|
+
readonly cell: (e: ExprOf<"ext">) => boolean;
|
|
897
|
+
readonly field: (e: ExprOf<"ref">) => boolean;
|
|
898
|
+
}
|
|
899
|
+
|
|
900
|
+
/** A bound function for `listy`: its node, and the scope of its binding (FN.BIND). */
|
|
901
|
+
interface ListFn {
|
|
902
|
+
readonly fn: ExprOf<"fn">;
|
|
903
|
+
readonly scope: ListScope;
|
|
904
|
+
}
|
|
789
905
|
|
|
790
906
|
/**
|
|
791
907
|
* 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.
|
|
908
|
+
* 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
|
|
909
|
+
* body of its function gives one (COMPILE.MODULE.LIST.CALL). The scope tells the names and the functions outside the expression.
|
|
793
910
|
*/
|
|
794
|
-
function listy(e: Expr,
|
|
911
|
+
function listy(e: Expr, scope: ListScope): boolean {
|
|
795
912
|
switch (e.tag) {
|
|
796
913
|
case "each":
|
|
797
914
|
return true;
|
|
@@ -799,33 +916,59 @@ function listy(e: Expr, isName: (name: string) => boolean, isCell: (e: ExprOf<"e
|
|
|
799
916
|
return isVexList(e.value);
|
|
800
917
|
case "app":
|
|
801
918
|
// 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,
|
|
919
|
+
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
920
|
case "var":
|
|
804
|
-
return
|
|
921
|
+
return scope.name(e.name);
|
|
805
922
|
case "let":
|
|
806
|
-
return listy(e.body,
|
|
923
|
+
return listy(e.body, scopeIn(e.bind, scope));
|
|
807
924
|
case "fold":
|
|
808
925
|
case "iterate":
|
|
809
|
-
return listy(e.result,
|
|
926
|
+
return listy(e.result, scopeIn(e.init, scope));
|
|
810
927
|
case "ext":
|
|
811
|
-
return
|
|
812
|
-
case "
|
|
928
|
+
return scope.cell(e);
|
|
929
|
+
case "ref":
|
|
930
|
+
return scope.field(e);
|
|
931
|
+
case "call": {
|
|
932
|
+
// A call of no function gives a reason in the printer. A value or a parameter with the name of a function makes
|
|
933
|
+
// the printer give that reason too, so the scope does not hide the function.
|
|
934
|
+
const f = scope.fn(e.fn);
|
|
935
|
+
return f !== undefined && listy(f.fn.body, paramsIn(f, e.args, scope));
|
|
936
|
+
}
|
|
813
937
|
case "fn":
|
|
814
938
|
case "rec":
|
|
815
|
-
case "ref":
|
|
816
939
|
return false;
|
|
817
940
|
}
|
|
818
941
|
}
|
|
819
942
|
|
|
820
|
-
/**
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
943
|
+
/**
|
|
944
|
+
* This function gives the scope of some bindings. A value hides a name outside, and a function is not a list. A
|
|
945
|
+
* function sees the scope outside the bindings, so it cannot call itself.
|
|
946
|
+
*/
|
|
947
|
+
function scopeIn(bind: Readonly<Record<string, Expr>>, scope: ListScope): ListScope {
|
|
948
|
+
const lists = new Map<string, boolean>();
|
|
949
|
+
const fns = new Map<string, ListFn>();
|
|
950
|
+
for (const [name, x] of Object.entries(bind)) {
|
|
951
|
+
if (x.tag === "fn") fns.set(name, { fn: x, scope });
|
|
952
|
+
lists.set(name, listy(x, scope));
|
|
953
|
+
}
|
|
954
|
+
return { ...scope, name: (name) => lists.get(name) ?? scope.name(name), fn: (name) => fns.get(name) ?? scope.fn(name) };
|
|
955
|
+
}
|
|
956
|
+
|
|
957
|
+
/**
|
|
958
|
+
* This function gives the scope of the body of a function at a call. The body sees the scope of the binding of the
|
|
959
|
+
* function, and each parameter holds a list when its argument does.
|
|
960
|
+
*/
|
|
961
|
+
function paramsIn(f: ListFn, args: readonly Expr[], scope: ListScope): ListScope {
|
|
962
|
+
const lists = new Map(args.map((x, i) => [f.fn.params[i], listy(x, scope)]));
|
|
963
|
+
return { ...f.scope, name: (name) => lists.get(name) ?? f.scope.name(name) };
|
|
824
964
|
}
|
|
825
965
|
|
|
826
|
-
/**
|
|
827
|
-
function
|
|
828
|
-
|
|
966
|
+
/**
|
|
967
|
+
* This function tells if an expression has a list literal with an item (LIST.LITERAL), or `fill` (LIST.FILL). Then a key
|
|
968
|
+
* of a list of the expression can be a key that is not the position of a record.
|
|
969
|
+
*/
|
|
970
|
+
function hasTextKeys(e: Expr): boolean {
|
|
971
|
+
return (e.tag === "lit" && isVexList(e.value) && e.value.items.length > 0) || (e.tag === "app" && e.op === "fill") || children(e).some(hasTextKeys);
|
|
829
972
|
}
|
|
830
973
|
|
|
831
974
|
/**
|
|
@@ -869,6 +1012,25 @@ const listKind = (op: string, item: Kind | undefined): Kind | undefined => (NUMB
|
|
|
869
1012
|
|
|
870
1013
|
const LOOPS = new WeakMap<Expr, boolean>();
|
|
871
1014
|
|
|
1015
|
+
/**
|
|
1016
|
+
* This function tells if the step of the name `name` of a loop appends to the list of the name (COMPILE.MODULE.APPEND.OWN).
|
|
1017
|
+
* It puts the append nodes of the form into `out`. The form is a read of the name,
|
|
1018
|
+
* `append(form, X)`, `if(c, form, form)` or a let with the form as its body. No other part of the form reads the name:
|
|
1019
|
+
* not `X`, not `c` and not a binding of a let.
|
|
1020
|
+
*/
|
|
1021
|
+
function ownForm(e: Expr, name: string, out: Expr[]): boolean {
|
|
1022
|
+
const free = (x: Expr): boolean => !namesOf(x).has(name);
|
|
1023
|
+
if (e.tag === "var") return e.name === name;
|
|
1024
|
+
if (e.tag === "let") return Object.values(e.bind).every(free) && ownForm(e.body, name, out);
|
|
1025
|
+
if (e.tag !== "app" || e.args.length === 0) return false;
|
|
1026
|
+
const [head, ...rest] = e.args as [Expr, ...Expr[]];
|
|
1027
|
+
// An if without three arguments gives a reason (#if), so the form does not check the count.
|
|
1028
|
+
if (e.op === "if") return free(head) && rest.every((x) => ownForm(x, name, out));
|
|
1029
|
+
if (e.op !== "append" || !rest.every(free) || !ownForm(head, name, out)) return false;
|
|
1030
|
+
out.push(e);
|
|
1031
|
+
return true;
|
|
1032
|
+
}
|
|
1033
|
+
|
|
872
1034
|
/** This function gives the names that an expression reads, also the names that it binds itself. */
|
|
873
1035
|
function namesOf(e: Expr, out = new Set<string>()): Set<string> {
|
|
874
1036
|
if (e.tag === "var") out.add(e.name);
|
|
@@ -1139,6 +1301,8 @@ class Printer {
|
|
|
1139
1301
|
readonly helpers = new Set<Helper>();
|
|
1140
1302
|
/** The declarations at the top of the module: the functions of the domains and the checks of the results. */
|
|
1141
1303
|
readonly top = new Map<string, string>();
|
|
1304
|
+
/** The array of the lists of each field of the input that the program reads (COMPILE.MODULE.LIST.INPUT). */
|
|
1305
|
+
readonly inputs = new Map<string, string>();
|
|
1142
1306
|
/** The statements at the start of a run: the constants of the run and the functions of the memo. */
|
|
1143
1307
|
readonly run: string[] = [];
|
|
1144
1308
|
/** The variables of the schema that the program reads. */
|
|
@@ -1163,6 +1327,8 @@ class Printer {
|
|
|
1163
1327
|
#loops = 1_000_000;
|
|
1164
1328
|
/** The node of the memo whose function the printer prints, so it prints the node itself. */
|
|
1165
1329
|
#inside: Expr | undefined;
|
|
1330
|
+
/** The owner of each append node of the step of a loop that the printer prints (COMPILE.MODULE.APPEND.OWN). */
|
|
1331
|
+
readonly #own = new Map<Expr, Owner>();
|
|
1166
1332
|
readonly #structures = new Map<string, string>();
|
|
1167
1333
|
readonly #kinds = new Map<string, Kind | undefined>();
|
|
1168
1334
|
readonly #ops = new Map<string, number>();
|
|
@@ -1267,7 +1433,23 @@ class Printer {
|
|
|
1267
1433
|
*/
|
|
1268
1434
|
against(kind: Kind, input: string): string {
|
|
1269
1435
|
const primitive = primitiveOf(kind);
|
|
1270
|
-
|
|
1436
|
+
return primitive === undefined ? `!${this.#isOf(kind)}(${input})` : `typeof ${input} !== "${primitive}"`;
|
|
1437
|
+
}
|
|
1438
|
+
|
|
1439
|
+
/**
|
|
1440
|
+
* 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
|
|
1441
|
+
* test of a primitive type checks the JavaScript type, and the test of a domain is the copy of its `is`.
|
|
1442
|
+
*/
|
|
1443
|
+
test(kind: Kind): string {
|
|
1444
|
+
const primitive = primitiveOf(kind);
|
|
1445
|
+
if (primitive === undefined) return this.#isOf(kind);
|
|
1446
|
+
const name = `is_${primitive}`;
|
|
1447
|
+
this.top.set(name, `const ${name} = (x) => typeof x === "${primitive}";`);
|
|
1448
|
+
return name;
|
|
1449
|
+
}
|
|
1450
|
+
|
|
1451
|
+
/** This method gives the name of the copy of the test `is` of the domain of a kind. */
|
|
1452
|
+
#isOf(kind: Kind): string {
|
|
1271
1453
|
const d = this.#domains.findIndex((x) => kindOfDomain(x) === kind);
|
|
1272
1454
|
const domain = this.#domains[d];
|
|
1273
1455
|
if (domain === undefined) throw new NotStandalone(`the schema has the kind ${kind}, and no domain has it`);
|
|
@@ -1276,7 +1458,7 @@ class Printer {
|
|
|
1276
1458
|
const src = copied(domain.is, [[...SAMPLES.number, ...SAMPLES.string, ...SAMPLES.boolean, null, {}, [], ...this.#samples(kind)]], `the test "is" of the domain ${domain.name}`);
|
|
1277
1459
|
this.top.set(name, `const ${name} = ${src};`);
|
|
1278
1460
|
}
|
|
1279
|
-
return
|
|
1461
|
+
return name;
|
|
1280
1462
|
}
|
|
1281
1463
|
|
|
1282
1464
|
/** This method gives a new name for the code. */
|
|
@@ -1351,7 +1533,8 @@ class Printer {
|
|
|
1351
1533
|
this.#keyOf.set(c, this.#constKey(e, ctx));
|
|
1352
1534
|
this.#constant.add(e);
|
|
1353
1535
|
}
|
|
1354
|
-
// A list is a value only at a place that takes a list
|
|
1536
|
+
// 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
|
|
1537
|
+
// function take one. A condition, an argument of and or of or, and a key of get take no list.
|
|
1355
1538
|
if (c.v.list !== undefined && !this.#wantList.has(e)) throw new NotStandalone("a list is a value of the program");
|
|
1356
1539
|
return this.#columnar(e, c, ctx) ? this.#column(e, c, ctx) : c;
|
|
1357
1540
|
}
|
|
@@ -1366,7 +1549,36 @@ class Printer {
|
|
|
1366
1549
|
|
|
1367
1550
|
/** This method tells if an expression gives a list at a place that takes one (`listy`). */
|
|
1368
1551
|
#isList(e: Expr, ctx: Ctx): boolean {
|
|
1369
|
-
|
|
1552
|
+
// A key of a node of the memo is a name of its function, and the name keeps the facts of a list.
|
|
1553
|
+
const key = ctx.keys.get(e);
|
|
1554
|
+
if (key !== undefined) return key.list !== undefined;
|
|
1555
|
+
return listy(e, this.#scopeOf(ctx));
|
|
1556
|
+
}
|
|
1557
|
+
|
|
1558
|
+
/**
|
|
1559
|
+
* This method tells if the body of an each can give a list. The facts of the names `as` of its items come from its
|
|
1560
|
+
* list, which the printer prints only in the loop. So here each such name can hold a list. Then a list op goes over the
|
|
1561
|
+
* array of the each, and that array gives the value of the interpreter too (COMPILE.MODULE.LIST.ITEM).
|
|
1562
|
+
*/
|
|
1563
|
+
#bodyList(e: ExprOf<"each">, ctx: Ctx): boolean {
|
|
1564
|
+
if (e.as === undefined) return this.#isList(e.body, ctx);
|
|
1565
|
+
// A list of the axis list is not in the memo, so the body is not a key of a node of the memo.
|
|
1566
|
+
const scope = this.#scopeOf(ctx);
|
|
1567
|
+
const names: readonly string[] = e.as;
|
|
1568
|
+
return listy(e.body, { ...scope, name: (name) => names.includes(name) || scope.name(name) });
|
|
1569
|
+
}
|
|
1570
|
+
|
|
1571
|
+
/** This method gives the scope of `listy` at a node: the names and the bound functions of its context. */
|
|
1572
|
+
#scopeOf(ctx: Ctx): ListScope {
|
|
1573
|
+
return {
|
|
1574
|
+
name: (name) => ctx.env.get(name)?.list !== undefined,
|
|
1575
|
+
fn: (name) => {
|
|
1576
|
+
const bound = ctx.fns.get(name);
|
|
1577
|
+
return bound === undefined ? undefined : { fn: bound.fn, scope: this.#scopeOf(bound.ctx) };
|
|
1578
|
+
},
|
|
1579
|
+
cell: (x) => this.#cellList(x) !== undefined,
|
|
1580
|
+
field: (x) => typeof this.#schema.fields?.[x.path.join(".")] === "object",
|
|
1581
|
+
};
|
|
1370
1582
|
}
|
|
1371
1583
|
|
|
1372
1584
|
/** 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 +1700,15 @@ class Printer {
|
|
|
1488
1700
|
return this.#call(e, ctx);
|
|
1489
1701
|
case "rec": {
|
|
1490
1702
|
const names = Object.keys(e.fields);
|
|
1491
|
-
const
|
|
1703
|
+
const exprs = Object.values(e.fields);
|
|
1704
|
+
// A field can hold a list (COMPILE.MODULE.LIST.FIELD).
|
|
1705
|
+
for (const x of exprs) this.#wantList.add(x);
|
|
1706
|
+
const raw = exprs.map((x) => this.expr(x, ctx));
|
|
1492
1707
|
const deps = depsOf(...raw);
|
|
1493
1708
|
// The interpreter evaluates each field, also after an error.
|
|
1494
|
-
const fields = this.#inOrder(this.#settle(raw, deps,
|
|
1709
|
+
const fields = this.#inOrder(this.#settle(raw, deps, exprs), true);
|
|
1495
1710
|
// 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
|
|
1711
|
+
const code = `({ ${fields.map((x, i) => `${names[i] === "__proto__" ? '["__proto__"]' : JSON.stringify(names[i])}: ${this.#plain(x.v)}`).join(", ")} })`;
|
|
1497
1712
|
return { s: stmtsOf(...fields), v: { code, kind: undefined, safe: fields.every((x) => x.v.safe), deps } };
|
|
1498
1713
|
}
|
|
1499
1714
|
case "app":
|
|
@@ -1633,6 +1848,8 @@ class Printer {
|
|
|
1633
1848
|
const [field, ...more] = e.path;
|
|
1634
1849
|
const kind = field === undefined ? undefined : this.#schema.fields?.[field];
|
|
1635
1850
|
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(".")}"`);
|
|
1851
|
+
// The check of the run keeps the array of each list of the input (COMPILE.MODULE.LIST.INPUT).
|
|
1852
|
+
const input = typeof kind === "object" ? this.#input(field) : undefined;
|
|
1636
1853
|
// A move to the origin cannot fail, and the schema has the field in each record.
|
|
1637
1854
|
const at = e.at ?? [];
|
|
1638
1855
|
const safe = at.every((m) => m.t === "origin");
|
|
@@ -1640,7 +1857,18 @@ class Printer {
|
|
|
1640
1857
|
const deps = this.#addressDeps(at, ctx, values);
|
|
1641
1858
|
// The interpreter evaluates the expressions of the address before its moves, and the first error stops them.
|
|
1642
1859
|
const parts = this.#inOrder(this.#settle(values, deps), false);
|
|
1643
|
-
|
|
1860
|
+
const address = this.#address(at, ctx, parts);
|
|
1861
|
+
if (typeof kind === "object") return { s: stmtsOf(...parts), v: { code: `${input as string}[${address}]`, kind: undefined, safe, deps, list: listOfKind(kind, true) } };
|
|
1862
|
+
return { s: stmtsOf(...parts), v: { code: `R[${address}][${JSON.stringify(field)}]`, kind, safe, deps } };
|
|
1863
|
+
}
|
|
1864
|
+
|
|
1865
|
+
/** This method gives the name of the array of the lists of a field of the input. */
|
|
1866
|
+
#input(field: string): string {
|
|
1867
|
+
const known = this.inputs.get(field);
|
|
1868
|
+
if (known !== undefined) return known;
|
|
1869
|
+
const name = this.fresh("LF");
|
|
1870
|
+
this.inputs.set(field, name);
|
|
1871
|
+
return name;
|
|
1644
1872
|
}
|
|
1645
1873
|
|
|
1646
1874
|
/** This method gives the code of the expressions of the computed moves of an address. They evaluate at the node. */
|
|
@@ -1744,27 +1972,31 @@ class Printer {
|
|
|
1744
1972
|
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
1973
|
const s: string[] = [];
|
|
1746
1974
|
const args = e.args.map((x): Arg => {
|
|
1975
|
+
// An argument can be a list, as a binding of a let can (COMPILE.MODULE.LIST.ARG).
|
|
1976
|
+
this.#wantList.add(x);
|
|
1747
1977
|
const c = this.#hoist(this.expr(x, ctx), hasLoop(x));
|
|
1978
|
+
const { kind, deps, list } = c.v;
|
|
1748
1979
|
// A value that cannot throw is the argument itself. A read of a name that can hold the error passes the name.
|
|
1749
1980
|
if (c.v.safe) {
|
|
1750
1981
|
s.push(...c.s);
|
|
1751
|
-
return { code: c.v.code, kind
|
|
1982
|
+
return { code: c.v.code, kind, deps, list };
|
|
1752
1983
|
}
|
|
1753
1984
|
// 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
|
|
1985
|
+
if (c.s.length === 0 && c.v.held !== undefined) return { code: c.v.held, kind, deps, list };
|
|
1755
1986
|
const b = this.fresh("b");
|
|
1756
1987
|
s.push(...this.#store(b, c));
|
|
1757
|
-
return { code: b, kind
|
|
1988
|
+
return { code: b, kind, deps, list };
|
|
1758
1989
|
});
|
|
1759
|
-
// Each parameter can hold the error of its argument, so one function serves the arguments of one kind.
|
|
1760
|
-
|
|
1990
|
+
// Each parameter can hold the error of its argument, so one function serves the arguments of one kind. The facts of
|
|
1991
|
+
// a list are a part of its kind.
|
|
1992
|
+
const sig = JSON.stringify(args.map((a) => (a.list === undefined ? (a.kind ?? null) : { list: a.list })));
|
|
1761
1993
|
const spec = bound.specs.get(sig) ?? this.#printFn(bound, args, sig);
|
|
1762
1994
|
// Each marker becomes the levels at the call. The levels of the arguments count for each call, because their
|
|
1763
1995
|
// statements read their keys, so the marker of the parameters gives no level.
|
|
1764
1996
|
const levels = (d: number): readonly number[] => (d === spec.origin ? [ctx.originLevel] : d === spec.focus ? [ctx.level] : d === spec.param ? [] : [d]);
|
|
1765
1997
|
const deps = new Set([...args.flatMap((a) => [...a.deps]), ...[...spec.deps].flatMap(levels)]);
|
|
1766
1998
|
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 } };
|
|
1999
|
+
return { s, v: { code: `${spec.name}(${[...args.map((a) => a.code), ...position].join(", ")})`, kind: spec.kind, safe: spec.safe, deps, list: spec.list } };
|
|
1768
2000
|
}
|
|
1769
2001
|
|
|
1770
2002
|
/**
|
|
@@ -1784,9 +2016,12 @@ class Printer {
|
|
|
1784
2016
|
const o = this.fresh("o");
|
|
1785
2017
|
const env = new Map(bound.ctx.env);
|
|
1786
2018
|
// 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]) }));
|
|
2019
|
+
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
2020
|
const scope: CallScope = { param, focus, repeats: nestsLoops(bound.fn.body), names: new Set(names), decls: [], root: bound.fn.body };
|
|
1789
2021
|
this.#scopes.push(scope);
|
|
2022
|
+
// 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
|
|
2023
|
+
// that takes a list, or it gives the reason.
|
|
2024
|
+
this.#wantList.add(bound.fn.body);
|
|
1790
2025
|
const body = this.expr(bound.fn.body, { origin: o, focus: k, level: focus, originLevel: origin, env, fns: bound.ctx.fns, keys: new Map() });
|
|
1791
2026
|
this.#scopes.pop();
|
|
1792
2027
|
const markers = new Set([origin, focus, param]);
|
|
@@ -1800,7 +2035,7 @@ class Printer {
|
|
|
1800
2035
|
const decl = s.length === 0 ? [`${head} ${body.v.code};`] : [`${head} {`, ...ind(s), ` return ${body.v.code};`, "};"];
|
|
1801
2036
|
(global ? this.run : bound.decls).push(...decl);
|
|
1802
2037
|
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 };
|
|
2038
|
+
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
2039
|
bound.specs.set(sig, spec);
|
|
1805
2040
|
return spec;
|
|
1806
2041
|
}
|
|
@@ -1824,24 +2059,57 @@ class Printer {
|
|
|
1824
2059
|
const [head] = args;
|
|
1825
2060
|
const rest = args.slice(1);
|
|
1826
2061
|
// An each whose body is a list gives a list of lists (LIST.FLAT), so a list op over it goes over its array.
|
|
1827
|
-
if (FOLD_OPS.has(op) && head?.tag === "each" && !this.#
|
|
2062
|
+
if (FOLD_OPS.has(op) && head?.tag === "each" && !this.#bodyList(head, ctx)) return this.#list(op, head, rest, ctx);
|
|
1828
2063
|
// A list op over a let with only literal options is the list op over the body of the let, so an each in the body
|
|
1829
2064
|
// is one loop with a running value, not an array. A builder sheet prints such a let, for example `sum(let($0 = 0, each(…)))`.
|
|
1830
2065
|
if (FOLD_OPS.has(op) && head?.tag === "let" && rest.every((x) => x.tag === "lit")) return this.#let(head, ctx, (body) => app(op, body, ...rest));
|
|
1831
2066
|
// sortBy and take are list ops for each receiver. Each other list op needs a list, and a domain can have its name.
|
|
1832
2067
|
if (head !== undefined && (op === "sortBy" || op === "take" || (op === "drop" && this.#isList(head, ctx)))) return this.#order(op, head, rest, ctx);
|
|
1833
|
-
if (head !== undefined && BUILD_OPS.has(op) && this.#isList(head, ctx)) return this.#build(op, head, rest, ctx);
|
|
2068
|
+
if (head !== undefined && BUILD_OPS.has(op) && this.#isList(head, ctx)) return this.#build(op, head, rest, ctx, this.#own.get(e));
|
|
1834
2069
|
if (head !== undefined && (FOLD_OPS.has(op) || op === "nth") && this.#isList(head, ctx)) return this.#overList(op, head, rest, ctx);
|
|
2070
|
+
// An argument can be a list (COMPILE.MODULE.LIST.ARG).
|
|
2071
|
+
for (const x of args) this.#wantList.add(x);
|
|
1835
2072
|
const raw = args.map((x) => this.expr(x, ctx));
|
|
1836
2073
|
const deps = depsOf(...raw);
|
|
1837
2074
|
// The interpreter evaluates each argument, also after an error.
|
|
1838
2075
|
const values = this.#inOrder(this.#settle(raw, deps, args), true);
|
|
2076
|
+
if (op === "fill" && this.#facts.own(op)) return this.#fill(values, deps);
|
|
1839
2077
|
return this.#opCall(op, values, deps);
|
|
1840
2078
|
}
|
|
1841
2079
|
|
|
2080
|
+
/**
|
|
2081
|
+
* This method prints `fill(n, value)` without a domain with the op (LIST.FILL, COMPILE.MODULE.FILL). The helper `FI`
|
|
2082
|
+
* gets each value, so an error of an argument after the value is the error of the op. The keys are not the positions
|
|
2083
|
+
* of records, so the axis `list` over the list cannot read a record at its keys.
|
|
2084
|
+
*/
|
|
2085
|
+
#fill(values: readonly Code[], deps: ReadonlySet<number>): Code {
|
|
2086
|
+
const value = values[1]?.v;
|
|
2087
|
+
const list: ListInfo = { item: value?.kind, inner: value?.list, texts: true };
|
|
2088
|
+
return { s: stmtsOf(...values), v: { code: `${this.use("FI")}(${values.map((x) => x.v.code).join(", ")})`, kind: undefined, safe: false, deps, list } };
|
|
2089
|
+
}
|
|
2090
|
+
|
|
2091
|
+
/**
|
|
2092
|
+
* This method gives the code of a value outside the list ops: a list is a `vex.list`, as in the interpreter
|
|
2093
|
+
* (COMPILE.MODULE.LIST.ARG, COMPILE.MODULE.LIST.FIELD). An error item has the error `VEX_ERROR`.
|
|
2094
|
+
*/
|
|
2095
|
+
#plain(v: Value): string {
|
|
2096
|
+
return v.list === undefined ? v.code : `${this.use("LV")}(${v.code}, ${String(depthOf(v.list))})`;
|
|
2097
|
+
}
|
|
2098
|
+
|
|
2099
|
+
/** This method gives the samples of a list of the facts `l`: no items, items with values, and an error item. */
|
|
2100
|
+
#listSamples(l: ListInfo): readonly unknown[] {
|
|
2101
|
+
const values = l.inner !== undefined ? [vexList([])] : l.item === undefined ? SAMPLES.number : this.#samples(l.item);
|
|
2102
|
+
const items = values.map((value, i) => ({ key: String(i), result: { ok: true as const, value } }));
|
|
2103
|
+
// An error item of a module has the error VEX_ERROR, which is not an error value of the interpreter.
|
|
2104
|
+
return [vexList([]), vexList(items), vexList([{ key: "0", result: { ok: false, error: { vexError: true } as never } }])];
|
|
2105
|
+
}
|
|
2106
|
+
|
|
1842
2107
|
/** This method prints the call of the op of a domain on some values, from the static site of their kinds. */
|
|
1843
2108
|
#opCall(op: string, values: readonly Code[], deps: ReadonlySet<number>): Code {
|
|
1844
|
-
const
|
|
2109
|
+
const lists = new Set(values.flatMap((x, i) => (x.v.list === undefined ? [] : [i])));
|
|
2110
|
+
// 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.
|
|
2111
|
+
if (lists.has(0)) throw new NotStandalone(isListOp(op) ? `the list op "${op}"` : `a list as the receiver of the op "${op}"`);
|
|
2112
|
+
const site = this.#facts.staticSite(op, values.map((x) => x.v.kind), lists);
|
|
1845
2113
|
if (site?.t !== "fn") throw new NotStandalone(`the kinds of the values of "${op}" do not decide its op`);
|
|
1846
2114
|
if (site.bad) return { s: stmtsOf(...values), v: { code: `${this.use("F")}()`, kind: site.returns, safe: false, deps } };
|
|
1847
2115
|
if (site.returns === undefined) throw new NotStandalone(`the op "${op}" does not declare the kind of its result`);
|
|
@@ -1852,14 +2120,15 @@ class Printer {
|
|
|
1852
2120
|
// A static site of a domain has the function of the op of that domain.
|
|
1853
2121
|
const fn = (d.ops[op] as { fn: (...a: never[]) => unknown }).fn;
|
|
1854
2122
|
const kinds = values.map((x) => x.v.kind).filter((k): k is Kind => k !== undefined);
|
|
1855
|
-
const
|
|
2123
|
+
const each = values.flatMap((x) => (x.v.list !== undefined ? [this.#listSamples(x.v.list)] : x.v.kind === undefined ? [] : [this.#samples(x.v.kind)]));
|
|
2124
|
+
const src = copied(fn, each, `the op "${op}" of the domain ${d.name}`);
|
|
1856
2125
|
// An inline form cannot throw for primitive values only.
|
|
1857
|
-
this.#forms.set(name, kinds.every((k) => primitiveOf(k) !== undefined) ? inlineForm(src) : undefined);
|
|
2126
|
+
this.#forms.set(name, lists.size === 0 && kinds.every((k) => primitiveOf(k) !== undefined) ? inlineForm(src) : undefined);
|
|
1858
2127
|
this.top.set(name, `const ${name} = ${src};`);
|
|
1859
2128
|
}
|
|
1860
2129
|
const form = this.#forms.get(name);
|
|
1861
2130
|
// 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));
|
|
2131
|
+
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
2132
|
if (inline) {
|
|
1864
2133
|
const text = form.parts.map((x) => (typeof x === "number" ? `(${(values[x] as Code).v.code})` : x)).join("");
|
|
1865
2134
|
const checked = this.check(site.returns);
|
|
@@ -1868,7 +2137,7 @@ class Printer {
|
|
|
1868
2137
|
}
|
|
1869
2138
|
this.#called.add(name);
|
|
1870
2139
|
// 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
|
|
2140
|
+
const code = this.#checked(site.returns, `${name}(${values.map((x) => this.#plain(x.v)).join(", ")})`);
|
|
1872
2141
|
return { s: stmtsOf(...values), v: { code, kind: site.returns, safe: false, deps } };
|
|
1873
2142
|
}
|
|
1874
2143
|
|
|
@@ -1956,9 +2225,10 @@ class Printer {
|
|
|
1956
2225
|
/**
|
|
1957
2226
|
* This method gives the loop over the targets of an axis: the statements before it, its bounds and the key that it
|
|
1958
2227
|
* skips. `start` has the levels of the address, and `inner` is the position at a target. The axes all, others,
|
|
1959
|
-
* window and list have a loop. In a tree space, the axes of a tree have a loop too.
|
|
2228
|
+
* window and list have a loop. In a tree space, the axes of a tree have a loop too. With `as`, a loop over the axis
|
|
2229
|
+
* list binds the value and the index of each item after its check (COMPILE.MODULE.LIST.ITEM).
|
|
1960
2230
|
*/
|
|
1961
|
-
#targetLoop(axis: Axis, at: readonly Move[], ctx: Ctx): {
|
|
2231
|
+
#targetLoop(axis: Axis, at: readonly Move[], ctx: Ctx, as?: ItemNames): {
|
|
1962
2232
|
readonly s: string[];
|
|
1963
2233
|
readonly j: string;
|
|
1964
2234
|
/** The head of the loop, and the statements at the start of each item before the try and inside it. */
|
|
@@ -1972,6 +2242,11 @@ class Printer {
|
|
|
1972
2242
|
readonly startSafe: boolean;
|
|
1973
2243
|
readonly tests: readonly Expr[];
|
|
1974
2244
|
readonly inner: Ctx;
|
|
2245
|
+
/** True when a target can be a key that is not the position of a record: a key of a literal or of `fill`. */
|
|
2246
|
+
readonly texts: boolean;
|
|
2247
|
+
/** The names `as` of the items, and their level. Only the body of an each and the steps of a fold read them. */
|
|
2248
|
+
readonly items: ReadonlyMap<string, Name>;
|
|
2249
|
+
readonly item: number | undefined;
|
|
1975
2250
|
} {
|
|
1976
2251
|
const { base: outer, tests } = testsOf(axis);
|
|
1977
2252
|
// The reverse order of an axis is a loop from its end (AXIS.REVERSE). The validation keeps a base axis inside.
|
|
@@ -1984,14 +2259,20 @@ class Printer {
|
|
|
1984
2259
|
if (base.t === "list") {
|
|
1985
2260
|
if (at.length > 0) throw new NotStandalone('the axis "list" with an address');
|
|
1986
2261
|
const list = this.#hoist(this.#listOf(base.list, ctx), hasLoop(base.list));
|
|
1987
|
-
//
|
|
1988
|
-
|
|
2262
|
+
// 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.
|
|
2263
|
+
const texts = (list.v.list as ListInfo).texts === true;
|
|
1989
2264
|
const a = this.fresh("A");
|
|
1990
2265
|
const q = this.fresh("q");
|
|
1991
2266
|
const head = reverse ? `for (let ${q} = ${a}.length - 1; ${q} >= 0; ${q}--) {` : `for (let ${q} = 0; ${q} < ${a}.length; ${q}++) {`;
|
|
1992
2267
|
const key = [`const ${j} = ${a}[${q}][0];`];
|
|
1993
2268
|
const check = [`if (${a}[${q}][1] === E) ${this.use("F")}();`];
|
|
1994
|
-
|
|
2269
|
+
const s = [...list.s, `const ${a} = ${list.v.code};`];
|
|
2270
|
+
const named = as === undefined ? undefined : this.#itemNames(as, list.v.list as ListInfo, `${a}[${q}][1]`, a, reverse);
|
|
2271
|
+
if (named !== undefined) {
|
|
2272
|
+
s.push(...named.s);
|
|
2273
|
+
check.push(...named.check);
|
|
2274
|
+
}
|
|
2275
|
+
return { s, j, head, key, check, skip: undefined, fixed: false, start: list.v.deps, startSafe: list.v.safe, tests, inner, texts, items: named?.items ?? NO_NAMES, item: named?.level };
|
|
1995
2276
|
}
|
|
1996
2277
|
const s: string[] = [];
|
|
1997
2278
|
let lo = "0";
|
|
@@ -2013,13 +2294,13 @@ class Printer {
|
|
|
2013
2294
|
if (this.#tree && isTreeAxis(base)) {
|
|
2014
2295
|
const range = this.#treeRange(base, f as string);
|
|
2015
2296
|
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 };
|
|
2297
|
+
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, items: NO_NAMES, item: undefined };
|
|
2017
2298
|
}
|
|
2018
2299
|
// 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
2300
|
if (this.#graph && GRAPH_AXES.has(base.t)) {
|
|
2020
2301
|
const range = this.#graphRange(base.t, f as string);
|
|
2021
2302
|
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 };
|
|
2303
|
+
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, items: NO_NAMES, item: undefined };
|
|
2023
2304
|
}
|
|
2024
2305
|
if (this.#graph && base.t === "window") throw new NotStandalone('the axis "window" in a graph space');
|
|
2025
2306
|
if (base.t === "others") skip = f;
|
|
@@ -2029,7 +2310,42 @@ class Printer {
|
|
|
2029
2310
|
s.push(`const ${h} = Math.min(n, ${f as string} + Math.min(${base.to}, n) + 1);`);
|
|
2030
2311
|
hi = h;
|
|
2031
2312
|
} 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 };
|
|
2313
|
+
return { s, j, head: forHead(j, lo, hi, reverse), key: [], check: [], skip, fixed: f === undefined, start, startSafe, tests, inner, texts: false, items: NO_NAMES, item: undefined };
|
|
2314
|
+
}
|
|
2315
|
+
|
|
2316
|
+
/**
|
|
2317
|
+
* This method binds the names `as` of a loop over the axis list (COMPILE.MODULE.LIST.ITEM). The statements come after
|
|
2318
|
+
* the check of the item, so an error item fails before they bind a name (AXIS.LIST.ITEM). The first name holds the
|
|
2319
|
+
* value of the item, with the facts of its list. The index counts the items with a value in the order of the list, as
|
|
2320
|
+
* `nth` does (AXIS.LIST.INDEX). In the reverse order, it counts down from the number of these items. The names have a
|
|
2321
|
+
* level of their own. Thus a part that reads them stays in the loop, and a key of a literal can still be a target.
|
|
2322
|
+
*/
|
|
2323
|
+
#itemNames(as: ItemNames, info: ListInfo, value: string, a: string, reverse: boolean): { readonly s: readonly string[]; readonly check: readonly string[]; readonly items: ReadonlyMap<string, Name>; readonly level: number } {
|
|
2324
|
+
// Stryker disable next-line UpdateOperator: a level of a loop is a name, so a count down gives other names, and the same code
|
|
2325
|
+
const level = this.#loops++;
|
|
2326
|
+
const deps = new Set([level]);
|
|
2327
|
+
const [item, index] = as;
|
|
2328
|
+
const y = this.fresh("y");
|
|
2329
|
+
const items = new Map<string, Name>([[item, { code: y, kind: info.item, lazy: false, deps, list: info.inner }]]);
|
|
2330
|
+
const check = [`const ${y} = ${value};`];
|
|
2331
|
+
const s: string[] = [];
|
|
2332
|
+
if (index !== undefined) {
|
|
2333
|
+
const i = this.fresh("i");
|
|
2334
|
+
const z = this.fresh("z");
|
|
2335
|
+
// The check before the index throws for an error item, so the count skips it.
|
|
2336
|
+
s.push(`let ${z} = ${reverse ? `${this.use("CT")}(${a}, false)` : "0"};`);
|
|
2337
|
+
check.push(`const ${i} = ${reverse ? `--${z}` : `${z}++`};`);
|
|
2338
|
+
items.set(index, { code: i, kind: "number", lazy: false, deps });
|
|
2339
|
+
}
|
|
2340
|
+
return { s, check, items, level };
|
|
2341
|
+
}
|
|
2342
|
+
|
|
2343
|
+
/**
|
|
2344
|
+
* 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
|
|
2345
|
+
* interpreter reads the record of such a key, and a module has no record for it.
|
|
2346
|
+
*/
|
|
2347
|
+
#readsNoTarget(texts: boolean, level: number, deps: readonly ReadonlySet<number>[]): void {
|
|
2348
|
+
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
2349
|
}
|
|
2034
2350
|
|
|
2035
2351
|
/**
|
|
@@ -2087,16 +2403,18 @@ class Printer {
|
|
|
2087
2403
|
#list(op: string, target: ExprOf<"each">, rest: readonly Expr[], ctx: Ctx): Code {
|
|
2088
2404
|
const { strict, step } = this.#foldOptions(op, rest);
|
|
2089
2405
|
const at = target.at ?? [];
|
|
2090
|
-
const { s, j, head, key, check, skip, fixed, start, startSafe, tests, inner } = this.#targetLoop(target.axis, at, ctx);
|
|
2406
|
+
const { s, j, head, key, check, skip, fixed, start, startSafe, tests, inner, texts, items, item: own } = this.#targetLoop(target.axis, at, ctx, target.as);
|
|
2091
2407
|
const { level } = inner;
|
|
2092
|
-
// Inside the loop, a constant of the run evaluates once, before the loop over the keys of the run.
|
|
2408
|
+
// Inside the loop, a constant of the run evaluates once, before the loop over the keys of the run. The tests do not
|
|
2409
|
+
// see the names of the items, and the body sees them (AXIS.LIST.SCOPE).
|
|
2093
2410
|
const testCodes = tests.map((t) => this.#hoist(this.expr(t, inner), hasLoop(t)));
|
|
2094
|
-
const body = this.#hoist(this.expr(target.body, inner), hasLoop(target.body));
|
|
2411
|
+
const body = this.#hoist(this.expr(target.body, { ...inner, env: withNames(inner.env, items) }), hasLoop(target.body));
|
|
2412
|
+
this.#readsNoTarget(texts, level, [body, ...testCodes].map((x) => x.v.deps));
|
|
2095
2413
|
// A count of all the items, whose body cannot fail, is the count of the records. A safe body covers its statements.
|
|
2096
2414
|
// 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
2415
|
// itself gives `#CYCLE!`.
|
|
2098
2416
|
if (op === "count" && fixed && tests.length === 0 && body.v.safe && !body.v.deps.has(CELLS)) return bare(plainValue("n", "number"));
|
|
2099
|
-
const deps = new Set([...start, ...[body, ...testCodes].flatMap((x) => [...x.v.deps])].filter((d) => d !== level));
|
|
2417
|
+
const deps = new Set([...start, ...[body, ...testCodes].flatMap((x) => [...x.v.deps])].filter((d) => d !== level && d !== own));
|
|
2100
2418
|
const r = this.#reduction(op, body.v.kind, step);
|
|
2101
2419
|
const { v } = r;
|
|
2102
2420
|
s.push(r.init);
|
|
@@ -2208,12 +2526,14 @@ class Printer {
|
|
|
2208
2526
|
*/
|
|
2209
2527
|
#eachList(e: ExprOf<"each">, ctx: Ctx): Code {
|
|
2210
2528
|
const at = e.at ?? [];
|
|
2211
|
-
const { s, j, head, key, check, skip, start, startSafe, tests, inner } = this.#targetLoop(e.axis, at, ctx);
|
|
2529
|
+
const { s, j, head, key, check, skip, start, startSafe, tests, inner, texts, items, item: own } = this.#targetLoop(e.axis, at, ctx, e.as);
|
|
2212
2530
|
const testCodes = tests.map((t) => this.#hoist(this.expr(t, inner), hasLoop(t)));
|
|
2213
2531
|
// The value of an item can be a list, for flat (LIST.FLAT). The facts of the list tell it.
|
|
2214
2532
|
if (this.#wantList.has(e)) this.#wantList.add(e.body);
|
|
2215
|
-
|
|
2216
|
-
const
|
|
2533
|
+
// Only the body sees the names of the items (AXIS.LIST.SCOPE).
|
|
2534
|
+
const body = this.#hoist(this.expr(e.body, { ...inner, env: withNames(inner.env, items) }), hasLoop(e.body));
|
|
2535
|
+
this.#readsNoTarget(texts, inner.level, [body, ...testCodes].map((x) => x.v.deps));
|
|
2536
|
+
const deps = new Set([...start, ...[body, ...testCodes].flatMap((x) => [...x.v.deps])].filter((d) => d !== inner.level && d !== own));
|
|
2217
2537
|
const list = this.fresh("L");
|
|
2218
2538
|
const v = this.fresh("x");
|
|
2219
2539
|
const item = [...check, ...testCodes.flatMap((t) => [...t.s, `if (!${this.#boolean(t.v)}) continue;`]), ...body.s];
|
|
@@ -2223,7 +2543,7 @@ class Printer {
|
|
|
2223
2543
|
...(skip === undefined ? [] : [`if (${j} === ${skip}) continue;`]),
|
|
2224
2544
|
...(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
2545
|
];
|
|
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 } } };
|
|
2546
|
+
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
2547
|
}
|
|
2228
2548
|
|
|
2229
2549
|
/**
|
|
@@ -2234,20 +2554,39 @@ class Printer {
|
|
|
2234
2554
|
const list = this.#listOf(head, ctx);
|
|
2235
2555
|
// A missing count is the literal null, which is not a whole number, so take and drop give their error.
|
|
2236
2556
|
const exprs = [head, ...(op === "sortBy" ? [] : [rest[0] ?? lit(null)])];
|
|
2237
|
-
const
|
|
2557
|
+
const options = rest.slice(exprs.length - 1);
|
|
2558
|
+
const strict = this.#strict(op, options, op === "sortBy" ? ["strict", "by"] : ["strict"]);
|
|
2559
|
+
const by = op === "sortBy" ? this.#sortValue(options, list.v.list as ListInfo) : undefined;
|
|
2238
2560
|
const raw = [list, ...exprs.slice(1).map((x) => this.expr(x, ctx))];
|
|
2239
2561
|
const deps = depsOf(...raw);
|
|
2240
2562
|
const parts = this.#inOrder(this.#settle(raw, deps, exprs), true);
|
|
2241
|
-
const helper = op === "sortBy" ? "SB" : op === "take" ? "TK" : "DR";
|
|
2563
|
+
const helper = by !== undefined ? "SK" : op === "sortBy" ? "SB" : op === "take" ? "TK" : "DR";
|
|
2564
|
+
const args = [...parts.map((x) => x.v.code), String(strict), ...(by === undefined ? [] : [by])];
|
|
2242
2565
|
// 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)}(${
|
|
2566
|
+
return { s: stmtsOf(...parts), v: { code: `${this.use(helper)}(${args.join(", ")})`, kind: undefined, safe: false, deps, list: list.v.list } };
|
|
2567
|
+
}
|
|
2568
|
+
|
|
2569
|
+
/**
|
|
2570
|
+
* This method gives the function of the option `by` of `sortBy` (COMPILE.MODULE.SORT.BY), or undefined without the
|
|
2571
|
+
* option. The function applies the op of the static site of the kind of the items. An empty list applies no op.
|
|
2572
|
+
*/
|
|
2573
|
+
#sortValue(options: readonly Expr[], info: ListInfo): string | undefined {
|
|
2574
|
+
const by = (options[0] as { readonly value?: { readonly by?: unknown } } | undefined)?.value?.by;
|
|
2575
|
+
if (by === undefined) return undefined;
|
|
2576
|
+
if (typeof by !== "string") throw new NotStandalone('the option "by" of "sortBy" is not a literal text');
|
|
2577
|
+
if (info.empty === true) return undefined;
|
|
2578
|
+
if (info.item === undefined) throw new NotStandalone(`the kinds of the items of "sortBy" do not decide the op "${by}" of the option by`);
|
|
2579
|
+
const x = this.fresh("x");
|
|
2580
|
+
const value = this.#opCall(by, [bare({ code: x, kind: info.item, safe: true, deps: NO_DEPS, plain: true })], NO_DEPS);
|
|
2581
|
+
return `((${x}) => ${value.v.code})`;
|
|
2244
2582
|
}
|
|
2245
2583
|
|
|
2246
2584
|
/**
|
|
2247
2585
|
* This method prints append, without and flat (LIST.BUILD), get (LIST.GET) and indexOf (LIST.INDEXOF) over the array
|
|
2248
|
-
* of a list. Each list that the op reads follows LIST.LENIENT, as in the interpreter.
|
|
2586
|
+
* of a list. Each list that the op reads follows LIST.LENIENT, as in the interpreter. An append with an owner appends
|
|
2587
|
+
* into the array of its name, if the name in the context is the name of the loop (COMPILE.MODULE.APPEND.OWN).
|
|
2249
2588
|
*/
|
|
2250
|
-
#build(op: string, head: Expr, rest: readonly Expr[], ctx: Ctx): Code {
|
|
2589
|
+
#build(op: string, head: Expr, rest: readonly Expr[], ctx: Ctx, owner: Owner | undefined): Code {
|
|
2251
2590
|
const list = this.#listOf(head, ctx);
|
|
2252
2591
|
const info = list.v.list as ListInfo;
|
|
2253
2592
|
const two = op === "append" || op === "without";
|
|
@@ -2259,10 +2598,11 @@ class Printer {
|
|
|
2259
2598
|
const deps = depsOf(...raw);
|
|
2260
2599
|
const parts = this.#inOrder(this.#settle(raw, deps, exprs), true);
|
|
2261
2600
|
const helper = BUILD_HELPERS[op] as BuildHelper;
|
|
2262
|
-
const
|
|
2263
|
-
|
|
2264
|
-
|
|
2265
|
-
})
|
|
2601
|
+
const args = [...parts.map((x) => x.v.code), String(strict)];
|
|
2602
|
+
// A function of the program can share a node with the step, but its body has its own names (FN.BIND).
|
|
2603
|
+
const w = owner !== undefined && ctx.env.get(owner.name) === owner.read ? (owner.w ??= this.fresh("w")) : undefined;
|
|
2604
|
+
const code = w === undefined ? `${this.use(helper)}(${args.join(", ")})` : `(${w} = ${this.use("AO")}(${[...args, w].join(", ")}))`;
|
|
2605
|
+
const value = (kind: Kind | undefined, facts: ListInfo | undefined): Code => ({ s: stmtsOf(...parts), v: { code, kind, safe: false, deps, list: facts } });
|
|
2266
2606
|
if (op === "get") return value(info.item, info.inner);
|
|
2267
2607
|
if (op === "indexOf") return value("number", undefined);
|
|
2268
2608
|
if (op === "without") return value(undefined, info);
|
|
@@ -2286,6 +2626,10 @@ class Printer {
|
|
|
2286
2626
|
const { item, inner } = list.v.list as ListInfo;
|
|
2287
2627
|
// The value of an item of a list of lists is a list, so nth and first give a list (LIST.FLAT).
|
|
2288
2628
|
if (op === "nth") return { s: stmtsOf(...parts), v: { code: `${this.use("NT")}(${[...parts.map((x) => x.v.code), String(strict)].join(", ")})`, kind: item, safe: false, deps, list: inner } };
|
|
2629
|
+
// count and first read the items with values on the array of the list, as nth does (COMPILE.MODULE.NTH.INDEX). Thus
|
|
2630
|
+
// a step of a loop that counts a list of n items costs O(1) after the first count.
|
|
2631
|
+
if (op === "count") return { s: l.s, v: { code: `${this.use("CT")}(${l.v.code}, ${String(strict)})`, kind: "number", safe: false, deps, list: undefined } };
|
|
2632
|
+
if (op === "first") return { s: l.s, v: { code: `${this.use("FS")}(${l.v.code}, ${String(strict)})`, kind: item, safe: false, deps, list: inner } };
|
|
2289
2633
|
const r = this.#reduction(op, item, step);
|
|
2290
2634
|
const { v } = r;
|
|
2291
2635
|
const s = [...l.s, r.init, `for (const [, ${v}] of ${l.v.code}) {`, ` if (${v} === E) ${strict ? `${this.use("F")}();` : "continue;"}`, ` ${r.step}`, "}"];
|
|
@@ -2302,8 +2646,8 @@ class Printer {
|
|
|
2302
2646
|
const env = new Map(ctx.env);
|
|
2303
2647
|
const vars = new Map<string, Name>();
|
|
2304
2648
|
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(
|
|
2649
|
+
// A step with a list literal or fill can give a name the keys of the literal or of fill (LOOP.LIST).
|
|
2650
|
+
const keyed = Object.values(step).some(hasTextKeys);
|
|
2307
2651
|
for (const [name, x] of Object.entries(init)) {
|
|
2308
2652
|
// 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
2653
|
this.#wantList.add(x);
|
|
@@ -2321,8 +2665,35 @@ class Printer {
|
|
|
2321
2665
|
return { s, env, vars, deps };
|
|
2322
2666
|
}
|
|
2323
2667
|
|
|
2324
|
-
/**
|
|
2325
|
-
|
|
2668
|
+
/**
|
|
2669
|
+
* This method gives the statements of one step of a loop: each new value first, and then each name gets its value.
|
|
2670
|
+
* `init` has the statements before the loop: the variable of each name that appends to its own list
|
|
2671
|
+
* (COMPILE.MODULE.APPEND.OWN). Each such name has the form of `ownForm`, and no step of another name and no `until`
|
|
2672
|
+
* reads it. The tests of a fold read only the names outside the fold, so they cannot read it.
|
|
2673
|
+
*/
|
|
2674
|
+
#loopStep(step: Names, inner: Ctx, vars: ReadonlyMap<string, Name>, until?: Expr): { readonly s: string[]; readonly deps: ReadonlySet<number>; readonly init: readonly string[] } {
|
|
2675
|
+
const owners: Owner[] = [];
|
|
2676
|
+
const nodes: Expr[] = [];
|
|
2677
|
+
const steps = Object.entries(step);
|
|
2678
|
+
for (const [name, x] of steps) {
|
|
2679
|
+
const own: Expr[] = [];
|
|
2680
|
+
const others = [...steps.filter(([k]) => k !== name).map(([, y]) => y), ...(until === undefined ? [] : [until])];
|
|
2681
|
+
if (!ownForm(x, name, own) || others.some((y) => namesOf(y).has(name))) continue;
|
|
2682
|
+
const owner: Owner = { name, read: vars.get(name) as Name, w: undefined };
|
|
2683
|
+
for (const node of own) this.#own.set(node, owner);
|
|
2684
|
+
owners.push(owner);
|
|
2685
|
+
nodes.push(...own);
|
|
2686
|
+
}
|
|
2687
|
+
try {
|
|
2688
|
+
const { s, deps } = this.#steps(step, inner, vars);
|
|
2689
|
+
return { s, deps, init: owners.flatMap((o) => (o.w === undefined ? [] : [`let ${o.w} = null;`])) };
|
|
2690
|
+
} finally {
|
|
2691
|
+
for (const node of nodes) this.#own.delete(node);
|
|
2692
|
+
}
|
|
2693
|
+
}
|
|
2694
|
+
|
|
2695
|
+
/** This method gives the statements of one step of a loop, without the variables of COMPILE.MODULE.APPEND.OWN. */
|
|
2696
|
+
#steps(step: Names, inner: Ctx, vars: ReadonlyMap<string, Name>): { readonly s: string[]; readonly deps: ReadonlySet<number> } {
|
|
2326
2697
|
const s: string[] = [];
|
|
2327
2698
|
const sets: string[] = [];
|
|
2328
2699
|
const deps = new Set<number>();
|
|
@@ -2352,7 +2723,7 @@ class Printer {
|
|
|
2352
2723
|
// A loop at a place that takes a list gives its result there (LOOP.LIST).
|
|
2353
2724
|
if (this.#wantList.has(e)) this.#wantList.add(e.result);
|
|
2354
2725
|
const until = e.until === undefined ? undefined : this.expr(e.until, inner);
|
|
2355
|
-
const step = this.#loopStep(e.step, inner, names.vars);
|
|
2726
|
+
const step = this.#loopStep(e.step, inner, names.vars, e.until);
|
|
2356
2727
|
const result = this.expr(e.result, inner);
|
|
2357
2728
|
const k = this.fresh("k");
|
|
2358
2729
|
const body = [
|
|
@@ -2362,7 +2733,7 @@ class Printer {
|
|
|
2362
2733
|
];
|
|
2363
2734
|
const inside = [...(until?.v.deps ?? []), ...step.deps, ...result.v.deps].filter((d) => d !== loop);
|
|
2364
2735
|
const deps = new Set([...names.deps, ...inside]);
|
|
2365
|
-
return { s: [...names.s, `for (let ${k} = 0; ; ${k}++) {`, ...ind(body), "}", ...result.s], v: { code: result.v.code, kind: result.v.kind, safe: false, deps, list: result.v.list } };
|
|
2736
|
+
return { s: [...names.s, ...step.init, `for (let ${k} = 0; ; ${k}++) {`, ...ind(body), "}", ...result.s], v: { code: result.v.code, kind: result.v.kind, safe: false, deps, list: result.v.list } };
|
|
2366
2737
|
}
|
|
2367
2738
|
|
|
2368
2739
|
/**
|
|
@@ -2374,11 +2745,14 @@ class Printer {
|
|
|
2374
2745
|
const loop = this.#loops++;
|
|
2375
2746
|
const names = this.#loopNames(e.init, e.step, ctx, loop);
|
|
2376
2747
|
if (this.#wantList.has(e)) this.#wantList.add(e.result);
|
|
2377
|
-
const t = this.#targetLoop(e.axis, e.at ?? [], ctx);
|
|
2748
|
+
const t = this.#targetLoop(e.axis, e.at ?? [], ctx, e.as);
|
|
2378
2749
|
const tests = t.tests.map((x) => this.#hoist(this.expr(x, t.inner), hasLoop(x)));
|
|
2379
2750
|
// The interpreter evaluates the tests at each target before the first step, so a module of a sheet does not have them.
|
|
2380
2751
|
if (tests.some((x) => x.v.deps.has(CELLS))) throw new NotStandalone("a test of the axis of a fold reads a cell");
|
|
2381
|
-
|
|
2752
|
+
// Only the steps see the names of the items (AXIS.LIST.SCOPE). A name of `as` is not a name of `init`, so the read of
|
|
2753
|
+
// each name of the fold stays its read, and an append into its own list keeps its owner (COMPILE.MODULE.APPEND.OWN).
|
|
2754
|
+
const step = this.#loopStep(e.step, { ...t.inner, env: withNames(names.env, t.items) }, names.vars);
|
|
2755
|
+
this.#readsNoTarget(t.texts, t.inner.level, [...tests.map((x) => x.v.deps), step.deps]);
|
|
2382
2756
|
const result = this.expr(e.result, { ...ctx, env: names.env });
|
|
2383
2757
|
const body = [
|
|
2384
2758
|
...t.key,
|
|
@@ -2387,9 +2761,9 @@ class Printer {
|
|
|
2387
2761
|
...tests.flatMap((c) => [...c.s, `if (!${this.#boolean(c.v)}) continue;`]),
|
|
2388
2762
|
...step.s,
|
|
2389
2763
|
];
|
|
2390
|
-
const inside = [...tests.flatMap((c) => [...c.v.deps]), ...step.deps].filter((d) => d !== loop && d !== t.inner.level);
|
|
2764
|
+
const inside = [...tests.flatMap((c) => [...c.v.deps]), ...step.deps].filter((d) => d !== loop && d !== t.inner.level && d !== t.item);
|
|
2391
2765
|
const deps = new Set([...names.deps, ...t.start, ...inside, ...[...result.v.deps].filter((d) => d !== loop)]);
|
|
2392
|
-
return { s: [...names.s, ...t.s, t.head, ...ind(body), "}", ...result.s], v: { code: result.v.code, kind: result.v.kind, safe: false, deps, list: result.v.list } };
|
|
2766
|
+
return { s: [...names.s, ...step.init, ...t.s, t.head, ...ind(body), "}", ...result.s], v: { code: result.v.code, kind: result.v.kind, safe: false, deps, list: result.v.list } };
|
|
2393
2767
|
}
|
|
2394
2768
|
|
|
2395
2769
|
/**
|
|
@@ -2398,6 +2772,8 @@ class Printer {
|
|
|
2398
2772
|
* is a constant of the run itself.
|
|
2399
2773
|
*/
|
|
2400
2774
|
#memoized(e: Expr, keys: readonly Expr[], ctx: Ctx): Code {
|
|
2775
|
+
// A key can be a list, for example the list of a let that nth reads in the node (COMPILE.MODULE.NTH.INDEX).
|
|
2776
|
+
for (const k of keys) this.#wantList.add(k);
|
|
2401
2777
|
const values = keys.map((k) => this.#hoist(this.expr(k, ctx)));
|
|
2402
2778
|
const varying = keys.filter((_k, i) => (values[i] as Code).v.deps.size > 0);
|
|
2403
2779
|
const params = varying.map(() => this.fresh("q"));
|
|
@@ -2405,7 +2781,7 @@ class Printer {
|
|
|
2405
2781
|
keys.map((k, i): [Expr, Name] => {
|
|
2406
2782
|
const x = (values[i] as Code).v;
|
|
2407
2783
|
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]) }];
|
|
2784
|
+
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
2785
|
}),
|
|
2410
2786
|
);
|
|
2411
2787
|
const outer = this.#inside;
|
|
@@ -2418,7 +2794,7 @@ class Printer {
|
|
|
2418
2794
|
}
|
|
2419
2795
|
// 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
2796
|
// 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 }]));
|
|
2797
|
+
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
2798
|
const structure = canonical(e, (x) => tokens.get(x as Expr));
|
|
2423
2799
|
let fn = this.#structures.get(structure);
|
|
2424
2800
|
if (fn === undefined) {
|
|
@@ -2587,6 +2963,19 @@ function reasonOf(thrown: unknown): Emitted {
|
|
|
2587
2963
|
return { ok: false, reason: thrown.message };
|
|
2588
2964
|
}
|
|
2589
2965
|
|
|
2966
|
+
/**
|
|
2967
|
+
* 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
|
|
2968
|
+
* the array of the list when the program reads the field (COMPILE.MODULE.LIST.INPUT). The code is true for a field
|
|
2969
|
+
* against the schema.
|
|
2970
|
+
*/
|
|
2971
|
+
function fieldCheck(p: Printer, field: string, kind: Kind | ListKind): string {
|
|
2972
|
+
const input = `r[${JSON.stringify(field)}]`;
|
|
2973
|
+
if (typeof kind !== "object") return p.against(kind, input);
|
|
2974
|
+
const read = `${p.use("LI")}(${input}, ${String(depthOf(listOfKind(kind)))}, ${p.test(leafOf(kind))})`;
|
|
2975
|
+
const keep = p.inputs.get(field);
|
|
2976
|
+
return `${keep === undefined ? read : `(${keep}[i] = ${read})`} === undefined`;
|
|
2977
|
+
}
|
|
2978
|
+
|
|
2590
2979
|
/**
|
|
2591
2980
|
* This function gives the text of a module: the declarations, the helpers, and the function of the run. The run checks
|
|
2592
2981
|
* its input, computes the parts of the tree and the constants of the run, and then gives the statements `body`.
|
|
@@ -2604,7 +2993,7 @@ function printModule(p: Printer, options: ModuleOptions, run: Run, body: readonl
|
|
|
2604
2993
|
let fieldChecks: string;
|
|
2605
2994
|
let varChecks: string;
|
|
2606
2995
|
try {
|
|
2607
|
-
fieldChecks = fields.map(([f, k]) => ` || ${p
|
|
2996
|
+
fieldChecks = fields.map(([f, k]) => ` || ${fieldCheck(p, f, k)}`).join("");
|
|
2608
2997
|
varChecks = vars.map(([v, k]) => ` || ${p.against(k, `vars[${JSON.stringify(v)}]`)}`).join("");
|
|
2609
2998
|
} catch (thrown) {
|
|
2610
2999
|
return reasonOf(thrown);
|
|
@@ -2640,6 +3029,7 @@ function printModule(p: Printer, options: ModuleOptions, run: Run, body: readonl
|
|
|
2640
3029
|
' if (!Array.isArray(records)) C("the records are not an array");',
|
|
2641
3030
|
" const R = records;",
|
|
2642
3031
|
" const n = R.length;",
|
|
3032
|
+
...[...p.inputs.values()].map((x) => ` const ${x} = [];`),
|
|
2643
3033
|
" for (let i = 0; i < n; i++) {",
|
|
2644
3034
|
" const r = R[i];",
|
|
2645
3035
|
` if (typeof r !== "object" || r === null${fieldChecks}) C(\`the record \${i} does not keep the schema\`);`,
|
|
@@ -2706,11 +3096,14 @@ const kindText = (k: Kind | undefined, l?: ListInfo): string => (l === undefined
|
|
|
2706
3096
|
const depthOf = (l: ListInfo): number => (l.inner === undefined ? 0 : 1 + depthOf(l.inner));
|
|
2707
3097
|
|
|
2708
3098
|
/** 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 };
|
|
3099
|
+
const listOfKind = (k: ListKind, all = false): ListInfo => {
|
|
3100
|
+
const texts = all || k.texts === true;
|
|
3101
|
+
return typeof k.list === "object" ? { item: undefined, inner: listOfKind(k.list, all), texts } : { item: k.list, texts };
|
|
2712
3102
|
};
|
|
2713
3103
|
|
|
3104
|
+
/** This function gives the kind of the items at the bottom of a list kind. */
|
|
3105
|
+
const leafOf = (k: ListKind): Kind => (typeof k.list === "object" ? leafOf(k.list) : k.list);
|
|
3106
|
+
|
|
2714
3107
|
/**
|
|
2715
3108
|
* This function gives the facts of the lists of a column from the list of its first formula. The other cells of the
|
|
2716
3109
|
* column can have other formulas. Thus a list without items does not tell that each list of the column is empty.
|