@mark1russell7/vex 0.5.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/space.ts CHANGED
@@ -1,9 +1,9 @@
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. */
6
- export type SpaceKind = "record" | "array" | "grid" | "tree";
6
+ export type SpaceKind = "record" | "array" | "grid" | "tree" | "graph";
7
7
 
8
8
  /**
9
9
  * A space: an immutable collection of records with keys. A Vex program evaluates at one key of a space.
@@ -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`. */
@@ -25,6 +30,10 @@ export interface Space<K extends string = string, O = unknown> {
25
30
  parentOf?(k: string): K | undefined;
26
31
  /** The children of the key `k` in a tree space, in key order. Other spaces do not have it. */
27
32
  childrenOf?(k: string): readonly K[];
33
+ /** The keys at the ends of the edges from `k`, in a graph space or a tree space. Other spaces do not have it. */
34
+ successorsOf?(k: string): readonly K[];
35
+ /** The keys with an edge to `k`, in key order, in a graph space or a tree space. Other spaces do not have it. */
36
+ predecessorsOf?(k: string): readonly K[];
28
37
  }
29
38
 
30
39
  /** The key type of a grid space. */
@@ -36,11 +45,13 @@ export type ArrayKey = `${number}`;
36
45
  class RecordSpace<K extends string, O> implements Space<K, O> {
37
46
  readonly kind: SpaceKind = "record";
38
47
  readonly keys: readonly K[];
48
+ readonly records: readonly O[];
39
49
  readonly #records: ReadonlyMap<string, O>;
40
50
 
41
51
  constructor(records: Readonly<Record<K, O>>) {
42
52
  const entries = Object.entries(records) as [K, O][];
43
53
  this.keys = Object.freeze(entries.map(([k]) => k));
54
+ this.records = Object.freeze(entries.map(([, o]) => o));
44
55
  this.#records = new Map(entries);
45
56
  }
46
57
 
@@ -63,38 +74,40 @@ class RecordSpace<K extends string, O> implements Space<K, O> {
63
74
  class ArraySpace<O> implements Space<ArrayKey, O> {
64
75
  readonly kind: SpaceKind = "array";
65
76
  readonly keys: readonly ArrayKey[];
66
- readonly #items: ReadonlyMap<string, O>;
77
+ readonly records: readonly O[];
67
78
 
68
79
  constructor(items: readonly O[]) {
69
- const entries = items.map((item, i): [ArrayKey, O] => [`${i}`, item]);
70
- this.keys = Object.freeze(entries.map(([k]) => k));
71
- 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));
72
82
  }
73
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.
74
86
  has(k: string): k is ArrayKey {
75
- return this.#items.has(k);
87
+ return this.keys[Number(k)] === k;
76
88
  }
77
89
  get(k: string): O | undefined {
78
- return this.#items.get(k);
90
+ return this.has(k) ? this.records[Number(k)] : undefined;
79
91
  }
80
92
  coords(k: string): readonly number[] | undefined {
81
93
  return this.has(k) ? [Number(k)] : undefined;
82
94
  }
83
95
  keyAt(coords: readonly number[]): ArrayKey | undefined {
84
- const k = String(coords[0]);
85
- return coords.length === 1 && this.has(k) ? k : undefined;
96
+ return coords.length === 1 ? this.keys[Number(coords[0])] : undefined;
86
97
  }
87
98
  }
88
99
 
