@mark1russell7/vex 0.11.2 → 0.13.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/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package",
3
3
  "name": "@mark1russell7/vex",
4
- "version": "0.11.2",
4
+ "version": "0.13.0",
5
5
  "description": "Vex: typed spreadsheet formulas over domain objects. The kernel and the typed builder.",
6
6
  "keywords": [
7
7
  "typescript",
@@ -49,7 +49,7 @@
49
49
  "access": "public"
50
50
  },
51
51
  "dependencies": {
52
- "@mark1russell7/coeval": "^0.6.3"
52
+ "@mark1russell7/coeval": "^0.7.0"
53
53
  },
54
54
  "devDependencies": {
55
55
  "@mark1russell7/cue": "github:mark1russell7/cue",
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Arrays as lists (LIST.ARRAY). A JSON array of a field or of a name reads as a list where a list op or the axis `list`
3
+ * needs a list. The package index does not export this module: `evaluate.ts` and `kernel.ts` use it.
4
+ */
5
+ import type { VexError } from "./errors.ts";
6
+ import { MAX_ITERATIONS } from "./ir.ts";
7
+ import { isVexList, vexList, type ListItem, type VexList } from "./list.ts";
8
+ import { fail, ok } from "./result.ts";
9
+
10
+ /**
11
+ * This function gives the list of an array (LIST.ARRAY). The key of each item is its position, from "0". A position
12
+ * without a value, or with `null`, gives an error item from `missing`, as a missing field does (REF.MISSING).
13
+ */
14
+ export function listOfArray(array: readonly unknown[], missing: (message: string) => VexError): VexList {
15
+ const items: ListItem[] = [];
16
+ // A loop over the positions, not `map`, so a hole of a sparse array is an error item too.
17
+ for (let i = 0; i < array.length; i++) {
18
+ const x = array[i];
19
+ items.push({ key: String(i), result: x === undefined || x === null ? fail(missing(`the array has no value at the position ${String(i)}`)) : ok(x) });
20
+ }
21
+ return vexList(items);
22
+ }
23
+
24
+ /** This function gives a list, the list of an array, or `undefined` for another value (LIST.ARRAY). */
25
+ export const asList = (u: unknown, missing: (message: string) => VexError): VexList | undefined => (isVexList(u) ? u : Array.isArray(u) ? listOfArray(u, missing) : undefined);
26
+
27
+ /**
28
+ * This function tells if a value is a count of `fill`: a whole number from 0 to the limit of `iterate`, 100000
29
+ * (LIST.FILL). Thus a list of `fill` is not larger than the steps of a loop.
30
+ */
31
+ export const isFillCount = (n: unknown): n is number => Number.isSafeInteger(n) && (n as number) >= 0 && (n as number) <= MAX_ITERATIONS;
32
+
33
+ /** This function gives the list of `fill` (LIST.FILL): `n` items with the value `value`, and the keys "0" to "n - 1". */
34
+ export const fillList = (n: number, value: unknown): VexList => vexList(Array.from({ length: n }, (_x, i): ListItem => ({ key: String(i), result: ok(value) })));
35
+
36
+ /** This function tells if a value can be the value of `indexOf`: a number, a text or a boolean (LIST.INDEXOF). */
37
+ export const isIndexValue = (u: unknown): u is number | string | boolean => typeof u === "number" || typeof u === "string" || typeof u === "boolean";
package/src/evaluate.ts CHANGED
@@ -2,6 +2,7 @@ import { fromDocument, isDocument, type Envelope } from "./document.ts";
2
2
  import { liftsAt, resolveOp, type AnyDomain, type ParamKind, type ResolvedOp } from "./domain.ts";
3
3
  import { formatError, isDepthError, isStackOverflow, vexError, type ErrorKind, type VexError } from "./errors.ts";
4
4
  import { addrExprs, children, shapeError, type Addr, type Axis, type Expr, type ExprOf, type FixedMove, type Move } from "./ir.ts";
5
+ import { asList, fillList, isFillCount, isIndexValue, listOfArray } from "./array-list.ts";
5
6
  import { isListOp, isVexList, vexList, type ListItem, type ListOp, type ListOptions, type VexList } from "./list.ts";
6
7
  import { fail, ok, type Result } from "./result.ts";
7
8
  import { axisTargets, fixAddr, resolveAddr, type Position, type Space } from "./space.ts";
@@ -209,6 +210,18 @@ class Compiler {
209
210
  return fail(vexError(kind, message, { path, origin: f.pos.origin, focus: f.pos.focus, ...extra }));
210
211
  }
211
212
 
213
+ /** This method gives the error of a position of an array without a value (LIST.ARRAY), at a node. */
214
+ #missing(f: Frame, path: readonly number[]): (message: string) => VexError {
215
+ return (message) => vexError("missing-field", message, { path, origin: f.pos.origin, focus: f.pos.focus });
216
+ }
217
+
218
+ /** This method gives the list of `fill(n, value)` (LIST.FILL). A count that is not a whole number from 0 to 100000 gives `#VALUE!`. */
219
+ #fill(values: readonly unknown[], f: Frame, path: readonly number[]): Result<VexList> {
220
+ const [n, value] = values;
221
+ if (!isFillCount(n)) return this.#err("kind-mismatch", `"fill" needs a whole number from 0 to 100000, not ${describeType(n)}`, f, path, { op: "fill" });
222
+ return value === undefined ? this.#err("bad-expression", '"fill" needs argument 2', f, path, { op: "fill" }) : ok(fillList(n, value));
223
+ }
224
+
212
225
  #emit(c: Ctx, info: Info, f: Frame, result: Result<unknown>, reads?: readonly Read[]): Result<unknown> {
