@mark1russell7/vex 0.6.0 → 0.8.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/README.md +1 -0
- package/build/index.d.ts +244 -33
- package/build/index.d.ts.map +1 -1
- package/build/index.js +1093 -122
- package/build/index.js.map +1 -1
- package/package.json +1 -1
- package/src/builder.ts +222 -28
- package/src/deps.ts +57 -8
- package/src/domain.ts +22 -0
- package/src/errors.ts +3 -1
- package/src/evaluate.ts +275 -20
- package/src/ir.ts +238 -51
- package/src/json.ts +44 -2
- package/src/list.ts +3 -3
- package/src/sheet.ts +259 -21
- package/src/space.ts +52 -11
package/src/sheet.ts
CHANGED
|
@@ -10,8 +10,8 @@
|
|
|
10
10
|
* spreadsheet has the same thing: a cell with a formula that is different from the other formulas of its column.
|
|
11
11
|
*/
|
|
12
12
|
import { vexError } from "./errors.ts";
|
|
13
|
-
import { evaluate, explain, nestingOf, type EvalOptions, type ExtHandler } from "./evaluate.ts";
|
|
14
|
-
import { ext, isMove, type
|
|
13
|
+
import { evaluate, explain, nestingOf, type CompileOptions, type EvalOptions, type ExtHandler, type Program } from "./evaluate.ts";
|
|
14
|
+
import { addrExprs, children, ext, isMove, listOf, moveExpr, shapeError, type Axis, type Expr, type FixedMove, type Move } from "./ir.ts";
|
|
15
15
|
import { fail, type Result } from "./result.ts";
|
|
16
16
|
import { resolveAddr, type Space } from "./space.ts";
|
|
17
17
|
import type { Trace } from "./trace.ts";
|
|
@@ -19,21 +19,24 @@ import type { Trace } from "./trace.ts";
|
|
|
19
19
|
/** The extension kind of a cell reference. */
|
|
20
20
|
export const CELL_KIND = "vex.cell";
|
|
21
21
|
|
|
22
|
-
/**
|
|
22
|
+
/**
|
|
23
|
+
* The data of a cell reference: the column, and the address from the focus. The data of an extension is not an
|
|
24
|
+
* expression, so the address has only fixed moves.
|
|
25
|
+
*/
|
|
23
26
|
export interface CellRef {
|
|
24
27
|
readonly column: string;
|
|
25
|
-
readonly at:
|
|
28
|
+
readonly at: readonly FixedMove[];
|
|
26
29
|
}
|
|
27
30
|
|
|
28
31
|
/** This function makes a cell reference: the column `column` at the address `at` from the focus. */
|
|
29
|
-
export const cell = (column: string, at:
|
|
32
|
+
export const cell = (column: string, at: readonly FixedMove[] = []): Expr => ext(CELL_KIND, { column, at } satisfies CellRef);
|
|
30
33
|
|
|
31
34
|
const isCellRef = (u: unknown): u is CellRef =>
|
|
32
35
|
typeof u === "object" &&
|
|
33
36
|
u !== null &&
|
|
34
37
|
typeof (u as { column?: unknown }).column === "string" &&
|
|
35
38
|
Array.isArray((u as { at?: unknown }).at) &&
|
|
36
|
-
(u as { at: readonly unknown[] }).at.every(isMove);
|
|
39
|
+
(u as { at: readonly unknown[] }).at.every((m) => isMove(m) && moveExpr(m) === undefined);
|
|
37
40
|
|
|
38
41
|
/** The formulas of single cells: for each column, the formula of each key that has its own formula. */
|
|
39
42
|
export type CellFormulas = ReadonlyMap<string, ReadonlyMap<string, Expr>>;
|
|
@@ -53,8 +56,26 @@ export type SheetOptions = Omit<EvalOptions, "origin" | "trace" | "tables"> & {
|
|
|
53
56
|
readonly name?: string;
|
|
54
57
|
/** The other tables, by name (SHEET.TABLES). A cell reference reads the table of the space where it evaluates. */
|
|
55
58
|
readonly tables?: ReadonlyMap<string, SheetTable>;
|
|
59
|
+
/**
|
|
60
|
+
* The compiler of the formulas of the columns (SHEET.COMPILE), for example `tiered` of `@mark1russell7/vex-compiler`.
|
|
61
|
+
* Without a compiler, the interpreter evaluates each formula. The compiled program must give the results of the
|
|
62
|
+
* interpreter.
|
|
63
|
+
*/
|
|
64
|
+
readonly compile?: CompileFn;
|
|
56
65
|
};
|
|
57
66
|
|
|
67
|
+
/** A compiler of the formulas of the columns of a run. */
|
|
68
|
+
export type CompileFn = (expr: Expr, options: CompileOptions) => Program;
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* The compiled programs of the formulas of the columns: one entry for each formula, for the last compiler and options.
|
|
72
|
+
* A compiled program reads the cells of the active run, so each run with the same compiler and options can use it.
|
|
73
|
+
*/
|
|
74
|
+
const PROGRAMS = new WeakMap<Expr, { readonly compile: CompileFn; readonly domains: unknown; readonly fns: unknown; readonly extensions: unknown; readonly program: Program }>();
|
|
75
|
+
|
|
76
|
+
/** The key of the options without extensions, for the extensions of the compiled programs. */
|
|
77
|
+
const NO_EXTENSIONS = {};
|
|
78
|
+
|
|
58
79
|
/** The state of one table in a run. */
|
|
59
80
|
interface Table {
|
|
60
81
|
/** The words for the table in a message: "the sheet" for the main table, or the table and its name. */
|
|
@@ -68,6 +89,8 @@ interface Table {
|
|
|
68
89
|
readonly warmed: Map<string, number>;
|
|
69
90
|
// The position of each key in the key order, made at the first warm-up.
|
|
70
91
|
index: ReadonlyMap<string, number> | undefined;
|
|
92
|
+
/** The result of each finished cell: for each column, the result at each key. */
|
|
93
|
+
readonly done: Map<string, Map<string, Result<unknown>>>;
|
|
71
94
|
}
|
|
72
95
|
|
|
73
96
|
const cycleError = (column: string, key: string): Result<never> =>
|
|
@@ -77,7 +100,135 @@ const cycleError = (column: string, key: string): Result<never> =>
|
|
|
77
100
|
const idOf = (t: Table, column: string, key: string): string => `${t.tag}\u0001${column}\u0000${key}`;
|
|
78
101
|
|
|
79
102
|
/** 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 });
|
|
103
|
+
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, done: new Map() });
|
|
104
|
+
|
|
105
|
+
/** This function gives the result of a finished cell, or `undefined`. */
|
|
106
|
+
const doneOf = (t: Table, column: string, key: string): Result<unknown> | undefined => t.done.get(column)?.get(key);
|
|
107
|
+
|
|
108
|
+
/** This function keeps the result of a finished cell. */
|
|
109
|
+
function setDone(t: Table, column: string, key: string, result: Result<unknown>): void {
|
|
110
|
+
let results = t.done.get(column);
|
|
111
|
+
if (results === undefined) {
|
|
112
|
+
results = new Map();
|
|
113
|
+
t.done.set(column, results);
|
|
114
|
+
}
|
|
115
|
+
results.set(key, result);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** A direction of the reads of a column from itself: to an earlier key, to a later key, or down a tree to the children. */
|
|
119
|
+
type Direction = "before" | "after" | "down";
|
|
120
|
+
|
|
121
|
+
/** This function adds the direction of one move or one axis of a read of a column from itself. */
|
|
122
|
+
function addDirection(d: Set<Direction>, m: Move | Axis): void {
|
|
123
|
+
// The reverse order reads the same keys as its axis.
|
|
124
|
+
if (m.t === "reverse") {
|
|
125
|
+
addDirection(d, m.axis);
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
if (m.t === "offset" || m.t === "window") {
|
|
129
|
+
// An offset moves by its first step that is not 0. A window reads the keys from `from` to `to`.
|
|
130
|
+
const steps = m.t === "offset" ? [m.d.find((x) => x !== 0) ?? 0] : [m.from, m.to];
|
|
131
|
+
// A step of 0 reads the cell itself, which is a cycle in each order.
|
|
132
|
+
// Stryker disable next-line EqualityOperator: see the comment above
|
|
133
|
+
if (steps.some((x) => x < 0)) d.add("before");
|
|
134
|
+
// Stryker disable next-line EqualityOperator: see the comment above
|
|
135
|
+
if (steps.some((x) => x > 0)) d.add("after");
|
|
136
|
+
} else if (m.t === "children" || m.t === "descendants") d.add("down");
|
|
137
|
+
// The items of a list can be at each key, so the axis list gives no direction, and the other reads decide the order.
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** This function gives the base axis of an axis, and the tests of its `where` axes. */
|
|
141
|
+
function partsOf(axis: Axis): { readonly base: Axis; readonly tests: readonly Expr[] } {
|
|
142
|
+
const tests: Expr[] = [];
|
|
143
|
+
let base = axis;
|
|
144
|
+
while (base.t === "where") {
|
|
145
|
+
tests.push(base.test);
|
|
146
|
+
base = base.axis;
|
|
147
|
+
}
|
|
148
|
+
return { base, tests };
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* This function gives the columns that the formulas of the column `self` read with a cell reference: its formula and
|
|
153
|
+
* the formulas of its cells. It also gives the directions of their reads of the column itself. A read in the body or
|
|
154
|
+
* in a test of an axis also has the direction of that axis. It walks each expression with a stack, not with recursion.
|
|
155
|
+
*/
|
|
156
|
+
function readsOf(t: Table, self: string): { readonly columns: ReadonlySet<string>; readonly directions: ReadonlySet<Direction> } {
|
|
157
|
+
const columns = new Set<string>();
|
|
158
|
+
const directions = new Set<Direction>();
|
|
159
|
+
const formula = t.columns.get(self);
|
|
160
|
+
// An expression that is not valid reads no column. Its evaluation gives the error (EVAL.SHAPE).
|
|
161
|
+
const todo: [Expr, Axis | undefined][] = [...(formula === undefined ? [] : [formula]), ...(t.cells.get(self)?.values() ?? [])].filter((e) => shapeError(e) === undefined).map((e) => [e, undefined]);
|
|
162
|
+
for (let item = todo.pop(); item !== undefined; item = todo.pop()) {
|
|
163
|
+
const [e, axis] = item;
|
|
164
|
+
if (e.tag === "each" || e.tag === "fold") {
|
|
165
|
+
const { base, tests } = partsOf(e.axis);
|
|
166
|
+
for (const x of [...(e.tag === "each" ? [e.body] : Object.values(e.step)), ...tests]) todo.push([x, base]);
|
|
167
|
+
// The values of init, the result of a fold, the list of the axis list and the expressions of the address evaluate
|
|
168
|
+
// at the node, so they keep the outer direction.
|
|
169
|
+
const list = listOf(e.axis);
|
|
170
|
+
for (const x of [...(e.tag === "fold" ? [...Object.values(e.init), e.result] : []), ...addrExprs(e.at), ...(list === undefined ? [] : [list])]) todo.push([x, axis]);
|
|
171
|
+
} else if (e.tag !== "ext") {
|
|
172
|
+
for (const child of children(e)) todo.push([child, axis]);
|
|
173
|
+
// The data of an extension of another kind can look like a cell reference. It only changes the order of a fill.
|
|
174
|
+
// Stryker disable next-line ConditionalExpression,LogicalOperator: see the comment above
|
|
175
|
+
} else if (e.kind === CELL_KIND && isCellRef(e.data)) {
|
|
176
|
+
columns.add(e.data.column);
|
|
177
|
+
// The directions of the reads of another column only change the order of a fill, because that column comes first.
|
|
178
|
+
// Stryker disable next-line ConditionalExpression: see the comment above
|
|
179
|
+
if (e.data.column === self) for (const m of [...(axis === undefined ? [] : [axis]), ...e.data.at]) addDirection(directions, m);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
return { columns, directions };
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* This function gives the columns of a table in an order where each column comes after the columns that it reads.
|
|
187
|
+
* The columns of a cycle keep their order. The columns with formulas of cells only come last.
|
|
188
|
+
*/
|
|
189
|
+
function columnOrder(t: Table): readonly string[] {
|
|
190
|
+
const names = new Set([...t.columns.keys(), ...t.cells.keys()]);
|
|
191
|
+
let left = [...names].map((c) => ({ c, needs: [...readsOf(t, c).columns].filter((x) => x !== c && names.has(x)) }));
|
|
192
|
+
const order: string[] = [];
|
|
193
|
+
const placed = new Set<string>();
|
|
194
|
+
// Each pass places each column whose reads are placed. A pass that places no column leaves a cycle, so it places
|
|
195
|
+
// the first column that is left.
|
|
196
|
+
while (left.length > 0) {
|
|
197
|
+
const ready = left.filter((x) => x.needs.every((n) => placed.has(n)));
|
|
198
|
+
for (const x of ready.length > 0 ? ready : left.slice(0, 1)) {
|
|
199
|
+
order.push(x.c);
|
|
200
|
+
placed.add(x.c);
|
|
201
|
+
}
|
|
202
|
+
left = left.filter((x) => !placed.has(x.c));
|
|
203
|
+
}
|
|
204
|
+
return order;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* This function gives the keys of a space in the order of the reads of a column from itself. A read of a later key
|
|
209
|
+
* reverses the order. In a tree, a read of the children puts the children before their parent.
|
|
210
|
+
*/
|
|
211
|
+
function keyOrder(s: Space, d: ReadonlySet<Direction>): readonly string[] {
|
|
212
|
+
const reverse = d.has("after") && !d.has("before");
|
|
213
|
+
const childrenOf = s.childrenOf?.bind(s);
|
|
214
|
+
if (childrenOf === undefined) return reverse ? s.keys.toReversed() : s.keys;
|
|
215
|
+
const post = d.has("down");
|
|
216
|
+
// The order with each parent before its children, and the order after the children is that order from the end, with
|
|
217
|
+
// the siblings in the other order. `push` puts the next key to visit at the end of the stack.
|
|
218
|
+
const backwards = post !== reverse;
|
|
219
|
+
const push = (stack: string[], keys: readonly string[]): void => {
|
|
220
|
+
for (const k of backwards ? keys : keys.toReversed()) stack.push(k);
|
|
221
|
+
};
|
|
222
|
+
const isChild = new Set(s.keys.flatMap((k) => childrenOf(k)));
|
|
223
|
+
const stack: string[] = [];
|
|
224
|
+
push(stack, s.keys.filter((k) => !isChild.has(k)));
|
|
225
|
+
const out: string[] = [];
|
|
226
|
+
for (let k = stack.pop(); k !== undefined; k = stack.pop()) {
|
|
227
|
+
out.push(k);
|
|
228
|
+
push(stack, childrenOf(k));
|
|
229
|
+
}
|
|
230
|
+
return post ? out.toReversed() : out;
|
|
231
|
+
}
|
|
81
232
|
|
|
82
233
|
/** The state of one cell in the search. */
|
|
83
234
|
interface Visit {
|
|
@@ -125,23 +276,33 @@ export class SheetRun {
|
|
|
125
276
|
readonly #byName = new Map<string, Table>();
|
|
126
277
|
readonly #bySpace = new Map<Space, Table>();
|
|
127
278
|
readonly #opts: Omit<EvalOptions, "origin" | "trace" | "space">;
|
|
128
|
-
readonly #done = new Map<string, Result<unknown>>();
|
|
129
279
|
// The cells on the stack of the search: started, but their component is not finished.
|
|
130
280
|
readonly #visits = new Map<string, Visit>();
|
|
131
281
|
// Stryker disable next-line ArrayDeclaration: the search never reads below the root of a component
|
|
132
282
|
readonly #stack: Visit[] = [];
|
|
133
283
|
// The cell whose formula is in evaluation. At the top level, it is a placeholder that is not a cell.
|
|
134
284
|
#top: Visit;
|
|
285
|
+
// The placeholder at the top in a fill, and true when the evaluation of a fill reads a cell that is not finished.
|
|
286
|
+
readonly #filling: Visit;
|
|
287
|
+
#missed = false;
|
|
135
288
|
#next = 0;
|
|
136
289
|
// The estimated frames of the stack that the evaluations in progress use, and the cost of each program.
|
|
137
290
|
#used = 0;
|
|
138
291
|
readonly #cost = new Map<Expr, number>();
|
|
139
292
|
readonly #budget: number;
|
|
293
|
+
readonly #compile: CompileFn | undefined;
|
|
294
|
+
readonly #compileOptions: CompileOptions;
|
|
295
|
+
// The run that evaluates a formula with a compiled program. Each run is synchronous, so a run inside the evaluation
|
|
296
|
+
// of another run gives the active run back when it ends.
|
|
297
|
+
static #active: SheetRun | undefined;
|
|
298
|
+
// The extensions of the compiled programs, for each object of extensions of the options. Their cell handler reads
|
|
299
|
+
// the cells of the active run, so a compiled program does not depend on one run.
|
|
300
|
+
static readonly #shared = new WeakMap<object, Readonly<Record<string, ExtHandler>>>();
|
|
140
301
|
|
|
141
302
|
/** `budget` is the budget of the stack in estimated frames. A test can make it small, so the run pauses often. */
|
|
142
303
|
constructor(columns: ReadonlyMap<string, Expr>, opts: SheetOptions, budget: number = STACK_BUDGET) {
|
|
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 };
|
|
304
|
+
const { cells, name, tables, space, compile, ...rest } = opts;
|
|
305
|
+
this.#main = { where: "the sheet", tag: "0", space, columns, cells: cells ?? new Map(), warmed: new Map(), index: undefined, done: new Map() };
|
|
145
306
|
this.#bySpace.set(space, this.#main);
|
|
146
307
|
if (name !== undefined) this.#byName.set(name, this.#main);
|
|
147
308
|
if (tables !== undefined) {
|
|
@@ -156,11 +317,27 @@ export class SheetRun {
|
|
|
156
317
|
}
|
|
157
318
|
// Stryker disable next-line all: the placeholder is not a cell, so the search reads none of its fields
|
|
158
319
|
this.#top = { id: "", table: this.#main, column: "", key: "", index: -1, low: -1, reread: false, result: cycleError("", ""), paused: false, need: undefined };
|
|
320
|
+
// Stryker disable next-line all: the placeholder is not a cell, so the search reads none of its fields
|
|
321
|
+
this.#filling = { id: "", table: this.#main, column: "", key: "", index: 0, low: 0, reread: false, result: cycleError("", ""), paused: false, need: undefined };
|
|
159
322
|
this.#budget = budget;
|
|
323
|
+
this.#compile = compile;
|
|
160
324
|
const spaces = Object.fromEntries([...this.#byName].map(([n, t]) => [n, t.space]));
|
|
161
325
|
this.#opts = { ...rest, tables: spaces, extensions: { ...rest.extensions, [CELL_KIND]: this.#handler } };
|
|
326
|
+
const outer = rest.extensions ?? NO_EXTENSIONS;
|
|
327
|
+
let shared = SheetRun.#shared.get(outer);
|
|
328
|
+
if (shared === undefined) {
|
|
329
|
+
shared = { ...rest.extensions, [CELL_KIND]: SheetRun.#cellOfActive };
|
|
330
|
+
SheetRun.#shared.set(outer, shared);
|
|
331
|
+
}
|
|
332
|
+
this.#compileOptions = { ...this.#opts, extensions: shared };
|
|
162
333
|
}
|
|
163
334
|
|
|
335
|
+
/** The cell handler of the compiled programs: it reads the cells of the active run. */
|
|
336
|
+
static readonly #cellOfActive: ExtHandler = (data, ctx) => {
|
|
337
|
+
const run = SheetRun.#active;
|
|
338
|
+
return run === undefined ? fail(vexError("unbound", "a compiled formula reads cells only in the evaluation of a sheet run")) : run.#handler(data, ctx);
|
|
339
|
+
};
|
|
340
|
+
|
|
164
341
|
/** This method gives the program of a cell: its own formula, or the formula of its column (SHEET.CELL.FORMULA). */
|
|
165
342
|
#programOf(t: Table, column: string, key: string): Expr | undefined {
|
|
166
343
|
// Stryker disable next-line ConditionalExpression: without formulas of cells, the lookup gives undefined anyway
|
|
@@ -181,7 +358,8 @@ export class SheetRun {
|
|
|
181
358
|
}
|
|
182
359
|
|
|
183
360
|
readonly #handler: ExtHandler = (data, ctx) => {
|
|
184
|
-
|
|
361
|
+
// The interpreter gives an error without an origin the path and the position of its node.
|
|
362
|
+
if (!isCellRef(data)) return fail(vexError("bad-expression", "a cell reference needs a column name and an address of fixed moves"));
|
|
185
363
|
const where = resolveAddr(ctx.space, ctx.position, data.at);
|
|
186
364
|
if (!where.ok) return fail({ ...where.error, path: ctx.path });
|
|
187
365
|
// The evaluation of a cell has the space of its table, and the body of the axis table has the space of that table.
|
|
@@ -199,6 +377,9 @@ export class SheetRun {
|
|
|
199
377
|
if (!("space" in t)) return t;
|
|
200
378
|
// 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.
|
|
201
379
|
if (this.#top.index >= 0) return this.#read(t, column, key);
|
|
380
|
+
// A finished cell needs no warm-up.
|
|
381
|
+
const done = doneOf(t, column, key);
|
|
382
|
+
if (done !== undefined) return done;
|
|
202
383
|
this.#warmTo(t, column, key);
|
|
203
384
|
return this.#drive(t, column, key);
|
|
204
385
|
}
|
|
@@ -218,7 +399,7 @@ export class SheetRun {
|
|
|
218
399
|
#costOf(program: Expr): number {
|
|
219
400
|
let cost = this.#cost.get(program);
|
|
220
401
|
if (cost === undefined) {
|
|
221
|
-
cost = 3 * nestingOf(program) + 16;
|
|
402
|
+
cost = 3 * (shapeError(program) === undefined ? nestingOf(program) : 1) + 16;
|
|
222
403
|
this.#cost.set(program, cost);
|
|
223
404
|
}
|
|
224
405
|
return cost;
|
|
@@ -241,12 +422,40 @@ export class SheetRun {
|
|
|
241
422
|
visit.need = undefined;
|
|
242
423
|
this.#top = visit;
|
|
243
424
|
this.#used += cost;
|
|
244
|
-
const result =
|
|
425
|
+
const result = this.#run(visit.table, visit.column, visit.key, program);
|
|
245
426
|
this.#used -= cost;
|
|
246
427
|
this.#top = caller;
|
|
247
428
|
if (!visit.paused) visit.result = result;
|
|
248
429
|
}
|
|
249
430
|
|
|
431
|
+
/** This method evaluates the formula `program` of a cell, with its compiled program or with the interpreter. */
|
|
432
|
+
#run(t: Table, column: string, key: string, program: Expr): Result<unknown> {
|
|
433
|
+
const options = { ...this.#opts, space: t.space, origin: key };
|
|
434
|
+
const compiled = this.#compiled(t, column, program);
|
|
435
|
+
if (compiled === undefined) return evaluate(program, options);
|
|
436
|
+
const active = SheetRun.#active;
|
|
437
|
+
SheetRun.#active = this;
|
|
438
|
+
const result = compiled.run(options);
|
|
439
|
+
SheetRun.#active = active;
|
|
440
|
+
return result;
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
/**
|
|
444
|
+
* This method gives the compiled program of the formula of a column, or `undefined` for the interpreter. A formula
|
|
445
|
+
* compiles once for each compiler and options, also across runs.
|
|
446
|
+
*/
|
|
447
|
+
#compiled(t: Table, column: string, program: Expr): Program | undefined {
|
|
448
|
+
const compile = this.#compile;
|
|
449
|
+
// The formula of a cell evaluates once in a run, so the run compiles only the formulas of the columns.
|
|
450
|
+
if (compile === undefined || t.columns.get(column) !== program) return undefined;
|
|
451
|
+
const { domains, fns, extensions } = this.#compileOptions;
|
|
452
|
+
const hit = PROGRAMS.get(program);
|
|
453
|
+
if (hit !== undefined && hit.compile === compile && hit.domains === domains && hit.fns === fns && hit.extensions === extensions) return hit.program;
|
|
454
|
+
const compiled = compile(program, this.#compileOptions);
|
|
455
|
+
PROGRAMS.set(program, { compile, domains, fns, extensions, program: compiled });
|
|
456
|
+
return compiled;
|
|
457
|
+
}
|
|
458
|
+
|
|
250
459
|
/** This method ends a cell whose evaluation did not pause: it finishes its component, or it gives its low to the caller. */
|
|
251
460
|
#end(visit: Visit, caller: Visit | undefined): void {
|
|
252
461
|
if (visit.low === visit.index) this.#finish(visit);
|
|
@@ -255,12 +464,17 @@ export class SheetRun {
|
|
|
255
464
|
|
|
256
465
|
/** This method reads a cell from the formula of the cell at the top. */
|
|
257
466
|
#read(t: Table, column: string, key: string): Result<unknown> {
|
|
258
|
-
const
|
|
259
|
-
const done = this.#done.get(id);
|
|
467
|
+
const done = doneOf(t, column, key);
|
|
260
468
|
if (done !== undefined) return done;
|
|
261
469
|
const caller = this.#top;
|
|
262
470
|
// A paused evaluation reads no other cell, so it does not follow a path that its final evaluation does not follow.
|
|
471
|
+
// In a fill, the cell goes to the search after the evaluation (SHEET.FILL).
|
|
263
472
|
if (caller.paused) return cycleError(column, key);
|
|
473
|
+
if (caller === this.#filling) {
|
|
474
|
+
this.#missed = true;
|
|
475
|
+
return cycleError(column, key);
|
|
476
|
+
}
|
|
477
|
+
const id = idOf(t, column, key);
|
|
264
478
|
const seen = this.#visits.get(id);
|
|
265
479
|
if (seen !== undefined) {
|
|
266
480
|
// A read of a cell that is not finished: the caller and this cell are on one cycle. The cell is on the
|
|
@@ -286,13 +500,12 @@ export class SheetRun {
|
|
|
286
500
|
return cycleError(column, key);
|
|
287
501
|
}
|
|
288
502
|
this.#end(visit, caller);
|
|
289
|
-
return
|
|
503
|
+
return doneOf(t, column, key) ?? cycleError(column, key);
|
|
290
504
|
}
|
|
291
505
|
|
|
292
506
|
/** This method evaluates a cell from the top level. The cells that pause go on a list, not on the call stack. */
|
|
293
507
|
#drive(t: Table, column: string, key: string): Result<unknown> {
|
|
294
|
-
const
|
|
295
|
-
const done = this.#done.get(id);
|
|
508
|
+
const done = doneOf(t, column, key);
|
|
296
509
|
if (done !== undefined) return done;
|
|
297
510
|
if (this.#programOf(t, column, key) === undefined) return this.#unbound(t, column, key);
|
|
298
511
|
const work: Visit[] = [this.#start(t, column, key)];
|
|
@@ -309,7 +522,7 @@ export class SheetRun {
|
|
|
309
522
|
work.pop();
|
|
310
523
|
this.#end(visit, work.at(-1));
|
|
311
524
|
}
|
|
312
|
-
return
|
|
525
|
+
return doneOf(t, column, key) ?? cycleError(column, key);
|
|
313
526
|
}
|
|
314
527
|
|
|
315
528
|
/** This method takes the component of `root` from the stack, and sets the final result of each of its cells. */
|
|
@@ -320,9 +533,9 @@ export class SheetRun {
|
|
|
320
533
|
// Stryker disable next-line ConditionalExpression,LogicalOperator: members.length > 1 implies root.reread
|
|
321
534
|
const cyclic = members.length > 1 || root.reread;
|
|
322
535
|
for (const m of members) {
|
|
323
|
-
// Stryker disable next-line CallExpression: a finished cell
|
|
536
|
+
// Stryker disable next-line CallExpression: a finished cell has a result, and a read looks for the result first
|
|
324
537
|
this.#visits.delete(m.id);
|
|
325
|
-
|
|
538
|
+
setDone(m.table, m.column, m.key, cyclic ? cycleError(m.column, m.key) : m.result);
|
|
326
539
|
}
|
|
327
540
|
}
|
|
328
541
|
|
|
@@ -335,6 +548,31 @@ export class SheetRun {
|
|
|
335
548
|
return { events: explain(program, { ...this.#opts, space: t.space, origin: key }).events, result };
|
|
336
549
|
}
|
|
337
550
|
|
|
551
|
+
/**
|
|
552
|
+
* This method evaluates each cell of the table `table`, or of the main table (SHEET.FILL). Each column comes after
|
|
553
|
+
* the columns that it reads, and the keys of a column come in the order of its reads from itself. Thus most reads
|
|
554
|
+
* find a finished cell. An evaluation that reads a cell that is not finished has no effect, and the search then
|
|
555
|
+
* evaluates its cell. A read of a cell gives the same result after a fill.
|
|
556
|
+
*/
|
|
557
|
+
fill(table?: string): void {
|
|
558
|
+
const t = table === undefined ? this.#main : this.#byName.get(table);
|
|
559
|
+
// A read inside a formula has a cell at the top. A fill there has no effect.
|
|
560
|
+
if (t === undefined || this.#top.index >= 0) return;
|
|
561
|
+
const host = this.#top;
|
|
562
|
+
for (const column of columnOrder(t)) {
|
|
563
|
+
for (const key of keyOrder(t.space, readsOf(t, column).directions)) {
|
|
564
|
+
const program = this.#programOf(t, column, key);
|
|
565
|
+
if (program === undefined || doneOf(t, column, key) !== undefined) continue;
|
|
566
|
+
this.#top = this.#filling;
|
|
567
|
+
this.#missed = false;
|
|
568
|
+
const result = this.#run(t, column, key, program);
|
|
569
|
+
this.#top = host;
|
|
570
|
+
if (this.#missed) this.#drive(t, column, key);
|
|
571
|
+
else setDone(t, column, key, result);
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
|
|
338
576
|
/**
|
|
339
577
|
* This method evaluates the column `column` at each key before `key`, in key order. A recurrence over the keys,
|
|
340
578
|
* for example a running total, then reads finished cells.
|
package/src/space.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { vexError } from "./errors.ts";
|
|
2
|
-
import type
|
|
2
|
+
import { moveExpr, type Addr, type Axis, type FixedMove } from "./ir.ts";
|
|
3
3
|
import { fail, ok, type Result } from "./result.ts";
|
|
4
4
|
|
|
5
5
|
/** The kind of a space. The kind sets which moves and axes are valid. */
|
|
@@ -13,6 +13,11 @@ export interface Space<K extends string = string, O = unknown> {
|
|
|
13
13
|
readonly kind: SpaceKind;
|
|
14
14
|
/** The keys, in their order. */
|
|
15
15
|
readonly keys: readonly K[];
|
|
16
|
+
/**
|
|
17
|
+
* The record of each key, in the order of `keys` (SPACE.RECORDS). A compiler reads a record by its index with it.
|
|
18
|
+
* A space without it gives each record with `get` only.
|
|
19
|
+
*/
|
|
20
|
+
readonly records?: readonly (O | undefined)[];
|
|
16
21
|
/** This function tells if the space has the key `k`. */
|
|
17
22
|
has(k: string): k is K;
|
|
18
23
|
/** This function gives the record at the key `k`, or `undefined`. */
|
|
@@ -40,11 +45,13 @@ export type ArrayKey = `${number}`;
|
|
|
40
45
|
class RecordSpace<K extends string, O> implements Space<K, O> {
|
|
41
46
|
readonly kind: SpaceKind = "record";
|
|
42
47
|
readonly keys: readonly K[];
|
|
48
|
+
readonly records: readonly O[];
|
|
43
49
|
readonly #records: ReadonlyMap<string, O>;
|
|
44
50
|
|
|
45
51
|
constructor(records: Readonly<Record<K, O>>) {
|
|
46
52
|
const entries = Object.entries(records) as [K, O][];
|
|
47
53
|
this.keys = Object.freeze(entries.map(([k]) => k));
|
|
54
|
+
this.records = Object.freeze(entries.map(([, o]) => o));
|
|
48
55
|
this.#records = new Map(entries);
|
|
49
56
|
}
|
|
50
57
|
|
|
@@ -67,38 +74,40 @@ class RecordSpace<K extends string, O> implements Space<K, O> {
|
|
|
67
74
|
class ArraySpace<O> implements Space<ArrayKey, O> {
|
|
68
75
|
readonly kind: SpaceKind = "array";
|
|
69
76
|
readonly keys: readonly ArrayKey[];
|
|
70
|
-
readonly
|
|
77
|
+
readonly records: readonly O[];
|
|
71
78
|
|
|
72
79
|
constructor(items: readonly O[]) {
|
|
73
|
-
|
|
74
|
-
this.
|
|
75
|
-
this.#items = new Map(entries);
|
|
80
|
+
this.keys = Object.freeze(Array.from(items, (_item, i): ArrayKey => `${i}`));
|
|
81
|
+
this.records = Object.freeze(Array.from(items));
|
|
76
82
|
}
|
|
77
83
|
|
|
84
|
+
// The key at the position i is the text of i, so the position of a key finds it. A text that is not a key of the
|
|
85
|
+
// space, for example "01" or "1.0", has no key at its position.
|
|
78
86
|
has(k: string): k is ArrayKey {
|
|
79
|
-
return this
|
|
87
|
+
return this.keys[Number(k)] === k;
|
|
80
88
|
}
|
|
81
89
|
get(k: string): O | undefined {
|
|
82
|
-
return this
|
|
90
|
+
return this.has(k) ? this.records[Number(k)] : undefined;
|
|
83
91
|
}
|
|
84
92
|
coords(k: string): readonly number[] | undefined {
|
|
85
93
|
return this.has(k) ? [Number(k)] : undefined;
|
|
86
94
|
}
|
|
87
95
|
keyAt(coords: readonly number[]): ArrayKey | undefined {
|
|
88
|
-
|
|
89
|
-
return coords.length === 1 && this.has(k) ? k : undefined;
|
|
96
|
+
return coords.length === 1 ? this.keys[Number(coords[0])] : undefined;
|
|
90
97
|
}
|
|
91
98
|
}
|
|
92
99
|
|
|
93
100
|
class GridSpace<O> implements Space<GridKey, O> {
|
|
94
101
|
readonly kind: SpaceKind = "grid";
|
|
95
102
|
readonly keys: readonly GridKey[];
|
|
103
|
+
readonly records: readonly O[];
|
|
96
104
|
readonly #cells: ReadonlyMap<string, O>;
|
|
97
105
|
readonly #coords: ReadonlyMap<string, readonly number[]>;
|
|
98
106
|
|
|
99
107
|
constructor(rows: readonly (readonly O[])[]) {
|
|
100
108
|
const entries = rows.flatMap((row, i) => row.map((cell, j): [GridKey, O, readonly number[]] => [`${i},${j}`, cell, Object.freeze([i, j])]));
|
|
101
109
|
this.keys = Object.freeze(entries.map(([k]) => k));
|
|
110
|
+
this.records = Object.freeze(entries.map(([, o]) => o));
|
|
102
111
|
this.#cells = new Map(entries.map(([k, cell]) => [k, cell]));
|
|
103
112
|
this.#coords = new Map(entries.map(([k, , c]) => [k, c]));
|
|
104
113
|
}
|
|
@@ -122,6 +131,7 @@ class GridSpace<O> implements Space<GridKey, O> {
|
|
|
122
131
|
class TreeSpace<K extends string, O> implements Space<K, O> {
|
|
123
132
|
readonly kind: SpaceKind = "tree";
|
|
124
133
|
readonly keys: readonly K[];
|
|
134
|
+
readonly records: readonly O[];
|
|
125
135
|
readonly #records: ReadonlyMap<string, O>;
|
|
126
136
|
readonly #parents: ReadonlyMap<string, K>;
|
|
127
137
|
readonly #children: ReadonlyMap<string, readonly K[]>;
|
|
@@ -129,6 +139,7 @@ class TreeSpace<K extends string, O> implements Space<K, O> {
|
|
|
129
139
|
constructor(records: Readonly<Record<K, O>>, parents: Readonly<Partial<Record<K, K | null>>>) {
|
|
130
140
|
const entries = Object.entries(records) as [K, O][];
|
|
131
141
|
this.keys = Object.freeze(entries.map(([k]) => k));
|
|
142
|
+
this.records = Object.freeze(entries.map(([, o]) => o));
|
|
132
143
|
this.#records = new Map(entries);
|
|
133
144
|
const parentOf = new Map<string, K>();
|
|
134
145
|
for (const [k, p] of Object.entries(parents) as [K, K | null | undefined][]) {
|
|
@@ -196,6 +207,7 @@ const NO_KEYS: readonly never[] = Object.freeze([]);
|
|
|
196
207
|
class GraphSpace<K extends string, O> implements Space<K, O> {
|
|
197
208
|
readonly kind: SpaceKind = "graph";
|
|
198
209
|
readonly keys: readonly K[];
|
|
210
|
+
readonly records: readonly O[];
|
|
199
211
|
readonly #records: ReadonlyMap<string, O>;
|
|
200
212
|
readonly #out: ReadonlyMap<string, readonly K[]>;
|
|
201
213
|
readonly #in: ReadonlyMap<string, readonly K[]>;
|
|
@@ -203,6 +215,7 @@ class GraphSpace<K extends string, O> implements Space<K, O> {
|
|
|
203
215
|
constructor(records: Readonly<Record<K, O>>, edges: Readonly<Partial<Record<K, readonly K[]>>>) {
|
|
204
216
|
const entries = Object.entries(records) as [K, O][];
|
|
205
217
|
this.keys = Object.freeze(entries.map(([k]) => k));
|
|
218
|
+
this.records = Object.freeze(entries.map(([, o]) => o));
|
|
206
219
|
this.#records = new Map(entries);
|
|
207
220
|
const out = new Map<string, readonly K[]>();
|
|
208
221
|
for (const [k, to] of Object.entries(edges) as [K, readonly K[] | undefined][]) {
|
|
@@ -283,7 +296,7 @@ export interface Position {
|
|
|
283
296
|
}
|
|
284
297
|
|
|
285
298
|
/** This function applies one move to the focus. It gives the new focus, or a `#REF!` error. */
|
|
286
|
-
export function applyMove(s: Space, at: Position, m:
|
|
299
|
+
export function applyMove(s: Space, at: Position, m: FixedMove): Result<string> {
|
|
287
300
|
const refError = (kind: "unknown-key" | "not-a-pair" | "out-of-bounds" | "no-offset" | "no-tree", message: string): Result<string> =>
|
|
288
301
|
fail(vexError(kind, message, { origin: at.origin, focus: at.focus }));
|
|
289
302
|
switch (m.t) {
|
|
@@ -331,8 +344,28 @@ export function applyMove(s: Space, at: Position, m: Move): Result<string> {
|
|
|
331
344
|
}
|
|
332
345
|
}
|
|
333
346
|
|
|
347
|
+
/**
|
|
348
|
+
* This function gives the fixed moves of an address. `values` has the value of the expression of each computed move,
|
|
349
|
+
* in order (NAV.COMPUTED). A key that is not a text, or a position that is not a number, gives `#VALUE!`.
|
|
350
|
+
*/
|
|
351
|
+
export function fixAddr(addr: Addr, values: readonly unknown[], at: Position): Result<readonly FixedMove[]> {
|
|
352
|
+
const out: FixedMove[] = [];
|
|
353
|
+
let next = 0;
|
|
354
|
+
for (const m of addr) {
|
|
355
|
+
if (moveExpr(m) === undefined) {
|
|
356
|
+
out.push(m as FixedMove);
|
|
357
|
+
continue;
|
|
358
|
+
}
|
|
359
|
+
const u = values[next++];
|
|
360
|
+
if (m.t === "key" && typeof u === "string") out.push({ t: "key", key: u });
|
|
361
|
+
else if (m.t === "index" && typeof u === "number") out.push({ t: "index", i: u });
|
|
362
|
+
else return fail(vexError("kind-mismatch", m.t === "key" ? `the key of a move is a ${typeof u}, not a text` : `the position of a move is a ${typeof u}, not a number`, at));
|
|
363
|
+
}
|
|
364
|
+
return ok(out);
|
|
365
|
+
}
|
|
366
|
+
|
|
334
367
|
/** This function applies the moves of an address in order. It gives the key where the address points. */
|
|
335
|
-
export function resolveAddr(s: Space, at: Position, addr:
|
|
368
|
+
export function resolveAddr(s: Space, at: Position, addr: readonly FixedMove[] | undefined): Result<string> {
|
|
336
369
|
let focus = at.focus;
|
|
337
370
|
for (const m of addr ?? []) {
|
|
338
371
|
const r = applyMove(s, { origin: at.origin, focus }, m);
|
|
@@ -417,9 +450,17 @@ export function axisTargets(s: Space, at: Position, a: Exclude<Axis, { readonly
|
|
|
417
450
|
case "predecessors":
|
|
418
451
|
case "reachable":
|
|
419
452
|
return graphTargets(s, at, a.t);
|
|
453
|
+
case "reverse": {
|
|
454
|
+
// The validation of the IR keeps a base axis inside reverse: not where, reverse or table.
|
|
455
|
+
const r = axisTargets(s, at, a.axis as Exclude<Axis, { readonly t: "where" }>);
|
|
456
|
+
return r.ok ? ok(r.value.toReversed()) : r;
|
|
457
|
+
}
|
|
420
458
|
case "table":
|
|
421
459
|
// The evaluator gives the axis table the space of its table. Here, without the tables, it has no targets.
|
|
422
460
|
return fail(vexError("no-table", `the axis "table" needs the tables of the evaluation, and "${a.name}" is not one of them`, at));
|
|
461
|
+
case "list":
|
|
462
|
+
// The evaluator gives the targets of the axis list from the value of its expression. A space alone has no list.
|
|
463
|
+
return fail(vexError("bad-expression", 'the axis "list" needs the evaluator, which gives the value of its list', at));
|
|
423
464
|
}
|
|
424
465
|
}
|
|
425
466
|
|