89
100
  class GridSpace<O> implements Space<GridKey, O> {
90
101
  readonly kind: SpaceKind = "grid";
91
102
  readonly keys: readonly GridKey[];
103
+ readonly records: readonly O[];
92
104
  readonly #cells: ReadonlyMap<string, O>;
93
105
  readonly #coords: ReadonlyMap<string, readonly number[]>;
94
106
 
95
107
  constructor(rows: readonly (readonly O[])[]) {
96
108
  const entries = rows.flatMap((row, i) => row.map((cell, j): [GridKey, O, readonly number[]] => [`${i},${j}`, cell, Object.freeze([i, j])]));
97
109
  this.keys = Object.freeze(entries.map(([k]) => k));
110
+ this.records = Object.freeze(entries.map(([, o]) => o));
98
111
  this.#cells = new Map(entries.map(([k, cell]) => [k, cell]));
99
112
  this.#coords = new Map(entries.map(([k, , c]) => [k, c]));
100
113
  }
@@ -118,6 +131,7 @@ class GridSpace<O> implements Space<GridKey, O> {
118
131
  class TreeSpace<K extends string, O> implements Space<K, O> {
119
132
  readonly kind: SpaceKind = "tree";
120
133
  readonly keys: readonly K[];
134
+ readonly records: readonly O[];
121
135
  readonly #records: ReadonlyMap<string, O>;
122
136
  readonly #parents: ReadonlyMap<string, K>;
123
137
  readonly #children: ReadonlyMap<string, readonly K[]>;
@@ -125,6 +139,7 @@ class TreeSpace<K extends string, O> implements Space<K, O> {
125
139
  constructor(records: Readonly<Record<K, O>>, parents: Readonly<Partial<Record<K, K | null>>>) {
126
140
  const entries = Object.entries(records) as [K, O][];
127
141
  this.keys = Object.freeze(entries.map(([k]) => k));
142
+ this.records = Object.freeze(entries.map(([, o]) => o));
128
143
  this.#records = new Map(entries);
129
144
  const parentOf = new Map<string, K>();
130
145
  for (const [k, p] of Object.entries(parents) as [K, K | null | undefined][]) {
@@ -169,6 +184,14 @@ class TreeSpace<K extends string, O> implements Space<K, O> {
169
184
  keyAt(): K | undefined {
170
185
  return undefined;
171
186
  }
187
+ // In a tree, the edges go from a parent to its children.
188
+ successorsOf(k: string): readonly K[] {
189
+ return this.childrenOf(k);
190
+ }
191
+ predecessorsOf(k: string): readonly K[] {
192
+ const p = this.#parents.get(k);
193
+ return p === undefined ? [] : [p];
194
+ }
172
195
  parentOf(k: string): K | undefined {
173
196
  return this.#parents.get(k);
174
197
  }
@@ -178,6 +201,65 @@ class TreeSpace<K extends string, O> implements Space<K, O> {
178
201
  }
179
202
 
180
203
  /** The constructors of spaces. */
204
+ /** The empty list of keys. */
205
+ const NO_KEYS: readonly never[] = Object.freeze([]);
206
+
207
+ class GraphSpace<K extends string, O> implements Space<K, O> {
208
+ readonly kind: SpaceKind = "graph";
209
+ readonly keys: readonly K[];
210
+ readonly records: readonly O[];
211
+ readonly #records: ReadonlyMap<string, O>;
212
+ readonly #out: ReadonlyMap<string, readonly K[]>;
213
+ readonly #in: ReadonlyMap<string, readonly K[]>;
214
+
215
+ constructor(records: Readonly<Record<K, O>>, edges: Readonly<Partial<Record<K, readonly K[]>>>) {
216
+ const entries = Object.entries(records) as [K, O][];
217
+ this.keys = Object.freeze(entries.map(([k]) => k));
218
+ this.records = Object.freeze(entries.map(([, o]) => o));
219
+ this.#records = new Map(entries);
220
+ const out = new Map<string, readonly K[]>();
221
+ for (const [k, to] of Object.entries(edges) as [K, readonly K[] | undefined][]) {
222
+ if (!this.#records.has(k)) throw new TypeError(`the graph has no key "${k}", but the edges name it`);
223
+ // A second edge to the same key is the same edge.
224
+ const ends = [...new Set(to ?? NO_KEYS)];
225
+ for (const t of ends) if (!this.#records.has(t)) throw new TypeError(`the edge from "${k}" goes to "${t}", which is not a key of the graph`);
226
+ out.set(k, Object.freeze(ends));
227
+ }
228
+ this.#out = out;
229
+ // The predecessors in key order: the keys in key order, and the ends of the edges of each key.
230
+ const into = new Map<string, K[]>();
231
+ for (const k of this.keys) {
232
+ for (const t of out.get(k) ?? NO_KEYS) {
233
+ const from = into.get(t);
234
+ if (from === undefined) into.set(t, [k]);
235
+ else from.push(k);
236
+ }
237
+ }
238
+ this.#in = new Map([...into].map(([k, from]) => [k, Object.freeze(from)]));
239
+ }
240
+
241
+ has(k: string): k is K {
242
+ return this.#records.has(k);
243
+ }
244
+ get(k: string): O | undefined {
245
+ return this.#records.get(k);
246
+ }
247
+ // Stryker disable next-line BlockStatement: the body gives undefined, and an empty body gives undefined too
248
+ coords(): readonly number[] | undefined {
249
+ return undefined;
250
+ }
251
+ // Stryker disable next-line BlockStatement: the body gives undefined, and an empty body gives undefined too
252
+ keyAt(): K | undefined {
253
+ return undefined;
254
+ }
255
+ successorsOf(k: string): readonly K[] {
256
+ return this.#out.get(k) ?? NO_KEYS;
257
+ }
258
+ predecessorsOf(k: string): readonly K[] {
259
+ return this.#in.get(k) ?? NO_KEYS;
260
+ }
261
+ }
262
+
181
263
  export const space = {
182
264
  /** This function makes a space from the entries of an object. The keys are the property names. */
183
265
  record<const R extends Readonly<Record<string, unknown>>>(records: R): Space<keyof R & string, R[keyof R]> {
@@ -198,6 +280,13 @@ export const space = {
198
280
  tree<const R extends Readonly<Record<string, unknown>>>(records: R, parents: Readonly<Partial<Record<keyof R & string, (keyof R & string) | null>>>): Space<keyof R & string, R[keyof R]> {
199
281
  return new TreeSpace<keyof R & string, R[keyof R]>(records, parents);
200
282
  },
283
+ /**
284
+ * This function makes a graph space: the records by key, and the edges from each key, in order. An edge to a key
285
+ * that is not in the graph throws a `TypeError`. A graph can have cycles, and an edge can go from a key to itself.
286
+ */
287
+ graph<const R extends Readonly<Record<string, unknown>>>(records: R, edges: Readonly<Partial<Record<keyof R & string, readonly (keyof R & string)[]>>>): Space<keyof R & string, R[keyof R]> {
288
+ return new GraphSpace<keyof R & string, R[keyof R]>(records, edges);
289
+ },
201
290
  } as const;
202
291
 
203
292
  /** The position of an evaluation: the key where it started, and the key where relative references read. */
@@ -207,7 +296,7 @@ export interface Position {
207
296
  }
208
297
 
209
298
  /** This function applies one move to the focus. It gives the new focus, or a `#REF!` error. */
210
- export function applyMove(s: Space, at: Position, m: Move): Result<string> {
299
+ export function applyMove(s: Space, at: Position, m: FixedMove): Result<string> {
211
300
  const refError = (kind: "unknown-key" | "not-a-pair" | "out-of-bounds" | "no-offset" | "no-tree", message: string): Result<string> =>
212
301
  fail(vexError(kind, message, { origin: at.origin, focus: at.focus }));
213
302
  switch (m.t) {
@@ -255,8 +344,28 @@ export function applyMove(s: Space, at: Position, m: Move): Result<string> {
255
344
  }
256
345
  }
257
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
+
258
367
  /** This function applies the moves of an address in order. It gives the key where the address points. */
259
- 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> {
260
369
  let focus = at.focus;
261
370
  for (const m of addr ?? []) {
262
371
  const r = applyMove(s, { origin: at.origin, focus }, m);
@@ -335,5 +444,59 @@ export function axisTargets(s: Space, at: Position, a: Exclude<Axis, { readonly
335
444
  case "descendants":
336
445
  case "siblings":
337
446
  return treeTargets(s, at, a.t);
447
+ case "window":
448
+ return windowTargets(s, at, a.from, a.to);
449
+ case "successors":
450
+ case "predecessors":
451
+ case "reachable":
452
+ return graphTargets(s, at, a.t);
453
+ case "table":
454
+ // The evaluator gives the axis table the space of its table. Here, without the tables, it has no targets.
455
+ return fail(vexError("no-table", `the axis "table" needs the tables of the evaluation, and "${a.name}" is not one of them`, at));
456
+ }
457
+ }
458
+
459
+ /**
460
+ * This function gives the targets of an axis of a graph. `reachable` has each key that a path of one or more edges
461
+ * reaches from the focus, once, in the order of a breadth-first search. The focus is not a target of `reachable`.
462
+ */
463
+ function graphTargets(s: Space, at: Position, t: "successors" | "predecessors" | "reachable"): Result<readonly string[]> {
464
+ const successorsOf = s.successorsOf?.bind(s);
465
+ const predecessorsOf = s.predecessorsOf?.bind(s);
466
+ if (successorsOf === undefined || predecessorsOf === undefined) {
467
+ return fail(vexError("no-graph", `"${t}" needs a graph space or a tree space, but this space is a ${s.kind}`, at));
468
+ }
469
+ if (t === "successors") return ok(successorsOf(at.focus));
470
+ if (t === "predecessors") return ok(predecessorsOf(at.focus));
471
+ // A queue, not recursion, so a long path does not need a deep call stack. A loop over an array also reads the
472
+ // keys that the loop adds to it.
473
+ const seen = new Set<string>([at.focus]);
474
+ const queue: string[] = [at.focus];
475
+ for (const k of queue) {
476
+ for (const next of successorsOf(k)) {
477
+ if (seen.has(next)) continue;
478
+ seen.add(next);
479
+ queue.push(next);
480
+ }
481
+ }
482
+ return ok(queue.slice(1));
483
+ }
484
+
485
+ /**
486
+ * This function gives the targets of the axis `window(from, to)`: the keys of the moves `offset(d)` for each `d`
487
+ * from `from` to `to`, in order. An offset outside the space has no target. The axis needs an array space or a tree
488
+ * space, where an offset has one number.
489
+ */
490
+ function windowTargets(s: Space, at: Position, from: number, to: number): Result<readonly string[]> {
491
+ const tree = s.parentOf !== undefined && s.childrenOf !== undefined;
492
+ if (!tree && s.coords(at.focus)?.length !== 1) {
493
+ return fail(vexError("no-offset", `"window" needs an array space or a tree space, but this space is a ${s.kind}`, at));
494
+ }
495
+ // An offset larger than the number of keys has no target, so the loop stays in the size of the space.
496
+ const out: string[] = [];
497
+ for (let d = Math.max(from, -s.keys.length); d <= Math.min(to, s.keys.length); d++) {
498
+ const r = applyMove(s, at, { t: "offset", d: [d] });
499
+ if (r.ok) out.push(r.value);
338
500
  }
501
+ return ok(out);
339
502
  }