@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/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
 
@@ -41,8 +47,16 @@ export type Expr =
41
47
  | { readonly tag: "var"; readonly name: string }
42
48
  | { readonly tag: "rec"; readonly fields: Readonly<Record<string, Expr>> }
43
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 }
44
52
  | { readonly tag: "ext"; readonly kind: string; readonly data: unknown };
45
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
+
46
60
  /** The tag of an expression kind. */
47
61
  export type ExprTag = Expr["tag"];
48
62
 
@@ -84,23 +98,59 @@ export function each(axis: Axis, body: Expr, at?: Addr): ExprOf<"each"> {
84
98
  return at === undefined || at.length === 0 ? { tag: "each", axis, body } : { tag: "each", axis, body, at };
85
99
  }
86
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
+
87
117
  /** This function makes an expression of an extension kind. */
88
118
  export const ext = (kind: string, data: unknown): ExprOf<"ext"> => ({ tag: "ext", kind, data });
89
119
 
90
120
  // ---------------------------------------------------------------- moves and axes
91
121
 
92
- /** The move to an absolute key. */
93
- export const key = (k: string): Move => ({ t: "key", key: k });
94
- /** The move to a position in the key order. */
95
- 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;
96
146
  /** The move to the other key of a space with two keys. */
97
- export const other: Move = Object.freeze({ t: "other" });
147
+ export const other: FixedMove = Object.freeze({ t: "other" });
98
148
  /** The relative move in an array (one number) or a grid (two numbers). */
99
- export const offset = (...d: readonly number[]): Move => ({ t: "offset", d });
149
+ export const offset = (...d: readonly number[]): FixedMove => ({ t: "offset", d });
100
150
  /** The move back to the origin of the evaluation. */
101
- export const origin: Move = Object.freeze({ t: "origin" });
151
+ export const origin: FixedMove = Object.freeze({ t: "origin" });
102
152
  /** The move to the parent of the focus in a tree space. */
103
- export const parent: Move = Object.freeze({ t: "parent" });
153
+ export const parent: FixedMove = Object.freeze({ t: "parent" });
104
154
 
105
155
  /** The axes. */
106
156
  export const axes = {
@@ -146,102 +196,181 @@ const isObject = (u: unknown): u is Readonly<Record<string, unknown>> => typeof
146
196
 
147
197
  const isStringArray = (u: unknown): u is readonly string[] => Array.isArray(u) && u.every((s) => typeof s === "string");
148
198
 
149
- /** 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. */
150
200
  export function isMove(u: unknown): u is Move {
151
- 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;
152
216
  switch (u["t"]) {
153
217
  case "key":
154
- return typeof u["key"] === "string";
218
+ return typeof u["key"] === "string" ? [] : isObject(u["key"]) ? [u["key"]] : undefined;
155
219
  case "index":
156
- return Number.isInteger(u["i"]);
220
+ return isNumber(u["i"]) ? [] : isObject(u["i"]) ? [u["i"]] : undefined;
157
221
  case "offset":
158
- 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;
159
223
  case "other":
160
224
  case "origin":
161
225
  case "parent":
162
- return true;
226
+ return [];
163
227
  default:
164
- return false;
228
+ return undefined;
165
229
  }
166
230
  }
167
231
 
168
232
  /** This function tells if a value is a valid axis. It checks the tests of `where` too. */
169
233
  export function isAxis(u: unknown): u is Axis {
170
- return validTree([{ axis: true, u }]);
234
+ return badPart([{ axis: true, u }], true) === undefined;
171
235
  }
172
236
 
173
237
  /** This function tells if a value is a valid expression. It checks the whole tree. */
174
238
  export function isExpr(u: unknown): u is Expr {
175
- 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";
176
257
  }
177
258
 
178
- 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
+ }
179
282
 
180
283
  /**
181
- * This function checks a tree of expressions and axes. It uses a stack, not recursion, so the input can be deep. For
182
- * 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.
183
287
  */