213
226
  if (c.trace !== undefined) {
214
227
  const event: TraceEvent = {
@@ -605,8 +618,10 @@ class Compiler {
605
618
  return (f, c) => {
606
619
  const r = node(f, c);
607
620
  if (!r.ok) return r;
608
- if (!isVexList(r.value)) return this.#err("kind-mismatch", `the axis "list" needs a list, not a ${describeType(r.value)}`, f, path);
609
- const items = r.value.items.map(({ key, result }) => (result.ok ? { key } : { key, test: result }));
621
+ // LIST.ARRAY: an array is a list with the positions as keys.
622
+ const listed = asList(r.value, this.#missing(f, path));
623
+ if (listed === undefined) return this.#err("kind-mismatch", `the axis "list" needs a list, not a ${describeType(r.value)}`, f, path);
624
+ const items = listed.items.map(({ key, result }) => (result.ok ? { key } : { key, test: result }));
610
625
  return ok(reverse ? items.toReversed() : items);
611
626
  };
612
627
  }
@@ -633,6 +648,9 @@ class Compiler {
633
648
  }
634
649
  }
635
650
  if (fn !== undefined) return this.#emit(c, info, f, this.#checkResult(this.#invoke(() => fn(...values), op, f, path), f, path, op));
651
+ // LIST.ARRAY and LIST.FILL come after the domains and the functions of the host, so each of their results stays.
652
+ if (listOp !== undefined && Array.isArray(self)) return this.#emit(c, info, f, this.#listOp(listOp, listOfArray(self, this.#missing(f, path)), values.slice(1), f, path));
653
+ if (op === "fill") return this.#emit(c, info, f, this.#fill(values, f, path));
636
654
  if (accepted !== undefined) return this.#emit(c, info, f, this.#err("unknown-op", `the domain "${accepted.name}" has no op "${op}"`, f, path, { op }));
637
655
  if (values.length === 0) return this.#emit(c, info, f, this.#err("unknown-op", `there is no function "${op}"`, f, path, { op }));
638
656
  return this.#emit(c, info, f, this.#err("not-instance", `no domain accepts the receiver of "${op}" (${describeType(self)})`, f, path, { op }));
@@ -753,7 +771,10 @@ class Compiler {
753
771
  return Number.isSafeInteger(n) && n >= 0 ? ok(n) : this.#err("kind-mismatch", `"${op}" needs a whole number from 0, not ${describeType(n)}`, f, path, { op });
754
772
  };
755
773
  // The second list of append and without follows the rules of the first list (LIST.BUILD).
756
- const other = (): Result<readonly ListItem[]> => (isVexList(rest[0]) ? goodItems(rest[0], strict) : this.#err("kind-mismatch", `"${op}" needs a list as its second argument, not a ${describeType(rest[0])}`, f, path, { op }));
774
+ const other = (): Result<readonly ListItem[]> => {
775
+ const second = asList(rest[0], this.#missing(f, path));
776
+ return second !== undefined ? goodItems(second, strict) : this.#err("kind-mismatch", `"${op}" needs a list as its second argument, not a ${describeType(rest[0])}`, f, path, { op });
777
+ };
757
778
  switch (op) {
758
779
  case "sortBy":
759
780
  return this.#sortBy(okItems, okValues, f, path);
@@ -775,6 +796,12 @@ class Compiler {
775
796
  }
776
797
  case "flat":
777
798
  return this.#flat(okValues, strict, f, path);
799
+ case "indexOf": {
800
+ const x = rest[0];
801
+ if (!isIndexValue(x)) return this.#err("kind-mismatch", `"indexOf" needs a number, a text or a boolean, not a ${describeType(x)}`, f, path, { op });
802
+ const i = okValues.indexOf(x);
803
+ return i >= 0 ? ok(i) : this.#err("missing-field", `the list has no item with the value ${JSON.stringify(x)}`, f, path, { op });
804
+ }
778
805
  case "nth": {
779
806
  const i = whole();
780
807
  if (!i.ok) return i;
@@ -844,8 +871,9 @@ class Compiler {
844
871
  */
845
872
  #flat(values: readonly unknown[], strict: boolean, f: Frame, path: readonly number[]): Result<VexList> {
846
873
  const out: ListItem[] = [];
847
- for (const inner of values) {
848
- if (!isVexList(inner)) return this.#err("kind-mismatch", `"flat" needs a list as the value of each item, but an item is a ${describeType(inner)}`, f, path, { op: "flat" });
874
+ for (const value of values) {
875
+ const inner = asList(value, this.#missing(f, path));
876
+ if (inner === undefined) return this.#err("kind-mismatch", `"flat" needs a list as the value of each item, but an item is a ${describeType(value)}`, f, path, { op: "flat" });
849
877
  const good = goodItems(inner, strict);
850
878
  if (!good.ok) return good;
851
879
  out.push(...good.value);
@@ -905,7 +933,7 @@ class Compiler {
905
933
  }
906
934
 
907
935
  /** The list ops with a second argument before their options: a count, a position, an op name or a list. */
908
- const WITH_ARGUMENT: ReadonlySet<ListOp> = new Set<ListOp>(["reduce", "take", "nth", "drop", "append", "without", "get"]);
936
+ const WITH_ARGUMENT: ReadonlySet<ListOp> = new Set<ListOp>(["reduce", "take", "nth", "drop", "append", "without", "get", "indexOf"]);
909
937
 
910
938
  /**
911
939
  * This function gives the items of a list that have a value (LIST.LENIENT). A list op does not skip `#DEPTH!`, so that
package/src/kernel.ts CHANGED
@@ -34,6 +34,7 @@ import {
34
34
  formulaEvaluators,
35
35
  ok,
36
36
  } from "@mark1russell7/coeval";
37
+ import { asList, fillList, isFillCount, isIndexValue, listOfArray } from "./array-list.ts";
37
38
  import { decodeValue } from "./codec.ts";
38
39
  import type { AnyDomain } from "./domain.ts";
39
40
  import { vexError, type ErrorCode, type ErrorDetails, type ErrorKind, type VexError } from "./errors.ts";
@@ -183,6 +184,9 @@ const kernelError = (kind: ErrorKind, message: string, details: ErrorDetails = {
183
184
  /** This function makes a failed result of the kernel. */
184
185
  const failed = (kind: ErrorKind, message: string): Failed => ({ ok: false, error: kernelError(kind, message) });
185
186
 
187
+ /** This function gives the error of a position of an array without a value (LIST.ARRAY). */
188
+ const missing = (message: string): VexError => vexError("missing-field", message);
189
+
186
190
  /** This function stops host code with an error of the kernel. The kernel catches the `Failure` and gives its error. */
187
191
  const stop = (kind: ErrorKind, message: string): never => {
188
192
  throw new Failure(kernelError(kind, message));
@@ -368,8 +372,10 @@ const axisEvaluator: EvalFn = ({ typePath, value, context }) => {
368
372
  targets: (from) => {
369
373
  const r = list.evaluate({ ...context, self: from });
370
374
  if (!r.ok) return r;
371
- if (!isVexList(r.value)) return failed("kind-mismatch", `the axis "list" needs a list, not a ${describe(r.value)}`);
372
- return ok(r.value.items.map(({ key, result }) => (result.ok ? { key } : { key, error: result.error })));
375
+ // LIST.ARRAY: an array is a list with the positions as keys.
376
+ const items = asList(r.value, missing);
377
+ 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 })));
373
379
  },
374
380
  });
375
381
  }
@@ -628,7 +634,7 @@ function callFound(found: Found, op: string, self: unknown, args: readonly unkno
628
634
  }
629
635
 
630
636
  /** The list ops with a second argument before their options: a count, a position, an op name or a list. */
631
- const WITH_ARGUMENT: ReadonlySet<string> = /* @__PURE__ */ new Set(["reduce", "take", "nth", "drop", "append", "without", "get"]);
637
+ const WITH_ARGUMENT: ReadonlySet<string> = /* @__PURE__ */ new Set(["reduce", "take", "nth", "drop", "append", "without", "get", "indexOf"]);
632
638
 
633
639
  /**
634
640
  * This function gives the items of a list that have a value (LIST.LENIENT). A list op does not skip `#DEPTH!`, so that
@@ -644,14 +650,16 @@ function goodOf(items: readonly ListItem[], strict: boolean): readonly ListItem[
644
650
 
645
651
  /** This function gives the items of the list `other` of `append` and `without` (LIST.BUILD). Another value gives `#VALUE!`. */
646
652
  function otherOf(op: string, other: unknown, strict: boolean): readonly ListItem[] {
647
- return isVexList(other) ? goodOf(other.items, strict) : stop("kind-mismatch", `"${op}" needs a list as its second argument, not a ${describe(other)}`);
653
+ const list = asList(other, missing);
654
+ return list !== undefined ? goodOf(list.items, strict) : stop("kind-mismatch", `"${op}" needs a list as its second argument, not a ${describe(other)}`);
648
655
  }
649
656
 
650
657
  /** This function joins the lists that are the values of the items, in order (LIST.FLAT). Each list follows LIST.BUILD. */
651
658
  function flat(vs: readonly unknown[], strict: boolean): unknown {
652
659
  const out: ListItem[] = [];
653
- for (const inner of vs) {
654
- if (!isVexList(inner)) return stop("kind-mismatch", `"flat" needs a list as the value of each item, but an item is a ${describe(inner)}`);
660
+ for (const v of vs) {
661
+ const inner = asList(v, missing);
662
+ if (inner === undefined) return stop("kind-mismatch", `"flat" needs a list as the value of each item, but an item is a ${describe(v)}`);
655
663
  out.push(...goodOf(inner.items, strict));
656
664
  }
657
665
  return vexList(out);
@@ -706,6 +714,13 @@ function listOp(op: string, items: readonly ListItem[], rest: readonly unknown[]
706
714
  const i = good.findIndex((it) => it.key === key);
707
715
  return i >= 0 ? vs[i] : stop("missing-field", `the list has no item with the key ${JSON.stringify(key)}`);
708
716
  }
717
+ case "indexOf": {
718
+ // The position of the first value, among the items with a value (LIST.INDEXOF).
719
+ const x = rest[0];
720
+ if (!isIndexValue(x)) return stop("kind-mismatch", `"indexOf" needs a number, a text or a boolean, not a ${describe(x)}`);
721
+ const i = vs.indexOf(x);
722
+ return i >= 0 ? i : stop("missing-field", `the list has no item with the value ${JSON.stringify(x)}`);
723
+ }
709
724
  case "sum":
710
725
  // Stryker disable next-line ArrayDeclaration: a sum needs no domain, and a text in the list accepts no value
711
726
  return checked(nums().reduce((s, x) => s + x, 0), op, []);
@@ -772,11 +787,20 @@ function dispatch(op: string, domains: readonly AnyDomain[], fns: Readonly<Recor
772
787
  }
773
788
  }
774
789
  if (free !== undefined) return checked(free(...values), op, domains);
790
+ // LIST.ARRAY and LIST.FILL come after the domains and the functions of the host, so each of their results stays.
791
+ if (listed && Array.isArray(self)) return listOp(op, listOfArray(self, missing).items, values.slice(1), domains);
792
+ if (op === "fill") return fill(values);
775
793
  if (accepted || values.length === 0) return stop("unknown-op", accepted ? `the domain of the receiver has no op "${op}"` : `there is no function "${op}"`);
776
794
  return stop("not-instance", `no domain accepts the receiver of "${op}" (${describe(self)})`);
777
795
  };
778
796
  }
779
797
 
798
+ /** This function gives the list of `fill(n, value)` (LIST.FILL). A count that is not a whole number from 0 to 100000 gives `#VALUE!`. */
799
+ function fill([n, value]: readonly unknown[]): unknown {
800
+ if (!isFillCount(n)) return stop("kind-mismatch", `"fill" needs a whole number from 0 to 100000, not ${describe(n)}`);
801
+ return value === undefined ? stop("bad-expression", '"fill" needs argument 2') : fillList(n, value);
802
+ }
803
+
780
804
  /** This function gives an argument of a special form. A missing argument gives `#VALUE!`. */
781
805
  const argOf = (args: readonly (() => Outcome)[], i: number, op: string): Outcome => args[i]?.() ?? failed("bad-expression", `"${op}" needs argument ${String(i + 1)}`);
782
806
 
package/src/list.ts CHANGED
@@ -53,12 +53,16 @@ export const isVexList = (u: unknown): u is VexList => {
53
53
 
54
54
  /**
55
55
  * The name of a core list op. `sortBy`, `take`, `drop`, `append`, `flat` and `without` give a list (LIST.BUILD), and
56
- * the other ops give a value. `get` gives the value at a key (LIST.GET).
56
+ * the other ops give a value. `get` gives the value at a key (LIST.GET), and `indexOf` gives the position of a value
57
+ * (LIST.INDEXOF).
57
58
  */
58
- export type ListOp = "count" | "sum" | "min" | "max" | "mean" | "any" | "all" | "none" | "values" | "keys" | "reduce" | "first" | "errors" | "sortBy" | "take" | "nth" | "drop" | "append" | "flat" | "without" | "get";
59
+ export type ListOp = "count" | "sum" | "min" | "max" | "mean" | "any" | "all" | "none" | "values" | "keys" | "reduce" | "first" | "errors" | "sortBy" | "take" | "nth" | "drop" | "append" | "flat" | "without" | "get" | "indexOf";
59
60
 
60
- /** The names of the core list ops. They apply when the first argument is a list. */
61
- export const LIST_OPS: ReadonlySet<string> = new Set<ListOp>(["count", "sum", "min", "max", "mean", "any", "all", "none", "values", "keys", "reduce", "first", "errors", "sortBy", "take", "nth", "drop", "append", "flat", "without", "get"]);
61
+ /**
62
+ * The names of the core list ops. They apply when the first argument is a list. They apply to an array too, when no
63
+ * domain and no function of the host has the op for it (LIST.ARRAY).
64
+ */
65
+ export const LIST_OPS: ReadonlySet<string> = new Set<ListOp>(["count", "sum", "min", "max", "mean", "any", "all", "none", "values", "keys", "reduce", "first", "errors", "sortBy", "take", "nth", "drop", "append", "flat", "without", "get", "indexOf"]);
62
66
 
63
67
  /** This function tells if a name is the name of a core list op. */
64
68
  export const isListOp = (op: string): op is ListOp => LIST_OPS.has(op);