@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/ir.ts CHANGED
@@ -3,15 +3,21 @@
3
3
  * shape as the expressions of `render`.
4
4
  */
5
5
 
6
- /** One move of an address. The moves of an address apply in order, from the focus of the evaluation. */
6
+ /**
7
+ * One move of an address. The moves of an address apply in order, from the focus of the evaluation. The key of `key`
8
+ * and the position of `index` can be an expression, which evaluates before the moves (NAV.COMPUTED).
9
+ */
7
10
  export type Move =
8
- | { readonly t: "key"; readonly key: string }
9
- | { readonly t: "index"; readonly i: number }
11
+ | { readonly t: "key"; readonly key: string | Expr }
12
+ | { readonly t: "index"; readonly i: number | Expr }
10
13
  | { readonly t: "other" }
11
14
  | { readonly t: "offset"; readonly d: readonly number[] }
12
15
  | { readonly t: "origin" }
13
16
  | { readonly t: "parent" };
14
17
 
18
+ /** A move with a fixed key or position: a move with no expression. */
19
+ export type FixedMove = Exclude<Move, { readonly t: "key" | "index" }> | { readonly t: "key"; readonly key: string } | { readonly t: "index"; readonly i: number };
20
+
15
21
  /** An address: a list of moves. The empty list is the focus. */
16
22
  export type Addr = readonly Move[];
17
23
 
@@ -25,6 +31,11 @@ export type Axis =
25
31
  | { readonly t: "ancestors" }
26
32
  | { readonly t: "descendants" }
27
33
  | { readonly t: "siblings" }
34
+ | { readonly t: "window"; readonly from: number; readonly to: number }
35
+ | { readonly t: "table"; readonly name: string }
36
+ | { readonly t: "successors" }
37
+ | { readonly t: "predecessors" }
38
+ | { readonly t: "reachable" }
28
39
  | { readonly t: "where"; readonly axis: Axis; readonly test: Expr };
29
40
 
30
41
  /** A Vex expression. */
@@ -36,8 +47,16 @@ export type Expr =
36
47
  | { readonly tag: "var"; readonly name: string }
37
48
  | { readonly tag: "rec"; readonly fields: Readonly<Record<string, Expr>> }
38
49
  | { readonly tag: "each"; readonly axis: Axis; readonly body: Expr; readonly at?: Addr }
50
+ | { readonly tag: "fold"; readonly axis: Axis; readonly init: Names; readonly step: Names; readonly result: Expr; readonly at?: Addr }
51
+ | { readonly tag: "iterate"; readonly limit: number; readonly init: Names; readonly step: Names; readonly until?: Expr; readonly result: Expr }
39
52
  | { readonly tag: "ext"; readonly kind: string; readonly data: unknown };
40
53
 
54
+ /** The names of a loop and an expression for each (LOOP.NAMES). */
55
+ export type Names = Readonly<Record<string, Expr>>;
56
+
57
+ /** The largest number of steps of `iterate` (ITERATE.LIMIT). */
58
+ export const MAX_ITERATIONS = 100_000;
59
+
41
60
  /** The tag of an expression kind. */
42
61
  export type ExprTag = Expr["tag"];
43
62
 
@@ -79,23 +98,59 @@ export function each(axis: Axis, body: Expr, at?: Addr): ExprOf<"each"> {
79
98
  return at === undefined || at.length === 0 ? { tag: "each", axis, body } : { tag: "each", axis, body, at };
80
99
  }
81
100
 
