@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/evaluate.ts CHANGED
@@ -1,9 +1,9 @@
1
1
  import { liftsAt, resolveOp, type AnyDomain, type ParamKind, type ResolvedOp } from "./domain.ts";
2
2
  import { formatError, isDepthError, isStackOverflow, vexError, type ErrorKind, type VexError } from "./errors.ts";
3
- import { children, type Axis, type Expr, type ExprOf, type Move } from "./ir.ts";
3
+ import { addrExprs, children, shapeError, type Addr, type Axis, type Expr, type ExprOf, type FixedMove, type Move } from "./ir.ts";
4
4
  import { isListOp, isVexList, vexList, type ListItem, type ListOp, type ListOptions, type VexList } from "./list.ts";
5
5
  import { fail, ok, type Result } from "./result.ts";
6
- import { axisTargets, resolveAddr, type Position, type Space } from "./space.ts";
6
+ import { axisTargets, fixAddr, resolveAddr, type Position, type Space } from "./space.ts";
7
7
  import type { Read, Trace, TraceEvent, TraceSink } from "./trace.ts";
8
8
 
9
9
  /** A free function op. The interpreter gives it the values of all arguments. */
@@ -33,6 +33,8 @@ export interface EvalOptions {
33
33
  readonly extensions?: Readonly<Record<string, ExtHandler>>;
34
34
  /** Variables that the program can read with `v(name)`. */
35
35
  readonly vars?: Readonly<Record<string, unknown>>;
36
+ /** The other spaces of the evaluation, by name. The axis `table(name)` reads them. */
37
+ readonly tables?: Readonly<Record<string, Space>>;
36
38
  /** A receiver of trace events. */
37
39
  readonly trace?: TraceSink;
38
40
  }
@@ -56,7 +58,7 @@ const isSpecialForm = (op: string): op is SpecialForm => SPECIAL_FORMS.has(op);
56
58
  export type CompileOptions = Pick<EvalOptions, "domains" | "fns" | "extensions">;
57
59
 
58
60
  /** The options of one run of a compiled program. */
59
- export type RunOptions = Pick<EvalOptions, "space" | "origin" | "vars" | "trace">;
61
+ export type RunOptions = Pick<EvalOptions, "space" | "origin" | "vars" | "trace" | "tables">;
60
62
 
61
63
  /**
62
64
  * A compiled program: the expression as a tree of functions. A program evaluates many times at different origins,
@@ -93,18 +95,18 @@ export function nestingOf(e: Expr): number {
93
95
  }
94
96
 
95
97
  export function compile(expr: Expr, opts: CompileOptions = {}): Program {
98
+ // EVAL.SHAPE: an expression that is not valid, for example from a newer version of Vex, gives an error before a walk.
96
99
  // EVAL.NESTING: a program nested too deep gives an error before the compiler walks it with recursion.
97
- const nesting = nestingOf(expr);
98
- const root: Node =
99
- nesting > MAX_NESTING
100
- ? (f) => fail(vexError("bad-expression", `the expression is nested ${nesting} levels deep, and the limit is ${MAX_NESTING}`, { path: [], origin: f.pos.origin, focus: f.pos.focus }))
101
- : new Compiler(opts).node(expr, []);
100
+ const shape = shapeError(expr);
101
+ const nesting = shape === undefined ? nestingOf(expr) : 0;
102
+ const bad = shape ?? (nesting > MAX_NESTING ? `the expression is nested ${nesting} levels deep, and the limit is ${MAX_NESTING}` : undefined);
103
+ const root: Node = bad === undefined ? new Compiler(opts).node(expr, []) : (f) => fail(vexError("bad-expression", bad, { path: [], origin: f.pos.origin, focus: f.pos.focus }));
102
104
  const run = (r: RunOptions): Result<unknown> => {
103
105
  const { space, origin } = r;
104
106
  if (!space.has(origin)) return fail(vexError("unknown-key", `the space has no key "${origin}"`, { origin, focus: origin }));
105
107
  const env = new Map<string, Result<unknown>>(Object.entries(r.vars ?? {}).map(([k, val]) => [k, ok(val)]));
106
108
  try {
107
- return root({ pos: { origin, focus: origin }, env }, { space, trace: r.trace });
109
+ return root({ pos: { origin, focus: origin }, env }, { space, trace: r.trace, tables: r.tables });
108
110
  } catch (thrown) {
109
111
  // A defect in an extension handler or in a test of the interpreter itself. Totality still holds.
110
112
  if (isStackOverflow(thrown)) return fail(vexError("depth", DEPTH_MESSAGE, { origin, focus: origin, thrown }));
@@ -146,12 +148,16 @@ export function explain(expr: Expr, opts: Omit<EvalOptions, "trace">): Trace {
146
148
  return compiled(expr, opts).explain(opts);
147
149
  }
148
150
 
149
- /** The state of one run that the nodes read: the space and the trace sink. */
151
+ /** The state of one run that the nodes read: the space, the trace sink and the other spaces. */
150
152
  interface Ctx {
151
153
  readonly space: Space;
152
154
  readonly trace: TraceSink | undefined;
155
+ readonly tables: Readonly<Record<string, Space>> | undefined;
153
156
  }
