@mark1russell7/vex 0.2.0 → 0.4.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/ir.ts CHANGED
@@ -35,7 +35,7 @@ export type Expr =
35
35
  | { readonly tag: "let"; readonly bind: Readonly<Record<string, Expr>>; readonly body: Expr }
36
36
  | { readonly tag: "var"; readonly name: string }
37
37
  | { readonly tag: "rec"; readonly fields: Readonly<Record<string, Expr>> }
38
- | { readonly tag: "each"; readonly axis: Axis; readonly body: Expr }
38
+ | { readonly tag: "each"; readonly axis: Axis; readonly body: Expr; readonly at?: Addr }
39
39
  | { readonly tag: "ext"; readonly kind: string; readonly data: unknown };
40
40
 
41
41
  /** The tag of an expression kind. */
@@ -71,8 +71,13 @@ export const v = (name: string): ExprOf<"var"> => ({ tag: "var", name });
71
71
  /** This function makes a record from field expressions. */
72
72
  export const rec = (fields: Readonly<Record<string, Expr>>): ExprOf<"rec"> => ({ tag: "rec", fields });
73
73
 
74
- /** This function evaluates `body` once for each target of `axis`. The result is a list. */
75
- export const each = (axis: Axis, body: Expr): ExprOf<"each"> => ({ tag: "each", axis, body });
74
+ /**
75
+ * This function evaluates `body` once for each target of `axis`. The result is a list. With `at`, the axis finds its
76
+ * targets from the key of that address, not from the focus.
77
+ */
78
+ export function each(axis: Axis, body: Expr, at?: Addr): ExprOf<"each"> {
79
+ return at === undefined || at.length === 0 ? { tag: "each", axis, body } : { tag: "each", axis, body, at };
80
+ }
76
81
 
77
82
  /** This function makes an expression of an extension kind. */
78
83
  export const ext = (kind: string, data: unknown): ExprOf<"ext"> => ({ tag: "ext", kind, data });
