@mark1russell7/vex 0.13.3 → 0.14.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/kernel.ts CHANGED
@@ -74,6 +74,9 @@ const move = (walker: string, parts: PartShape): Kind => ({ verbs: { eval: "form
74
74
  /** The scope of a loop: the names of `init`, for the steps, the test `until` and the result (LOOP.NAMES). */
75
75
  const LOOP_SCOPE = [{ names: { keysAt: ["init"] }, in: [["step", "*"], ["until"], ["result"]] }] as const;
76
76
 
77
+ /** The names of the items of a loop over the axis `list`: one or two distinct texts (AXIS.LIST.SCOPE). */
78
+ const ITEM_NAMES: PartShape = { shape: "list", item: { shape: "text" }, distinct: true };
79
+
77
80
  /**
78
81
  * This function gives the world of Vex. The module uses it one time, and the annotation `__PURE__` lets a bundler
79
82
  * remove the world from a program that does not use it.
@@ -101,11 +104,17 @@ function worldOfVex(): World {
101
104
  summary: "A function of a let. Its body evaluates at the position of each call.",
102
105
  },
103
106
  call: { verbs: { eval: "vex.call" }, parts: closed({ fn: { shape: "term", kinds: [["ref"]] }, args: TERMS }, ["fn", "args"]), summary: "A call of a function of a let." },
104
- each: { verbs: { eval: "vex.each" }, parts: closed({ axis: AXIS, body: TERM, at: ADDRESS }, ["axis", "body"]), summary: "The body at each target of an axis: a list." },
107
+ each: {
108
+ verbs: { eval: "vex.each" },
109
+ parts: closed({ axis: AXIS, as: ITEM_NAMES, body: TERM, at: ADDRESS }, ["axis", "body"]),
110
+ // The names of the items are names of the body only. The test of where does not see them (AXIS.LIST.SCOPE).
111
+ scope: [{ names: { listAt: ["as"] }, in: [["body"]] }],
112
+ summary: "The body at each target of an axis: a list.",
113
+ },
105
114
  fold: {
106
115
  verbs: { eval: "vex.fold" },
107
- parts: closed({ axis: AXIS, init: NAMES, step: NAMES, result: TERM, at: ADDRESS }, ["axis", "init", "step", "result"]),
108
- scope: LOOP_SCOPE,
116
+ parts: closed({ axis: AXIS, as: ITEM_NAMES, init: NAMES, step: NAMES, result: TERM, at: ADDRESS }, ["axis", "init", "step", "result"]),
117
+ scope: [...LOOP_SCOPE, { names: { listAt: ["as"] }, in: [["step", "*"]] }],
109
118
  summary: "A step at each target of an axis, in order, and a result.",
110
119
  },
111
120
  iterate: {
@@ -312,10 +321,15 @@ const WALKERS: Readonly<Record<string, Walker>> = {
312
321
  * (`vexDefinitions`).
313
322
  */
314
323
 
315
- /** A target of an axis: its key, or its key and an error (AXIS.WHERE, AXIS.LIST). */
324
+ /**
325
+ * A target of an axis: its key, or its key and an error (AXIS.WHERE, AXIS.LIST). A target of the axis `list` also has
326
+ * the value of its item and its position as `nth` counts it (AXIS.LIST.ITEM, AXIS.LIST.INDEX).
327
+ */
316
328
  interface Target {
317
329
  readonly key: string;
318
330
  readonly error?: VexError;
331
+ readonly value?: unknown;
332
+ readonly index?: number;
319
333
  }
320
334
 
321
335
  /** The value of an axis document: the targets from a position. `table` names the table of the axis table. */
@@ -375,7 +389,9 @@ const axisEvaluator: EvalFn = ({ typePath, value, context }) => {
375
389
  // LIST.ARRAY: an array is a list with the positions as keys.
376
390
  const items = asList(r.value, missing);
377
391
  if (items === undefined) return failed("kind-mismatch", `the axis "list" needs a list, not a ${describe(r.value)}`);
378
- return ok(items.items.map(({ key, result }) => (result.ok ? { key } : { key, error: result.error })));
392
+ // The index counts the items with a value, as nth does: nth skips the error items (LIST.LENIENT).
393
+ let index = 0;
394
+ return ok(items.items.map(({ key, result }): Target => (result.ok ? { key, value: result.value, index: index++ } : { key, error: result.error })));
379
395
  },
380
396
  });
381
397
  }
