@mark1russell7/vex-compiler 0.13.2 → 0.13.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/index.d.ts +11 -2
- package/build/index.d.ts.map +1 -1
- package/build/index.js +148 -51
- package/build/index.js.map +1 -1
- package/package.json +4 -4
- package/src/index.ts +1 -1
- package/src/module.ts +152 -56
- package/src/sheet-order.ts +11 -4
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://json.schemastore.org/package",
|
|
3
3
|
"name": "@mark1russell7/vex-compiler",
|
|
4
|
-
"version": "0.13.
|
|
4
|
+
"version": "0.13.3",
|
|
5
5
|
"description": "The Vex compiler: generated JavaScript for Vex programs, at run time and at build time, with the results of the interpreter.",
|
|
6
6
|
"keywords": [
|
|
7
7
|
"vex",
|
|
@@ -43,15 +43,15 @@
|
|
|
43
43
|
},
|
|
44
44
|
"devDependencies": {
|
|
45
45
|
"@mark1russell7/cue": "github:mark1russell7/cue",
|
|
46
|
-
"@mark1russell7/vex-domains": "0.13.
|
|
47
|
-
"@mark1russell7/vex-testkit": "0.13.
|
|
46
|
+
"@mark1russell7/vex-domains": "0.13.3",
|
|
47
|
+
"@mark1russell7/vex-testkit": "0.13.3",
|
|
48
48
|
"@types/node": "^26.6.4",
|
|
49
49
|
"fast-check": "^4.10.2",
|
|
50
50
|
"typescript": "^7.0.2",
|
|
51
51
|
"vitest": "^5.0.3"
|
|
52
52
|
},
|
|
53
53
|
"dependencies": {
|
|
54
|
-
"@mark1russell7/vex": "0.13.
|
|
54
|
+
"@mark1russell7/vex": "0.13.3"
|
|
55
55
|
},
|
|
56
56
|
"scripts": {
|
|
57
57
|
"build": "tsdown",
|
package/src/index.ts
CHANGED
|
@@ -3,6 +3,6 @@
|
|
|
3
3
|
*/
|
|
4
4
|
export { generate, load, tiered, type Generated, type GenerateOptions, type Tier2, type TieredProgram, type TierStats } from "./tiers.ts";
|
|
5
5
|
export type { Schema } from "./facts.ts";
|
|
6
|
-
export { emitModule, emitSheetModule, type Emitted, type ModuleOptions, type SheetModuleOptions } from "./module.ts";
|
|
6
|
+
export { emitModule, emitSheetModule, type Emitted, type ListKind, type ModuleOptions, type SheetModuleOptions } from "./module.ts";
|
|
7
7
|
export { FALLBACK, createRuntime, type Fallback, type Runtime, type RuntimeOptions } from "./runtime.ts";
|
|
8
8
|
export type { LExpr, LoopProgram, LStmt, PrimOp, RuntimeFn } from "./loop.ts";
|
package/src/module.ts
CHANGED
|
@@ -19,12 +19,14 @@
|
|
|
19
19
|
* the fields and the variables of the schema. It takes the axes `all`, `others` and `window`. A tree space also has the
|
|
20
20
|
* move `parent` and the axes of a tree (COMPILE.MODULE.TREE). A graph space has the axes of a graph
|
|
21
21
|
* (COMPILE.MODULE.GRAPH). A list is an array of pairs of a key and a value. The list ops, `reduce`, list literals and
|
|
22
|
-
* lists as names of loops are in a module (COMPILE.MODULE.LIST, COMPILE.MODULE.REDUCE). The
|
|
23
|
-
*
|
|
22
|
+
* lists as names of loops are in a module (COMPILE.MODULE.LIST, COMPILE.MODULE.REDUCE). The value of a program can be a
|
|
23
|
+
* list, and the run gives it as a `vex.list` (COMPILE.MODULE.LIST.RESULT). The kinds of each op site must decide its op.
|
|
24
|
+
* Another construct gives a reason, not code.
|
|
24
25
|
*
|
|
25
26
|
* `emitSheetModule` prints the formula columns of a sheet as one module (COMPILE.MODULE.SHEET). Each column is an array
|
|
26
27
|
* of results, and the run fills the arrays in the static order of `SheetRun.fill`. A read of a cell that is not finished
|
|
27
|
-
* starts the search of `SheetRun`. Thus each cell on a cycle gives the error of Vex.
|
|
28
|
+
* starts the search of `SheetRun`. Thus each cell on a cycle gives the error of Vex. A cell can hold a list, and a
|
|
29
|
+
* formula reads it with the list ops (COMPILE.MODULE.SHEET.LIST).
|
|
28
30
|
*/
|
|
29
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";
|
|
30
32
|
import { factsOf, kindOfDomain, primitiveOf, type Facts, type Kind, type Schema } from "./facts.ts";
|
|
@@ -57,12 +59,22 @@ export interface SheetModuleOptions extends ModuleOptions {
|
|
|
57
59
|
/**
|
|
58
60
|
* The kind of the values of each column. The printer prints each column after the columns that it reads. A column
|
|
59
61
|
* that a formula reads before its own formula prints needs its kind here, for example a column that reads itself.
|
|
62
|
+
* A column of lists has a `ListKind` (COMPILE.MODULE.SHEET.LIST).
|
|
60
63
|
*/
|
|
61
|
-
readonly kinds?: Readonly<Record<string, Kind>>;
|
|
64
|
+
readonly kinds?: Readonly<Record<string, Kind | ListKind>>;
|
|
62
65
|
/** The budget of the stack of the search of a run, in estimated frames, as in `SheetRun`. The default is 3000. */
|
|
63
66
|
readonly budget?: number;
|
|
64
67
|
}
|
|
65
68
|
|
|
69
|
+
/**
|
|
70
|
+
* The kind of a column of lists in a module of a sheet (COMPILE.MODULE.SHEET.LIST): the kind of the items, which can be
|
|
71
|
+
* a list too. With `texts`, a key of an item can be the text of a key of a list literal.
|
|
72
|
+
*/
|
|
73
|
+
export interface ListKind {
|
|
74
|
+
readonly list: Kind | ListKind;
|
|
75
|
+
readonly texts?: boolean;
|
|
76
|
+
}
|
|
77
|
+
|
|
66
78
|
/** The source of a standalone module, or the reason that the program cannot be one. */
|
|
67
79
|
export type Emitted = { readonly ok: true; readonly source: string } | { readonly ok: false; readonly reason: string };
|
|
68
80
|
|
|
@@ -153,6 +165,8 @@ interface SheetInfo {
|
|
|
153
165
|
readonly columns: ReadonlyMap<string, number>;
|
|
154
166
|
/** The kind of each column that the printer knows: a kind of the options, or the kind of a printed formula. */
|
|
155
167
|
readonly kinds: Map<string, Kind | undefined>;
|
|
168
|
+
/** The facts of the lists of each column of lists that the printer knows (COMPILE.MODULE.SHEET.LIST). */
|
|
169
|
+
readonly lists: Map<string, ListInfo>;
|
|
156
170
|
/** True when each read of a cell reads a finished cell, so a read starts no search (COMPILE.MODULE.SHEET.DIRECT). */
|
|
157
171
|
readonly direct: boolean;
|
|
158
172
|
}
|
|
@@ -248,7 +262,7 @@ type TreeHelper = "PT" | "CH" | "SG" | "PR" | "UP" | "SO" | "AN" | "BF";
|
|
|
248
262
|
type GraphHelper = "GR" | "GI" | "RB";
|
|
249
263
|
|
|
250
264
|
/** The helpers of a sheet (COMPILE.MODULE.SHEET): the state of a run of a sheet, and the order of the keys of a tree. */
|
|
251
|
-
type SheetHelper = "SH" | "KO" | "DO";
|
|
265
|
+
type SheetHelper = "SH" | "KO" | "DO" | "LO" | "LC";
|
|
252
266
|
|
|
253
267
|
/** The helpers of the generated code. A module has only the helpers that it uses. */
|
|
254
268
|
const HELPERS: Readonly<Record<Exclude<Helper, "S">, string>> = {
|
|
@@ -422,6 +436,11 @@ const HELPERS: Readonly<Record<Exclude<Helper, "S">, string>> = {
|
|
|
422
436
|
// A cell without a formula has the error sentinel from the start, as the error of its read.
|
|
423
437
|
// A column of a direct fill (COMPILE.MODULE.SHEET.DIRECT): the error sentinel of a cell changes to VEX_ERROR.
|
|
424
438
|
DO: "function DO(d) { for (let k = 0; k < d.length; k++) if (d[k] === E) d[k] = VEX_ERROR; return d; }",
|
|
439
|
+
// A list of a result (COMPILE.MODULE.LIST.RESULT): a `vex.list` with a text key for each item. An error item has the
|
|
440
|
+
// error VEX_ERROR. The depth `h` is the number of the levels of lists in the items.
|
|
441
|
+
LO: 'function LO(l, h) { return { kind: "vex.list", items: l.map(([k, v]) => ({ key: `${k}`, result: v === E ? { ok: false, error: VEX_ERROR } : { ok: true, value: h > 0 ? LO(v, h - 1) : v } })) }; }',
|
|
442
|
+
// A column of lists (COMPILE.MODULE.SHEET.LIST): each cell with a list gives a `vex.list`.
|
|
443
|
+
LC: "function LC(d, h) { for (let k = 0; k < d.length; k++) if (d[k] !== VEX_ERROR) d[k] = LO(d[k], h); return d; }",
|
|
425
444
|
SH: [
|
|
426
445
|
"function SH(n, cols, own, budget) {",
|
|
427
446
|
" const pg = (c, k) => {",
|
|
@@ -716,7 +735,7 @@ const NEEDS: Readonly<Record<Helper, readonly Helper[]>> = {
|
|
|
716
735
|
PT: ["C"], GR: ["C"], UP: ["F"], SO: ["F"],
|
|
717
736
|
CH: [], SG: [], PR: [], AN: [], BF: [],
|
|
718
737
|
GI: [], RB: [],
|
|
719
|
-
SH: [], KO: [], DO: [],
|
|
738
|
+
SH: [], KO: [], DO: [], LO: [], LC: ["LO"],
|
|
720
739
|
};
|
|
721
740
|
|
|
722
741
|
/** The parts of a tree that a run computes before the loop over its keys, if the program needs them. */
|
|
@@ -772,23 +791,25 @@ const LIST_RESULTS: ReadonlySet<string> = new Set(["sortBy", "take", "drop", "ap
|
|
|
772
791
|
* This function tells if an expression gives a list. An each, a list literal and a list op of `LIST_RESULTS` give a
|
|
773
792
|
* list. A name of a list, and a let or a loop whose result is a list, give a list too. `isName` tells if a name outside the expression holds a list.
|
|
774
793
|
*/
|
|
775
|
-
function listy(e: Expr, isName: (name: string) => boolean): boolean {
|
|
794
|
+
function listy(e: Expr, isName: (name: string) => boolean, isCell: (e: ExprOf<"ext">) => boolean): boolean {
|
|
776
795
|
switch (e.tag) {
|
|
777
796
|
case "each":
|
|
778
797
|
return true;
|
|
779
798
|
case "lit":
|
|
780
799
|
return isVexList(e.value);
|
|
781
800
|
case "app":
|
|
782
|
-
|
|
801
|
+
// A branch of if and ifError can be a list (COMPILE.MODULE.LIST.RESULT).
|
|
802
|
+
return LIST_RESULTS.has(e.op) || ((e.op === "if" || e.op === "ifError") && e.args.slice(e.op === "if" ? 1 : 0).some((x) => listy(x, isName, isCell)));
|
|
783
803
|
case "var":
|
|
784
804
|
return isName(e.name);
|
|
785
805
|
case "let":
|
|
786
|
-
return listy(e.body, namesIn(e.bind, isName));
|
|
806
|
+
return listy(e.body, namesIn(e.bind, isName, isCell), isCell);
|
|
787
807
|
case "fold":
|
|
788
808
|
case "iterate":
|
|
789
|
-
return listy(e.result, namesIn(e.init, isName));
|
|
790
|
-
case "call":
|
|
809
|
+
return listy(e.result, namesIn(e.init, isName, isCell), isCell);
|
|
791
810
|
case "ext":
|
|
811
|
+
return isCell(e);
|
|
812
|
+
case "call":
|
|
792
813
|
case "fn":
|
|
793
814
|
case "rec":
|
|
794
815
|
case "ref":
|
|
@@ -797,8 +818,8 @@ function listy(e: Expr, isName: (name: string) => boolean): boolean {
|
|
|
797
818
|
}
|
|
798
819
|
|
|
799
820
|
/** This function tells if a name holds a list in the scope of some bindings. A binding hides a name outside, and a function is not a list. */
|
|
800
|
-
function namesIn(bind: Readonly<Record<string, Expr>>, isName: (name: string) => boolean): (name: string) => boolean {
|
|
801
|
-
const lists = new Map(Object.entries(bind).map(([name, x]) => [name, x.tag !== "fn" && listy(x, isName)]));
|
|
821
|
+
function namesIn(bind: Readonly<Record<string, Expr>>, isName: (name: string) => boolean, isCell: (e: ExprOf<"ext">) => boolean): (name: string) => boolean {
|
|
822
|
+
const lists = new Map(Object.entries(bind).map(([name, x]) => [name, x.tag !== "fn" && listy(x, isName, isCell)]));
|
|
802
823
|
return (name) => lists.get(name) ?? isName(name);
|
|
803
824
|
}
|
|
804
825
|
|
|
@@ -807,13 +828,23 @@ function hasKeyedLiteral(e: Expr): boolean {
|
|
|
807
828
|
return (e.tag === "lit" && isVexList(e.value) && e.value.items.length > 0) || children(e).some(hasKeyedLiteral);
|
|
808
829
|
}
|
|
809
830
|
|
|
810
|
-
/**
|
|
811
|
-
function
|
|
831
|
+
/**
|
|
832
|
+
* This function gives the facts of the list of `append` from the facts of its two lists. It also gives the list of
|
|
833
|
+
* `if` from its two branches. An empty list fits each list. The op `op` names the op in the reason.
|
|
834
|
+
*/
|
|
835
|
+
function joinLists(a: ListInfo, b: ListInfo, op: string): ListInfo {
|
|
812
836
|
if (a.empty === true) return b;
|
|
813
837
|
if (b.empty === true) return a;
|
|
814
|
-
if ((a.inner === undefined) !== (b.inner === undefined)) throw new NotStandalone(
|
|
838
|
+
if ((a.inner === undefined) !== (b.inner === undefined)) throw new NotStandalone(`"${op}" of a list of lists and a list of values`);
|
|
815
839
|
const texts = a.texts === true || b.texts === true;
|
|
816
|
-
return { item: join(a.item, b.item), inner: a.inner === undefined ? undefined : joinLists(a.inner, b.inner as ListInfo), texts };
|
|
840
|
+
return { item: join(a.item, b.item), inner: a.inner === undefined ? undefined : joinLists(a.inner, b.inner as ListInfo, op), texts };
|
|
841
|
+
}
|
|
842
|
+
|
|
843
|
+
/** This function gives the facts of the list of `if` or `ifError` from its two branches. Two values that are not lists give undefined. */
|
|
844
|
+
function branchLists(op: string, a: ListInfo | undefined, b: ListInfo | undefined): ListInfo | undefined {
|
|
845
|
+
if (a === undefined && b === undefined) return undefined;
|
|
846
|
+
if (a === undefined || b === undefined) throw new NotStandalone(`"${op}" of a list and a value that is not a list`);
|
|
847
|
+
return joinLists(a, b, op);
|
|
817
848
|
}
|
|
818
849
|
|
|
819
850
|
/**
|
|
@@ -1335,7 +1366,12 @@ class Printer {
|
|
|
1335
1366
|
|
|
1336
1367
|
/** This method tells if an expression gives a list at a place that takes one (`listy`). */
|
|
1337
1368
|
#isList(e: Expr, ctx: Ctx): boolean {
|
|
1338
|
-
return listy(e, (name) => ctx.env.get(name)?.list !== undefined);
|
|
1369
|
+
return listy(e, (name) => ctx.env.get(name)?.list !== undefined, (x) => this.#cellList(x) !== undefined);
|
|
1370
|
+
}
|
|
1371
|
+
|
|
1372
|
+
/** This method gives the facts of the list of a read of a cell. A read of a column that holds no list gives undefined. */
|
|
1373
|
+
#cellList(e: ExprOf<"ext">): ListInfo | undefined {
|
|
1374
|
+
return e.kind === CELL_KIND && isCellRef(e.data) ? this.#sheet?.lists.get(e.data.column) : undefined;
|
|
1339
1375
|
}
|
|
1340
1376
|
|
|
1341
1377
|
/** This method prints a list literal (LIST.LITERAL) as an array of pairs of a key and a value. An error item holds the sentinel. */
|
|
@@ -1487,10 +1523,13 @@ class Printer {
|
|
|
1487
1523
|
const deps = new Set([...this.#addressDeps(at, ctx, []), CELLS]);
|
|
1488
1524
|
const index = sheet.columns.get(column);
|
|
1489
1525
|
// The read of a column that the sheet does not have is an error. A kind of the options lets an op take it.
|
|
1490
|
-
|
|
1526
|
+
const list = sheet.lists.get(column);
|
|
1527
|
+
if (index === undefined) return bare({ code: `${F}()`, kind: sheet.kinds.get(column), safe: false, deps, list });
|
|
1491
1528
|
if (!sheet.kinds.has(column)) throw new NotStandalone(`a formula reads the column "${column}" before its formula, so the column needs its kind in the option kinds`);
|
|
1492
|
-
|
|
1493
|
-
const
|
|
1529
|
+
// A direct fill reads the array of the column. The search reads the cell with the function of its state.
|
|
1530
|
+
const address = this.#address(at, ctx, []);
|
|
1531
|
+
const read = sheet.direct ? `D[${String(index)}][${address}]` : `${READ_CELL}(${String(index)}, ${address})`;
|
|
1532
|
+
const v = { code: `${this.use("G")}(${read})`, kind: sheet.kinds.get(column), safe: false, deps, list };
|
|
1494
1533
|
// The read itself gives the result or the error sentinel. A move of the address can throw, so then the read is not
|
|
1495
1534
|
// a value that holds the sentinel.
|
|
1496
1535
|
return bare(at.every((m) => m.t === "origin") ? { ...v, held: read } : v);
|
|
@@ -1777,6 +1816,8 @@ class Printer {
|
|
|
1777
1816
|
|
|
1778
1817
|
#app(e: ExprOf<"app">, ctx: Ctx): Code {
|
|
1779
1818
|
const { op, args } = e;
|
|
1819
|
+
// A branch of if and of ifError is at a place that takes a list when the node is.
|
|
1820
|
+
if ((op === "if" || op === "ifError") && this.#wantList.has(e)) for (const x of args.slice(op === "if" ? 1 : 0)) this.#wantList.add(x);
|
|
1780
1821
|
if (op === "if") return this.#if(args, ctx);
|
|
1781
1822
|
if (op === "and" || op === "or") return this.#andOr(op === "and", args, ctx);
|
|
1782
1823
|
if (op === "ifError") return this.#ifError(args, ctx);
|
|
@@ -1838,7 +1879,7 @@ class Printer {
|
|
|
1838
1879
|
const raw = [this.expr(c, ctx), this.expr(a, ctx), this.expr(b, ctx)];
|
|
1839
1880
|
const deps = depsOf(...raw);
|
|
1840
1881
|
const [cond, yes, no] = this.#settle(raw, deps, [c, a, b]) as [Code, Code, Code];
|
|
1841
|
-
const v = { kind: join(yes.v.kind, no.v.kind), safe: this.#safeBoolean(cond.v) && yes.v.safe && no.v.safe, deps };
|
|
1882
|
+
const v = { kind: join(yes.v.kind, no.v.kind), safe: this.#safeBoolean(cond.v) && yes.v.safe && no.v.safe, deps, list: branchLists("if", yes.v.list, no.v.list) };
|
|
1842
1883
|
if (yes.s.length === 0 && no.s.length === 0) return { s: cond.s, v: { ...v, code: `(${this.#boolean(cond.v)} ? ${yes.v.code} : ${no.v.code})` } };
|
|
1843
1884
|
const t = this.fresh("t");
|
|
1844
1885
|
const s = [...cond.s, `let ${t};`, `if (${this.#boolean(cond.v)}) {`, ...ind(yes.s), ` ${t} = ${yes.v.code};`, "} else {", ...ind(no.s), ` ${t} = ${no.v.code};`, "}"];
|
|
@@ -1870,7 +1911,7 @@ class Printer {
|
|
|
1870
1911
|
if (first.v.safe) return first;
|
|
1871
1912
|
const t = this.fresh("t");
|
|
1872
1913
|
const s = [`let ${t};`, "try {", ...ind(first.s), ` ${t} = ${first.v.code};`, "} catch {", ...ind(second.s), ` ${t} = ${second.v.code};`, "}"];
|
|
1873
|
-
return { s, v: { code: t, kind: join(first.v.kind, second.v.kind), safe: second.v.safe, deps } };
|
|
1914
|
+
return { s, v: { code: t, kind: join(first.v.kind, second.v.kind), safe: second.v.safe, deps, list: branchLists("ifError", first.v.list, second.v.list) } };
|
|
1874
1915
|
}
|
|
1875
1916
|
|
|
1876
1917
|
#opIndex(op: string): number {
|
|
@@ -2225,7 +2266,7 @@ class Printer {
|
|
|
2225
2266
|
if (op === "get") return value(info.item, info.inner);
|
|
2226
2267
|
if (op === "indexOf") return value("number", undefined);
|
|
2227
2268
|
if (op === "without") return value(undefined, info);
|
|
2228
|
-
if (op === "append") return value(undefined, joinLists(info, (parts[1] as Code).v.list as ListInfo));
|
|
2269
|
+
if (op === "append") return value(undefined, joinLists(info, (parts[1] as Code).v.list as ListInfo, op));
|
|
2229
2270
|
// flat: the value of each item must be a list, so a list of values gives a reason. An empty list gives an empty list.
|
|
2230
2271
|
if (info.empty === true) return value(undefined, info);
|
|
2231
2272
|
if (info.inner === undefined) throw new NotStandalone('"flat" over a list whose items are not lists');
|
|
@@ -2495,6 +2536,8 @@ class Printer {
|
|
|
2495
2536
|
/** This method gives the code of the program at the key of the run. A constant of the run evaluates once. */
|
|
2496
2537
|
/** This method gives the code of a program at the key `o` of the run. A sheet has one program for each formula. */
|
|
2497
2538
|
root(expr: Expr): Code {
|
|
2539
|
+
// The value of a program and of a cell can be a list (COMPILE.MODULE.LIST.RESULT).
|
|
2540
|
+
this.#wantList.add(expr);
|
|
2498
2541
|
return this.#hoist(this.expr(expr, { origin: "o", focus: "o", level: 1, originLevel: 1, env: new Map(), fns: new Map(), keys: new Map() }));
|
|
2499
2542
|
}
|
|
2500
2543
|
|
|
@@ -2637,7 +2680,9 @@ export function emitModule(source: Expr | Envelope, options: ModuleOptions): Emi
|
|
|
2637
2680
|
} catch (thrown) {
|
|
2638
2681
|
return reasonOf(thrown);
|
|
2639
2682
|
}
|
|
2640
|
-
|
|
2683
|
+
// A list gives a vex.list (COMPILE.MODULE.LIST.RESULT).
|
|
2684
|
+
const result = value.v.list === undefined ? value.v.code : `${p.use("LO")}(${value.v.code}, ${String(depthOf(value.v.list))})`;
|
|
2685
|
+
const body = ["const out = [];", "for (let o = 0; o < n; o++) {", " try {", ...ind(ind(value.s)), ` out.push(${result});`, " } catch {", " out.push(VEX_ERROR);", " }", "}", "return out;"];
|
|
2641
2686
|
return printModule(p, options, run, body);
|
|
2642
2687
|
}
|
|
2643
2688
|
|
|
@@ -2654,8 +2699,23 @@ interface Formula {
|
|
|
2654
2699
|
/** This function gives the words for a formula in a reason: the formula of a column, or of one cell. */
|
|
2655
2700
|
const formulaText = (f: Formula): string => (f.key === undefined ? `the formula of the column "${f.column}"` : `the formula of the cell "${f.column}" at "${String(f.key)}"`);
|
|
2656
2701
|
|
|
2657
|
-
/** This function gives the words for a kind in a reason. */
|
|
2658
|
-
const kindText = (k: Kind | undefined): string => k ?? "that the printer does not know";
|
|
2702
|
+
/** This function gives the words for a kind in a reason. A list gives the kind of its items. */
|
|
2703
|
+
const kindText = (k: Kind | undefined, l?: ListInfo): string => (l === undefined ? (k ?? "that the printer does not know") : `list of ${l.inner === undefined ? kindText(l.item) : kindText(undefined, l.inner)}`);
|
|
2704
|
+
|
|
2705
|
+
/** This function gives the number of the levels of lists in the items of a list: 0 for a list of values. */
|
|
2706
|
+
const depthOf = (l: ListInfo): number => (l.inner === undefined ? 0 : 1 + depthOf(l.inner));
|
|
2707
|
+
|
|
2708
|
+
/** This function gives the facts of the lists of a column from the kind of the option `kinds` (COMPILE.MODULE.SHEET.LIST). */
|
|
2709
|
+
const listOfKind = (k: ListKind): ListInfo => {
|
|
2710
|
+
const texts = k.texts === true;
|
|
2711
|
+
return typeof k.list === "object" ? { item: undefined, inner: listOfKind(k.list), texts } : { item: k.list, texts };
|
|
2712
|
+
};
|
|
2713
|
+
|
|
2714
|
+
/**
|
|
2715
|
+
* This function gives the facts of the lists of a column from the list of its first formula. The other cells of the
|
|
2716
|
+
* column can have other formulas. Thus a list without items does not tell that each list of the column is empty.
|
|
2717
|
+
*/
|
|
2718
|
+
const columnList = (l: ListInfo): ListInfo => ({ item: l.item, inner: l.inner === undefined ? undefined : columnList(l.inner), texts: l.texts === true });
|
|
2659
2719
|
|
|
2660
2720
|
/**
|
|
2661
2721
|
* This function prints the formula columns of a sheet as a standalone ES module (COMPILE.MODULE.SHEET). The function of
|
|
@@ -2686,22 +2746,43 @@ export function emitSheetModule(columns: ReadonlyMap<string, Expr>, options: She
|
|
|
2686
2746
|
const shape = shapeError(f.expr);
|
|
2687
2747
|
if (shape !== undefined) return { ok: false, reason: `${formulaText(f)}: ${shape}` };
|
|
2688
2748
|
}
|
|
2689
|
-
const kinds = new Map<string, Kind | undefined>(
|
|
2749
|
+
const kinds = new Map<string, Kind | undefined>();
|
|
2750
|
+
const lists = new Map<string, ListInfo>();
|
|
2751
|
+
for (const [c, k] of Object.entries(options.kinds ?? {})) {
|
|
2752
|
+
kinds.set(c, typeof k === "object" ? undefined : k);
|
|
2753
|
+
if (typeof k === "object") lists.set(c, listOfKind(k));
|
|
2754
|
+
}
|
|
2690
2755
|
const index = new Map(names.map((c, i) => [c, i]));
|
|
2691
2756
|
// The memo of the printer covers each formula, so the formulas share their nodes of the memo.
|
|
2692
2757
|
// A sheet whose reads all read finished cells needs no search: each cell is the value of its formula
|
|
2693
2758
|
// (COMPILE.MODULE.SHEET.DIRECT). A sheet with formulas of cells always has the search.
|
|
2694
2759
|
const direct = formulas.every((f) => f.key === undefined) && order.every((c) => readsFinished(columns, order, c, run.tree));
|
|
2695
|
-
const p = new Printer(rec(Object.fromEntries(formulas.map((f, i) => [`f${String(i)}`, f.expr]))), options, { columns: index, kinds, direct });
|
|
2760
|
+
const p = new Printer(rec(Object.fromEntries(formulas.map((f, i) => [`f${String(i)}`, f.expr]))), options, { columns: index, kinds, lists, direct });
|
|
2696
2761
|
const fns: string[] = [];
|
|
2697
2762
|
const decls: string[] = [];
|
|
2763
|
+
// The statements that put the value of each formula into the array of its column at the key `o`, for a direct fill.
|
|
2764
|
+
const blocks = new Map<string, readonly string[]>();
|
|
2698
2765
|
try {
|
|
2699
2766
|
for (const f of formulas) {
|
|
2700
2767
|
const code = p.root(f.expr);
|
|
2701
|
-
const kind = code.v
|
|
2702
|
-
// The first formula of a column without a kind of the options gives the kind of the column.
|
|
2703
|
-
|
|
2704
|
-
|
|
2768
|
+
const { kind, list } = code.v;
|
|
2769
|
+
// The first formula of a column without a kind of the options gives the kind of the column. Each other formula
|
|
2770
|
+
// must give a value of that kind, or a list that fits the lists of the column (COMPILE.MODULE.SHEET.LIST).
|
|
2771
|
+
if (!kinds.has(f.column)) {
|
|
2772
|
+
kinds.set(f.column, kind);
|
|
2773
|
+
if (list !== undefined) lists.set(f.column, columnList(list));
|
|
2774
|
+
} else {
|
|
2775
|
+
const known = lists.get(f.column);
|
|
2776
|
+
if (kinds.get(f.column) !== kind || (known === undefined) !== (list === undefined) || (known !== undefined && !fits(known, list as ListInfo))) {
|
|
2777
|
+
throw new NotStandalone(`${formulaText(f)} gives a value of the kind ${kindText(kind, list)}, not of the kind ${kindText(kinds.get(f.column), known)} of its column`);
|
|
2778
|
+
}
|
|
2779
|
+
}
|
|
2780
|
+
// COMPILE.MODULE.ONCE: a direct fill has the code of each formula in its loop over the keys, with no function.
|
|
2781
|
+
if (direct) {
|
|
2782
|
+
const at = `D[${String(index.get(f.column))}][o]`;
|
|
2783
|
+
blocks.set(f.column, code.v.safe && code.s.length === 0 ? [`${at} = ${code.v.code};`] : ["try {", ...ind(code.s), ` ${at} = ${code.v.code};`, "} catch {", ` ${at} = E;`, "}"]);
|
|
2784
|
+
continue;
|
|
2785
|
+
}
|
|
2705
2786
|
const fn = p.fresh("cf");
|
|
2706
2787
|
fns.push(fn);
|
|
2707
2788
|
decls.push(...(code.v.safe && code.s.length === 0 ? [`const ${fn} = (o) => ${code.v.code};`] : [`const ${fn} = (o) => {`, " try {", ...ind(ind(code.s)), ` return ${code.v.code};`, " } catch {", " return E;", " }", "};"]));
|
|
@@ -2710,43 +2791,58 @@ export function emitSheetModule(columns: ReadonlyMap<string, Expr>, options: She
|
|
|
2710
2791
|
} catch (thrown) {
|
|
2711
2792
|
return reasonOf(thrown);
|
|
2712
2793
|
}
|
|
2713
|
-
// The program of each column, and of each cell with its own formula, with its cost in estimated frames, as in SheetRun.
|
|
2714
|
-
const entry = (i: number): string => `[${fns[i] as string}, ${String(3 * nestingOf((formulas[i] as Formula).expr) + 16)}]`;
|
|
2715
|
-
const own = names.map((c) => {
|
|
2716
|
-
const at = formulas.flatMap((f, i) => (f.column === c && f.key !== undefined ? [`${String(f.key)}: ${entry(i)}`] : []));
|
|
2717
|
-
return at.length === 0 ? "undefined" : `{ ${at.join(", ")} }`;
|
|
2718
|
-
});
|
|
2719
|
-
const cols = names.map((c) => {
|
|
2720
|
-
const i = formulas.findIndex((f) => f.column === c && f.key === undefined);
|
|
2721
|
-
return i < 0 ? "undefined" : entry(i);
|
|
2722
|
-
});
|
|
2723
2794
|
p.use(direct ? "DO" : "SH");
|
|
2724
|
-
// The function of the formula of each column, for a direct fill. A direct fill has no formulas of cells.
|
|
2725
|
-
const fnOf = new Map(formulas.map((f, i) => [f.column, fns[i] as string]));
|
|
2726
|
-
const fillOf = (c: string, at: string): string => (direct ? `D[${at}][o] = ${fnOf.get(c) as string}(o);` : `SS.f(${at}, o);`);
|
|
2727
2795
|
// A tree gives the keys in the order of a fill with the helper KO, once for each order.
|
|
2728
2796
|
const orders = new Map<string, string>();
|
|
2729
|
-
const
|
|
2797
|
+
const headOf = (c: string): string => {
|
|
2730
2798
|
const { reverse, post, back } = keyOrderOf(readsOf(columns, cells, c).directions);
|
|
2731
|
-
|
|
2732
|
-
if (!run.tree) return reverse ? `for (let o = n - 1; o >= 0; o--) ${fillOf(c, at)}` : `for (let o = 0; o < n; o++) ${fillOf(c, at)}`;
|
|
2799
|
+
if (!run.tree) return reverse ? "for (let o = n - 1; o >= 0; o--)" : "for (let o = 0; o < n; o++)";
|
|
2733
2800
|
const args = `${p.use("KO")}(H, RT, ${String(post)}, ${String(back)})`;
|
|
2734
2801
|
let keys = orders.get(args);
|
|
2735
2802
|
if (keys === undefined) {
|
|
2736
2803
|
keys = p.fresh("K");
|
|
2737
2804
|
orders.set(args, keys);
|
|
2738
2805
|
}
|
|
2739
|
-
return `for (const o of ${keys})
|
|
2740
|
-
}
|
|
2806
|
+
return `for (const o of ${keys})`;
|
|
2807
|
+
};
|
|
2808
|
+
let fill: string[];
|
|
2809
|
+
if (direct) {
|
|
2810
|
+
// COMPILE.MODULE.ONCE: the columns that follow each other in the order share one loop over the keys when they have
|
|
2811
|
+
// the same order of the keys, and each read of a column of the loop reads a finished cell.
|
|
2812
|
+
const loops: { head: string; columns: string[] }[] = [];
|
|
2813
|
+
for (const c of order) {
|
|
2814
|
+
const head = headOf(c);
|
|
2815
|
+
const last = loops.at(-1);
|
|
2816
|
+
if (last?.head === head && readsFinished(columns, order, c, run.tree, new Set(last.columns))) last.columns.push(c);
|
|
2817
|
+
else loops.push({ head, columns: [c] });
|
|
2818
|
+
}
|
|
2819
|
+
fill = [];
|
|
2820
|
+
for (const { head, columns: cs } of loops) fill.push(`${head} {`, ...cs.flatMap((c) => ind(blocks.get(c) as readonly string[])), "}");
|
|
2821
|
+
} else {
|
|
2822
|
+
// The program of each column, and of each cell with its own formula, with its cost in estimated frames, as in SheetRun.
|
|
2823
|
+
const entry = (i: number): string => `[${fns[i] as string}, ${String(3 * nestingOf((formulas[i] as Formula).expr) + 16)}]`;
|
|
2824
|
+
const own = names.map((c) => {
|
|
2825
|
+
const at = formulas.flatMap((f, i) => (f.column === c && f.key !== undefined ? [`${String(f.key)}: ${entry(i)}`] : []));
|
|
2826
|
+
return at.length === 0 ? "undefined" : `{ ${at.join(", ")} }`;
|
|
2827
|
+
});
|
|
2828
|
+
const cols = names.map((c) => {
|
|
2829
|
+
const i = formulas.findIndex((f) => f.column === c && f.key === undefined);
|
|
2830
|
+
return i < 0 ? "undefined" : entry(i);
|
|
2831
|
+
});
|
|
2832
|
+
decls.push(`const SS = SH(n, [${cols.join(", ")}], [${own.join(", ")}], ${String(budget)});`, `const ${READ_CELL} = SS.r;`);
|
|
2833
|
+
fill = order.map((c) => `${headOf(c)} SS.f(${String(index.get(c))}, o);`);
|
|
2834
|
+
}
|
|
2741
2835
|
if (run.tree) p.treeParts.add("children");
|
|
2836
|
+
// A column of lists gives a vex.list in each cell with a list (COMPILE.MODULE.LIST.RESULT).
|
|
2837
|
+
const resultOf = (c: string, read: string): string => {
|
|
2838
|
+
const l = lists.get(c);
|
|
2839
|
+
return l === undefined ? read : `${p.use("LC")}(${read}, ${String(depthOf(l))})`;
|
|
2840
|
+
};
|
|
2742
2841
|
const body = [
|
|
2743
|
-
...decls,
|
|
2744
|
-
...(direct
|
|
2745
|
-
? [`const D = [${names.map(() => "new Array(n)").join(", ")}];`, `const ${READ_CELL} = (c, k) => D[c][k];`]
|
|
2746
|
-
: [`const SS = SH(n, [${cols.join(", ")}], [${own.join(", ")}], ${String(budget)});`, `const ${READ_CELL} = SS.r;`]),
|
|
2842
|
+
...(direct ? [`const D = [${names.map(() => "new Array(n)").join(", ")}];`] : decls),
|
|
2747
2843
|
...[...orders].map(([args, keys]) => `const ${keys} = ${args};`),
|
|
2748
2844
|
...fill,
|
|
2749
|
-
`return { ${names.map((c, i) => `${JSON.stringify(c)}: ${direct ? `DO(D[${String(i)}])` : `SS.o(${String(i)})`}`).join(", ")} };`,
|
|
2845
|
+
`return { ${names.map((c, i) => `${JSON.stringify(c)}: ${resultOf(c, direct ? `DO(D[${String(i)}])` : `SS.o(${String(i)})`)}`).join(", ")} };`,
|
|
2750
2846
|
];
|
|
2751
2847
|
return printModule(p, options, run, body);
|
|
2752
2848
|
}
|
package/src/sheet-order.ts
CHANGED
|
@@ -145,8 +145,12 @@ function baseOf(axis: Axis): Axis {
|
|
|
145
145
|
* - in a tree in post-order, at the key of a target of the axis `children` of the key.
|
|
146
146
|
*
|
|
147
147
|
* A read in the body of a function can evaluate at each place of a call, so it is not one of these forms.
|
|
148
|
+
*
|
|
149
|
+
* The columns of `fused` come before `self` in one loop over the keys (COMPILE.MODULE.ONCE). The loop evaluates each of
|
|
150
|
+
* them at a key before `self` at that key. Thus a read of one of them reads a finished cell only at the key itself, or
|
|
151
|
+
* in one of the three forms.
|
|
148
152
|
*/
|
|
149
|
-
export function readsFinished(columns: ReadonlyMap<string, Expr>, order: readonly string[], self: string, tree: boolean): boolean {
|
|
153
|
+
export function readsFinished(columns: ReadonlyMap<string, Expr>, order: readonly string[], self: string, tree: boolean, fused: ReadonlySet<string> = new Set()): boolean {
|
|
150
154
|
const formula = columns.get(self);
|
|
151
155
|
if (formula === undefined || shapeError(formula) !== undefined) return false;
|
|
152
156
|
const { reverse, post } = keyOrderOf(readsOf(columns, new Map(), self).directions);
|
|
@@ -166,12 +170,15 @@ export function readsFinished(columns: ReadonlyMap<string, Expr>, order: readonl
|
|
|
166
170
|
const { column, at } = e.data;
|
|
167
171
|
const index = order.indexOf(column);
|
|
168
172
|
if (index > position) return false;
|
|
169
|
-
if (column !== self) continue;
|
|
173
|
+
if (column !== self && !fused.has(column)) continue;
|
|
170
174
|
const [move, ...rest] = at;
|
|
175
|
+
// The cell of a fused column at the key itself is finished. The cell of `self` at the key is a cycle.
|
|
176
|
+
const here = column !== self && place === "key" && at.every((m) => m.t === "origin");
|
|
171
177
|
const ok =
|
|
172
|
-
|
|
178
|
+
here ||
|
|
179
|
+
(place === "key"
|
|
173
180
|
? move !== undefined && rest.length === 0 && ((tree && !post && move.t === "parent") || (!tree && !reverse && move.t === "offset" && move.d.length === 1 && (move.d[0] ?? 0) < 0))
|
|
174
|
-
: place === "children" && tree && post && at.length === 0;
|
|
181
|
+
: place === "children" && tree && post && at.length === 0);
|
|
175
182
|
if (!ok) return false;
|
|
176
183
|
}
|
|
177
184
|
}
|