154
157
 
158
+ /** This function gives the axis inside the `where` axes of an axis. */
159
+ const baseAxis = (a: Axis): Exclude<Axis, { readonly t: "where" }> => (a.t === "where" ? baseAxis(a.axis) : a);
160
+
155
161
  /** A compiled node: it evaluates in a frame of a run. */
156
162
  type Node = (f: Frame, c: Ctx) => Result<unknown>;
157
163
 
@@ -234,6 +240,10 @@ class Compiler {
234
240
  return isSpecialForm(e.op) ? this.#special(e.op, this.#nodes(e.args, path), info) : this.#app(e.op, this.#nodes(e.args, path), info);
235
241
  case "each":
236
242
  return this.#each(e, info);
243
+ case "fold":
244
+ return this.#fold(e, info);
245
+ case "iterate":
246
+ return this.#iterate(e, info);
237
247
  case "ext": {
238
248
  const extensions = this.#extensions ?? {};
239
249
  const handler = Object.hasOwn(extensions, e.kind) ? extensions[e.kind] : undefined;
@@ -268,10 +278,32 @@ class Compiler {
268
278
  return isStackOverflow(thrown) ? this.#err("depth", DEPTH_MESSAGE, f, path, { ...extra, thrown }) : this.#err("threw", message, f, path, { ...extra, thrown });
269
279
  }
270
280
 
281
+ /**
282
+ * This method compiles an address. Its function gives the key where the address points. The expressions of the
283
+ * computed moves evaluate first, at the position of the node, and their child indexes start at `first`. An error of
284
+ * an expression keeps its path, and an error of a move gets the path of the node.
285
+ */
286
+ #address(at: Addr, path: readonly number[], first: number): (f: Frame, c: Ctx) => Result<string> {
287
+ const nodes = addrExprs(at).map((x, i) => this.node(x, [...path, first + i]));
288
+ const moved = (r: Result<string>): Result<string> => (r.ok ? r : fail({ ...r.error, path }));
289
+ if (nodes.length === 0) return (f, c) => moved(resolveAddr(c.space, f.pos, at as readonly FixedMove[]));
290
+ return (f, c) => {
291
+ const values: unknown[] = [];
292
+ for (const n of nodes) {
293
+ const r = n(f, c);
294
+ if (!r.ok) return r;
295
+ values.push(r.value);
296
+ }
297
+ const fixed = fixAddr(at, values, f.pos);
298
+ return fixed.ok ? moved(resolveAddr(c.space, f.pos, fixed.value)) : moved(fixed);
299
+ };
300
+ }
301
+
271
302
  #ref(e: ExprOf<"ref">, info: Info): Node {
272
303
  const { path } = info;
273
304
  const segs = e.path;
274
305
  const at = e.at ?? [];
306
+ const address = this.#address(at, path, 0);
275
307
  const label = segs.join(".");
276
308
  const steps = segs.map((seg, i) => ({ seg, where: segs.slice(0, i + 1).join("."), valid: isFieldName(seg) }));
277
309
  return (f, c) => {
@@ -279,8 +311,8 @@ class Compiler {
279
311
  // The empty address resolves to the focus, so this fast path changes no result.
280
312
  // Stryker disable next-line ConditionalExpression,EqualityOperator: resolveAddr of [] gives the focus too
281
313
  if (at.length > 0) {
282
- const where = resolveAddr(c.space, f.pos, at);
283
- if (!where.ok) return this.#emit(c, info, f, fail({ ...where.error, path }));
314
+ const where = address(f, c);
315
+ if (!where.ok) return this.#emit(c, info, f, where);
284
316
  key = where.value;
285
317
  }
286
318
  const failed = (r: Result<unknown>): Result<unknown> => this.#emit(c, info, f, r, [{ key, path: segs, ok: false }]);
@@ -321,29 +353,154 @@ class Compiler {
321
353
  #each(e: ExprOf<"each">, info: Info): Node {
322
354
  const { path } = info;
323
355
  const at = e.at ?? [];
324
- const targets = this.#targets(e.axis, path, { next: 1 });
356
+ const counter = { next: 1 };
357
+ const targets = this.#targets(e.axis, path, counter);
325
358
  const body = this.node(e.body, [...path, 0]);
359
+ const address = this.#address(at, path, counter.next);
326
360
  return (f, c) => {
327
361
  // An axis with an address finds its targets from the key of the address. The origin does not change.
328
362
  let from = f;
329
363
  // Stryker disable next-line ConditionalExpression,EqualityOperator: resolveAddr of [] gives the focus too
330
364
  if (at.length > 0) {
331
- const where = resolveAddr(c.space, f.pos, at);
332
- if (!where.ok) return this.#emit(c, info, f, fail({ ...where.error, path }));
365
+ const where = address(f, c);
366
+ if (!where.ok) return this.#emit(c, info, f, where);
333
367
  from = { pos: { origin: f.pos.origin, focus: where.value }, env: f.env };
334
368
  }
335
- const ts = targets(from, c);
369
+ // The axis table moves the evaluation to the space of its table, where the origin of this space is not a key.
370
+ // Thus there the origin is the target, and a value of this space goes in through a variable.
371
+ const base = baseAxis(e.axis);
372
+ let inner = c;
373
+ if (base.t === "table") {
374
+ const space = c.tables !== undefined && Object.hasOwn(c.tables, base.name) ? c.tables[base.name] : undefined;
375
+ if (space === undefined) return this.#emit(c, info, f, this.#err("no-table", `the evaluation has no table "${base.name}"`, f, path));
376
+ inner = { ...c, space };
377
+ }
378
+ const ts = targets(from, inner);
336
379
  if (!ts.ok) return this.#emit(c, info, f, ts);
337
380
  const items: ListItem[] = ts.value.map(({ key, test }) => {
338
381
  if (test !== undefined && !test.ok) return { key, result: test };
339
- return { key, result: body({ pos: { origin: f.pos.origin, focus: key }, env: f.env }, c) };
382
+ return { key, result: body({ pos: { origin: base.t === "table" ? key : f.pos.origin, focus: key }, env: f.env }, inner) };
340
383
  });
341
384
  return this.#emit(c, info, f, ok(vexList(items)));
342
385
  };
343
386
  }
344
387
 
388
+ /**
389
+ * This method compiles the names of a loop: `init` at the indexes from 0, and `step` after them (LOOP.NAMES). Its
390
+ * functions give the first values, and the values after one step. The first error stops each of them.
391
+ */
392
+ #names(e: ExprOf<"fold"> | ExprOf<"iterate">, path: readonly number[]): {
393
+ readonly first: (f: Frame, c: Ctx) => Result<Map<string, Result<unknown>>>;
394
+ readonly next: (f: Frame, c: Ctx) => Result<Map<string, Result<unknown>>>;
395
+ } {
396
+ const inits = Object.entries(e.init).map(([name, x], i) => [name, this.node(x, [...path, i])] as const);
397
+ const steps = Object.entries(e.step).map(([name, x], i) => [name, this.node(x, [...path, inits.length + i])] as const);
398
+ return {
399
+ first: (f, c) => {
400
+ const env = new Map(f.env);
401
+ for (const [name, n] of inits) {
402
+ const r = n(f, c);
403
+ if (!r.ok) return r;
404
+ env.set(name, r);
405
+ }
406
+ return ok(env);
407
+ },
408
+ // Each value of a step reads the values before the step, so the names change only after all the values.
409
+ next: (f, c) => {
410
+ const values: (readonly [string, Result<unknown>])[] = [];
411
+ for (const [name, n] of steps) {
412
+ const r = n(f, c);
413
+ if (!r.ok) return r;
414
+ values.push([name, r]);
415
+ }
416
+ const env = new Map(f.env);
417
+ for (const [name, r] of values) env.set(name, r);
418
+ return ok(env);
419
+ },
420
+ };
421
+ }
422
+
423
+ /**
424
+ * This method compiles a fold (FOLD.ORDER, FOLD.ERROR). `init` evaluates at the node, then the address and the
425
+ * targets. A step evaluates at each target in order. `result` evaluates at the node with the last values.
426
+ */
427
+ #fold(e: ExprOf<"fold">, info: Info): Node {
428
+ const { path } = info;
429
+ const at = e.at ?? [];
430
+ const names = this.#names(e, path);
431
+ const counter = { next: Object.keys(e.init).length + Object.keys(e.step).length };
432
+ const targets = this.#targets(e.axis, path, counter);
433
+ const address = this.#address(at, path, counter.next);
434
+ const result = this.node(e.result, [...path, counter.next + addrExprs(at).length]);
435
+ const base = baseAxis(e.axis);
436
+ return (f, c) => {
437
+ const first = names.first(f, c);
438
+ if (!first.ok) return this.#emit(c, info, f, first);
439
+ let env = first.value;
440
+ let from = f;
441
+ // Stryker disable next-line ConditionalExpression,EqualityOperator: resolveAddr of [] gives the focus too
442
+ if (at.length > 0) {
443
+ const where = address(f, c);
444
+ if (!where.ok) return this.#emit(c, info, f, where);
445
+ from = { pos: { origin: f.pos.origin, focus: where.value }, env: f.env };
446
+ }
447
+ let inner = c;
448
+ if (base.t === "table") {
449
+ const space = c.tables !== undefined && Object.hasOwn(c.tables, base.name) ? c.tables[base.name] : undefined;
450
+ if (space === undefined) return this.#emit(c, info, f, this.#err("no-table", `the evaluation has no table "${base.name}"`, f, path));
451
+ inner = { ...c, space };
452
+ }
453
+ const ts = targets(from, inner);
454
+ if (!ts.ok) return this.#emit(c, info, f, ts);
455
+ for (const { key, test } of ts.value) {
456
+ if (test !== undefined && !test.ok) return this.#emit(c, info, f, test);
457
+ const after = names.next({ pos: { origin: base.t === "table" ? key : f.pos.origin, focus: key }, env }, inner);
458
+ if (!after.ok) return this.#emit(c, info, f, after);
459
+ env = after.value;
460
+ }
461
+ return this.#emit(c, info, f, result({ pos: f.pos, env }, c));
462
+ };
463
+ }
464
+
465
+ /**
466
+ * This method compiles an iteration (ITERATE.LIMIT, ITERATE.UNTIL, ITERATE.ERROR). The test `until` evaluates before
467
+ * each step and after the last step. `result` evaluates with the last values.
468
+ */
469
+ #iterate(e: ExprOf<"iterate">, info: Info): Node {
470
+ const { path } = info;
471
+ const names = this.#names(e, path);
472
+ const untilAt = Object.keys(e.init).length + Object.keys(e.step).length;
473
+ const untilPath = [...path, untilAt];
474
+ const until = e.until === undefined ? undefined : this.node(e.until, untilPath);
475
+ const result = this.node(e.result, [...path, untilAt + (until === undefined ? 0 : 1)]);
476
+ const { limit } = e;
477
+ return (f, c) => {
478
+ const first = names.first(f, c);
479
+ if (!first.ok) return this.#emit(c, info, f, first);
480
+ let env = first.value;
481
+ for (let k = 0; ; k++) {
482
+ const frame: Frame = { pos: f.pos, env };
483
+ if (until !== undefined) {
484
+ const t = until(frame, c);
485
+ if (!t.ok) return this.#emit(c, info, f, t);
486
+ if (t.value === true) break;
487
+ if (t.value !== false) return this.#emit(c, info, f, this.#err("kind-mismatch", `the test "until" of "iterate" gave a ${typeof t.value}, not a boolean`, f, untilPath));
488
+ }
489
+ if (k === limit) {
490
+ if (until !== undefined) return this.#emit(c, info, f, this.#err("limit", `"iterate" made its ${String(limit)} steps, and its test "until" is not true`, f, path));
491
+ break;
492
+ }
493
+ const after = names.next(frame, c);
494
+ if (!after.ok) return this.#emit(c, info, f, after);
495
+ env = after.value;
496
+ }
497
+ return this.#emit(c, info, f, result({ pos: f.pos, env }, c));
498
+ };
499
+ }
500
+
345
501
  /** This method compiles the targets of an axis. For `where`, a failed test keeps the target with its error. */
