@mark1russell7/vex 0.3.0 → 0.5.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 +73 -13
- package/build/index.d.ts.map +1 -1
- package/build/index.js +566 -153
- package/build/index.js.map +1 -1
- package/package.json +3 -2
- package/src/builder.ts +69 -16
- package/src/deps.ts +13 -11
- package/src/errors.ts +16 -2
- package/src/evaluate.ts +87 -17
- package/src/ir.ts +76 -45
- package/src/json.ts +170 -52
- package/src/sheet.ts +149 -31
- package/src/space.ts +10 -0
package/src/json.ts
CHANGED
|
@@ -1,79 +1,197 @@
|
|
|
1
1
|
import type { AnyDomain } from "./domain.ts";
|
|
2
|
-
import { vexError } from "./errors.ts";
|
|
2
|
+
import { isStackOverflow, vexError } from "./errors.ts";
|
|
3
3
|
import { isExpr, type Expr } from "./ir.ts";
|
|
4
4
|
import { fail, ok, type Result } from "./result.ts";
|
|
5
5
|
|
|
6
|
-
/**
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
6
|
+
/**
|
|
7
|
+
* The JSON form of the values in a literal. JSON data stays as it is, with three exceptions. Each exception is a record
|
|
8
|
+
* with the key `$vex`:
|
|
9
|
+
*
|
|
10
|
+
* - `{ "$vex": "domain", "domain": name, "value": v }`: a value of a domain, with the `encode` of the domain.
|
|
11
|
+
* - `{ "$vex": "number", "value": "-0" }`: a number that JSON has no text for: `-0`, `NaN`, `Infinity` or `-Infinity`.
|
|
12
|
+
* - `{ "$vex": "escape", "value": record }`: a record of the data that has the key `$vex` itself (IR.JSON.ESCAPE).
|
|
13
|
+
*
|
|
14
|
+
* A record with the key `$vex` and another form stays data, so a file from an older version reads as before.
|
|
15
|
+
*
|
|
16
|
+
* The functions walk the tree of the expression, so only the value of a literal gets this form. A field of a literal
|
|
17
|
+
* that looks like an expression stays data. The data of an extension is plain JSON, as before.
|
|
18
|
+
*/
|
|
19
|
+
type Encoded =
|
|
20
|
+
| { readonly $vex: "domain"; readonly domain: string; readonly value: unknown }
|
|
21
|
+
| { readonly $vex: "number"; readonly value: "-0" | "NaN" | "Infinity" | "-Infinity" }
|
|
22
|
+
| { readonly $vex: "escape"; readonly value: Readonly<Record<string, unknown>> };
|
|
23
|
+
|
|
24
|
+
const isRecord = (u: unknown): u is Readonly<Record<string, unknown>> => typeof u === "object" && u !== null && !Array.isArray(u);
|
|
25
|
+
|
|
26
|
+
const isPlainRecord = (u: unknown): u is Readonly<Record<string, unknown>> => {
|
|
27
|
+
if (!isRecord(u)) return false;
|
|
28
|
+
const proto: unknown = Object.getPrototypeOf(u);
|
|
29
|
+
return proto === Object.prototype || proto === null;
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
/** This function gives the JSON form of a value, or the reason why the value has no JSON form. */
|
|
33
|
+
function encodeValue(u: unknown, domains: readonly AnyDomain[]): Result<unknown> {
|
|
34
|
+
if (u === null || typeof u === "string" || typeof u === "boolean") return ok(u);
|
|
35
|
+
if (typeof u === "number") {
|
|
36
|
+
if (Object.is(u, -0)) return ok({ $vex: "number", value: "-0" } satisfies Encoded);
|
|
37
|
+
// Stryker disable next-line EqualityOperator: here u is an infinity, so u > 0 and u >= 0 are the same test
|
|
38
|
+
return Number.isFinite(u) ? ok(u) : ok({ $vex: "number", value: Number.isNaN(u) ? "NaN" : u > 0 ? "Infinity" : "-Infinity" } satisfies Encoded);
|
|
39
|
+
}
|
|
40
|
+
if (Array.isArray(u)) {
|
|
41
|
+
const out: unknown[] = [];
|
|
42
|
+
for (const x of u) {
|
|
43
|
+
const r = encodeValue(x, domains);
|
|
44
|
+
if (!r.ok) return r;
|
|
45
|
+
out.push(r.value);
|
|
46
|
+
}
|
|
47
|
+
return ok(out);
|
|
48
|
+
}
|
|
49
|
+
if (isPlainRecord(u)) {
|
|
50
|
+
const out: Record<string, unknown> = {};
|
|
51
|
+
for (const [k, x] of Object.entries(u)) {
|
|
52
|
+
const r = encodeValue(x, domains);
|
|
53
|
+
if (!r.ok) return r;
|
|
54
|
+
out[k] = r.value;
|
|
55
|
+
}
|
|
56
|
+
return ok(Object.hasOwn(u, "$vex") ? ({ $vex: "escape", value: out } satisfies Encoded) : out);
|
|
57
|
+
}
|
|
58
|
+
// A plain array or record stays data. Another object is a value of a domain, or it has no JSON form.
|
|
59
|
+
const d = domains.find((dom) => dom.encode !== undefined && dom.is(u));
|
|
60
|
+
if (d?.encode !== undefined) return ok({ $vex: "domain", domain: d.name, value: d.encode(u) } satisfies Encoded);
|
|
61
|
+
return fail(vexError("bad-expression", "a literal value is not JSON data and no domain encodes it"));
|
|
11
62
|
}
|
|
12
63
|
|
|
13
|
-
const
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
if (
|
|
18
|
-
const
|
|
19
|
-
|
|
64
|
+
const NUMBERS: Readonly<Record<string, number>> = { "-0": -0, NaN: Number.NaN, Infinity: Number.POSITIVE_INFINITY, "-Infinity": Number.NEGATIVE_INFINITY };
|
|
65
|
+
|
|
66
|
+
/** This function reads a value from its JSON form. */
|
|
67
|
+
function decodeValue(u: unknown, domains: readonly AnyDomain[]): Result<unknown> {
|
|
68
|
+
if (Array.isArray(u)) {
|
|
69
|
+
const out: unknown[] = [];
|
|
70
|
+
for (const x of u) {
|
|
71
|
+
const r = decodeValue(x, domains);
|
|
72
|
+
if (!r.ok) return r;
|
|
73
|
+
out.push(r.value);
|
|
74
|
+
}
|
|
75
|
+
return ok(out);
|
|
20
76
|
}
|
|
21
|
-
return
|
|
22
|
-
|
|
77
|
+
if (!isRecord(u)) return ok(u);
|
|
78
|
+
const fields = (record: Readonly<Record<string, unknown>>): Result<unknown> => {
|
|
79
|
+
const out: Record<string, unknown> = {};
|
|
80
|
+
for (const [k, x] of Object.entries(record)) {
|
|
81
|
+
const r = decodeValue(x, domains);
|
|
82
|
+
if (!r.ok) return r;
|
|
83
|
+
out[k] = r.value;
|
|
84
|
+
}
|
|
85
|
+
return ok(out);
|
|
86
|
+
};
|
|
87
|
+
// A record without the key $vex matches none of the forms below, so it stays data too.
|
|
88
|
+
const kind = u["$vex"];
|
|
89
|
+
if (kind === "escape" && isRecord(u["value"])) return fields(u["value"]);
|
|
90
|
+
if (kind === "number" && typeof u["value"] === "string" && Object.hasOwn(NUMBERS, u["value"])) return ok(NUMBERS[u["value"]]);
|
|
91
|
+
if (kind === "domain" && typeof u["domain"] === "string") {
|
|
92
|
+
const name = u["domain"];
|
|
93
|
+
const d = domains.find((dom) => dom.name === name);
|
|
94
|
+
if (d?.decode === undefined) return fail(vexError("bad-expression", `no domain "${name}" decodes a literal`));
|
|
95
|
+
return ok(d.decode(u["value"]));
|
|
96
|
+
}
|
|
97
|
+
// A form that this version does not know stays data, so a file from an older version reads as before.
|
|
98
|
+
return fields(u);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** This function applies `f` to each literal value of a JSON tree of an expression. */
|
|
102
|
+
function mapValues(u: unknown, f: (value: unknown) => Result<unknown>): Result<unknown> {
|
|
103
|
+
if (!isRecord(u)) return ok(u);
|
|
104
|
+
const out: Record<string, unknown> = { ...u };
|
|
105
|
+
const child = (key: string): Result<unknown> | undefined => {
|
|
106
|
+
const r = mapValues(u[key], f);
|
|
107
|
+
if (r.ok) out[key] = r.value;
|
|
108
|
+
return r.ok ? undefined : r;
|
|
109
|
+
};
|
|
110
|
+
const each = (key: string): Result<unknown> | undefined => {
|
|
111
|
+
const list = u[key];
|
|
112
|
+
if (Array.isArray(list)) {
|
|
113
|
+
const items: unknown[] = [];
|
|
114
|
+
for (const x of list) {
|
|
115
|
+
const r = mapValues(x, f);
|
|
116
|
+
if (!r.ok) return r;
|
|
117
|
+
items.push(r.value);
|
|
118
|
+
}
|
|
119
|
+
out[key] = items;
|
|
120
|
+
} else if (isRecord(list)) {
|
|
121
|
+
const rec: Record<string, unknown> = {};
|
|
122
|
+
for (const [k, x] of Object.entries(list)) {
|
|
123
|
+
const r = mapValues(x, f);
|
|
124
|
+
if (!r.ok) return r;
|
|
125
|
+
rec[k] = r.value;
|
|
126
|
+
}
|
|
127
|
+
out[key] = rec;
|
|
128
|
+
}
|
|
129
|
+
return undefined;
|
|
130
|
+
};
|
|
131
|
+
const axis = (a: unknown): Result<unknown> => {
|
|
132
|
+
if (!isRecord(a) || a["t"] !== "where") return ok(a);
|
|
133
|
+
const inner = axis(a["axis"]);
|
|
134
|
+
if (!inner.ok) return inner;
|
|
135
|
+
const test = mapValues(a["test"], f);
|
|
136
|
+
return test.ok ? ok({ ...a, axis: inner.value, test: test.value }) : test;
|
|
137
|
+
};
|
|
138
|
+
switch (u["tag"]) {
|
|
139
|
+
case "lit": {
|
|
140
|
+
if (!Object.hasOwn(u, "value")) return ok(out);
|
|
141
|
+
const r = f(u["value"]);
|
|
142
|
+
if (!r.ok) return r;
|
|
143
|
+
out["value"] = r.value;
|
|
144
|
+
return ok(out);
|
|
145
|
+
}
|
|
146
|
+
case "app":
|
|
147
|
+
return each("args") ?? ok(out);
|
|
148
|
+
case "let":
|
|
149
|
+
return each("bind") ?? child("body") ?? ok(out);
|
|
150
|
+
case "rec":
|
|
151
|
+
return each("fields") ?? ok(out);
|
|
152
|
+
case "each": {
|
|
153
|
+
const a = axis(u["axis"]);
|
|
154
|
+
if (!a.ok) return a;
|
|
155
|
+
out["axis"] = a.value;
|
|
156
|
+
return child("body") ?? ok(out);
|
|
157
|
+
}
|
|
158
|
+
default:
|
|
159
|
+
return ok(out);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
23
162
|
|
|
24
163
|
/**
|
|
25
|
-
* This function gives the JSON text of an expression. A literal that is a domain value needs a domain with
|
|
26
|
-
* `encode`. A literal that is not JSON data and has no such domain gives the error `#VALUE!`.
|
|
164
|
+
* This function gives the JSON text of an expression. A literal value that is a domain value needs a domain with
|
|
165
|
+
* `encode`. A literal value that is not JSON data and has no such domain gives the error `#VALUE!`.
|
|
27
166
|
*/
|
|
28
167
|
// Stryker disable next-line ArrayDeclaration: a list with a value that is not a domain encodes no value
|
|
29
168
|
export function serialize(e: Expr, domains: readonly AnyDomain[] = []): Result<string> {
|
|
30
|
-
const failure: { message: string }[] = [];
|
|
31
|
-
const replacer = function (this: unknown, k: string, value: unknown): unknown {
|
|
32
|
-
// JSON.stringify gives each replacer call an object as this.
|
|
33
|
-
const holder = this as Record<string, unknown>;
|
|
34
|
-
if (k !== "value" || holder["tag"] !== "lit") return value;
|
|
35
|
-
if (isPlainJson(value)) return value;
|
|
36
|
-
const d = domains.find((dom) => dom.encode !== undefined && dom.is(value));
|
|
37
|
-
if (d?.encode !== undefined) {
|
|
38
|
-
const encoded: EncodedValue = { $vex: "domain", domain: d.name, value: d.encode(value) };
|
|
39
|
-
return encoded;
|
|
40
|
-
}
|
|
41
|
-
failure.push({ message: `a literal value is not JSON data and no domain encodes it` });
|
|
42
|
-
return null;
|
|
43
|
-
};
|
|
44
|
-
let text: string;
|
|
45
169
|
try {
|
|
46
|
-
|
|
170
|
+
// A getter of a literal value can throw, so the encoding is inside the try too.
|
|
171
|
+
const tree = mapValues(e, (v) => encodeValue(v, domains));
|
|
172
|
+
return tree.ok ? ok(JSON.stringify(tree.value)) : fail(tree.error);
|
|
47
173
|
} catch (thrown) {
|
|
174
|
+
if (isStackOverflow(thrown)) return fail(vexError("depth", "the expression is too deep for the call stack of the engine", { thrown }));
|
|
48
175
|
return fail(vexError("threw", "the expression has no JSON form", { thrown }));
|
|
49
176
|
}
|
|
50
|
-
const first = failure[0];
|
|
51
|
-
return first === undefined ? ok(text) : fail(vexError("bad-expression", first.message));
|
|
52
177
|
}
|
|
53
178
|
|
|
54
|
-
const isEncoded = (u: unknown): u is EncodedValue =>
|
|
55
|
-
(u as { $vex?: unknown } | null)?.$vex === "domain" && typeof (u as { domain?: unknown }).domain === "string";
|
|
56
|
-
|
|
57
179
|
/** This function reads an expression from JSON text. It checks the whole tree. */
|
|
58
180
|
// Stryker disable next-line ArrayDeclaration: a list with a value that is not a domain decodes no value
|
|
59
181
|
export function parse(text: string, domains: readonly AnyDomain[] = []): Result<Expr> {
|
|
60
182
|
let raw: unknown;
|
|
61
|
-
const failure: string[] = [];
|
|
62
183
|
try {
|
|
63
|
-
raw = JSON.parse(text
|
|
64
|
-
if (!isEncoded(value)) return value;
|
|
65
|
-
const d = domains.find((dom) => dom.name === value.domain);
|
|
66
|
-
if (d?.decode === undefined) {
|
|
67
|
-
failure.push(`no domain "${value.domain}" decodes a literal`);
|
|
68
|
-
return value;
|
|
69
|
-
}
|
|
70
|
-
const decoded: unknown = d.decode(value.value);
|
|
71
|
-
return decoded;
|
|
72
|
-
});
|
|
184
|
+
raw = JSON.parse(text);
|
|
73
185
|
} catch (thrown) {
|
|
74
186
|
return fail(vexError("bad-expression", "the text is not JSON", { thrown }));
|
|
75
187
|
}
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
188
|
+
try {
|
|
189
|
+
const tree = mapValues(raw, (v) => decodeValue(v, domains));
|
|
190
|
+
if (!tree.ok) return fail(tree.error);
|
|
191
|
+
return isExpr(tree.value) ? ok(tree.value) : fail(vexError("bad-expression", "the JSON is not a valid Vex expression"));
|
|
192
|
+
} catch (thrown) {
|
|
193
|
+
// A JSON text nested deeper than the call stack, or a decoder of a domain that throws.
|
|
194
|
+
if (isStackOverflow(thrown)) return fail(vexError("depth", "the JSON is too deep for the call stack of the engine", { thrown }));
|
|
195
|
+
return fail(vexError("threw", "a decoder of a domain threw an exception", { thrown }));
|
|
196
|
+
}
|
|
79
197
|
}
|
package/src/sheet.ts
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
* JSON form, `deps` and the traces work without a change.
|
|
8
8
|
*/
|
|
9
9
|
import { vexError } from "./errors.ts";
|
|
10
|
-
import { evaluate, explain, type EvalOptions, type ExtHandler } from "./evaluate.ts";
|
|
10
|
+
import { evaluate, explain, nestingOf, type EvalOptions, type ExtHandler } from "./evaluate.ts";
|
|
11
11
|
import { ext, isMove, type Addr, type Expr } from "./ir.ts";
|
|
12
12
|
import { fail, type Result } from "./result.ts";
|
|
13
13
|
import { resolveAddr } from "./space.ts";
|
|
@@ -38,15 +38,9 @@ export type SheetOptions = Omit<EvalOptions, "origin" | "trace">;
|
|
|
38
38
|
const cycleError = (column: string, key: string): Result<never> =>
|
|
39
39
|
fail(vexError("cycle", `the cell "${column}" at "${key}" is on a cycle of cell references`, { origin: key, focus: key }));
|
|
40
40
|
|
|
41
|
-
/**
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
*
|
|
45
|
-
* The run is a depth-first search with the algorithm of Tarjan for strongly connected components. A cell finishes
|
|
46
|
-
* when its component finishes. Each cell of a component with two or more cells, or with a reference to itself,
|
|
47
|
-
* gives `#CYCLE!`. A read of a cell that is not finished gives `#CYCLE!` too. Thus the order of the evaluations
|
|
48
|
-
* does not change a result, also when `ifError` catches the error of a cycle.
|
|
49
|
-
*/
|
|
41
|
+
/** The id of a cell. */
|
|
42
|
+
const idOf = (column: string, key: string): string => `${column}\u0000${key}`;
|
|
43
|
+
|
|
50
44
|
/** The state of one cell in the search. */
|
|
51
45
|
interface Visit {
|
|
52
46
|
readonly id: string;
|
|
@@ -56,23 +50,58 @@ interface Visit {
|
|
|
56
50
|
low: number;
|
|
57
51
|
reread: boolean;
|
|
58
52
|
result: Result<unknown>;
|
|
53
|
+
/** True when the last evaluation paused, because a cell that it reads is not finished. */
|
|
54
|
+
paused: boolean;
|
|
55
|
+
/** The cell that the evaluation waits for: a cell that the run started, or a cell that paused too. */
|
|
56
|
+
need: Visit | undefined;
|
|
59
57
|
}
|
|
60
58
|
|
|
59
|
+
/**
|
|
60
|
+
* The budget of the stack for the recursion of a run, in estimated frames. Each engine has more stack than this, so
|
|
61
|
+
* the recursion of a run cannot fill the stack (SHEET.DEEP).
|
|
62
|
+
*/
|
|
63
|
+
const STACK_BUDGET = 3000;
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* One run of a sheet. It keeps the result of each cell that it evaluated. The space does not change, so a cell has
|
|
67
|
+
* one result in a run.
|
|
68
|
+
*
|
|
69
|
+
* The run is a depth-first search with the algorithm of Tarjan for strongly connected components. A cell finishes
|
|
70
|
+
* when its component finishes. Each cell of a component with two or more cells, or with a reference to itself,
|
|
71
|
+
* gives `#CYCLE!`. A read of a cell that is not finished gives `#CYCLE!` too. Thus the order of the evaluations
|
|
72
|
+
* does not change a result, also when `ifError` catches the error of a cycle.
|
|
73
|
+
*
|
|
74
|
+
* The search does not depend on the call stack of the engine (SHEET.DEEP). A read of a cell evaluates that cell
|
|
75
|
+
* with recursion while the stack of the run stays in a budget. When a read is over the budget, the run starts the
|
|
76
|
+
* cell, and the cell that reads it pauses. A paused evaluation reads no other cell and changes no state of the
|
|
77
|
+
* search. The run then evaluates the started cell from its own list, and it evaluates the paused cell again after
|
|
78
|
+
* that cell. A formula is pure (EVAL.PURE), so the second evaluation gives the result of one evaluation.
|
|
79
|
+
*/
|
|
61
80
|
export class SheetRun {
|
|
62
81
|
readonly #columns: ReadonlyMap<string, Expr>;
|
|
63
82
|
readonly #opts: SheetOptions;
|
|
64
83
|
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;
|
|
65
88
|
// The cells on the stack of the search: started, but their component is not finished.
|
|
66
89
|
readonly #visits = new Map<string, Visit>();
|
|
67
90
|
// Stryker disable next-line ArrayDeclaration: the search never reads below the root of a component
|
|
68
91
|
readonly #stack: Visit[] = [];
|
|
69
92
|
// The cell whose formula is in evaluation. At the top level, it is a placeholder that is not a cell.
|
|
70
93
|
// Stryker disable next-line all: the placeholder is not a cell, so the search reads none of its fields
|
|
71
|
-
#top: Visit = { id: "", column: "", key: "", index: -1, low: -1, reread: false, result: cycleError("", "") };
|
|
94
|
+
#top: Visit = { id: "", column: "", key: "", index: -1, low: -1, reread: false, result: cycleError("", ""), paused: false, need: undefined };
|
|
72
95
|
#next = 0;
|
|
96
|
+
// The estimated frames of the stack that the evaluations in progress use, and the cost of a cell of each column.
|
|
97
|
+
#used = 0;
|
|
98
|
+
readonly #cost = new Map<string, number>();
|
|
99
|
+
readonly #budget: number;
|
|
73
100
|
|
|
74
|
-
|
|
101
|
+
/** `budget` is the budget of the stack in estimated frames. A test can make it small, so the run pauses often. */
|
|
102
|
+
constructor(columns: ReadonlyMap<string, Expr>, opts: SheetOptions, budget: number = STACK_BUDGET) {
|
|
75
103
|
this.#columns = columns;
|
|
104
|
+
this.#budget = budget;
|
|
76
105
|
this.#opts = { ...opts, extensions: { ...opts.extensions, [CELL_KIND]: this.#handler } };
|
|
77
106
|
}
|
|
78
107
|
|
|
@@ -80,15 +109,78 @@ export class SheetRun {
|
|
|
80
109
|
if (!isCellRef(data)) return fail(vexError("bad-expression", "a cell reference needs a column name and an address", { path: ctx.path }));
|
|
81
110
|
const where = resolveAddr(ctx.space, ctx.position, data.at);
|
|
82
111
|
if (!where.ok) return fail({ ...where.error, path: ctx.path });
|
|
83
|
-
return this
|
|
112
|
+
return this.#read(data.column, where.value);
|
|
84
113
|
};
|
|
85
114
|
|
|
86
|
-
/**
|
|
115
|
+
/**
|
|
116
|
+
* This method gives the result of one cell: the column `column` at the key `key`. A read from a host first evaluates
|
|
117
|
+
* the column at the keys before `key`, in key order. Thus a recurrence over the keys reads finished cells.
|
|
118
|
+
*/
|
|
87
119
|
cell(column: string, key: string): Result<unknown> {
|
|
88
|
-
|
|
120
|
+
// 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);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** 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 (!this.#columns.has(column)) return;
|
|
129
|
+
const keys = this.#opts.space.keys;
|
|
130
|
+
this.#index ??= new Map(keys.map((k, i) => [k, i]));
|
|
131
|
+
const end = this.#index.get(key) ?? 0;
|
|
132
|
+
const start = this.#warmed.get(column) ?? 0;
|
|
133
|
+
for (let i = start; i < end; i++) this.#drive(column, keys[i] ?? key);
|
|
134
|
+
if (end > start) this.#warmed.set(column, end);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** This method gives the estimated frames of the stack that one evaluation of a cell of `column` uses. */
|
|
138
|
+
#costOf(column: string, program: Expr): number {
|
|
139
|
+
let cost = this.#cost.get(column);
|
|
140
|
+
if (cost === undefined) {
|
|
141
|
+
cost = 3 * nestingOf(program) + 16;
|
|
142
|
+
this.#cost.set(column, cost);
|
|
143
|
+
}
|
|
144
|
+
return cost;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** This method puts a new cell on the stack of the search. */
|
|
148
|
+
#start(column: string, key: string): Visit {
|
|
149
|
+
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 };
|
|
151
|
+
this.#visits.set(visit.id, visit);
|
|
152
|
+
this.#stack.push(visit);
|
|
153
|
+
return visit;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** This method evaluates the formula of a cell once. When the evaluation pauses, the result of the cell does not change. */
|
|
157
|
+
#evaluate(visit: Visit, program: Expr): void {
|
|
158
|
+
const caller = this.#top;
|
|
159
|
+
const cost = this.#costOf(visit.column, program);
|
|
160
|
+
visit.paused = false;
|
|
161
|
+
visit.need = undefined;
|
|
162
|
+
this.#top = visit;
|
|
163
|
+
this.#used += cost;
|
|
164
|
+
const result = evaluate(program, { ...this.#opts, origin: visit.key });
|
|
165
|
+
this.#used -= cost;
|
|
166
|
+
this.#top = caller;
|
|
167
|
+
if (!visit.paused) visit.result = result;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** This method ends a cell whose evaluation did not pause: it finishes its component, or it gives its low to the caller. */
|
|
171
|
+
#end(visit: Visit, caller: Visit | undefined): void {
|
|
172
|
+
if (visit.low === visit.index) this.#finish(visit);
|
|
173
|
+
else if (caller !== undefined) caller.low = Math.min(caller.low, visit.low);
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** 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);
|
|
89
179
|
const done = this.#done.get(id);
|
|
90
180
|
if (done !== undefined) return done;
|
|
91
181
|
const caller = this.#top;
|
|
182
|
+
// A paused evaluation reads no other cell, so it does not follow a path that its final evaluation does not follow.
|
|
183
|
+
if (caller.paused) return cycleError(column, key);
|
|
92
184
|
const seen = this.#visits.get(id);
|
|
93
185
|
if (seen !== undefined) {
|
|
94
186
|
// A read of a cell that is not finished: the caller and this cell are on one cycle. The cell is on the
|
|
@@ -100,23 +192,52 @@ export class SheetRun {
|
|
|
100
192
|
}
|
|
101
193
|
const program = this.#columns.get(column);
|
|
102
194
|
if (program === undefined) return fail(vexError("unbound", `the sheet has no column "${column}"`, { origin: key, focus: key }));
|
|
195
|
+
const visit = this.#start(column, key);
|
|
196
|
+
if (this.#used + this.#costOf(column, program) > this.#budget) {
|
|
197
|
+
// Over the budget: the caller pauses, and the run evaluates the new cell from its own list.
|
|
198
|
+
caller.paused = true;
|
|
199
|
+
caller.need = visit;
|
|
200
|
+
return cycleError(column, key);
|
|
201
|
+
}
|
|
202
|
+
this.#evaluate(visit, program);
|
|
203
|
+
if (visit.paused) {
|
|
204
|
+
caller.paused = true;
|
|
205
|
+
caller.need = visit;
|
|
206
|
+
return cycleError(column, key);
|
|
207
|
+
}
|
|
208
|
+
this.#end(visit, caller);
|
|
209
|
+
return this.#done.get(id) ?? cycleError(column, key);
|
|
210
|
+
}
|
|
103
211
|
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
this.#
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
this.#
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
212
|
+
/** 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);
|
|
215
|
+
const done = this.#done.get(id);
|
|
216
|
+
if (done !== undefined) return done;
|
|
217
|
+
if (!this.#columns.has(column)) return fail(vexError("unbound", `the sheet has no column "${column}"`, { origin: key, focus: key }));
|
|
218
|
+
const work: Visit[] = [this.#start(column, key)];
|
|
219
|
+
for (let visit = work.at(-1); visit !== undefined; visit = work.at(-1)) {
|
|
220
|
+
const program = this.#columns.get(visit.column);
|
|
221
|
+
/* v8 ignore next -- @preserve: a visit exists only for a column with a program */
|
|
222
|
+
if (program === undefined) break;
|
|
223
|
+
this.#evaluate(visit, program);
|
|
224
|
+
if (visit.paused) {
|
|
225
|
+
// The cells that the evaluation waits for go on the list, the last one on the top.
|
|
226
|
+
for (let need = visit.need; need !== undefined; need = need.need) work.push(need);
|
|
227
|
+
continue;
|
|
228
|
+
}
|
|
229
|
+
work.pop();
|
|
230
|
+
this.#end(visit, work.at(-1));
|
|
231
|
+
}
|
|
114
232
|
return this.#done.get(id) ?? cycleError(column, key);
|
|
115
233
|
}
|
|
116
234
|
|
|
117
235
|
/** This method takes the component of `root` from the stack, and sets the final result of each of its cells. */
|
|
118
236
|
#finish(root: Visit): void {
|
|
119
|
-
|
|
237
|
+
// The root is near the top of the stack, so the search starts at the top: a deep chain needs no long scan.
|
|
238
|
+
const members = this.#stack.splice(this.#stack.lastIndexOf(root));
|
|
239
|
+
// A component of two or more cells reads its root again, so root.reread alone decides. The length test is a guard.
|
|
240
|
+
// Stryker disable next-line ConditionalExpression,LogicalOperator: members.length > 1 implies root.reread
|
|
120
241
|
const cyclic = members.length > 1 || root.reread;
|
|
121
242
|
for (const m of members) {
|
|
122
243
|
// Stryker disable next-line CallExpression: a finished cell is in #done, and cell() reads #done first
|
|
@@ -135,12 +256,9 @@ export class SheetRun {
|
|
|
135
256
|
|
|
136
257
|
/**
|
|
137
258
|
* This method evaluates the column `column` at each key before `key`, in key order. A recurrence over the keys,
|
|
138
|
-
* for example a running total, then reads finished cells
|
|
259
|
+
* for example a running total, then reads finished cells.
|
|
139
260
|
*/
|
|
140
261
|
warm(column: string, key: string): void {
|
|
141
|
-
|
|
142
|
-
if (k === key) return;
|
|
143
|
-
this.cell(column, k);
|
|
144
|
-
}
|
|
262
|
+
this.#warmTo(column, key);
|
|
145
263
|
}
|
|
146
264
|
}
|
package/src/space.ts
CHANGED
|
@@ -225,6 +225,16 @@ export function applyMove(s: Space, at: Position, m: Move): Result<string> {
|
|
|
225
225
|
return ok(at.focus === a ? (b ?? at.focus) : (a ?? at.focus));
|
|
226
226
|
}
|
|
227
227
|
case "offset": {
|
|
228
|
+
// In a tree space, an offset with one number moves among the siblings in key order. The roots are siblings.
|
|
229
|
+
const parentOf = s.parentOf?.bind(s);
|
|
230
|
+
const childrenOf = s.childrenOf?.bind(s);
|
|
231
|
+
if (parentOf !== undefined && childrenOf !== undefined && m.d.length === 1) {
|
|
232
|
+
const p = parentOf(at.focus);
|
|
233
|
+
const group = p === undefined ? s.keys.filter((k) => parentOf(k) === undefined) : childrenOf(p);
|
|
234
|
+
const i = group.indexOf(at.focus);
|
|
235
|
+
const k = i < 0 ? undefined : group[i + (m.d[0] ?? 0)];
|
|
236
|
+
return k === undefined ? refError("out-of-bounds", `the offset [${m.d.join(",")}] from "${at.focus}" is outside its siblings`) : ok(k);
|
|
237
|
+
}
|
|
228
238
|
const c = s.coords(at.focus);
|
|
229
239
|
if (c === undefined || c.length !== m.d.length) {
|
|
230
240
|
return refError("no-offset", `an offset of length ${m.d.length} is not valid in a ${s.kind} space`);
|