@@ -127,9 +132,9 @@ export function isMove(u: unknown): u is Move {
127
132
  case "key":
128
133
  return typeof u["key"] === "string";
129
134
  case "index":
130
- return typeof u["i"] === "number" && Number.isInteger(u["i"]);
135
+ return Number.isInteger(u["i"]);
131
136
  case "offset":
132
- return Array.isArray(u["d"]) && u["d"].every((n) => typeof n === "number" && Number.isInteger(n));
137
+ return Array.isArray(u["d"]) && u["d"].every((n) => Number.isInteger(n));
133
138
  case "other":
134
139
  case "origin":
135
140
  case "parent":
@@ -180,7 +185,7 @@ export function isExpr(u: unknown): u is Expr {
180
185
  case "rec":
181
186
  return isExprRecord(u["fields"]);
182
187
  case "each":
183
- return isAxis(u["axis"]) && isExpr(u["body"]);
188
+ return isAxis(u["axis"]) && isExpr(u["body"]) && (u["at"] === undefined || (Array.isArray(u["at"]) && u["at"].every(isMove)));
184
189
  case "ext":
185
190
  return typeof u["kind"] === "string" && "data" in u;
186
191
  default:
@@ -198,7 +203,7 @@ export function children(e: Expr): readonly Expr[] {
198
203
  case "rec":
199
204
  return Object.values(e.fields);
200
205
  case "each":
201
- return e.axis.t === "where" ? [e.body, ...whereTests(e.axis)] : [e.body];
206
+ return [e.body, ...whereTests(e.axis)];
202
207
  case "lit":
203
208
  case "ref":
204
209
  case "var":
package/src/json.ts CHANGED
@@ -3,74 +3,188 @@ import { 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
- /** The JSON form of a domain value inside a literal. */
7
- interface EncodedValue {
8
- readonly $vex: "domain";
9
- readonly domain: string;
10
- readonly value: unknown;
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 isPlainJson = (u: unknown): boolean => {
14
- if (u === null || typeof u === "string" || typeof u === "boolean") return true;
15
- if (typeof u === "number") return Number.isFinite(u);
16
- if (Array.isArray(u)) return u.every(isPlainJson);
17
- if (typeof u === "object") {
18
- const proto: unknown = Object.getPrototypeOf(u);
19
- return (proto === Object.prototype || proto === null) && Object.values(u).every(isPlainJson);
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 false;
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
  */
167
+ // Stryker disable next-line ArrayDeclaration: a list with a value that is not a domain encodes no value
28
168
  export function serialize(e: Expr, domains: readonly AnyDomain[] = []): Result<string> {
29
- const failure: { message: string }[] = [];
30
- const replacer = function (this: unknown, k: string, value: unknown): unknown {
31
- const holder = this as Record<string, unknown> | null;
32
- if (k !== "value" || holder === null || holder["tag"] !== "lit") return value;
33
- if (isPlainJson(value)) return value;
34
- const d = domains.find((dom) => dom.encode !== undefined && dom.is(value));
35
- if (d?.encode !== undefined) {
36
- const encoded: EncodedValue = { $vex: "domain", domain: d.name, value: d.encode(value) };
37
- return encoded;
38
- }
39
- failure.push({ message: `a literal value is not JSON data and no domain encodes it` });
40
- return null;
41
- };
42
- let text: string;
43
169
  try {
44
- text = JSON.stringify(e, replacer);
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);
45
173
  } catch (thrown) {
46
174
  return fail(vexError("threw", "the expression has no JSON form", { thrown }));
47
175
  }
48
- const first = failure[0];
49
- return first === undefined ? ok(text) : fail(vexError("bad-expression", first.message));
50
176
  }
51
177
 
52
- const isEncoded = (u: unknown): u is EncodedValue =>
53
- typeof u === "object" && u !== null && (u as { $vex?: unknown }).$vex === "domain" && typeof (u as { domain?: unknown }).domain === "string";
54
-
55
178
  /** This function reads an expression from JSON text. It checks the whole tree. */
179
+ // Stryker disable next-line ArrayDeclaration: a list with a value that is not a domain decodes no value
56
180
  export function parse(text: string, domains: readonly AnyDomain[] = []): Result<Expr> {
57
181
  let raw: unknown;
58
- const failure: string[] = [];
59
182
  try {
60
- raw = JSON.parse(text, (_k, value: unknown) => {
61
- if (!isEncoded(value)) return value;
62
- const d = domains.find((dom) => dom.name === value.domain);
63
- if (d?.decode === undefined) {
64
- failure.push(`no domain "${value.domain}" decodes a literal`);
65
- return value;
66
- }
67
- const decoded: unknown = d.decode(value.value);
68
- return decoded;
69
- });
183
+ raw = JSON.parse(text);
70
184
  } catch (thrown) {
71
185
  return fail(vexError("bad-expression", "the text is not JSON", { thrown }));
72
186
  }
73
- const first = failure[0];
74
- if (first !== undefined) return fail(vexError("bad-expression", first));
75
- return isExpr(raw) ? ok(raw) : fail(vexError("bad-expression", "the JSON is not a valid Vex expression"));
187
+ const tree = mapValues(raw, (v) => decodeValue(v, domains));
188
+ if (!tree.ok) return fail(tree.error);
189
+ return isExpr(tree.value) ? ok(tree.value) : fail(vexError("bad-expression", "the JSON is not a valid Vex expression"));
76
190
  }
package/src/list.ts CHANGED
@@ -17,7 +17,7 @@ export const vexList = <T>(items: readonly ListItem<T>[]): VexList<T> => Object.
17
17
 
18
18
  /** This function tells if a value is a Vex list. */
19
19
  export const isVexList = (u: unknown): u is VexList =>
20
- typeof u === "object" && u !== null && (u as { kind?: unknown }).kind === "vex.list" && Array.isArray((u as { items?: unknown }).items);
20
+ (u as { kind?: unknown } | null | undefined)?.kind === "vex.list" && Array.isArray((u as { items?: unknown }).items);
21
21
 
22
22
  /** The name of a core list op. */
23
23
  export type ListOp = "count" | "sum" | "min" | "max" | "mean" | "any" | "all" | "none" | "values" | "keys" | "reduce" | "first" | "errors";
package/src/sheet.ts CHANGED
@@ -54,7 +54,7 @@ interface Visit {
54
54
  readonly key: string;
55
55
  readonly index: number;
56
56
  low: number;
57
- selfLoop: boolean;
57
+ reread: boolean;
58
58
  result: Result<unknown>;
59
59
  }
60
60
 
@@ -62,11 +62,17 @@ export class SheetRun {
62
62
  readonly #columns: ReadonlyMap<string, Expr>;
63
63
  readonly #opts: SheetOptions;
64
64
  readonly #done = new Map<string, Result<unknown>>();
65
+ // For each column, the number of keys at the start of the key order that a warm-up evaluated.
66
+ readonly #warmed = new Map<string, number>();
67
+ // The position of each key in the key order, made at the first warm-up.
68
+ #index: ReadonlyMap<string, number> | undefined;
65
69
  // The cells on the stack of the search: started, but their component is not finished.
66
70
  readonly #visits = new Map<string, Visit>();
71
+ // Stryker disable next-line ArrayDeclaration: the search never reads below the root of a component
67
72
  readonly #stack: Visit[] = [];
68
73
  // The cell whose formula is in evaluation. At the top level, it is a placeholder that is not a cell.
69
- #top: Visit = { id: "", column: "", key: "", index: -1, low: -1, selfLoop: false, result: cycleError("", "") };
74
+ // Stryker disable next-line all: the placeholder is not a cell, so the search reads none of its fields
75
+ #top: Visit = { id: "", column: "", key: "", index: -1, low: -1, reread: false, result: cycleError("", "") };
70
76
  #next = 0;
71
77
 
72
78
  constructor(columns: ReadonlyMap<string, Expr>, opts: SheetOptions) {
@@ -81,24 +87,48 @@ export class SheetRun {
81
87
  return this.cell(data.column, where.value);
82
88
  };
83
89
 
84
- /** This method gives the result of one cell: the column `column` at the key `key`. */
90
+ /**
91
+ * This method gives the result of one cell: the column `column` at the key `key`. A read from a host first evaluates
92
+ * the column at the keys before `key`, in key order. Thus a recurrence over the keys reads finished cells, and a
93
+ * first read at the last key does not go deep into the call stack.
94
+ */
85
95
  cell(column: string, key: string): Result<unknown> {
96
+ // 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.
97
+ if (this.#top.index < 0) this.#warmTo(column, key);
98
+ return this.#cell(column, key);
99
+ }
100
+
101
+ /** This method evaluates the column `column` at each key before `key` that it did not evaluate before, in key order. */
102
+ #warmTo(column: string, key: string): void {
103
+ if (!this.#columns.has(column)) return;
104
+ const keys = this.#opts.space.keys;
105
+ this.#index ??= new Map(keys.map((k, i) => [k, i]));
106
+ const end = this.#index.get(key) ?? 0;
107
+ const start = this.#warmed.get(column) ?? 0;
108
+ for (let i = start; i < end; i++) this.#cell(column, keys[i] ?? key);
109
+ if (end > start) this.#warmed.set(column, end);
110
+ }
111
+
112
+ /** This method evaluates one cell, without the warm-up of `cell`. */
113
+ #cell(column: string, key: string): Result<unknown> {
86
114
  const id = `${column}\u0000${key}`;
87
115
  const done = this.#done.get(id);
88
116
  if (done !== undefined) return done;
89
117
  const caller = this.#top;
90
118
  const seen = this.#visits.get(id);
91
119
  if (seen !== undefined) {
92
- // A read of a cell that is not finished: the caller and this cell are on one cycle.
120
+ // A read of a cell that is not finished: the caller and this cell are on one cycle. The cell is on the
121
+ // stack of the search, so it is in the component of the caller. Thus a component with one cell is cyclic
122
+ // only if that cell reads itself.
93
123
  caller.low = Math.min(caller.low, seen.index);
94
- if (caller === seen) seen.selfLoop = true;
124
+ seen.reread = true;
95
125
  return cycleError(column, key);
96
126
  }
97
127
  const program = this.#columns.get(column);
98
128
  if (program === undefined) return fail(vexError("unbound", `the sheet has no column "${column}"`, { origin: key, focus: key }));
99
129
 
100
130
  const n = this.#next++;
101
- const visit: Visit = { id, column, key, index: n, low: n, selfLoop: false, result: cycleError(column, key) };
131
+ const visit: Visit = { id, column, key, index: n, low: n, reread: false, result: cycleError(column, key) };
102
132
  this.#visits.set(id, visit);
103
133
  this.#stack.push(visit);
104
134
  this.#top = visit;
@@ -113,8 +143,11 @@ export class SheetRun {
113
143
  /** This method takes the component of `root` from the stack, and sets the final result of each of its cells. */
114
144
  #finish(root: Visit): void {
115
145
  const members = this.#stack.splice(this.#stack.indexOf(root));
116
- const cyclic = members.length > 1 || root.selfLoop;
146
+ // A component of two or more cells reads its root again, so root.reread alone decides. The length test is a guard.
147
+ // Stryker disable next-line ConditionalExpression,LogicalOperator: members.length > 1 implies root.reread
148
+ const cyclic = members.length > 1 || root.reread;
117
149
  for (const m of members) {
150
+ // Stryker disable next-line CallExpression: a finished cell is in #done, and cell() reads #done first
118
151
  this.#visits.delete(m.id);
119
152
  this.#done.set(m.id, cyclic ? cycleError(m.column, m.key) : m.result);
120
153
  }
@@ -133,9 +166,6 @@ export class SheetRun {
133
166
  * for example a running total, then reads finished cells and does not go deep into the call stack.
134
167
  */
135
168
  warm(column: string, key: string): void {
136
- for (const k of this.#opts.space.keys) {
137
- if (k === key) return;
138
- this.cell(column, k);
139
- }
169
+ this.#warmTo(column, key);
140
170
  }
141
171
  }
package/src/space.ts CHANGED
@@ -50,9 +50,11 @@ class RecordSpace<K extends string, O> implements Space<K, O> {
50
50
  get(k: string): O | undefined {
51
51
  return this.#records.get(k);
52
52
  }
53
+ // Stryker disable next-line BlockStatement: the body gives undefined, and an empty body gives undefined too
53
54
  coords(): readonly number[] | undefined {
54
55
  return undefined;
55
56
  }
57
+ // Stryker disable next-line BlockStatement: the body gives undefined, and an empty body gives undefined too
56
58
  keyAt(): K | undefined {
57
59
  return undefined;
58
60
  }
@@ -79,7 +81,7 @@ class ArraySpace<O> implements Space<ArrayKey, O> {
79
81
  return this.has(k) ? [Number(k)] : undefined;
80
82
  }
81
83
  keyAt(coords: readonly number[]): ArrayKey | undefined {
82
- const k = coords.join(",");
84
+ const k = String(coords[0]);
83
85
  return coords.length === 1 && this.has(k) ? k : undefined;
84
86
  }
85
87
  }
@@ -107,8 +109,9 @@ class GridSpace<O> implements Space<GridKey, O> {
107
109
  return this.#coords.get(k);
108
110
  }
109
111
  keyAt(coords: readonly number[]): GridKey | undefined {
112
+ // Each key has two coordinates, so a list with more or fewer coordinates gives no key.
110
113
  const k = coords.join(",");
111
- return coords.length === 2 && this.has(k) ? k : undefined;
114
+ return this.has(k) ? k : undefined;
112
115
  }
113
116
  }
114
117
 
@@ -145,6 +148,8 @@ class TreeSpace<K extends string, O> implements Space<K, O> {
145
148
  const children = new Map<string, K[]>(this.keys.map((k) => [k, []]));
146
149
  for (const k of this.keys) {
147
150
  const p = parentOf.get(k);
151
+ // Each parent is a key, so its list exists, and the test of p only skips the roots.
152
+ // Stryker disable next-line ConditionalExpression,OptionalChaining: a root has no list to push to
148
153
  if (p !== undefined) children.get(p)?.push(k);
149
154
  }
150
155
  this.#children = new Map([...children].map(([k, c]) => [k, Object.freeze(c)]));
@@ -156,9 +161,11 @@ class TreeSpace<K extends string, O> implements Space<K, O> {
156
161
  get(k: string): O | undefined {
157
162
  return this.#records.get(k);
158
163
  }
164
+ // Stryker disable next-line BlockStatement: the body gives undefined, and an empty body gives undefined too
159
165
  coords(): readonly number[] | undefined {
160
166
  return undefined;
161
167
  }
168
+ // Stryker disable next-line BlockStatement: the body gives undefined, and an empty body gives undefined too
162
169
  keyAt(): K | undefined {
163
170
  return undefined;
164
171
  }
@@ -208,7 +215,7 @@ export function applyMove(s: Space, at: Position, m: Move): Result<string> {
208
215
  return s.has(m.key) ? ok(m.key) : refError("unknown-key", `the space has no key "${m.key}"`);
209
216
  case "index": {
210
217
  const k = s.keys[m.i];
211
- return m.i >= 0 && k !== undefined ? ok(k) : refError("out-of-bounds", `the space has no key at index ${m.i}`);
218
+ return k !== undefined ? ok(k) : refError("out-of-bounds", `the space has no key at index ${m.i}`);
212
219
  }
213
220
  case "other": {
214
221
  if (s.keys.length !== 2) return refError("not-a-pair", `"other" needs a space with 2 keys, but this space has ${s.keys.length}`);
@@ -218,6 +225,16 @@ export function applyMove(s: Space, at: Position, m: Move): Result<string> {
218
225
  return ok(at.focus === a ? (b ?? at.focus) : (a ?? at.focus));
219
226
  }
220
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
+ }
221
238
  const c = s.coords(at.focus);
222
239
  if (c === undefined || c.length !== m.d.length) {
223
240
  return refError("no-offset", `an offset of length ${m.d.length} is not valid in a ${s.kind} space`);
package/src/traversal.ts CHANGED
@@ -3,7 +3,7 @@ import { vexError, type VexError } from "./errors.ts";
3
3
  import { evaluate, type FreeFn } from "./evaluate.ts";
4
4
  import { app, lit, v } from "./ir.ts";
5
5
  import { vexList, type ListItem } from "./list.ts";
6
- import { fail, ok, toOptional, type Optional, type Result } from "./result.ts";
6
+ import { fail, none, ok, toOptional, type Optional, type Result } from "./result.ts";
7
7
  import { space as spaces, type Space } from "./space.ts";
8
8
 
9
9
  /** A monoid: an associative `concat` with an identity element `empty`. */
@@ -84,7 +84,6 @@ export function traversal<K extends string, T>(items: readonly TraversalItem<K,
84
84
  origin: "$",
85
85
  domains: env.domains,
86
86
  vars: { $list: list },
87
- ...(env.options?.fns === undefined ? {} : { fns: env.options.fns }),
88
87
  });
89
88
  };
90
89
  const t: Traversal<K, T> = {
@@ -92,7 +91,7 @@ export function traversal<K extends string, T>(items: readonly TraversalItem<K,
92
91
  strict: () => traversal(items, env, true),
93
92
  get: (k) => {
94
93
  const item = items.find((it) => it.key === k);
95
- return item === undefined ? toOptional(fail(vexError("unknown-key", `no item has the key "${k}"`))) : toOptional(item.result);
94
+ return item === undefined ? none() : toOptional(item.result);
96
95
  },
97
96
  values: () => items.flatMap((it) => (it.result.ok ? [it.result.value] : [])),
98
97
  keys: () => items.flatMap((it) => (it.result.ok ? [it.key] : [])),