@mark1russell7/vex 0.5.0 → 0.6.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 +93 -12
- package/build/index.d.ts.map +1 -1
- package/build/index.js +315 -74
- package/build/index.js.map +1 -1
- package/package.json +1 -1
- package/src/builder.ts +56 -3
- package/src/errors.ts +4 -0
- package/src/evaluate.ts +24 -6
- package/src/ir.ts +26 -1
- package/src/sheet.ts +142 -59
- package/src/space.ts +131 -1
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://json.schemastore.org/package",
|
|
3
3
|
"name": "@mark1russell7/vex",
|
|
4
|
-
"version": "0.
|
|
4
|
+
"version": "0.6.0",
|
|
5
5
|
"description": "Vex: typed spreadsheet formulas over domain objects. The kernel and the typed builder.",
|
|
6
6
|
"keywords": [
|
|
7
7
|
"typescript",
|
package/src/builder.ts
CHANGED
|
@@ -6,7 +6,7 @@ import type { AnyDomain, Domain, OpSpec } from "./domain.ts";
|
|
|
6
6
|
import type { VexError } from "./errors.ts";
|
|
7
7
|
import { evaluate, explain, type EvalOptions, type ExtHandler, type FreeFn } from "./evaluate.ts";
|
|
8
8
|
import { app, each, ext, index as indexMove, key as keyMove, let_, lit, offset as offsetMove, other as otherMove, origin as originMove, parent as parentMove, rec, ref, toPath, v, type Addr, type Axis, type Expr, type Move } from "./ir.ts";
|
|
9
|
-
import { cell as cellRef, SheetRun } from "./sheet.ts";
|
|
9
|
+
import { cell as cellRef, SheetRun, type CellFormulas } from "./sheet.ts";
|
|
10
10
|
import { toOptional, type Optional, type Result } from "./result.ts";
|
|
11
11
|
import type { Space } from "./space.ts";
|
|
12
12
|
import type { Trace } from "./trace.ts";
|
|
@@ -221,6 +221,22 @@ export interface ChainBase<Ctx extends ChainContext, T> {
|
|
|
221
221
|
descendants<U>(body: (c: ChainOf<Ctx, T>) => ChainBase<Ctx, U>, opts?: AxisOpts<Ctx, T>): ListChain<Ctx, U>;
|
|
222
222
|
/** The siblings axis of a tree space: the other children of the parent, or the other roots for a root. */
|
|
223
223
|
siblings<U>(body: (c: ChainOf<Ctx, T>) => ChainBase<Ctx, U>, opts?: AxisOpts<Ctx, T>): ListChain<Ctx, U>;
|
|
224
|
+
/**
|
|
225
|
+
* The window axis of an array space or a tree space: the keys at the offsets from `from` to `to` of the focus, in
|
|
226
|
+
* order. The offset 0 is the focus. An offset outside the space has no target.
|
|
227
|
+
*/
|
|
228
|
+
window<U>(from: number, to: number, body: (c: ChainOf<Ctx, T>) => ChainBase<Ctx, U>, opts?: AxisOpts<Ctx, T>): ListChain<Ctx, U>;
|
|
229
|
+
/**
|
|
230
|
+
* The table axis: the body evaluates at each key of the table `name` of the evaluation, in the space of that table.
|
|
231
|
+
* The body reads the fields of that table, but the types of the chain are the types of this space.
|
|
232
|
+
*/
|
|
233
|
+
table<U>(name: string, body: (c: ChainOf<Ctx, T>) => ChainBase<Ctx, U>, opts?: AxisOpts<Ctx, T>): ListChain<Ctx, U>;
|
|
234
|
+
/** The successors axis of a graph space: the ends of the edges from the focus. In a tree space, the children. */
|
|
235
|
+
successors<U>(body: (c: ChainOf<Ctx, T>) => ChainBase<Ctx, U>, opts?: AxisOpts<Ctx, T>): ListChain<Ctx, U>;
|
|
236
|
+
/** The predecessors axis of a graph space: the keys with an edge to the focus. In a tree space, the parent. */
|
|
237
|
+
predecessors<U>(body: (c: ChainOf<Ctx, T>) => ChainBase<Ctx, U>, opts?: AxisOpts<Ctx, T>): ListChain<Ctx, U>;
|
|
238
|
+
/** The reachable axis of a graph space: each key that a path of edges reaches, in breadth-first order. */
|
|
239
|
+
reachable<U>(body: (c: ChainOf<Ctx, T>) => ChainBase<Ctx, U>, opts?: AxisOpts<Ctx, T>): ListChain<Ctx, U>;
|
|
224
240
|
}
|
|
225
241
|
|
|
226
242
|
/** The options of an axis. */
|
|
@@ -360,8 +376,19 @@ export interface Sheet<Ctx extends ChainContext, Cols, Decl = object> {
|
|
|
360
376
|
* `cell` and its type: the column itself (a recurrence) or a later column. It has no effect at run time.
|
|
361
377
|
*/
|
|
362
378
|
declare<D extends Readonly<Record<string, unknown>>>(): Sheet<Ctx, Cols, Decl & D>;
|
|
379
|
+
/**
|
|
380
|
+
* This method gives a new sheet in which the cell of the column `column` at the key `k` has its own formula. That
|
|
381
|
+
* formula replaces the formula of the column at the key `k`. It must give a value of the type of the column.
|
|
382
|
+
*/
|
|
383
|
+
cellFormula<const N extends keyof (Cols & Decl) & string>(
|
|
384
|
+
k: Ctx["keys"],
|
|
385
|
+
column: N,
|
|
386
|
+
formula: (r: SheetRoot<Ctx, Cols & Decl>) => ChainBase<Ctx, (Cols & Decl)[N]>,
|
|
387
|
+
): Sheet<Ctx, Cols, Decl>;
|
|
363
388
|
/** The program of each column. */
|
|
364
389
|
readonly columns: Readonly<Record<string, Expr>>;
|
|
390
|
+
/** The program of each cell with its own formula, by column and then by key. */
|
|
391
|
+
readonly cellFormulas: Readonly<Record<string, Readonly<Record<string, Expr>>>>;
|
|
365
392
|
/** This method evaluates one cell, and gives the error if there is one. */
|
|
366
393
|
result<N extends keyof Cols & string>(k: Ctx["keys"], column: N): Result<Cols[N]>;
|
|
367
394
|
/** This method evaluates one cell. An error gives `none`. */
|
|
@@ -573,6 +600,21 @@ class ChainImpl {
|
|
|
573
600
|
siblings(body: (c: ChainImpl) => { readonly program: Expr }, opts?: { readonly where?: (c: ChainImpl) => { readonly program: Expr } }): ListChainImpl {
|
|
574
601
|
return this.#axis({ t: "siblings" }, body, opts);
|
|
575
602
|
}
|
|
603
|
+
window(from: number, to: number, body: (c: ChainImpl) => { readonly program: Expr }, opts?: { readonly where?: (c: ChainImpl) => { readonly program: Expr } }): ListChainImpl {
|
|
604
|
+
return this.#axis({ t: "window", from, to }, body, opts);
|
|
605
|
+
}
|
|
606
|
+
table(name: string, body: (c: ChainImpl) => { readonly program: Expr }, opts?: { readonly where?: (c: ChainImpl) => { readonly program: Expr } }): ListChainImpl {
|
|
607
|
+
return this.#axis({ t: "table", name }, body, opts);
|
|
608
|
+
}
|
|
609
|
+
successors(body: (c: ChainImpl) => { readonly program: Expr }, opts?: { readonly where?: (c: ChainImpl) => { readonly program: Expr } }): ListChainImpl {
|
|
610
|
+
return this.#axis({ t: "successors" }, body, opts);
|
|
611
|
+
}
|
|
612
|
+
predecessors(body: (c: ChainImpl) => { readonly program: Expr }, opts?: { readonly where?: (c: ChainImpl) => { readonly program: Expr } }): ListChainImpl {
|
|
613
|
+
return this.#axis({ t: "predecessors" }, body, opts);
|
|
614
|
+
}
|
|
615
|
+
reachable(body: (c: ChainImpl) => { readonly program: Expr }, opts?: { readonly where?: (c: ChainImpl) => { readonly program: Expr } }): ListChainImpl {
|
|
616
|
+
return this.#axis({ t: "reachable" }, body, opts);
|
|
617
|
+
}
|
|
576
618
|
}
|
|
577
619
|
|
|
578
620
|
/** This function gives the options of an evaluation of a chain or a list chain at the origin `k`. */
|
|
@@ -704,25 +746,36 @@ class SheetRootImpl extends RootImpl {
|
|
|
704
746
|
class SheetImpl {
|
|
705
747
|
readonly #env: Env;
|
|
706
748
|
readonly #columns: ReadonlyMap<string, Expr>;
|
|
707
|
-
|
|
749
|
+
readonly #cells: CellFormulas;
|
|
750
|
+
constructor(env: Env, columns: ReadonlyMap<string, Expr>, cells: CellFormulas = new Map()) {
|
|
708
751
|
this.#env = env;
|
|
709
752
|
this.#columns = columns;
|
|
753
|
+
this.#cells = cells;
|
|
710
754
|
}
|
|
711
755
|
get columns(): Readonly<Record<string, Expr>> {
|
|
712
756
|
return Object.freeze(Object.fromEntries(this.#columns));
|
|
713
757
|
}
|
|
758
|
+
get cellFormulas(): Readonly<Record<string, Readonly<Record<string, Expr>>>> {
|
|
759
|
+
return Object.freeze(Object.fromEntries([...this.#cells].map(([c, keys]) => [c, Object.freeze(Object.fromEntries(keys))])));
|
|
760
|
+
}
|
|
714
761
|
declare(): SheetImpl {
|
|
715
762
|
return this;
|
|
716
763
|
}
|
|
717
764
|
column(name: string, formula: (r: SheetRootImpl) => { readonly program: Expr }): SheetImpl {
|
|
718
765
|
const program = formula(new SheetRootImpl(this.#env)).program;
|
|
719
|
-
return new SheetImpl(this.#env, new Map([...this.#columns, [name, program]]));
|
|
766
|
+
return new SheetImpl(this.#env, new Map([...this.#columns, [name, program]]), this.#cells);
|
|
767
|
+
}
|
|
768
|
+
cellFormula(k: string, column: string, formula: (r: SheetRootImpl) => { readonly program: Expr }): SheetImpl {
|
|
769
|
+
const program = formula(new SheetRootImpl(this.#env)).program;
|
|
770
|
+
const keys = new Map([...(this.#cells.get(column) ?? []), [k, program]]);
|
|
771
|
+
return new SheetImpl(this.#env, this.#columns, new Map([...this.#cells, [column, keys]]));
|
|
720
772
|
}
|
|
721
773
|
#run(): SheetRun {
|
|
722
774
|
const { space: s, domains, options } = this.#env;
|
|
723
775
|
return new SheetRun(this.#columns, {
|
|
724
776
|
space: s,
|
|
725
777
|
domains,
|
|
778
|
+
cells: this.#cells,
|
|
726
779
|
// Stryker disable next-line ConditionalExpression: an undefined option and an absent option are the same
|
|
727
780
|
...(options.fns === undefined ? {} : { fns: options.fns }),
|
|
728
781
|
// Stryker disable next-line ConditionalExpression: an undefined option and an absent option are the same
|
package/src/errors.ts
CHANGED
|
@@ -12,6 +12,8 @@ export type ErrorKind =
|
|
|
12
12
|
| "no-offset"
|
|
13
13
|
| "no-grid"
|
|
14
14
|
| "no-tree"
|
|
15
|
+
| "no-table"
|
|
16
|
+
| "no-graph"
|
|
15
17
|
| "missing-field"
|
|
16
18
|
| "empty"
|
|
17
19
|
| "not-instance"
|
|
@@ -34,6 +36,8 @@ const CODE_OF: Readonly<Record<ErrorKind, ErrorCode>> = {
|
|
|
34
36
|
"no-offset": "#REF!",
|
|
35
37
|
"no-grid": "#REF!",
|
|
36
38
|
"no-tree": "#REF!",
|
|
39
|
+
"no-table": "#REF!",
|
|
40
|
+
"no-graph": "#REF!",
|
|
37
41
|
"missing-field": "#N/A",
|
|
38
42
|
empty: "#N/A",
|
|
39
43
|
"not-instance": "#VALUE!",
|
package/src/evaluate.ts
CHANGED
|
@@ -33,6 +33,8 @@ export interface EvalOptions {
|
|
|
33
33
|
readonly extensions?: Readonly<Record<string, ExtHandler>>;
|
|
34
34
|
/** Variables that the program can read with `v(name)`. */
|
|
35
35
|
readonly vars?: Readonly<Record<string, unknown>>;
|
|
36
|
+
/** The other spaces of the evaluation, by name. The axis `table(name)` reads them. */
|
|
37
|
+
readonly tables?: Readonly<Record<string, Space>>;
|
|
36
38
|
/** A receiver of trace events. */
|
|
37
39
|
readonly trace?: TraceSink;
|
|
38
40
|
}
|
|
@@ -56,7 +58,7 @@ const isSpecialForm = (op: string): op is SpecialForm => SPECIAL_FORMS.has(op);
|
|
|
56
58
|
export type CompileOptions = Pick<EvalOptions, "domains" | "fns" | "extensions">;
|
|
57
59
|
|
|
58
60
|
/** The options of one run of a compiled program. */
|
|
59
|
-
export type RunOptions = Pick<EvalOptions, "space" | "origin" | "vars" | "trace">;
|
|
61
|
+
export type RunOptions = Pick<EvalOptions, "space" | "origin" | "vars" | "trace" | "tables">;
|
|
60
62
|
|
|
61
63
|
/**
|
|
62
64
|
* A compiled program: the expression as a tree of functions. A program evaluates many times at different origins,
|
|
@@ -104,7 +106,7 @@ export function compile(expr: Expr, opts: CompileOptions = {}): Program {
|
|
|
104
106
|
if (!space.has(origin)) return fail(vexError("unknown-key", `the space has no key "${origin}"`, { origin, focus: origin }));
|
|
105
107
|
const env = new Map<string, Result<unknown>>(Object.entries(r.vars ?? {}).map(([k, val]) => [k, ok(val)]));
|
|
106
108
|
try {
|
|
107
|
-
return root({ pos: { origin, focus: origin }, env }, { space, trace: r.trace });
|
|
109
|
+
return root({ pos: { origin, focus: origin }, env }, { space, trace: r.trace, tables: r.tables });
|
|
108
110
|
} catch (thrown) {
|
|
109
111
|
// A defect in an extension handler or in a test of the interpreter itself. Totality still holds.
|
|
110
112
|
if (isStackOverflow(thrown)) return fail(vexError("depth", DEPTH_MESSAGE, { origin, focus: origin, thrown }));
|
|
@@ -146,12 +148,16 @@ export function explain(expr: Expr, opts: Omit<EvalOptions, "trace">): Trace {
|
|
|
146
148
|
return compiled(expr, opts).explain(opts);
|
|
147
149
|
}
|
|
148
150
|
|
|
149
|
-
/** The state of one run that the nodes read: the space and the
|
|
151
|
+
/** The state of one run that the nodes read: the space, the trace sink and the other spaces. */
|
|
150
152
|
interface Ctx {
|
|
151
153
|
readonly space: Space;
|
|
152
154
|
readonly trace: TraceSink | undefined;
|
|
155
|
+
readonly tables: Readonly<Record<string, Space>> | undefined;
|
|
153
156
|
}
|
|
154
157
|
|
|
158
|
+
/** This function gives the axis inside the `where` axes of an axis. */
|
|
159
|
+
const baseAxis = (a: Axis): Exclude<Axis, { readonly t: "where" }> => (a.t === "where" ? baseAxis(a.axis) : a);
|
|
160
|
+
|
|
155
161
|
/** A compiled node: it evaluates in a frame of a run. */
|
|
156
162
|
type Node = (f: Frame, c: Ctx) => Result<unknown>;
|
|
157
163
|
|
|
@@ -332,11 +338,20 @@ class Compiler {
|
|
|
332
338
|
if (!where.ok) return this.#emit(c, info, f, fail({ ...where.error, path }));
|
|
333
339
|
from = { pos: { origin: f.pos.origin, focus: where.value }, env: f.env };
|
|
334
340
|
}
|
|
335
|
-
|
|
341
|
+
// The axis table moves the evaluation to the space of its table, where the origin of this space is not a key.
|
|
342
|
+
// Thus there the origin is the target, and a value of this space goes in through a variable.
|
|
343
|
+
const base = baseAxis(e.axis);
|
|
344
|
+
let inner = c;
|
|
345
|
+
if (base.t === "table") {
|
|
346
|
+
const space = c.tables !== undefined && Object.hasOwn(c.tables, base.name) ? c.tables[base.name] : undefined;
|
|
347
|
+
if (space === undefined) return this.#emit(c, info, f, this.#err("no-table", `the evaluation has no table "${base.name}"`, f, path));
|
|
348
|
+
inner = { ...c, space };
|
|
349
|
+
}
|
|
350
|
+
const ts = targets(from, inner);
|
|
336
351
|
if (!ts.ok) return this.#emit(c, info, f, ts);
|
|
337
352
|
const items: ListItem[] = ts.value.map(({ key, test }) => {
|
|
338
353
|
if (test !== undefined && !test.ok) return { key, result: test };
|
|
339
|
-
return { key, result: body({ pos: { origin: f.pos.origin, focus: key }, env: f.env },
|
|
354
|
+
return { key, result: body({ pos: { origin: base.t === "table" ? key : f.pos.origin, focus: key }, env: f.env }, inner) };
|
|
340
355
|
});
|
|
341
356
|
return this.#emit(c, info, f, ok(vexList(items)));
|
|
342
357
|
};
|
|
@@ -344,6 +359,7 @@ class Compiler {
|
|
|
344
359
|
|
|
345
360
|
/** This method compiles the targets of an axis. For `where`, a failed test keeps the target with its error. */
|
|
346
361
|
#targets(a: Axis, path: readonly number[], counter: { next: number }): (f: Frame, c: Ctx) => Result<readonly { readonly key: string; readonly test?: Result<unknown> }[]> {
|
|
362
|
+
if (a.t === "table") return (_f, c) => ok(c.space.keys.map((key) => ({ key })));
|
|
347
363
|
if (a.t !== "where") {
|
|
348
364
|
return (f, c) => {
|
|
349
365
|
const keys = axisTargets(c.space, f.pos, a);
|
|
@@ -353,6 +369,8 @@ class Compiler {
|
|
|
353
369
|
const inner = this.#targets(a.axis, path, counter);
|
|
354
370
|
const testPath = [...path, counter.next++];
|
|
355
371
|
const test = this.node(a.test, testPath);
|
|
372
|
+
// In the space of the axis table, the origin of the test is the target, as for the body.
|
|
373
|
+
const sameOrigin = baseAxis(a).t === "table";
|
|
356
374
|
return (f, c) => {
|
|
357
375
|
const ts = inner(f, c);
|
|
358
376
|
if (!ts.ok) return ts;
|
|
@@ -362,7 +380,7 @@ class Compiler {
|
|
|
362
380
|
out.push(t);
|
|
363
381
|
continue;
|
|
364
382
|
}
|
|
365
|
-
const at: Frame = { pos: { origin: f.pos.origin, focus: t.key }, env: f.env };
|
|
383
|
+
const at: Frame = { pos: { origin: sameOrigin ? t.key : f.pos.origin, focus: t.key }, env: f.env };
|
|
366
384
|
const r = test(at, c);
|
|
367
385
|
if (!r.ok) out.push({ key: t.key, test: r });
|
|
368
386
|
else if (r.value === true) out.push({ key: t.key });
|
package/src/ir.ts
CHANGED
|
@@ -25,6 +25,11 @@ export type Axis =
|
|
|
25
25
|
| { readonly t: "ancestors" }
|
|
26
26
|
| { readonly t: "descendants" }
|
|
27
27
|
| { readonly t: "siblings" }
|
|
28
|
+
| { readonly t: "window"; readonly from: number; readonly to: number }
|
|
29
|
+
| { readonly t: "table"; readonly name: string }
|
|
30
|
+
| { readonly t: "successors" }
|
|
31
|
+
| { readonly t: "predecessors" }
|
|
32
|
+
| { readonly t: "reachable" }
|
|
28
33
|
| { readonly t: "where"; readonly axis: Axis; readonly test: Expr };
|
|
29
34
|
|
|
30
35
|
/** A Vex expression. */
|
|
@@ -115,6 +120,22 @@ export const axes = {
|
|
|
115
120
|
descendants: Object.freeze({ t: "descendants" }) as Axis,
|
|
116
121
|
/** The other children of the parent of the focus. For a root, the other roots. */
|
|
117
122
|
siblings: Object.freeze({ t: "siblings" }) as Axis,
|
|
123
|
+
/**
|
|
124
|
+
* The keys at the offsets from `from` to `to` of the focus, in order: a window of rows. The offset 0 is the focus. In
|
|
125
|
+
* a tree space, the offsets go among the siblings. An offset outside the space has no target.
|
|
126
|
+
*/
|
|
127
|
+
window: (from: number, to: number): Axis => ({ t: "window", from, to }),
|
|
128
|
+
/**
|
|
129
|
+
* Each key of the table `name` of the evaluation, in key order. The body evaluates in the space of that table, and
|
|
130
|
+
* there the origin is the target.
|
|
131
|
+
*/
|
|
132
|
+
table: (name: string): Axis => ({ t: "table", name }),
|
|
133
|
+
/** The keys at the ends of the edges from the focus, in a graph space. In a tree space, the children. */
|
|
134
|
+
successors: Object.freeze({ t: "successors" }) as Axis,
|
|
135
|
+
/** The keys with an edge to the focus, in key order. In a tree space, the parent. */
|
|
136
|
+
predecessors: Object.freeze({ t: "predecessors" }) as Axis,
|
|
137
|
+
/** Each key that a path of edges reaches from the focus, in breadth-first order, without the focus. */
|
|
138
|
+
reachable: Object.freeze({ t: "reachable" }) as Axis,
|
|
118
139
|
/** The targets of `axis` where `test` gives `true`. */
|
|
119
140
|
where: (axis: Axis, test: Expr): Axis => ({ t: "where", axis, test }),
|
|
120
141
|
} as const;
|
|
@@ -171,10 +192,14 @@ function validTree(todo: { readonly axis: boolean; readonly u: unknown }[]): boo
|
|
|
171
192
|
const t = u["t"];
|
|
172
193
|
if (t === "neighbors") {
|
|
173
194
|
if (u["n"] !== 4 && u["n"] !== 8) return false;
|
|
195
|
+
} else if (t === "window") {
|
|
196
|
+
if (!Number.isSafeInteger(u["from"]) || !Number.isSafeInteger(u["to"])) return false;
|
|
197
|
+
} else if (t === "table") {
|
|
198
|
+
if (typeof u["name"] !== "string") return false;
|
|
174
199
|
} else if (t === "where") {
|
|
175
200
|
push(true, [u["axis"]]);
|
|
176
201
|
push(false, [u["test"]]);
|
|
177
|
-
} else if (!["all", "others", "other", "children", "ancestors", "descendants", "siblings"].includes(t as string)) {
|
|
202
|
+
} else if (!["all", "others", "other", "children", "ancestors", "descendants", "siblings", "successors", "predecessors", "reachable"].includes(t as string)) {
|
|
178
203
|
return false;
|
|
179
204
|
}
|
|
180
205
|
continue;
|
package/src/sheet.ts
CHANGED
|
@@ -5,12 +5,15 @@
|
|
|
5
5
|
*
|
|
6
6
|
* A cell reference is the extension node `ext("vex.cell", { column, at })`. Thus the IR has no new kind, and the
|
|
7
7
|
* JSON form, `deps` and the traces work without a change.
|
|
8
|
+
*
|
|
9
|
+
* A cell can have its own formula. That formula replaces the formula of the column at the key of the cell. A
|
|
10
|
+
* spreadsheet has the same thing: a cell with a formula that is different from the other formulas of its column.
|
|
8
11
|
*/
|
|
9
12
|
import { vexError } from "./errors.ts";
|
|
10
13
|
import { evaluate, explain, nestingOf, type EvalOptions, type ExtHandler } from "./evaluate.ts";
|
|
11
14
|
import { ext, isMove, type Addr, type Expr } from "./ir.ts";
|
|
12
15
|
import { fail, type Result } from "./result.ts";
|
|
13
|
-
import { resolveAddr } from "./space.ts";
|
|
16
|
+
import { resolveAddr, type Space } from "./space.ts";
|
|
14
17
|
import type { Trace } from "./trace.ts";
|
|
15
18
|
|
|
16
19
|
/** The extension kind of a cell reference. */
|
|
@@ -32,18 +35,54 @@ const isCellRef = (u: unknown): u is CellRef =>
|
|
|
32
35
|
Array.isArray((u as { at?: unknown }).at) &&
|
|
33
36
|
(u as { at: readonly unknown[] }).at.every(isMove);
|
|
34
37
|
|
|
35
|
-
/** The
|
|
36
|
-
export type
|
|
38
|
+
/** The formulas of single cells: for each column, the formula of each key that has its own formula. */
|
|
39
|
+
export type CellFormulas = ReadonlyMap<string, ReadonlyMap<string, Expr>>;
|
|
40
|
+
|
|
41
|
+
/** A table of a run: its space, the formulas of its columns, and the formulas of its cells. */
|
|
42
|
+
export interface SheetTable {
|
|
43
|
+
readonly space: Space;
|
|
44
|
+
readonly columns: ReadonlyMap<string, Expr>;
|
|
45
|
+
readonly cells?: CellFormulas;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** The options of a sheet run: the evaluation options without the origin and the trace, and the tables. */
|
|
49
|
+
export type SheetOptions = Omit<EvalOptions, "origin" | "trace" | "tables"> & {
|
|
50
|
+
/** The cells with their own formula. The formula of a cell replaces the formula of its column at its key. */
|
|
51
|
+
readonly cells?: CellFormulas;
|
|
52
|
+
/** The name of this table, so the axis `table(name)` in a formula of another table can read it. */
|
|
53
|
+
readonly name?: string;
|
|
54
|
+
/** The other tables, by name (SHEET.TABLES). A cell reference reads the table of the space where it evaluates. */
|
|
55
|
+
readonly tables?: ReadonlyMap<string, SheetTable>;
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
/** The state of one table in a run. */
|
|
59
|
+
interface Table {
|
|
60
|
+
/** The words for the table in a message: "the sheet" for the main table, or the table and its name. */
|
|
61
|
+
readonly where: string;
|
|
62
|
+
/** A short text for the ids of the cells of the table. */
|
|
63
|
+
readonly tag: string;
|
|
64
|
+
readonly space: Space;
|
|
65
|
+
readonly columns: ReadonlyMap<string, Expr>;
|
|
66
|
+
readonly cells: CellFormulas;
|
|
67
|
+
// For each column, the number of keys at the start of the key order that a warm-up evaluated.
|
|
68
|
+
readonly warmed: Map<string, number>;
|
|
69
|
+
// The position of each key in the key order, made at the first warm-up.
|
|
70
|
+
index: ReadonlyMap<string, number> | undefined;
|
|
71
|
+
}
|
|
37
72
|
|
|
38
73
|
const cycleError = (column: string, key: string): Result<never> =>
|
|
39
74
|
fail(vexError("cycle", `the cell "${column}" at "${key}" is on a cycle of cell references`, { origin: key, focus: key }));
|
|
40
75
|
|
|
41
76
|
/** The id of a cell. */
|
|
42
|
-
const idOf = (column: string, key: string): string => `${column}\u0000${key}`;
|
|
77
|
+
const idOf = (t: Table, column: string, key: string): string => `${t.tag}\u0001${column}\u0000${key}`;
|
|
78
|
+
|
|
79
|
+
/** This function gives the state of a table at the start of a run. */
|
|
80
|
+
const tableState = (where: string, i: number, t: SheetTable): Table => ({ where, tag: String(i), space: t.space, columns: t.columns, cells: t.cells ?? new Map(), warmed: new Map(), index: undefined });
|
|
43
81
|
|
|
44
82
|
/** The state of one cell in the search. */
|
|
45
83
|
interface Visit {
|
|
46
84
|
readonly id: string;
|
|
85
|
+
readonly table: Table;
|
|
47
86
|
readonly column: string;
|
|
48
87
|
readonly key: string;
|
|
49
88
|
readonly index: number;
|
|
@@ -76,78 +115,119 @@ const STACK_BUDGET = 3000;
|
|
|
76
115
|
* cell, and the cell that reads it pauses. A paused evaluation reads no other cell and changes no state of the
|
|
77
116
|
* search. The run then evaluates the started cell from its own list, and it evaluates the paused cell again after
|
|
78
117
|
* that cell. A formula is pure (EVAL.PURE), so the second evaluation gives the result of one evaluation.
|
|
118
|
+
*
|
|
119
|
+
* A run can have more tables (SHEET.TABLES). Each table has its own space, and one search covers the cells of all
|
|
120
|
+
* the tables. Thus a cycle across tables gives `#CYCLE!` too.
|
|
79
121
|
*/
|
|
80
122
|
export class SheetRun {
|
|
81
|
-
readonly #
|
|
82
|
-
|
|
123
|
+
readonly #main: Table;
|
|
124
|
+
// The tables by name and by space. A cell reference reads the table of the space where it evaluates.
|
|
125
|
+
readonly #byName = new Map<string, Table>();
|
|
126
|
+
readonly #bySpace = new Map<Space, Table>();
|
|
127
|
+
readonly #opts: Omit<EvalOptions, "origin" | "trace" | "space">;
|
|
83
128
|
readonly #done = new Map<string, Result<unknown>>();
|
|
84
|
-
// For each column, the number of keys at the start of the key order that a warm-up evaluated.
|
|
85
|
-
readonly #warmed = new Map<string, number>();
|
|
86
|
-
// The position of each key in the key order, made at the first warm-up.
|
|
87
|
-
#index: ReadonlyMap<string, number> | undefined;
|
|
88
129
|
// The cells on the stack of the search: started, but their component is not finished.
|
|
89
130
|
readonly #visits = new Map<string, Visit>();
|
|
90
131
|
// Stryker disable next-line ArrayDeclaration: the search never reads below the root of a component
|
|
91
132
|
readonly #stack: Visit[] = [];
|
|
92
133
|
// The cell whose formula is in evaluation. At the top level, it is a placeholder that is not a cell.
|
|
93
|
-
|
|
94
|
-
#top: Visit = { id: "", column: "", key: "", index: -1, low: -1, reread: false, result: cycleError("", ""), paused: false, need: undefined };
|
|
134
|
+
#top: Visit;
|
|
95
135
|
#next = 0;
|
|
96
|
-
// The estimated frames of the stack that the evaluations in progress use, and the cost of
|
|
136
|
+
// The estimated frames of the stack that the evaluations in progress use, and the cost of each program.
|
|
97
137
|
#used = 0;
|
|
98
|
-
readonly #cost = new Map<
|
|
138
|
+
readonly #cost = new Map<Expr, number>();
|
|
99
139
|
readonly #budget: number;
|
|
100
140
|
|
|
101
141
|
/** `budget` is the budget of the stack in estimated frames. A test can make it small, so the run pauses often. */
|
|
102
142
|
constructor(columns: ReadonlyMap<string, Expr>, opts: SheetOptions, budget: number = STACK_BUDGET) {
|
|
103
|
-
|
|
143
|
+
const { cells, name, tables, space, ...rest } = opts;
|
|
144
|
+
this.#main = { where: "the sheet", tag: "0", space, columns, cells: cells ?? new Map(), warmed: new Map(), index: undefined };
|
|
145
|
+
this.#bySpace.set(space, this.#main);
|
|
146
|
+
if (name !== undefined) this.#byName.set(name, this.#main);
|
|
147
|
+
if (tables !== undefined) {
|
|
148
|
+
let i = 0;
|
|
149
|
+
for (const [n, t] of tables) {
|
|
150
|
+
if (this.#byName.has(n)) continue;
|
|
151
|
+
const other = tableState(`the table "${n}"`, ++i, t);
|
|
152
|
+
this.#byName.set(n, other);
|
|
153
|
+
// A table with the space of an earlier table does not take its cells: the first table keeps the space.
|
|
154
|
+
if (!this.#bySpace.has(t.space)) this.#bySpace.set(t.space, other);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
// Stryker disable next-line all: the placeholder is not a cell, so the search reads none of its fields
|
|
158
|
+
this.#top = { id: "", table: this.#main, column: "", key: "", index: -1, low: -1, reread: false, result: cycleError("", ""), paused: false, need: undefined };
|
|
104
159
|
this.#budget = budget;
|
|
105
|
-
|
|
160
|
+
const spaces = Object.fromEntries([...this.#byName].map(([n, t]) => [n, t.space]));
|
|
161
|
+
this.#opts = { ...rest, tables: spaces, extensions: { ...rest.extensions, [CELL_KIND]: this.#handler } };
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** This method gives the program of a cell: its own formula, or the formula of its column (SHEET.CELL.FORMULA). */
|
|
165
|
+
#programOf(t: Table, column: string, key: string): Expr | undefined {
|
|
166
|
+
// Stryker disable next-line ConditionalExpression: without formulas of cells, the lookup gives undefined anyway
|
|
167
|
+
const own = t.cells.size === 0 ? undefined : t.cells.get(column)?.get(key);
|
|
168
|
+
return own ?? t.columns.get(column);
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** This method gives the error of a cell without a program. */
|
|
172
|
+
#unbound(t: Table, column: string, key: string): Result<never> {
|
|
173
|
+
const message = t.cells.has(column) ? `the cell "${column}" at "${key}" has no formula` : `${t.where} has no column "${column}"`;
|
|
174
|
+
return fail(vexError("unbound", message, { origin: key, focus: key }));
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** This method gives the table of a name for a read from a host. Without a name, it is the main table. */
|
|
178
|
+
#named(table: string | undefined, key: string): Table | Result<never> {
|
|
179
|
+
if (table === undefined) return this.#main;
|
|
180
|
+
return this.#byName.get(table) ?? fail(vexError("no-table", `the run has no table "${table}"`, { origin: key, focus: key }));
|
|
106
181
|
}
|
|
107
182
|
|
|
108
183
|
readonly #handler: ExtHandler = (data, ctx) => {
|
|
109
184
|
if (!isCellRef(data)) return fail(vexError("bad-expression", "a cell reference needs a column name and an address", { path: ctx.path }));
|
|
110
185
|
const where = resolveAddr(ctx.space, ctx.position, data.at);
|
|
111
186
|
if (!where.ok) return fail({ ...where.error, path: ctx.path });
|
|
112
|
-
|
|
187
|
+
// The evaluation of a cell has the space of its table, and the body of the axis table has the space of that table.
|
|
188
|
+
/* v8 ignore next -- @preserve: each space of an evaluation of the run is the space of a table */
|
|
189
|
+
return this.#read(this.#bySpace.get(ctx.space) ?? this.#main, data.column, where.value);
|
|
113
190
|
};
|
|
114
191
|
|
|
115
192
|
/**
|
|
116
|
-
* This method gives the result of one cell: the column `column` at the key `key
|
|
117
|
-
* the column at the keys before `key`, in key order. Thus a recurrence
|
|
193
|
+
* This method gives the result of one cell: the column `column` at the key `key` of the main table, or of the table
|
|
194
|
+
* `table`. A read from a host first evaluates the column at the keys before `key`, in key order. Thus a recurrence
|
|
195
|
+
* over the keys reads finished cells.
|
|
118
196
|
*/
|
|
119
|
-
cell(column: string, key: string): Result<unknown> {
|
|
197
|
+
cell(column: string, key: string, table?: string): Result<unknown> {
|
|
198
|
+
const t = this.#named(table, key);
|
|
199
|
+
if (!("space" in t)) return t;
|
|
120
200
|
// The placeholder at the top has the index -1. A read inside a formula has a cell at the top, so it does not warm.
|
|
121
|
-
if (this.#top.index >= 0) return this.#read(column, key);
|
|
122
|
-
this.#warmTo(column, key);
|
|
123
|
-
return this.#drive(column, key);
|
|
201
|
+
if (this.#top.index >= 0) return this.#read(t, column, key);
|
|
202
|
+
this.#warmTo(t, column, key);
|
|
203
|
+
return this.#drive(t, column, key);
|
|
124
204
|
}
|
|
125
205
|
|
|
126
206
|
/** This method evaluates the column `column` at each key before `key` that it did not evaluate before, in key order. */
|
|
127
|
-
#warmTo(column: string, key: string): void {
|
|
128
|
-
if (!
|
|
129
|
-
const keys =
|
|
130
|
-
|
|
131
|
-
const end =
|
|
132
|
-
const start =
|
|
133
|
-
for (let i = start; i < end; i++) this.#drive(column, keys[i] ?? key);
|
|
134
|
-
if (end > start)
|
|
207
|
+
#warmTo(t: Table, column: string, key: string): void {
|
|
208
|
+
if (!t.columns.has(column)) return;
|
|
209
|
+
const keys = t.space.keys;
|
|
210
|
+
t.index ??= new Map(keys.map((k, i) => [k, i]));
|
|
211
|
+
const end = t.index.get(key) ?? 0;
|
|
212
|
+
const start = t.warmed.get(column) ?? 0;
|
|
213
|
+
for (let i = start; i < end; i++) this.#drive(t, column, keys[i] ?? key);
|
|
214
|
+
if (end > start) t.warmed.set(column, end);
|
|
135
215
|
}
|
|
136
216
|
|
|
137
|
-
/** This method gives the estimated frames of the stack that one evaluation of
|
|
138
|
-
#costOf(
|
|
139
|
-
let cost = this.#cost.get(
|
|
217
|
+
/** This method gives the estimated frames of the stack that one evaluation of the program `program` uses. */
|
|
218
|
+
#costOf(program: Expr): number {
|
|
219
|
+
let cost = this.#cost.get(program);
|
|
140
220
|
if (cost === undefined) {
|
|
141
221
|
cost = 3 * nestingOf(program) + 16;
|
|
142
|
-
this.#cost.set(
|
|
222
|
+
this.#cost.set(program, cost);
|
|
143
223
|
}
|
|
144
224
|
return cost;
|
|
145
225
|
}
|
|
146
226
|
|
|
147
227
|
/** This method puts a new cell on the stack of the search. */
|
|
148
|
-
#start(column: string, key: string): Visit {
|
|
228
|
+
#start(t: Table, column: string, key: string): Visit {
|
|
149
229
|
const n = this.#next++;
|
|
150
|
-
const visit: Visit = { id: idOf(column, key), column, key, index: n, low: n, reread: false, result: cycleError(column, key), paused: false, need: undefined };
|
|
230
|
+
const visit: Visit = { id: idOf(t, column, key), table: t, column, key, index: n, low: n, reread: false, result: cycleError(column, key), paused: false, need: undefined };
|
|
151
231
|
this.#visits.set(visit.id, visit);
|
|
152
232
|
this.#stack.push(visit);
|
|
153
233
|
return visit;
|
|
@@ -156,12 +236,12 @@ export class SheetRun {
|
|
|
156
236
|
/** This method evaluates the formula of a cell once. When the evaluation pauses, the result of the cell does not change. */
|
|
157
237
|
#evaluate(visit: Visit, program: Expr): void {
|
|
158
238
|
const caller = this.#top;
|
|
159
|
-
const cost = this.#costOf(
|
|
239
|
+
const cost = this.#costOf(program);
|
|
160
240
|
visit.paused = false;
|
|
161
241
|
visit.need = undefined;
|
|
162
242
|
this.#top = visit;
|
|
163
243
|
this.#used += cost;
|
|
164
|
-
const result = evaluate(program, { ...this.#opts, origin: visit.key });
|
|
244
|
+
const result = evaluate(program, { ...this.#opts, space: visit.table.space, origin: visit.key });
|
|
165
245
|
this.#used -= cost;
|
|
166
246
|
this.#top = caller;
|
|
167
247
|
if (!visit.paused) visit.result = result;
|
|
@@ -174,8 +254,8 @@ export class SheetRun {
|
|
|
174
254
|
}
|
|
175
255
|
|
|
176
256
|
/** This method reads a cell from the formula of the cell at the top. */
|
|
177
|
-
#read(column: string, key: string): Result<unknown> {
|
|
178
|
-
const id = idOf(column, key);
|
|
257
|
+
#read(t: Table, column: string, key: string): Result<unknown> {
|
|
258
|
+
const id = idOf(t, column, key);
|
|
179
259
|
const done = this.#done.get(id);
|
|
180
260
|
if (done !== undefined) return done;
|
|
181
261
|
const caller = this.#top;
|
|
@@ -190,10 +270,10 @@ export class SheetRun {
|
|
|
190
270
|
seen.reread = true;
|
|
191
271
|
return cycleError(column, key);
|
|
192
272
|
}
|
|
193
|
-
const program = this.#
|
|
194
|
-
if (program === undefined) return
|
|
195
|
-
const visit = this.#start(column, key);
|
|
196
|
-
if (this.#used + this.#costOf(
|
|
273
|
+
const program = this.#programOf(t, column, key);
|
|
274
|
+
if (program === undefined) return this.#unbound(t, column, key);
|
|
275
|
+
const visit = this.#start(t, column, key);
|
|
276
|
+
if (this.#used + this.#costOf(program) > this.#budget) {
|
|
197
277
|
// Over the budget: the caller pauses, and the run evaluates the new cell from its own list.
|
|
198
278
|
caller.paused = true;
|
|
199
279
|
caller.need = visit;
|
|
@@ -210,15 +290,15 @@ export class SheetRun {
|
|
|
210
290
|
}
|
|
211
291
|
|
|
212
292
|
/** This method evaluates a cell from the top level. The cells that pause go on a list, not on the call stack. */
|
|
213
|
-
#drive(column: string, key: string): Result<unknown> {
|
|
214
|
-
const id = idOf(column, key);
|
|
293
|
+
#drive(t: Table, column: string, key: string): Result<unknown> {
|
|
294
|
+
const id = idOf(t, column, key);
|
|
215
295
|
const done = this.#done.get(id);
|
|
216
296
|
if (done !== undefined) return done;
|
|
217
|
-
if (
|
|
218
|
-
const work: Visit[] = [this.#start(column, key)];
|
|
297
|
+
if (this.#programOf(t, column, key) === undefined) return this.#unbound(t, column, key);
|
|
298
|
+
const work: Visit[] = [this.#start(t, column, key)];
|
|
219
299
|
for (let visit = work.at(-1); visit !== undefined; visit = work.at(-1)) {
|
|
220
|
-
const program = this.#
|
|
221
|
-
/* v8 ignore next -- @preserve: a visit exists only for a
|
|
300
|
+
const program = this.#programOf(visit.table, visit.column, visit.key);
|
|
301
|
+
/* v8 ignore next -- @preserve: a visit exists only for a cell with a program */
|
|
222
302
|
if (program === undefined) break;
|
|
223
303
|
this.#evaluate(visit, program);
|
|
224
304
|
if (visit.paused) {
|
|
@@ -246,19 +326,22 @@ export class SheetRun {
|
|
|
246
326
|
}
|
|
247
327
|
}
|
|
248
328
|
|
|
249
|
-
/** This method evaluates one cell with a trace of the nodes of its
|
|
250
|
-
explain(column: string, key: string): Trace {
|
|
251
|
-
const result = this.cell(column, key);
|
|
252
|
-
const
|
|
253
|
-
|
|
254
|
-
|
|
329
|
+
/** This method evaluates one cell with a trace of the nodes of its program. The result is the result of the cell. */
|
|
330
|
+
explain(column: string, key: string, table?: string): Trace {
|
|
331
|
+
const result = this.cell(column, key, table);
|
|
332
|
+
const t = this.#named(table, key);
|
|
333
|
+
const program = "space" in t ? this.#programOf(t, column, key) : undefined;
|
|
334
|
+
if (program === undefined || !("space" in t)) return { events: [], result };
|
|
335
|
+
return { events: explain(program, { ...this.#opts, space: t.space, origin: key }).events, result };
|
|
255
336
|
}
|
|
256
337
|
|
|
257
338
|
/**
|
|
258
339
|
* This method evaluates the column `column` at each key before `key`, in key order. A recurrence over the keys,
|
|
259
340
|
* for example a running total, then reads finished cells.
|
|
260
341
|
*/
|
|
261
|
-
warm(column: string, key: string): void {
|
|
262
|
-
this.#
|
|
342
|
+
warm(column: string, key: string, table?: string): void {
|
|
343
|
+
const t = this.#named(table, key);
|
|
344
|
+
// Stryker disable next-line all: a warm-up changes no result, only the depth of the recursion (SHEET.ORDER)
|
|
345
|
+
if ("space" in t) this.#warmTo(t, column, key);
|
|
263
346
|
}
|
|
264
347
|
}
|