184
- 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;
185
291
  const push = (axis: boolean, values: readonly unknown[]): void => {
186
292
  for (const u of values) todo.push({ axis, u });
187
293
  };
188
294
  for (let item = todo.pop(); item !== undefined; item = todo.pop()) {
189
295
  const { u } = item;
190
- if (!isObject(u)) return false;
296
+ if (!isObject(u)) return item;
191
297
  if (item.axis) {
192
298
  const t = u["t"];
193
299
  if (t === "neighbors") {
194
- if (u["n"] !== 4 && u["n"] !== 8) return false;
300
+ if (u["n"] !== 4 && u["n"] !== 8) return item;
195
301
  } else if (t === "window") {
196
- if (!Number.isSafeInteger(u["from"]) || !Number.isSafeInteger(u["to"])) return false;
302
+ if (!windowNumber(u["from"]) || !windowNumber(u["to"])) return item;
197
303
  } else if (t === "table") {
198
- if (typeof u["name"] !== "string") return false;
304
+ if (typeof u["name"] !== "string") return item;
199
305
  } else if (t === "where") {
200
306
  push(true, [u["axis"]]);
201
307
  push(false, [u["test"]]);
202
308
  } else if (!["all", "others", "other", "children", "ancestors", "descendants", "siblings", "successors", "predecessors", "reachable"].includes(t as string)) {
203
- return false;
309
+ return item;
204
310
  }
205
311
  continue;
206
312
  }
207
313
  switch (u["tag"]) {
208
314
  case "lit":
209
- if (!("value" in u)) return false;
315
+ if (!("value" in u)) return item;
210
316
  break;
211
- case "ref":
212
- 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);
213
321
  break;
322
+ }
214
323
  case "app":
215
- if (typeof u["op"] !== "string" || !Array.isArray(u["args"])) return false;
324
+ if (typeof u["op"] !== "string" || !Array.isArray(u["args"])) return item;
216
325
  push(false, u["args"]);
217
326
  break;
218
327
  case "let":
219
- if (!isObject(u["bind"]) || Array.isArray(u["bind"])) return false;
328
+ if (!isObject(u["bind"]) || Array.isArray(u["bind"])) return item;
220
329
  push(false, [...Object.values(u["bind"]), u["body"]]);
221
330
  break;
222
331
  case "var":
223
- if (typeof u["name"] !== "string") return false;
332
+ if (typeof u["name"] !== "string") return item;
224
333
  break;
225
334
  case "rec":
226
- if (!isObject(u["fields"]) || Array.isArray(u["fields"])) return false;
335
+ if (!isObject(u["fields"]) || Array.isArray(u["fields"])) return item;
227
336
  push(false, Object.values(u["fields"]));
228
337
  break;
229
- case "each":
230
- 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;
231
349
  push(true, [u["axis"]]);
232
- 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"]])]);
233
358
  break;
359
+ }
234
360
  case "ext":
235
- if (typeof u["kind"] !== "string" || !("data" in u)) return false;
361
+ if (typeof u["kind"] !== "string" || !("data" in u)) return item;
236
362
  break;
237
363
  default:
238
- return false;
364
+ return item;
239
365
  }
240
366
  }
241
- return true;
367
+ return undefined;
242
368
  }
243
369
 
244
- /** 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
+ */
245
374
  export function children(e: Expr): readonly Expr[] {
246
375
  switch (e.tag) {
247
376
  case "app":
@@ -251,9 +380,14 @@ export function children(e: Expr): readonly Expr[] {
251
380
  case "rec":
252
381
  return Object.values(e.fields);
253
382
  case "each":
254
- return [e.body, ...whereTests(e.axis)];
255
- 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];
256
388
  case "ref":
389
+ return addrExprs(e.at);
390
+ case "lit":
257
391
  case "var":
258
392
  case "ext":
259
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
  }