@mark1russell7/vex 0.6.0 → 0.7.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/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 Addr, type Expr } from "./ir.ts";
13
+ import { evaluate, explain, nestingOf, type CompileOptions, type EvalOptions, type ExtHandler, type Program } from "./evaluate.ts";
14
+ import { addrExprs, children, ext, isMove, 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
- /** The data of a cell reference: the column, and the address from the focus. */
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: Addr;
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: Addr = []): Expr => ext(CELL_KIND, { column, at } satisfies CellRef);
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,128 @@ 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
+ if (m.t === "offset" || m.t === "window") {
124
+ // An offset moves by its first step that is not 0. A window reads the keys from `from` to `to`.
125
+ const steps = m.t === "offset" ? [m.d.find((x) => x !== 0) ?? 0] : [m.from, m.to];
126
+ // A step of 0 reads the cell itself, which is a cycle in each order.
127
+ // Stryker disable next-line EqualityOperator: see the comment above
128
+ if (steps.some((x) => x < 0)) d.add("before");
129
+ // Stryker disable next-line EqualityOperator: see the comment above
130
+ if (steps.some((x) => x > 0)) d.add("after");
131
+ } else if (m.t === "children" || m.t === "descendants") d.add("down");
132
+ }
133
+
134
+ /** This function gives the base axis of an axis, and the tests of its `where` axes. */
135
+ function partsOf(axis: Axis): { readonly base: Axis; readonly tests: readonly Expr[] } {
136
+ const tests: Expr[] = [];
137
+ let base = axis;
138
+ while (base.t === "where") {
139
+ tests.push(base.test);
140
+ base = base.axis;
141
+ }
142
+ return { base, tests };
143
+ }
144
+
145
+ /**
146
+ * This function gives the columns that the formulas of the column `self` read with a cell reference: its formula and
147
+ * the formulas of its cells. It also gives the directions of their reads of the column itself. A read in the body or
148
+ * in a test of an axis also has the direction of that axis. It walks each expression with a stack, not with recursion.
149
+ */
150
+ function readsOf(t: Table, self: string): { readonly columns: ReadonlySet<string>; readonly directions: ReadonlySet<Direction> } {
151
+ const columns = new Set<string>();
152
+ const directions = new Set<Direction>();
153
+ const formula = t.columns.get(self);
154
+ // An expression that is not valid reads no column. Its evaluation gives the error (EVAL.SHAPE).
155
+ const todo: [Expr, Axis | undefined][] = [...(formula === undefined ? [] : [formula]), ...(t.cells.get(self)?.values() ?? [])].filter((e) => shapeError(e) === undefined).map((e) => [e, undefined]);
156
+ for (let item = todo.pop(); item !== undefined; item = todo.pop()) {
157
+ const [e, axis] = item;
158
+ if (e.tag === "each" || e.tag === "fold") {
159
+ const { base, tests } = partsOf(e.axis);
160
+ for (const x of [...(e.tag === "each" ? [e.body] : Object.values(e.step)), ...tests]) todo.push([x, base]);
161
+ // The values of init, the result of a fold and the expressions of the address evaluate at the node, so they keep
162
+ // the outer direction.
163
+ for (const x of [...(e.tag === "fold" ? [...Object.values(e.init), e.result] : []), ...addrExprs(e.at)]) todo.push([x, axis]);
164
+ } else if (e.tag !== "ext") {
165
+ for (const child of children(e)) todo.push([child, axis]);
166
+ // The data of an extension of another kind can look like a cell reference. It only changes the order of a fill.
167
+ // Stryker disable next-line ConditionalExpression,LogicalOperator: see the comment above
168
+ } else if (e.kind === CELL_KIND && isCellRef(e.data)) {
169
+ columns.add(e.data.column);
170
+ // The directions of the reads of another column only change the order of a fill, because that column comes first.
171
+ // Stryker disable next-line ConditionalExpression: see the comment above
172
+ if (e.data.column === self) for (const m of [...(axis === undefined ? [] : [axis]), ...e.data.at]) addDirection(directions, m);
173
+ }
174
+ }
175
+ return { columns, directions };
176
+ }
177
+
178
+ /**
179
+ * This function gives the columns of a table in an order where each column comes after the columns that it reads.
180
+ * The columns of a cycle keep their order. The columns with formulas of cells only come last.
181
+ */
182
+ function columnOrder(t: Table): readonly string[] {
183
+ const names = new Set([...t.columns.keys(), ...t.cells.keys()]);
184
+ let left = [...names].map((c) => ({ c, needs: [...readsOf(t, c).columns].filter((x) => x !== c && names.has(x)) }));
185
+ const order: string[] = [];
186
+ const placed = new Set<string>();
187
+ // Each pass places each column whose reads are placed. A pass that places no column leaves a cycle, so it places
188
+ // the first column that is left.
189
+ while (left.length > 0) {
190
+ const ready = left.filter((x) => x.needs.every((n) => placed.has(n)));
191
+ for (const x of ready.length > 0 ? ready : left.slice(0, 1)) {
192
+ order.push(x.c);
193
+ placed.add(x.c);
194
+ }
195
+ left = left.filter((x) => !placed.has(x.c));
196
+ }
197
+ return order;
198
+ }
199
+
200
+ /**
201
+ * 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
202
+ * reverses the order. In a tree, a read of the children puts the children before their parent.
203
+ */
204
+ function keyOrder(s: Space, d: ReadonlySet<Direction>): readonly string[] {
205
+ const reverse = d.has("after") && !d.has("before");
206
+ const childrenOf = s.childrenOf?.bind(s);
207
+ if (childrenOf === undefined) return reverse ? s.keys.toReversed() : s.keys;
208
+ const post = d.has("down");
209
+ // The order with each parent before its children, and the order after the children is that order from the end, with
210
+ // the siblings in the other order. `push` puts the next key to visit at the end of the stack.
211
+ const backwards = post !== reverse;
212
+ const push = (stack: string[], keys: readonly string[]): void => {
213
+ for (const k of backwards ? keys : keys.toReversed()) stack.push(k);
214
+ };
215
+ const isChild = new Set(s.keys.flatMap((k) => childrenOf(k)));
216
+ const stack: string[] = [];
217
+ push(stack, s.keys.filter((k) => !isChild.has(k)));
218
+ const out: string[] = [];
219
+ for (let k = stack.pop(); k !== undefined; k = stack.pop()) {
220
+ out.push(k);
221
+ push(stack, childrenOf(k));
222
+ }
223
+ return post ? out.toReversed() : out;
224
+ }
81
225
 