101
+ /**
102
+ * This function makes a fold: a step at each target of `axis`, in order. `init` gives the names and their first
103
+ * values, and `step` gives the next values. `result` gives the value from the last values (LOOP.NAMES, FOLD.ORDER).
104
+ */
105
+ export function fold(axis: Axis, init: Names, step: Names, result: Expr, at?: Addr): ExprOf<"fold"> {
106
+ return at === undefined || at.length === 0 ? { tag: "fold", axis, init, step, result } : { tag: "fold", axis, init, step, result, at };
107
+ }
108
+
109
+ /**
110
+ * This function makes an iteration: up to `limit` steps. `init` gives the names and their first values, and `step`
111
+ * gives the next values. A true `until` stops it, and `result` gives the value (ITERATE.LIMIT, ITERATE.UNTIL).
112
+ */
113
+ export function iterate(limit: number, init: Names, step: Names, result: Expr, until?: Expr): ExprOf<"iterate"> {
114
+ return until === undefined ? { tag: "iterate", limit, init, step, result } : { tag: "iterate", limit, init, step, until, result };
115
+ }
116
+
82
117
  /** This function makes an expression of an extension kind. */
83
118
  export const ext = (kind: string, data: unknown): ExprOf<"ext"> => ({ tag: "ext", kind, data });
84
119
 
85
120
  // ---------------------------------------------------------------- moves and axes
86
121
 
87
- /** The move to an absolute key. */
88
- export const key = (k: string): Move => ({ t: "key", key: k });
89
- /** The move to a position in the key order. */
90
- export const index = (i: number): Move => ({ t: "index", i });
122
+ /** The move to an absolute key. The key can be an expression that gives a text. */
123
+ export function key(k: string): FixedMove;
124
+ export function key(k: string | Expr): Move;
125
+ export function key(k: string | Expr): Move {
126
+ return { t: "key", key: k };
127
+ }
128
+ /** The move to a position in the key order. The position can be an expression that gives a number. */
129
+ export function index(i: number): FixedMove;
130
+ export function index(i: number | Expr): Move;
131
+ export function index(i: number | Expr): Move {
132
+ return { t: "index", i };
133
+ }
134
+
135
+ /** This function gives the expression of a move with a computed key or position, or `undefined`. */
136
+ export function moveExpr(m: Move): Expr | undefined {
137
+ if (m.t === "key") return typeof m.key === "string" ? undefined : m.key;
138
+ return m.t === "index" && typeof m.i !== "number" ? m.i : undefined;
139
+ }
140
+
141
+ /** This function gives the expressions of the computed moves of an address, in the order of the moves. */
142
+ export const addrExprs = (at: Addr | undefined): readonly Expr[] => (at ?? []).flatMap((m) => moveExpr(m) ?? []);
143
+
144
+ /** This function tells if each move of an address is fixed. */
145
+ export const isFixedAddr = (at: Addr | undefined): at is readonly FixedMove[] => addrExprs(at).length === 0;
91
146
  /** The move to the other key of a space with two keys. */
92
- export const other: Move = Object.freeze({ t: "other" });
147
+ export const other: FixedMove = Object.freeze({ t: "other" });
93
148
  /** The relative move in an array (one number) or a grid (two numbers). */
94
- export const offset = (...d: readonly number[]): Move => ({ t: "offset", d });
149
+ export const offset = (...d: readonly number[]): FixedMove => ({ t: "offset", d });
95
150
  /** The move back to the origin of the evaluation. */
96
- export const origin: Move = Object.freeze({ t: "origin" });
151
+ export const origin: FixedMove = Object.freeze({ t: "origin" });
97
152
  /** The move to the parent of the focus in a tree space. */
98
- export const parent: Move = Object.freeze({ t: "parent" });
153
+ export const parent: FixedMove = Object.freeze({ t: "parent" });
99
154
 
100
155
  /** The axes. */