346
502
  #targets(a: Axis, path: readonly number[], counter: { next: number }): (f: Frame, c: Ctx) => Result<readonly { readonly key: string; readonly test?: Result<unknown> }[]> {
503
+ if (a.t === "table") return (_f, c) => ok(c.space.keys.map((key) => ({ key })));
347
504
  if (a.t !== "where") {
348
505
  return (f, c) => {
349
506
  const keys = axisTargets(c.space, f.pos, a);
@@ -353,6 +510,8 @@ class Compiler {
353
510
  const inner = this.#targets(a.axis, path, counter);
354
511
  const testPath = [...path, counter.next++];
355
512
  const test = this.node(a.test, testPath);
513
+ // In the space of the axis table, the origin of the test is the target, as for the body.
514
+ const sameOrigin = baseAxis(a).t === "table";
356
515
  return (f, c) => {
357
516
  const ts = inner(f, c);
358
517
  if (!ts.ok) return ts;
@@ -362,7 +521,7 @@ class Compiler {
362
521
  out.push(t);
363
522
  continue;
364
523
  }
365
- const at: Frame = { pos: { origin: f.pos.origin, focus: t.key }, env: f.env };
524
+ const at: Frame = { pos: { origin: sameOrigin ? t.key : f.pos.origin, focus: t.key }, env: f.env };
366
525
  const r = test(at, c);
367
526
  if (!r.ok) out.push({ key: t.key, test: r });
368
527
  else if (r.value === true) out.push({ key: t.key });
@@ -584,11 +743,12 @@ class Compiler {
584
743
  }
585
744
 
586
745
  const FORBIDDEN_FIELDS = new Set(["__proto__", "constructor", "prototype"]);
587
- const isFieldName = (seg: string): boolean => seg.length > 0 && !FORBIDDEN_FIELDS.has(seg);
746
+ /** This function tells if a segment of a path can name a field. A compiler uses the same rule as the interpreter. */
747
+ export const isFieldName = (seg: string): boolean => seg.length > 0 && !FORBIDDEN_FIELDS.has(seg);
588
748
 
589
749
  /** This function runs the `is` test of a domain. A test that throws counts as `false`. */
590
750
  // Stryker disable BlockStatement: an empty catch gives undefined, which also counts as false
591
- function safeIs(d: AnyDomain, value: unknown): boolean {
751
+ export function safeIs(d: AnyDomain, value: unknown): boolean {
592
752
  try {
593
753
  return d.is(value);
594
754
  } catch {
@@ -598,7 +758,8 @@ function safeIs(d: AnyDomain, value: unknown): boolean {
598
758
  // Stryker restore BlockStatement
599
759
 
600
760
 
601
- function matchesKind(kind: ParamKind, value: unknown, domain: AnyDomain): boolean {
761
+ /** This function tells if an argument has the kind of a parameter of an op of the domain `domain`. */
762
+ export function matchesKind(kind: ParamKind, value: unknown, domain: AnyDomain): boolean {
602
763
  switch (kind) {
603
764
  case "domain":
604
765
  return safeIs(domain, value);
@@ -641,7 +802,10 @@ export function labelOf(e: Expr): string {
641
802
  case "rec":
642
803
  return `{ ${Object.keys(e.fields).join(", ")} }`;
643
804
  case "each":
644
- return e.at === undefined ? `each ${e.axis.t}` : `each ${e.axis.t} from ${e.at.map(moveText).join(".")}`;
805
+ case "fold":
806
+ return e.at === undefined ? `${e.tag} ${e.axis.t}` : `${e.tag} ${e.axis.t} from ${e.at.map(moveText).join(".")}`;
807
+ case "iterate":
808
+ return `iterate ${String(e.limit)}`;
645
809
  case "ext":
646
810
  return e.kind;
647
811
  }
@@ -651,9 +815,9 @@ export function labelOf(e: Expr): string {
651
815
  function moveText(m: Move): string {
652
816
  switch (m.t) {
653
817
  case "key":
654
- return `key(${m.key})`;
818
+ return `key(${typeof m.key === "string" ? m.key : labelOf(m.key)})`;
655
819
  case "index":
656
- return `index(${m.i})`;
820
+ return `index(${typeof m.i === "number" ? String(m.i) : labelOf(m.i)})`;
657
821
  case "offset":
658
822
  return `offset(${m.d.join(", ")})`;
659
823
  case "other":