@@ -418,7 +434,8 @@ function whereTargets(base: Targets, test: Part, ctx: Context, from: Place): Out
418
434
  }
419
435
  const r = test.evaluate({ ...ctx, self: placeOf(base, from, t.key) });
420
436
  if (!r.ok) out.push({ key: t.key, error: toVexError(r.error) });
421
- else if (r.value === true) out.push({ key: t.key });
437
+ // The target keeps the value and the index of its item (AXIS.LIST.ITEM).
438
+ else if (r.value === true) out.push(t);
422
439
  else if (r.value !== false) out.push({ key: t.key, error: vexError("kind-mismatch", `the test of "where" gave a ${typeof r.value}, not a boolean`) });
423
440
  }
424
441
  return ok(out);
@@ -462,6 +479,22 @@ function bindAll(record: Part | undefined, ctx: Context, names: Readonly<Record<
462
479
  return ok(out);
463
480
  }
464
481
 
482
+ /**
483
+ * This function adds the names `as` of a loop to the names of a body or of a step. The first name holds the value of
484
+ * the item, and the second its index (AXIS.LIST.ITEM, AXIS.LIST.INDEX). A loop without `as` keeps its names.
485
+ */
486
+ function withItem(names: Readonly<Record<string, unknown>>, as: readonly string[] | undefined, t: Target): Readonly<Record<string, unknown>> {
487
+ if (as === undefined) return names;
488
+ const out: Record<string, unknown> = { ...names };
489
+ const [item, index] = as;
490
+ setName(out, item as string, t.value);
491
+ if (index !== undefined) setName(out, index, t.index);
492
+ return out;
493
+ }
494
+
495
+ /** This function gives the names `as` of a loop, or `undefined` (AXIS.LIST.SCOPE). */
496
+ const itemNamesOf = (value: unknown): readonly string[] | undefined => (value as { readonly as?: readonly string[] }).as;
497
+
465
498
  /** The evaluators of the loops: each, fold and iterate (LOOP.NAMES, FOLD.ORDER, ITERATE.LIMIT). */