101
156
  export const axes = {
@@ -115,6 +170,22 @@ export const axes = {
115
170
  descendants: Object.freeze({ t: "descendants" }) as Axis,
116
171
  /** The other children of the parent of the focus. For a root, the other roots. */
117
172
  siblings: Object.freeze({ t: "siblings" }) as Axis,
173
+ /**
174
+ * The keys at the offsets from `from` to `to` of the focus, in order: a window of rows. The offset 0 is the focus. In
175
+ * a tree space, the offsets go among the siblings. An offset outside the space has no target.
176
+ */
177
+ window: (from: number, to: number): Axis => ({ t: "window", from, to }),
178
+ /**
179
+ * Each key of the table `name` of the evaluation, in key order. The body evaluates in the space of that table, and
180
+ * there the origin is the target.
181
+ */
182
+ table: (name: string): Axis => ({ t: "table", name }),
183
+ /** The keys at the ends of the edges from the focus, in a graph space. In a tree space, the children. */
184
+ successors: Object.freeze({ t: "successors" }) as Axis,
185
+ /** The keys with an edge to the focus, in key order. In a tree space, the parent. */
186
+ predecessors: Object.freeze({ t: "predecessors" }) as Axis,
187
+ /** Each key that a path of edges reaches from the focus, in breadth-first order, without the focus. */
188
+ reachable: Object.freeze({ t: "reachable" }) as Axis,
118
189
  /** The targets of `axis` where `test` gives `true`. */
119
190
  where: (axis: Axis, test: Expr): Axis => ({ t: "where", axis, test }),
120
191
  } as const;
@@ -125,98 +196,181 @@ const isObject = (u: unknown): u is Readonly<Record<string, unknown>> => typeof
125
196
 
126
197
  const isStringArray = (u: unknown): u is readonly string[] => Array.isArray(u) && u.every((s) => typeof s === "string");
127
198
 
128
- /** This function tells if a value is a valid move. */
199
+ /** This function tells if a value is a valid move. The expression of a computed move must be valid too. */
129
200
  export function isMove(u: unknown): u is Move {
130
- if (!isObject(u)) return false;
201
+ const exprs = moveParts(u);
202
+ return exprs !== undefined && exprs.every(isExpr);
203
+ }
204
+
205
+ /**
206
+ * A test of the numbers of a move or of a window. The JSON form needs whole numbers. An expression in code can have any
207
+ * number, and a number that is not whole has a meaning at run time (EVAL.SHAPE).
208
+ */
209
+ type NumberTest = (x: unknown) => boolean;
210
+
211
+ const anyNumber: NumberTest = (x) => typeof x === "number";
212
+
213
+ /** This function checks the fixed parts of a move. It gives the expressions of the move, or `undefined` for a bad move. */
214
+ function moveParts(u: unknown, isNumber: NumberTest = Number.isInteger): readonly unknown[] | undefined {
215
+ if (!isObject(u)) return undefined;
131
216
  switch (u["t"]) {
132
217
  case "key":
133
- return typeof u["key"] === "string";
218
+ return typeof u["key"] === "string" ? [] : isObject(u["key"]) ? [u["key"]] : undefined;
134
219
  case "index":
135
- return Number.isInteger(u["i"]);
220
+ return isNumber(u["i"]) ? [] : isObject(u["i"]) ? [u["i"]] : undefined;
136
221
  case "offset":
137
- return Array.isArray(u["d"]) && u["d"].every((n) => Number.isInteger(n));
222
+ return Array.isArray(u["d"]) && u["d"].every((n) => isNumber(n)) ? [] : undefined;
138
223
  case "other":
139
224
  case "origin":
140
225
  case "parent":
141
- return true;
226
+ return [];
142
227
  default:
143
- return false;
228
+ return undefined;
144
229
  }
145
230
  }
146
231
 
147
232
  /** This function tells if a value is a valid axis. It checks the tests of `where` too. */
148
233
  export function isAxis(u: unknown): u is Axis {
149
- return validTree([{ axis: true, u }]);
234
+ return badPart([{ axis: true, u }], true) === undefined;
150
235
  }
151
236
 
152
237
  /** This function tells if a value is a valid expression. It checks the whole tree. */
153
238
  export function isExpr(u: unknown): u is Expr {
154
- return validTree([{ axis: false, u }]);
239
+ return badPart([{ axis: false, u }], true) === undefined;
240
+ }
241
+
242
+ /** The tags of the expressions of this version of Vex. */
243
+ const TAGS: ReadonlySet<unknown> = new Set(["lit", "ref", "app", "let", "var", "rec", "each", "fold", "iterate", "ext"]);
244
+
245
+ /**
246
+ * This function gives the reason that a value is not a valid expression, or `undefined` for a valid expression
247
+ * (EVAL.SHAPE). An expression from a newer version of Vex can have a tag that this version does not know. Unlike
248
+ * `isExpr`, it accepts a number that is not whole in a move or in a window, because it has a meaning at run time.
249
+ */
250
+ export function shapeError(u: unknown): string | undefined {
251
+ const bad = badPart([{ axis: false, u }], false);
252
+ if (bad === undefined) return undefined;
253
+ const tag = isObject(bad.u) ? bad.u["tag"] : undefined;
254
+ if (bad.axis) return "the expression has an axis that is not valid";
255
+ if (typeof tag === "string" && !TAGS.has(tag)) return `the expression has a node with the tag "${tag}", and this version of Vex does not know it`;
256
+ return typeof tag === "string" ? `the expression has a node "${tag}" with parts that are not valid` : "the expression has a part that is not a node";
155
257
  }
156
258
 
157
- const isAddr = (u: unknown): boolean => u === undefined || (Array.isArray(u) && u.every(isMove));
259
+ /**
260
+ * This function checks the names of a loop: `init` and `step` are records, and each name of `step` is a name of `init`.
261
+ * It gives the expressions of `init`, of `step` and `result`, or `undefined` (LOOP.NAMES).
262
+ */
263
+ function loopParts(u: Readonly<Record<string, unknown>>): readonly unknown[] | undefined {
264
+ const { init, step } = u;
265
+ if (!isObject(init) || Array.isArray(init) || !isObject(step) || Array.isArray(step)) return undefined;
266
+ if (!Object.keys(step).every((n) => Object.hasOwn(init, n))) return undefined;
267
+ return [...Object.values(init), ...Object.values(step), u["result"]];
268
+ }
269
+
270
+ /** This function checks the fixed parts of an address. It gives the expressions of its moves, or `undefined`. */
271
+ function addrParts(u: unknown, isNumber: NumberTest): readonly unknown[] | undefined {
272
+ if (u === undefined) return [];
273
+ if (!Array.isArray(u)) return undefined;
274
+ const out: unknown[] = [];
275
+ for (const m of u) {
276
+ const parts = moveParts(m, isNumber);
277
+ if (parts === undefined) return undefined;
278
+ out.push(...parts);
279
+ }
280
+ return out;
281
+ }
158
282
 
159
283
  /**
160
- * This function checks a tree of expressions and axes. It uses a stack, not recursion, so the input can be deep. For
161
- * example, a deep JSON file from a stranger does not need a deep call stack (EVAL.NESTING).
284
+ * This function checks a tree of expressions and axes, and it gives the first part that is not valid. It uses a stack,
285
+ * not recursion, so the input can be deep. For example, a deep JSON file from a stranger does not need a deep call
286
+ * stack (EVAL.NESTING). With `whole`, the numbers of the moves and of the windows must be whole, as the JSON form needs.
162
287
  */
163
- function validTree(todo: { readonly axis: boolean; readonly u: unknown }[]): boolean {
288
+ function badPart(todo: { readonly axis: boolean; readonly u: unknown }[], whole: boolean): { readonly axis: boolean; readonly u: unknown } | undefined {
289
+ const moveNumber = whole ? Number.isInteger : anyNumber;
290
+ const windowNumber = whole ? Number.isSafeInteger : anyNumber;
164
291
  const push = (axis: boolean, values: readonly unknown[]): void => {
165
292
  for (const u of values) todo.push({ axis, u });
166
293
  };
167
294
  for (let item = todo.pop(); item !== undefined; item = todo.pop()) {
168
295
  const { u } = item;
169
- if (!isObject(u)) return false;
296
+ if (!isObject(u)) return item;
170
297
  if (item.axis) {
171
298
  const t = u["t"];
172
299
  if (t === "neighbors") {
173
- if (u["n"] !== 4 && u["n"] !== 8) return false;
300
+ if (u["n"] !== 4 && u["n"] !== 8) return item;
301
+ } else if (t === "window") {
302
+ if (!windowNumber(u["from"]) || !windowNumber(u["to"])) return item;
303
+ } else if (t === "table") {
304
+ if (typeof u["name"] !== "string") return item;
174
305
  } else if (t === "where") {
175
306
  push(true, [u["axis"]]);
176
307
  push(false, [u["test"]]);
177
- } else if (!["all", "others", "other", "children", "ancestors", "descendants", "siblings"].includes(t as string)) {
178
- return false;
308
+ } else if (!["all", "others", "other", "children", "ancestors", "descendants", "siblings", "successors", "predecessors", "reachable"].includes(t as string)) {
309
+ return item;
179
310
  }
180
311
  continue;
181
312
  }
182
313
  switch (u["tag"]) {
183
314
  case "lit":
184
- if (!("value" in u)) return false;
315
+ if (!("value" in u)) return item;
185
316
  break;
186
- case "ref":
187
- if (!isStringArray(u["path"]) || !isAddr(u["at"])) return false;
317
+ case "ref": {
318
+ const at = addrParts(u["at"], moveNumber);
319
+ if (!isStringArray(u["path"]) || at === undefined) return item;
320
+ push(false, at);
188
321
  break;
322
+ }
189
323
  case "app":
190
- if (typeof u["op"] !== "string" || !Array.isArray(u["args"])) return false;
324
+ if (typeof u["op"] !== "string" || !Array.isArray(u["args"])) return item;
191
325
  push(false, u["args"]);
192
326
  break;
193
327
  case "let":
194
- if (!isObject(u["bind"]) || Array.isArray(u["bind"])) return false;
328
+ if (!isObject(u["bind"]) || Array.isArray(u["bind"])) return item;
195
329
  push(false, [...Object.values(u["bind"]), u["body"]]);
196
330
  break;
197
331
  case "var":
198
- if (typeof u["name"] !== "string") return false;
332
+ if (typeof u["name"] !== "string") return item;
199
333
  break;
200
334
  case "rec":
201
- if (!isObject(u["fields"]) || Array.isArray(u["fields"])) return false;
335
+ if (!isObject(u["fields"]) || Array.isArray(u["fields"])) return item;
202
336
  push(false, Object.values(u["fields"]));
203
337
  break;
204
- case "each":
205
- if (!isAddr(u["at"])) return false;
338
+ case "each": {
339
+ const at = addrParts(u["at"], moveNumber);
340
+ if (at === undefined) return item;
341
+ push(true, [u["axis"]]);
342
+ push(false, [u["body"], ...at]);
343
+ break;
344
+ }
345
+ case "fold": {
346
+ const at = addrParts(u["at"], moveNumber);
347
+ const names = loopParts(u);
348
+ if (at === undefined || names === undefined) return item;
206
349
  push(true, [u["axis"]]);
207
- push(false, [u["body"]]);
350
+ push(false, [...names, ...at]);
351
+ break;
352
+ }
353
+ case "iterate": {
354
+ const limit = u["limit"];
355
+ const names = loopParts(u);
356
+ if (typeof limit !== "number" || !Number.isInteger(limit) || limit < 0 || limit > MAX_ITERATIONS || names === undefined) return item;
357
+ push(false, [...names, ...(u["until"] === undefined ? [] : [u["until"]])]);
208
358
  break;
359
+ }
209
360
  case "ext":
210
- if (typeof u["kind"] !== "string" || !("data" in u)) return false;
361
+ if (typeof u["kind"] !== "string" || !("data" in u)) return item;
211
362
  break;
212
363
  default:
213
- return false;
364
+ return item;
214
365
  }
215
366
  }
216
- return true;
367
+ return undefined;
217
368
  }
218
369
 
219
- /** This function gives the child expressions of an expression, in the order of their child index. */
370
+ /**
371
+ * This function gives the child expressions of an expression, in the order of their child index. The expressions of
372
+ * the computed moves of an address come last. They evaluate at the position of their node, also for an axis.
373
+ */
220
374
  export function children(e: Expr): readonly Expr[] {
221
375
  switch (e.tag) {
222
376
  case "app":
@@ -226,9 +380,14 @@ export function children(e: Expr): readonly Expr[] {
226
380
  case "rec":
227
381
  return Object.values(e.fields);
228
382
  case "each":
229
- return [e.body, ...whereTests(e.axis)];
230
- case "lit":
383
+ return [e.body, ...whereTests(e.axis), ...addrExprs(e.at)];
384
+ case "fold":
385
+ return [...Object.values(e.init), ...Object.values(e.step), ...whereTests(e.axis), ...addrExprs(e.at), e.result];
386
+ case "iterate":
387
+ return [...Object.values(e.init), ...Object.values(e.step), ...(e.until === undefined ? [] : [e.until]), e.result];
231
388
  case "ref":
389
+ return addrExprs(e.at);
390
+ case "lit":
232
391
  case "var":
233
392
  case "ext":
234
393
  return [];
package/src/json.ts CHANGED
@@ -128,6 +128,24 @@ function mapValues(u: unknown, f: (value: unknown) => Result<unknown>): Result<u
128
128
  }
129
129
  return undefined;
130
130
  };
131
+ // The expression of a computed move is a tree of the expression too (NAV.COMPUTED).
132
+ const address = (): Result<unknown> | undefined => {
133
+ const at = u["at"];
134
+ if (!Array.isArray(at)) return undefined;
135
+ const moves: unknown[] = [];
136
+ for (const m of at) {
137
+ const field = isRecord(m) ? (m["t"] === "key" ? "key" : m["t"] === "index" ? "i" : undefined) : undefined;
138
+ if (field === undefined || !isRecord(m) || !isRecord(m[field])) {
139
+ moves.push(m);
140
+ continue;
141
+ }
142
+ const r = mapValues(m[field], f);
143
+ if (!r.ok) return r;
144
+ moves.push({ ...m, [field]: r.value });
145
+ }
146
+ out["at"] = moves;
147
+ return undefined;
148
+ };
131
149
  const axis = (a: unknown): Result<unknown> => {
132
150
  if (!isRecord(a) || a["t"] !== "where") return ok(a);
133
151
  const inner = axis(a["axis"]);
@@ -153,8 +171,18 @@ function mapValues(u: unknown, f: (value: unknown) => Result<unknown>): Result<u
153
171
  const a = axis(u["axis"]);
154
172
  if (!a.ok) return a;
155
173
  out["axis"] = a.value;
156
- return child("body") ?? ok(out);
174
+ return child("body") ?? address() ?? ok(out);
175
+ }
176
+ case "fold": {
177
+ const a = axis(u["axis"]);
178
+ if (!a.ok) return a;
179
+ out["axis"] = a.value;
180
+ return each("init") ?? each("step") ?? child("result") ?? address() ?? ok(out);
157
181
  }
182
+ case "iterate":
183
+ return each("init") ?? each("step") ?? (u["until"] === undefined ? undefined : child("until")) ?? child("result") ?? ok(out);
184
+ case "ref":
185
+ return address() ?? ok(out);
158
186
  default:
159
187
  return ok(out);
160
188
  }