82
226
  /** The state of one cell in the search. */
83
227
  interface Visit {
@@ -125,23 +269,33 @@ export class SheetRun {
125
269
  readonly #byName = new Map<string, Table>();
126
270
  readonly #bySpace = new Map<Space, Table>();
127
271
  readonly #opts: Omit<EvalOptions, "origin" | "trace" | "space">;
128
- readonly #done = new Map<string, Result<unknown>>();
129
272
  // The cells on the stack of the search: started, but their component is not finished.
130
273
  readonly #visits = new Map<string, Visit>();
131
274
  // Stryker disable next-line ArrayDeclaration: the search never reads below the root of a component
132
275
  readonly #stack: Visit[] = [];
133
276
  // The cell whose formula is in evaluation. At the top level, it is a placeholder that is not a cell.
134
277
  #top: Visit;
278
+ // The placeholder at the top in a fill, and true when the evaluation of a fill reads a cell that is not finished.
279
+ readonly #filling: Visit;
280
+ #missed = false;
135
281
  #next = 0;
136
282
  // The estimated frames of the stack that the evaluations in progress use, and the cost of each program.
137
283
  #used = 0;
138
284
  readonly #cost = new Map<Expr, number>();
139
285
  readonly #budget: number;
286
+ readonly #compile: CompileFn | undefined;
287
+ readonly #compileOptions: CompileOptions;
288
+ // The run that evaluates a formula with a compiled program. Each run is synchronous, so a run inside the evaluation
289
+ // of another run gives the active run back when it ends.
290
+ static #active: SheetRun | undefined;
291
+ // The extensions of the compiled programs, for each object of extensions of the options. Their cell handler reads
292
+ // the cells of the active run, so a compiled program does not depend on one run.
293
+ static readonly #shared = new WeakMap<object, Readonly<Record<string, ExtHandler>>>();
140
294
 
141
295
  /** `budget` is the budget of the stack in estimated frames. A test can make it small, so the run pauses often. */
142
296
  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 };
297
+ const { cells, name, tables, space, compile, ...rest } = opts;
298
+ this.#main = { where: "the sheet", tag: "0", space, columns, cells: cells ?? new Map(), warmed: new Map(), index: undefined, done: new Map() };
145
299
  this.#bySpace.set(space, this.#main);
146
300
  if (name !== undefined) this.#byName.set(name, this.#main);
147
301
  if (tables !== undefined) {
@@ -156,11 +310,27 @@ export class SheetRun {
156
310
  }
157
311
  // Stryker disable next-line all: the placeholder is not a cell, so the search reads none of its fields
158
312
  this.#top = { id: "", table: this.#main, column: "", key: "", index: -1, low: -1, reread: false, result: cycleError("", ""), paused: false, need: undefined };
313
+ // Stryker disable next-line all: the placeholder is not a cell, so the search reads none of its fields
314
+ this.#filling = { id: "", table: this.#main, column: "", key: "", index: 0, low: 0, reread: false, result: cycleError("", ""), paused: false, need: undefined };
159
315
  this.#budget = budget;
316
+ this.#compile = compile;
160
317
  const spaces = Object.fromEntries([...this.#byName].map(([n, t]) => [n, t.space]));
161
318
  this.#opts = { ...rest, tables: spaces, extensions: { ...rest.extensions, [CELL_KIND]: this.#handler } };
319
+ const outer = rest.extensions ?? NO_EXTENSIONS;
320
+ let shared = SheetRun.#shared.get(outer);
321
+ if (shared === undefined) {
322
+ shared = { ...rest.extensions, [CELL_KIND]: SheetRun.#cellOfActive };
323
+ SheetRun.#shared.set(outer, shared);
324
+ }
325
+ this.#compileOptions = { ...this.#opts, extensions: shared };
162
326
  }
163
327
 
328
+ /** The cell handler of the compiled programs: it reads the cells of the active run. */
329
+ static readonly #cellOfActive: ExtHandler = (data, ctx) => {
330
+ const run = SheetRun.#active;
331
+ return run === undefined ? fail(vexError("unbound", "a compiled formula reads cells only in the evaluation of a sheet run")) : run.#handler(data, ctx);
332
+ };
333
+
164
334
  /** This method gives the program of a cell: its own formula, or the formula of its column (SHEET.CELL.FORMULA). */
165
335
  #programOf(t: Table, column: string, key: string): Expr | undefined {
166
336
  // Stryker disable next-line ConditionalExpression: without formulas of cells, the lookup gives undefined anyway
@@ -181,7 +351,8 @@ export class SheetRun {
181
351
  }
182
352
 
183
353
  readonly #handler: ExtHandler = (data, ctx) => {
184
- if (!isCellRef(data)) return fail(vexError("bad-expression", "a cell reference needs a column name and an address", { path: ctx.path }));
354
+ // The interpreter gives an error without an origin the path and the position of its node.
355
+ if (!isCellRef(data)) return fail(vexError("bad-expression", "a cell reference needs a column name and an address of fixed moves"));
185
356
  const where = resolveAddr(ctx.space, ctx.position, data.at);
186
357
  if (!where.ok) return fail({ ...where.error, path: ctx.path });
187
358
  // 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 +370,9 @@ export class SheetRun {
199
370
  if (!("space" in t)) return t;
200
371
  // 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
372
  if (this.#top.index >= 0) return this.#read(t, column, key);
373
+ // A finished cell needs no warm-up.
374
+ const done = doneOf(t, column, key);
375
+ if (done !== undefined) return done;
202
376
  this.#warmTo(t, column, key);
203
377
  return this.#drive(t, column, key);
204
378
  }
@@ -218,7 +392,7 @@ export class SheetRun {
218
392
  #costOf(program: Expr): number {
219
393
  let cost = this.#cost.get(program);
220
394
  if (cost === undefined) {
221
- cost = 3 * nestingOf(program) + 16;
395
+ cost = 3 * (shapeError(program) === undefined ? nestingOf(program) : 1) + 16;
222
396
  this.#cost.set(program, cost);
223
397
  }
224
398
  return cost;
@@ -241,12 +415,40 @@ export class SheetRun {
241
415
  visit.need = undefined;
242
416
  this.#top = visit;
243
417
  this.#used += cost;
244
- const result = evaluate(program, { ...this.#opts, space: visit.table.space, origin: visit.key });
418
+ const result = this.#run(visit.table, visit.column, visit.key, program);
245
419
  this.#used -= cost;
246
420
  this.#top = caller;
247
421
  if (!visit.paused) visit.result = result;
248
422
  }
249
423
 
424
+ /** This method evaluates the formula `program` of a cell, with its compiled program or with the interpreter. */
425
+ #run(t: Table, column: string, key: string, program: Expr): Result<unknown> {
426
+ const options = { ...this.#opts, space: t.space, origin: key };
427
+ const compiled = this.#compiled(t, column, program);
428
+ if (compiled === undefined) return evaluate(program, options);
429
+ const active = SheetRun.#active;
430
+ SheetRun.#active = this;
431
+ const result = compiled.run(options);
432
+ SheetRun.#active = active;
433
+ return result;
434
+ }
435
+
436
+ /**
437
+ * This method gives the compiled program of the formula of a column, or `undefined` for the interpreter. A formula
438
+ * compiles once for each compiler and options, also across runs.
439
+ */
440
+ #compiled(t: Table, column: string, program: Expr): Program | undefined {
441
+ const compile = this.#compile;
442
+ // The formula of a cell evaluates once in a run, so the run compiles only the formulas of the columns.
443
+ if (compile === undefined || t.columns.get(column) !== program) return undefined;
444
+ const { domains, fns, extensions } = this.#compileOptions;
445
+ const hit = PROGRAMS.get(program);
446
+ if (hit !== undefined && hit.compile === compile && hit.domains === domains && hit.fns === fns && hit.extensions === extensions) return hit.program;
447
+ const compiled = compile(program, this.#compileOptions);
448
+ PROGRAMS.set(program, { compile, domains, fns, extensions, program: compiled });
449
+ return compiled;
450
+ }
451
+
250
452
  /** This method ends a cell whose evaluation did not pause: it finishes its component, or it gives its low to the caller. */
251
453
  #end(visit: Visit, caller: Visit | undefined): void {
252
454
  if (visit.low === visit.index) this.#finish(visit);
@@ -255,12 +457,17 @@ export class SheetRun {
255
457
 
256
458
  /** This method reads a cell from the formula of the cell at the top. */
257
459
  #read(t: Table, column: string, key: string): Result<unknown> {
258
- const id = idOf(t, column, key);
259
- const done = this.#done.get(id);
460
+ const done = doneOf(t, column, key);
260
461
  if (done !== undefined) return done;
261
462
  const caller = this.#top;
262
463
  // A paused evaluation reads no other cell, so it does not follow a path that its final evaluation does not follow.
464
+ // In a fill, the cell goes to the search after the evaluation (SHEET.FILL).
263
465
  if (caller.paused) return cycleError(column, key);
466
+ if (caller === this.#filling) {
467
+ this.#missed = true;
468
+ return cycleError(column, key);
469
+ }
470
+ const id = idOf(t, column, key);
264
471
  const seen = this.#visits.get(id);
265
472
  if (seen !== undefined) {
266
473
  // 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 +493,12 @@ export class SheetRun {
286
493
  return cycleError(column, key);
287
494
  }
288
495
  this.#end(visit, caller);
289
- return this.#done.get(id) ?? cycleError(column, key);
496
+ return doneOf(t, column, key) ?? cycleError(column, key);
290
497
  }
291
498
 
292
499
  /** This method evaluates a cell from the top level. The cells that pause go on a list, not on the call stack. */
293
500
  #drive(t: Table, column: string, key: string): Result<unknown> {
294
- const id = idOf(t, column, key);
295
- const done = this.#done.get(id);
501
+ const done = doneOf(t, column, key);
296
502
  if (done !== undefined) return done;
297
503
  if (this.#programOf(t, column, key) === undefined) return this.#unbound(t, column, key);
298
504
  const work: Visit[] = [this.#start(t, column, key)];
@@ -309,7 +515,7 @@ export class SheetRun {
309
515
  work.pop();
310
516
  this.#end(visit, work.at(-1));
311
517
  }
312
- return this.#done.get(id) ?? cycleError(column, key);
518
+ return doneOf(t, column, key) ?? cycleError(column, key);
313
519
  }
314
520
 
315
521
  /** This method takes the component of `root` from the stack, and sets the final result of each of its cells. */
@@ -320,9 +526,9 @@ export class SheetRun {
320
526
  // Stryker disable next-line ConditionalExpression,LogicalOperator: members.length > 1 implies root.reread
321
527
  const cyclic = members.length > 1 || root.reread;
322
528
  for (const m of members) {
323
- // Stryker disable next-line CallExpression: a finished cell is in #done, and cell() reads #done first
529
+ // Stryker disable next-line CallExpression: a finished cell has a result, and a read looks for the result first
324
530
  this.#visits.delete(m.id);
325
- this.#done.set(m.id, cyclic ? cycleError(m.column, m.key) : m.result);
531
+ setDone(m.table, m.column, m.key, cyclic ? cycleError(m.column, m.key) : m.result);
326
532
  }
327
533
  }
328
534
 
@@ -335,6 +541,31 @@ export class SheetRun {
335
541
  return { events: explain(program, { ...this.#opts, space: t.space, origin: key }).events, result };
336
542
  }
337
543
 
544
+ /**
545
+ * This method evaluates each cell of the table `table`, or of the main table (SHEET.FILL). Each column comes after
546
+ * the columns that it reads, and the keys of a column come in the order of its reads from itself. Thus most reads
547
+ * find a finished cell. An evaluation that reads a cell that is not finished has no effect, and the search then
548
+ * evaluates its cell. A read of a cell gives the same result after a fill.
549
+ */
550
+ fill(table?: string): void {
551
+ const t = table === undefined ? this.#main : this.#byName.get(table);
552
+ // A read inside a formula has a cell at the top. A fill there has no effect.
553
+ if (t === undefined || this.#top.index >= 0) return;
554
+ const host = this.#top;
555
+ for (const column of columnOrder(t)) {
556
+ for (const key of keyOrder(t.space, readsOf(t, column).directions)) {
557
+ const program = this.#programOf(t, column, key);
558
+ if (program === undefined || doneOf(t, column, key) !== undefined) continue;
559
+ this.#top = this.#filling;
560
+ this.#missed = false;
561
+ const result = this.#run(t, column, key, program);
562
+ this.#top = host;
563
+ if (this.#missed) this.#drive(t, column, key);
564
+ else setDone(t, column, key, result);
565
+ }
566
+ }
567
+ }
568
+
338
569
  /**
339
570
  * This method evaluates the column `column` at each key before `key`, in key order. A recurrence over the keys,
340
571
  * 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 { Addr, Axis, Move } from "./ir.ts";
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 #items: ReadonlyMap<string, O>;
77
+ readonly records: readonly O[];
71
78
 
72
79
  constructor(items: readonly O[]) {
73
- const entries = items.map((item, i): [ArrayKey, O] => [`${i}`, item]);
74
- this.keys = Object.freeze(entries.map(([k]) => k));
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.#items.has(k);
87
+ return this.keys[Number(k)] === k;
80
88
  }
81
89
  get(k: string): O | undefined {
82
- return this.#items.get(k);
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
- const k = String(coords[0]);
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: Move): Result<string> {
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: Addr | undefined): Result<string> {
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);