466
499
  const LOOPS: Readonly<Record<string, EvalFn>> = {
467
500
  "vex.each": ({ value, context }) => {
@@ -469,7 +502,11 @@ const LOOPS: Readonly<Record<string, EvalFn>> = {
469
502
  if (!found.ok) return found;
470
503
  const { axis, from, targets } = found.value;
471
504
  const body = partAt(value, "body");
472
- const items: ListItem[] = targets.map(({ key, error }) => ({ key, result: error === undefined ? toVexResult(body.evaluate({ ...context, self: placeOf(axis, from, key) })) : vexFail(error) }));
505
+ const as = itemNamesOf(value);
506
+ const items: ListItem[] = targets.map((t) => ({
507
+ key: t.key,
508
+ result: t.error === undefined ? toVexResult(body.evaluate({ ...context, self: placeOf(axis, from, t.key), names: withItem(context.names, as, t) })) : vexFail(t.error),
509
+ }));
473
510
  return ok(vexList(items));
474
511
  },
475
512
 
@@ -482,9 +519,11 @@ const LOOPS: Readonly<Record<string, EvalFn>> = {
482
519
  const found = targetsOf(value, context);
483
520
  if (!found.ok) return found;
484
521
  const { axis, from, targets } = found.value;
485
- for (const { key, error } of targets) {
486
- if (error !== undefined) return { ok: false, error: toKernelError(error) };
487
- const next = bindAll(step, { ...context, self: placeOf(axis, from, key), names }, names);
522
+ const as = itemNamesOf(value);
523
+ for (const t of targets) {
524
+ if (t.error !== undefined) return { ok: false, error: toKernelError(t.error) };
525
+ // The step sees the names of the item, and the next names do not keep them (AXIS.LIST.SCOPE).
526
+ const next = bindAll(step, { ...context, self: placeOf(axis, from, t.key), names: withItem(names, as, t) }, names);
488
527
  if (!next.ok) return next;
489
528
  names = next.value;
490
529
  }
@@ -686,9 +725,10 @@ function listOp(op: string, items: readonly ListItem[], rest: readonly unknown[]
686
725
  case "first":
687
726
  return vs.length > 0 ? vs[0] : empty();
688
727
  case "sortBy": {
689
- const kind = typeof vs[0];
690
- if (vs.some((x) => typeof x !== kind || (kind !== "number" && kind !== "string") || Number.isNaN(x))) stop("kind-mismatch", '"sortBy" needs numbers without NaN or texts, all of one kind');
691
- return vexList(good.map((it, i) => ({ it, i })).toSorted((a, b) => compare(vs[a.i], vs[b.i])).map(({ it }) => it));
728
+ const ks = sortValues(o, vs, domains);
729
+ const kind = typeof ks[0];
730
+ if (ks.some((x) => typeof x !== kind || (kind !== "number" && kind !== "string") || Number.isNaN(x))) stop("kind-mismatch", '"sortBy" needs numbers without NaN or texts, all of one kind');
731
+ return vexList(good.map((it, i) => ({ it, i })).toSorted((a, b) => compare(ks[a.i], ks[b.i])).map(({ it }) => it));
692
732
  }
693
733
  case "take":
694
734
  case "drop":
@@ -745,6 +785,20 @@ function listOp(op: string, items: readonly ListItem[], rest: readonly unknown[]
745
785
  }
746
786
  }
747
787
 
788
+ /**
789
+ * This function gives the sort values of `sortBy` (LIST.SORT.BY). Without the option `by`, they are the values. With
790
+ * it, the op of that name applies to each value, in order, and the first error stops the sort.
791
+ */
792
+ function sortValues(o: unknown, vs: readonly unknown[], domains: readonly AnyDomain[]): readonly unknown[] {
793
+ const by = (o as { readonly by?: unknown } | null | undefined)?.by;
794
+ if (by === undefined) return vs;
795
+ if (typeof by !== "string") return stop("kind-mismatch", '"sortBy" needs an op name in the option "by"');
796
+ return vs.map((x) => {
797
+ const found = domains.filter((d) => accepts(d, x)).map((d) => opOf(d, x, by)).find((f) => f !== undefined);
798
+ return found === undefined ? stop("unknown-op", `no domain gives "${by}" for a ${describe(x)}`) : callFound(found, by, x, [], domains);
799
+ });
800
+ }
801
+
748
802
  /** This function compares two numbers or two texts for `sortBy`. Equal values keep their order (LIST.SORT). */
749
803
  const compare = (a: unknown, b: unknown): number => ((a as number) < (b as number) ? -1 : (a as number) > (b as number) ? 1 : 0);
750
804
 
package/src/write.ts CHANGED
@@ -50,6 +50,9 @@ const NONE: readonly Job[] = [];
50
50
  const term = (e: Expr): Job => ({ t: "term", e });
51
51
  const envelope = (e: Expr): Job => ({ t: "envelope", e });
52
52
 
53
+ /** This function gives the field `as` of a loop: a new list of its names, or no field (AXIS.LIST.SCOPE). */
54
+ const itemsOf = (as: readonly string[] | undefined): { readonly as?: Json } => (as === undefined ? {} : { as: [...as] });
55
+
53
56
  /** This function gives a record from names and the documents of their values, from an index of the documents. */
54
57
  function namesOf(names: readonly string[], docs: readonly Json[], from: number): JsonRecord {
55
58
  const out: Record<string, Json> = {};
@@ -148,7 +151,8 @@ class Writer {
148
151
  const axis = docs[0] as Json;
149
152
  const body = docs[1] as Json;
150
153
  const address = at.make(docs.slice(2));
151
- return this.#keep(typed("each", reads ? { body, axis, ...address } : { axis, body, ...address }), e);
154
+ const as = itemsOf(e.as);
155
+ return this.#keep(typed("each", reads ? { body, axis, ...as, ...address } : { axis, ...as, body, ...address }), e);
152
156
  },
153
157
  };
154
158
  }
@@ -164,7 +168,8 @@ class Writer {
164
168
  const names = { init: namesOf(init, docs, 1), step: namesOf(step, docs, 1 + init.length) };
165
169
  const result = docs[after] as Json;
166
170
  const address = at.make(docs.slice(after + 1));
167
- return this.#keep(typed("fold", reads ? { ...names, axis, ...address, result } : { axis, ...names, result, ...address }), e);
171
+ const as = itemsOf(e.as);
172
+ return this.#keep(typed("fold", reads ? { ...names, axis, ...as, ...address, result } : { axis, ...as, ...names, result, ...address }), e);
168
173
  },
169
174
  };
170
175
  }