@mark1russell7/vex 0.17.2 → 0.19.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.17.2",
4
+ "version": "0.19.0",
5
5
  "description": "Vex: typed spreadsheet formulas over domain objects. The kernel and the typed builder.",
6
6
  "keywords": [
7
7
  "typescript",
@@ -49,11 +49,12 @@
49
49
  "access": "public"
50
50
  },
51
51
  "dependencies": {
52
- "@mark1russell7/coeval": "^0.15.0"
52
+ "@mark1russell7/coeval": "^0.34.0"
53
53
  },
54
54
  "devDependencies": {
55
- "@mark1russell7/cue": "github:mark1russell7/cue",
56
- "@mark1russell7/optional": "github:mark1russell7/optional",
55
+ "@mark1russell7/cue": "github:mark1russell7/cue#9c99ad65d51cefcba5a8b6dc89358d7a94758ca7",
56
+ "@mark1russell7/optional": "github:mark1russell7/optional#1c649e1ea49991d1574a74f0c402220502e219a7",
57
+ "@mark1russell7/rigor-bench": "^0.2.17",
57
58
  "@types/node": "^26.6.4",
58
59
  "typescript": "^7.0.2",
59
60
  "vitest": "^5.0.3"
package/src/builder.ts CHANGED
@@ -5,7 +5,7 @@
5
5
  import type { AnyDomain, Domain, OpSpec, PrimitiveKind } from "./domain.ts";
6
6
  import type { VexError } from "./errors.ts";
7
7
  import { evaluate, explain, type EvalOptions, type ExtHandler, type FreeFn } from "./evaluate.ts";
8
- import { app, call as callExpr, children, each, ext, fn as fnExpr, fold as foldExpr, index as indexMove, iterate as iterateExpr, key as keyMove, let_, lit, listOf, offset as offsetMove, other as otherMove, origin as originMove, parent as parentMove, rec, ref, toPath, v, type Axis, type Expr, type FixedMove, type ItemNames, type Move } from "./ir.ts";
8
+ import { addrExprs, app, axisExprs, call as callExpr, children, dataLimit, each, ext, fix as fixExpr, fn as fnExpr, fold as foldExpr, index as indexMove, iterate as iterateExpr, key as keyMove, last as lastExpr, let_, lit, listOf, offset as offsetMove, other as otherMove, origin as originMove, parent as parentMove, rec, ref, toPath, v, type Addr, type Axis, type DataLimit, type Expr, type FixJoin, type ItemNames, type Move } from "./ir.ts";
9
9
  import { cell as cellRef, SheetRun, type CellFormulas } from "./sheet.ts";
10
10
  import { ok, toOptional, type Optional, type Result } from "./result.ts";
11
11
  import type { Space } from "./space.ts";
@@ -32,6 +32,12 @@ const argToken = <T>(expr: Expr): Arg<T> => ({ kind: "vex.arg", expr });
32
32
 
33
33
  // ---------------------------------------------------------------- type helpers
34
34
 
35
+ /**
36
+ * The value of a column with the join `J`: a boolean for `or` and `and`, and a number for `max` and `min` (FIX.KIND). A
37
+ * union of joins has no one kind, so it gives `never`.
38
+ */
39
+ export type FixValue<J extends FixJoin> = [J] extends ["or" | "and"] ? boolean : [J] extends ["max" | "min"] ? number : never;
40
+
35
41
  /** The keys of any member of a union of record types. */
36
42
  type AllKeys<O> = O extends unknown ? keyof O : never;
37
43
 
@@ -210,24 +216,36 @@ export interface ChainBase<Ctx extends ChainContext, T> {
210
216
  /** This method evaluates each branch with the current value, and gives a record of the results. */
211
217
  fork<const B extends Readonly<Record<string, (c: ChainOf<Ctx, T>) => ChainBase<Ctx, unknown>>>>(branches: B): ChainOf<Ctx, { readonly [N in keyof B]: ValueOf<ReturnType<B[N]>> }>;
212
218
  /**
213
- * This method makes up to `limit` steps (ITERATE.LIMIT). `init` gives the names and their first values, and `step`
214
- * gives the next values. A true `until` stops the steps (ITERATE.UNTIL). `result` gives the value of the chain. A
215
- * name with a list chain as its first value is a list chain (BUILD.LIST.LOOP), and a list result gives a list chain.
219
+ * This method makes up to `limit` steps (ITERATE.LIMIT). A list chain or a `DataLimit` gives a limit from the data
220
+ * (ITERATE.LIMIT.DATA). `init` gives the names and their first values, and `step` gives the next values. A true
221
+ * `until` stops the steps (ITERATE.UNTIL). `result` gives the value of the chain. A name with a list chain as its
222
+ * first value is a list chain (BUILD.LIST.LOOP), and a list result gives a list chain.
216
223
  */
217
224
  iterate<const I extends Readonly<Record<string, unknown>>, U>(
218
- limit: number,
225
+ limit: number | DataLimit | ListChain<Ctx, unknown>,
219
226
  init: I,
220
227
  step: (vars: LoopVars<Ctx, I>) => NoInfer<LoopStep<Ctx, I>>,
221
228
  result: (vars: LoopVars<Ctx, I>) => ListChain<Ctx, U>,
222
229
  opts?: { readonly until?: (vars: LoopVars<Ctx, I>) => ArgInput<boolean, Ctx, false> },
223
230
  ): ListChain<Ctx, U>;
224
231
  iterate<const I extends Readonly<Record<string, unknown>>, R>(
225
- limit: number,
232
+ limit: number | DataLimit | ListChain<Ctx, unknown>,
226
233
  init: I,
227
234
  step: (vars: LoopVars<Ctx, I>) => NoInfer<LoopStep<Ctx, I>>,
228
235
  result: (vars: LoopVars<Ctx, I>) => ArgInput<R, Ctx, false>,
229
236
  opts?: { readonly until?: (vars: LoopVars<Ctx, I>) => ArgInput<boolean, Ctx, false> },
230
237
  ): ChainOf<Ctx, R>;
238
+ /**
239
+ * This method makes a fixed-point column (BUILD.FIX). `init` gives each row its value of round 0. `step` gets a chain
240
+ * of the last round at the focus, and it gives the next value of the row. `join` keeps each row on one way (FIX.JOIN).
241
+ * The value of the chain is the row of the focus, and the rounds end when no row changes (FIX.ROUNDS).
242
+ */
243
+ fix<J extends FixJoin>(
244
+ name: string,
245
+ join: J,
246
+ init: ArgInput<FixValue<J>, Ctx, false>,
247
+ step: (last: ChainOf<Ctx, FixValue<J>>) => NoInfer<ArgInput<FixValue<J>, Ctx, false>>,
248
+ ): ChainOf<Ctx, FixValue<J>>;
231
249
  /** This method binds names for the body. The body gets a variable token for each name. */
232
250
  with<const B extends Readonly<Record<string, unknown>>, U>(
233
251
  binds: B,
@@ -419,6 +437,11 @@ export interface ListChain<Ctx extends ChainContext, U> {
419
437
  take(n: number, opts?: ListOpts): ListChain<Ctx, U>;
420
438
  /** The value of the item at the position `i`, from 0 (LIST.NTH). */
421
439
  nth(i: number, opts?: ListOpts): ChainOf<Ctx, U>;
440
+ /**
441
+ * This list with `value` as the value of the item at the position `i`, from 0 (LIST.SETNTH). The item keeps its key.
442
+ * A chain or `lit` gives the value, and a chain can give the position. Both evaluate at the focus.
443
+ */
444
+ setNth<V>(i: number | ChainBase<Ctx, number>, value: ChainBase<Ctx, V> | Arg<V>, opts?: ListOpts): ListChain<Ctx, U | V>;
422
445
  /**
423
446
  * The value of the first item with the key `k` (LIST.GET). A chain of a text gives the key, and it evaluates at the
424
447
  * focus. A key that no item has gives `#N/A`. Thus a step reads the old value of each key.
@@ -506,13 +529,13 @@ export interface Root<Ctx extends ChainContext> {
506
529
  /** The root of a column formula: the root of the builder, and references to the cells of the sheet. */
507
530
  export interface SheetRoot<Ctx extends ChainContext, Cols> extends Root<Ctx> {
508
531
  /**
509
- * This method makes a cell reference: the column `column` at the key `at`, or at the address `at` from the focus.
510
- * The address has only fixed moves. Without `at`, it reads at the focus. The type is the type of a column before
511
- * this one.
532
+ * This method reads a cell: the column `column` at the key `at`, or at the address `at` from the focus. The address
533
+ * can have computed moves (SHEET.CELL.COMPUTED). Without `at`, it reads at the focus. The type is the type of a column
534
+ * before this one.
512
535
  */
513
- cell<N extends keyof Cols & string>(column: N, at?: Ctx["keys"] | readonly FixedMove[]): Arg<Cols[N]>;
536
+ cell<N extends keyof Cols & string>(column: N, at?: Ctx["keys"] | Addr): Arg<Cols[N]>;
514
537
  /** This method makes a cell reference to any column, also this column or a later one. The caller gives the type. */
515
- cell<T>(column: string, at?: Ctx["keys"] | readonly FixedMove[]): Arg<T>;
538
+ cell<T>(column: string, at?: Ctx["keys"] | Addr): Arg<T>;
516
539
  }
517
540
 
518
541
  /** One row of a sheet: the key and the result of each column. */
@@ -659,12 +682,34 @@ function inItemLoop<T>(build: () => T): T {
659
682
  }
660
683
  }
661
684
 
662
- /** This function tells if the expression reads the name, in one of its parts. It uses a stack, not recursion. */
685
+ /**
686
+ * The number of the open steps of `fix`. The name of a column ends with this number. Thus an inner `fix` does not hide
687
+ * the column around it, also when the chain of the inner `fix` starts at the root (BUILD.FIX).
688
+ */
689
+ let fixDepth = 0;
690
+
691
+ /** This function gives the value of `build`, with the next number for the columns inside it. */
692
+ function inFixStep<T>(build: () => T): T {
693
+ fixDepth += 1;
694
+ try {
695
+ return build();
696
+ } finally {
697
+ fixDepth -= 1;
698
+ }
699
+ }
700
+
701
+ /**
702
+ * This function tells if the expression reads the name, in one of its parts. It uses a stack, not recursion. An `each`
703
+ * or a `fold` can have the name in its item names (`as`). Then it binds the name again for its body or its step, and
704
+ * those parts do not count (V-065). A chain made at the same depth of the loops has the same names, so a fold can hold such a chain in its step.
705
+ */
663
706
  function reads(e: Expr, name: string): boolean {
664
707
  const todo: Expr[] = [e];
665
708
  for (let x = todo.pop(); x !== undefined; x = todo.pop()) {
666
709
  if (x.tag === "var" && x.name === name) return true;
667
- todo.push(...children(x));
710
+ if (x.tag === "each" && x.as?.includes(name) === true) todo.push(...axisExprs(x.axis), ...addrExprs(x.at));
711
+ else if (x.tag === "fold" && x.as?.includes(name) === true) todo.push(...Object.values(x.init), ...axisExprs(x.axis), ...addrExprs(x.at), x.result);
712
+ else todo.push(...children(x));
668
713
  }
669
714
  return false;
670
715
  }
@@ -824,7 +869,7 @@ class ChainImpl {
824
869
  }
825
870
 
826
871
  iterate(
827
- limit: number,
872
+ limit: number | DataLimit | ListChainImpl,
828
873
  init: Readonly<Record<string, unknown>>,
829
874
  step: (vars: Readonly<Record<string, ChainImpl | ListChainImpl>>) => Readonly<Record<string, unknown>>,
830
875
  result: (vars: Readonly<Record<string, ChainImpl | ListChainImpl>>) => unknown,
@@ -834,7 +879,18 @@ class ChainImpl {
834
879
  const next = stepExprs(step(vars), unique, this.#s.addr);
835
880
  const until = opts?.until === undefined ? undefined : toExpr(opts.until(vars), this.#s.addr);
836
881
  const r = result(vars);
837
- return chainOf({ ...this.#s, expr: iterateExpr(limit, first, next, toExpr(r, this.#s.addr), until) }, r);
882
+ // The list of a limit reads the names outside the iteration, so the chain of the limit comes first (ITERATE.LIMIT.DATA).
883
+ const bound = isChainLike(limit) ? dataLimit({ t: "list", list: toExpr(limit, this.#s.addr) }) : limit;
884
+ return chainOf({ ...this.#s, expr: iterateExpr(bound, first, next, toExpr(r, this.#s.addr), until) }, r);
885
+ }
886
+
887
+ fix(name: string, join: FixJoin, init: unknown, step: (last: ChainImpl) => unknown): ChainImpl {
888
+ const { addr, depth } = this.#s;
889
+ const column = `${name}$${String(fixDepth)}`;
890
+ // The read has no address, and an axis moves the focus of the read (FIX.LAST).
891
+ const read = new ChainImpl({ ...this.#s, expr: lastExpr(column), addr: [], depth: depth + 1 });
892
+ const next = inFixStep(() => toExpr(step(read), addr));
893
+ return new ChainImpl({ ...this.#s, expr: fixExpr(column, join, toExpr(init, addr), next) });
838
894
  }
839
895
 
840
896
  #axis(a: Axis, body: (c: ChainImpl) => { readonly program: Expr }, opts?: AxisOptsImpl): ListChainImpl {
@@ -988,6 +1044,9 @@ class ListChainImpl {
988
1044
  nth(i: number, opts?: ListOpts): ChainImpl {
989
1045
  return this.#op("nth", [lit(i)], opts);
990
1046
  }
1047
+ setNth(i: number | { readonly program: Expr }, value: unknown, opts?: ListOpts): ListChainImpl {
1048
+ return this.#list("setNth", [typeof i === "number" ? lit(i) : i.program, toExpr(value, this.#s.addr)], opts);
1049
+ }
991
1050
  get(k: string | { readonly program: Expr }, opts?: ListOpts): ChainImpl {
992
1051
  // A text is a key, not a field reference, as for the move to(k).
993
1052
  return this.#op("get", [typeof k === "string" ? lit(k) : k.program], opts);
@@ -1085,7 +1144,7 @@ class RootImpl {
1085
1144
  }
1086
1145
 
1087
1146
  class SheetRootImpl extends RootImpl {
1088
- cell(column: string, at?: string | readonly FixedMove[]): Arg<unknown> {
1147
+ cell(column: string, at?: string | Addr): Arg<unknown> {
1089
1148
  return argToken(cellRef(column, typeof at === "string" ? [keyMove(at)] : at));
1090
1149
  }
1091
1150
  }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * The step of each construct of Vex (STEP.LADDER). The construct of a node is its tag. An `iterate` with a limit from
3
+ * the data has its own construct `iterate.size` (ITERATE.LIMIT.DATA). The step of this construct, of `fix` and of `last` is
4
+ * `B`. The step of each other construct is `A`. A function cannot call itself (FN.TOTAL). The table is its own module, so a test can declare a construct of a higher step.
5
+ */
6
+ import type { ExprTag } from "./ir.ts";
7
+
8
+ /** A step of Vex. Step A has loops with a fixed count. Step B adds limits from the data and fixed points. Step C adds functions that call themselves, with a budget. */
9
+ export type VexStep = "A" | "B" | "C";
10
+
11
+ /** The construct of an `iterate` with a limit from the data. */
12
+ export const ITERATE_SIZE = "iterate.size";
13
+
14
+ /** The step that each construct of Vex needs. The name of a construct is the tag of its node, or `ITERATE_SIZE`. */
15
+ export const CONSTRUCT_STEPS: Readonly<Record<ExprTag | typeof ITERATE_SIZE, VexStep>> = {
16
+ lit: "A",
17
+ ref: "A",
18
+ app: "A",
19
+ let: "A",
20
+ var: "A",
21
+ rec: "A",
22
+ each: "A",
23
+ fold: "A",
24
+ iterate: "A",
25
+ [ITERATE_SIZE]: "B",
26
+ fix: "B",
27
+ last: "B",
28
+ fn: "A",
29
+ call: "A",
30
+ ext: "A",
31
+ };
package/src/deps.ts CHANGED
@@ -4,7 +4,7 @@
4
4
  * a function at each of its calls (FN.CALL).
5
5
  */
6
6
  import { pathMatches, refsOf, type DocVisit, type Key, type RefUse } from "@mark1russell7/coeval";
7
- import type { Addr, Axis, Expr, ExprOf } from "./ir.ts";
7
+ import type { Addr, Axis, DataLimit, Expr, ExprOf } from "./ir.ts";
8
8
  import { VEX_WORLD } from "./kernel.ts";
9
9
  import { writeDocument } from "./write.ts";
10
10
 
@@ -122,6 +122,12 @@ export function deps(e: Expr): readonly Dependency[] {
122
122
  const around: Around = { t: node.axis.t, at: node.at ?? [] };
123
123
  if (head === "body" || head === "step") axes = { item: around, up: axes };
124
124
  else if (head === "axis") axis = around;
125
+ } else if (kind === "fix") {
126
+ // The start and the step of a column read at each row (FIX.ROWS).
127
+ axes = { item: { t: "all", at: [] }, up: axes };
128
+ } else if (kind === "size") {
129
+ // The size of the writer is the data limit of its node, so the axis has no address (ITERATE.LIMIT.DATA).
130
+ axis = { t: ((nodes.get(parent.doc) as ExprOf<"iterate">).limit as DataLimit).axis.t, at: [] };
125
131
  }
126
132
  if (kind === "fn") {
127
133
  fn = parent;
package/src/document.ts CHANGED
@@ -15,7 +15,9 @@
15
15
  * | `rec` | `{ "type": "record", "value": { ...fields } }` |
16
16
  * | `each` | `{ "type": "each", "value": { "axis", "as"?, "body", "at"? } }` |
17
17
  * | `fold` | `{ "type": "fold", "value": { "axis", "as"?, "init", "step", "result", "at"? } }` |
18
- * | `iterate` | `{ "type": "iterate", "value": { "limit", "init", "step", "until"?, "result" } }` |
18
+ * | `iterate` | `{ "type": "iterate", "value": { "limit", "init", "step", "until"?, "result" } }`. A data limit is `{ "type": "size", "value": { "axis" } }`. |
19
+ * | `fix` | `{ "type": "fix", "value": { "name", "join", "init", "step" } }` |
20
+ * | `last` | `{ "type": "last", "value": name }` |
19
21
  * | `ext` | `{ "type": ["ext", ...keys], "value": data }` |
20
22
  * | a move | `{ "type": ["moves", kind], "value": v }` |
21
23
  * | an axis | `{ "type": ["axes", name], "value": { ...parameters } }` |
@@ -32,7 +34,7 @@ import { check, isEnvelope, typeName, typePath, type Envelope, type Issue, type
32
34
  import { decodeValue } from "./codec.ts";
33
35
  import type { AnyDomain } from "./domain.ts";
34
36
  import { isStackOverflow, vexError, type VexError } from "./errors.ts";
35
- import { app, call, each, ext, fn, fold, index, iterate, key, let_, lit, offset, origin, other, parent, rec, ref, shapeError, v, type Addr, type Axis, type Expr, type ItemNames, type Move, type Names } from "./ir.ts";
37
+ import { app, call, dataLimit, each, ext, fix, fn, fold, index, iterate, key, last, let_, lit, offset, origin, other, parent, rec, ref, shapeError, v, type Addr, type Axis, type DataLimit, type Expr, type FixJoin, type ItemNames, type Move, type Names } from "./ir.ts";
36
38
  import { MAX_DOCUMENT_DEPTH, TERM_KINDS, vexChecker } from "./kernel.ts";
37
39
  import { fail, ok, type Result } from "./result.ts";
38
40
  import { itemNamesError } from "./item-names.ts";
@@ -183,11 +185,16 @@ class Reader {
183
185
  const as = this.#items(f, axis, at);
184
186
  return fold(axis, init, step, this.term(f["result"], into(at, "result")), this.#address(f["at"], into(at, "at")), as);
185
187
  }
188
+ case "fix":
189
+ // The contract gives the name and one of the joins (DOC.CONSTRUCT).
190
+ return fix(f["name"] as string, f["join"] as FixJoin, this.term(f["init"], into(at, "init")), this.term(f["step"], into(at, "step")));
191
+ case "last":
192
+ return last(u.value as string);
186
193
  default: {
187
- // iterate: the contract gives a whole number from 0 to MAX_ITERATIONS for the limit (ITERATE.LIMIT).
194
+ // iterate: the contract gives a whole number from 0 to MAX_ITERATIONS, or an envelope of a limit (ITERATE.LIMIT).
188
195
  const [init, step] = this.#loop(f, at);
189
196
  const until = f["until"] === undefined ? undefined : this.term(f["until"], into(at, "until"));
190
- return iterate(f["limit"] as number, init, step, this.term(f["result"], into(at, "result")), until);
197
+ return iterate(this.#limit(f["limit"], into(at, "limit")), init, step, this.term(f["result"], into(at, "result")), until);
191
198
  }
192
199
  }
193
200
  }
@@ -240,6 +247,13 @@ class Reader {
240
247
  * This method reads the names `as` of a loop (AXIS.LIST.SCOPE). The contract gives a list of distinct texts. The
241
248
  * grammar of Vex needs one or two names, the axis `list` and no name of `init`.
242
249
  */
250
+ /** This method reads the limit of `iterate`: a bare number, the envelope of a number, or the size of an axis (ITERATE.LIMIT.DATA). */
251
+ #limit(u: unknown, where: string): number | DataLimit {
252
+ if (!isEnvelope(u)) return u as number;
253
+ const value = u.value as number | { readonly axis: Envelope };
254
+ return typeof value === "number" ? value : dataLimit(this.#axis(value.axis, into(into(where, "value"), "axis")));
255
+ }
256
+
243
257
  #items(f: Readonly<Record<string, unknown>>, axis: Axis, at: string): ItemNames | undefined {
244
258
  const reason = itemNamesError({ as: f["as"], axis, init: f["init"] });
245
259
  return reason === undefined ? (f["as"] as ItemNames | undefined) : bad(into(at, "as"), reason);
package/src/domain.ts CHANGED
@@ -9,8 +9,79 @@ export type Law = "commutative" | "associative" | "idempotent";
9
9
  /** The kind of a parameter. The interpreter checks the arguments of an op that declares its parameters. */
10
10
  export type ParamKind = "domain" | "number" | "boolean" | "string" | "any";
11
11
 
12
- /** The kind of the result of an op: a kind of a parameter, or `domain:Name` for a value of the domain `Name`. */
13
- export type ReturnKind = ParamKind | `domain:${string}`;
12
+ /**
13
+ * The kind of the result of an op. It is a kind of a parameter, or `domain:Name` for a value of the domain `Name`. It is
14
+ * `list:Kind` for a `vex.list` with items of a primitive type.
15
+ */
16
+ export type ReturnKind = ParamKind | `domain:${string}` | `list:${PrimitiveKind}`;
17
+
18
+ /**
19
+ * How the size of one argument adds to the size of the result of an op (LOOP.SIZE.OPS). The size of a value counts the
20
+ * texts, the fields, the keys and the items in it.
21
+ *
22
+ * - `0`: the argument does not add to the size.
23
+ * - `1`: the size of the argument adds one time.
24
+ * - `"scaled"`: the size of the argument adds a fixed number of times, for example two times.
25
+ * - `"many"`: the size of the argument adds more than one time.
26
+ * - `"unbounded"`: the size of the result has no bound in the size of the argument.
27
+ * - `"text"`: the size adds one time for a text, and a fixed number of times for another value, as its JSON text.
28
+ * - `"copies"`: the size adds one time for each copy. The first argument is the number of the copies.
29
+ * - `"each"`: the size adds one time for each item of the first argument.
30
+ * - `"number"`: the argument is a number that sets a count. A literal number gives that count, and another number
31
+ * gives a fixed bound.
32
+ * - `"limit"`: the size adds one time for each item that the literal number at the position `limit` keeps. Each item
33
+ * adds a key with a fixed bound. Without a literal number, this use is the same as `"many"`.
34
+ */
35
+ export type SizeUse = 0 | 1 | "scaled" | "many" | "unbounded" | "text" | "copies" | "each" | "number" | "limit";
36
+
37
+ /**
38
+ * A measure of a value for the check of sizes (LOOP.SIZE.OPS). `size` is the size of the value, and `count` is the
39
+ * number of its items. `inner` is the sum of the counts of the values of its items. `item` is the size of its largest
40
+ * item. The items of a record are its fields, and a text is its own item. `part` is the largest `item` of its items. It is
41
+ * not larger than `item`.
42
+ */
43
+ export type SizeMeasure = "size" | "count" | "inner" | "item" | "part";
44
+
45
+ /** One term of a size rule: a use of the same measure of the argument, or a use of the measure that the pair names. */
46
+ export type SizeTerm = SizeUse | readonly [use: SizeUse, of: SizeMeasure];
47
+
48
+ /**
49
+ * The size rule of an op: how the measures of its result follow from its arguments (LOOP.SIZE.OPS). The check of sizes
50
+ * reads it in the steps of `fold` and `iterate` (LOOP.SIZE).
51
+ *
52
+ * - `"scalar"`: the result is a number or a boolean.
53
+ * - `"fixed"`: the result has a size with a fixed bound, for example a 2D vector.
54
+ * - `"reduce"`: the rule of the list op `reduce`. The op that its second argument names gives the size.
55
+ * - A record: `SizeTerms`.
56
+ */
57
+ export type SizeRule = "scalar" | "fixed" | "reduce" | SizeTerms;
58
+
59
+ /**
60
+ * The size rule of an op as data (LOOP.SIZE.OPS). `size`, `count`, `inner`, `item` and `part` have one term for each
61
+ * argument. `rest` is the use of the arguments after them, and its default is `"many"`. Without `count`, `inner` or `item`,
62
+ * that measure of the result is its size. Without `part`, the largest part of the result is its largest item. The terms of
63
+ * `item` and `part` give the largest bound of the arguments, because the largest item comes from one argument. A literal
64
+ * number at the position `limit` sets the count. With `keys: "position"`, the items get their positions as new keys. With
65
+ * `constant: true`, the result can also hold a part with a fixed size. With `union: true`, the result holds each key of
66
+ * its arguments one time, so the bound of the result is the largest bound of the arguments.
67
+ *
68
+ * `byParts` is a second rule for a result that is a part of an argument, or that holds a fixed number of its items. The
69
+ * second reading of the check uses this rule (LOOP.SIZE.READINGS). A rule with `limit` keeps the first rule when the limit
70
+ * is not a literal number or when a key can be long.
71
+ */
72
+ export interface SizeTerms {
73
+ readonly size: readonly SizeTerm[];
74
+ readonly count?: readonly SizeTerm[];
75
+ readonly inner?: readonly SizeTerm[];
76
+ readonly item?: readonly SizeTerm[];
77
+ readonly part?: readonly SizeTerm[];
78
+ readonly rest?: SizeUse;
79
+ readonly limit?: number;
80
+ readonly keys?: "position";
81
+ readonly constant?: true;
82
+ readonly union?: true;
83
+ readonly byParts?: SizeTerms;
84
+ }
14
85
 
15
86
  /** The description of one op of a domain. */
16
87
  export interface OpSpec<D = never> {
@@ -28,16 +99,56 @@ export interface OpSpec<D = never> {
28
99
  /** The kinds of the parameters after the receiver. When set, the interpreter checks the arguments. */
29
100
  readonly params?: readonly ParamKind[];
30
101
  /**
31
- * The kind of the result: `domain` for a value of this domain, and `domain:Name` for a value of the domain `Name`. A
32
- * compiler reads it to know the kinds of the values of a program (KIND.RETURNS). The interpreter does not check it,
33
- * and the law checker of the test kit does.
102
+ * The kind of the result. It is `domain` for a value of this domain, or `domain:Name` for a value of the domain `Name`.
103
+ * It is `list:Kind` for a `vex.list` with items of that primitive type (KIND.RETURNS.LIST). A compiler reads it to know
104
+ * the kinds of the values of a program (KIND.RETURNS). The interpreter does not check it, and the law checker of the
105
+ * test kit does.
34
106
  */
35
107
  readonly returns?: ReturnKind;
108
+ /**
109
+ * The size rule of the op (LOOP.SIZE.OPS). Without it, an op whose result is a number or a boolean has the rule
110
+ * `"scalar"`. An op of a domain with `size: "fixed"` has the rule `"fixed"`. Another op has no rule, so a step of a
111
+ * loop cannot use its result in the size of a list name (LOOP.SIZE).
112
+ */
113
+ readonly size?: SizeRule;
114
+ /**
115
+ * This field gives the direction of the result of the op for each argument, with the receiver first (FIX.OPS). `up`
116
+ * means that the result does not fall as the argument rises. `down` means that the result does not rise. An op without
117
+ * it cannot take a value that reads `last`, and an argument without a direction must not read `last`.
118
+ */
119
+ readonly monotone?: readonly Monotone[];
120
+ }
121
+
122
+ /** A direction of an op: the result follows the argument (`up`) or moves against it (`down`). */
123
+ export type Monotone = "up" | "down";
124
+
125
+ /**
126
+ * The form of a domain in a standalone module (COMPILE.MODULE.FORM). A module has no import, so it cannot hold a value of
127
+ * a class. Each part replaces the part of the domain with the same name, only in a module. A compiler copies the text of
128
+ * each function, so a function reads only its parameters.
129
+ */
130
+ export interface ModuleForm {
131
+ /** The test of a value in a module. */
132
+ readonly is?: (u: unknown) => boolean;
133
+ /** The scalar lift in a module. */
134
+ readonly fromScalar?: (n: number) => unknown;
135
+ /** Some values of the module form. A compiler checks each copy with them. */
136
+ readonly samples?: () => readonly unknown[];
137
+ /**
138
+ * The plain data of a literal of the program, or `undefined` for a value of another domain. This function runs in the
139
+ * compiler, not in a module, so it can read a class.
140
+ */
141
+ readonly literal?: (value: unknown) => Readonly<Record<string, unknown>> | undefined;
142
+ /** The parts of each op in a module. */
143
+ readonly ops?: Readonly<Record<string, { readonly fn?: (self: never, ...args: never[]) => unknown; readonly identity?: () => unknown; readonly returns?: ReturnKind }>>;
36
144
  }
37
145
 
38
146
  /** A JavaScript type of primitive values that a domain can accept. */
39
147
  export type PrimitiveKind = "number" | "string" | "boolean";
40
148
 
149
+ /** This function gives the kind of the items of a result of the kind `list:Kind`, or `undefined` for another kind. */
150
+ export const listItemKind = (r: ReturnKind | undefined): PrimitiveKind | undefined => (r?.startsWith("list:") === true ? (r.slice("list:".length) as PrimitiveKind) : undefined);
151
+
41
152
  /** The type of an op that lifts number arguments. Use it to type the ops of a domain under `isolatedDeclarations`. */
42
153
  export type LiftedOp<D> = OpSpec<D> & { readonly liftScalar: true };
43
154
 
@@ -63,8 +174,18 @@ export interface DomainSpec<Name extends string, D, Ops extends Readonly<Record<
63
174
  * (KIND.PRIMITIVE). A compiler then finds the op of such a value before a run.
64
175
  */
65
176
  readonly primitive?: PrimitiveKind;
177
+ /**
178
+ * The field names of a value, if `is` accepts only plain objects with exactly these fields (KIND.FIELDS). Two domains
179
+ * with different names have no common value, so a compiler finds the domain of such a value before a run.
180
+ */
181
+ readonly fields?: readonly string[];
66
182
  /** The ops of the domain, with their metadata. */
67
183
  readonly ops: Ops;
184
+ /**
185
+ * With `"fixed"`, each value of the domain has a size with a fixed bound, for example a 2D vector. Then each op of the
186
+ * domain has the size rule `"fixed"` or `"scalar"`, unless the op has its own rule (LOOP.SIZE.OPS).
187
+ */
188
+ readonly size?: "fixed";
68
189
  /** With `"all"`, each method of a value is an op, also without an entry in `ops`. The default is `"declared"`. */
69
190
  readonly methods?: "declared" | "all";
70
191
  /** The scalar lift: it makes a domain value from a number. */
@@ -82,6 +203,8 @@ export interface DomainSpec<Name extends string, D, Ops extends Readonly<Record<
82
203
  * results (KIND.DOMAIN).
83
204
  */
84
205
  readonly samples?: () => readonly D[];
206
+ /** The form of the domain in a standalone module, for a domain with values of a class (COMPILE.MODULE.FORM). */
207
+ readonly moduleForm?: ModuleForm;
85
208
  }
86
209
 
87
210
  /** A domain. Make one with `defineDomain`. */
@@ -0,0 +1,114 @@
1
+ /**
2
+ * The texts of the errors of the nodes of a program. The interpreter and the materialize step of the compiler use them.
3
+ * Thus tier 1 and tier 2 give the same error (docs/COMPILER.md §4.1).
4
+ */
5
+ import type { ParamKind } from "./domain.ts";
6
+ import { vexError, type ErrorKind, type VexError } from "./errors.ts";
7
+ import { isVexList } from "./list.ts";
8
+ import type { Position } from "./space.ts";
9
+
10
+ /** The part of an error that does not depend on the position of its node: the kind, the sentence and the op name. */
11
+ export interface ErrorText {
12
+ readonly kind: ErrorKind;
13
+ readonly message: string;
14
+ readonly op?: string;
15
+ }
16
+
17
+ /** This function gives a short name for the type of a value, for error messages. */
18
+ export function describeType(u: unknown): string {
19
+ if (u === null) return "null";
20
+ if (Array.isArray(u)) return "array";
21
+ if (isVexList(u)) return "list";
22
+ if (typeof u === "object") {
23
+ const name = (Object.getPrototypeOf(u) as { constructor?: { name?: unknown } } | null)?.constructor?.name;
24
+ return typeof name === "string" && name !== "Object" ? name : "object";
25
+ }
26
+ return typeof u;
27
+ }
28
+
29
+ /** The texts of the errors. Each function takes the facts of the error that do not come from the position of its node. */
30
+ export const errorText = {
31
+ /** A name without a binding (`var`). */
32
+ unbound: (name: string): ErrorText => ({ kind: "unbound", message: `the name "${name}" has no binding` }),
33
+ /** A read of a function as a value (FN.VALUE). */
34
+ functionValue: (name: string): ErrorText => ({ kind: "kind-mismatch", message: `the name "${name}" is a function, not a value` }),
35
+ /** A call of a name without a binding (FN.CALL). */
36
+ noFunction: (name: string): ErrorText => ({ kind: "unbound", message: `the function "${name}" has no binding` }),
37
+ /** A call of a name that holds a value (FN.CALL). */
38
+ notFunction: (name: string): ErrorText => ({ kind: "kind-mismatch", message: `the name "${name}" is a value, not a function` }),
39
+ /** A call with the wrong number of arguments (FN.CALL). */
40
+ arity: (name: string, params: number, args: number): ErrorText => ({ kind: "bad-expression", message: `the function "${name}" takes ${String(params)} arguments, not ${String(args)}` }),
41
+ /** An extension kind without a handler. */
42
+ noHandler: (kind: string): ErrorText => ({ kind: "unknown-op", message: `no handler for the extension kind "${kind}"` }),
43
+ /** An exception of an op, of an extension or of `fromScalar`. */
44
+ threw: (op: string): ErrorText => ({ kind: "threw", message: `"${op}" threw an exception`, op }),
45
+ /** A reference that reads no value. `where` is the part of the path that failed. */
46
+ missing: (key: string, where: string): ErrorText => ({ kind: "missing-field", message: `the record at "${key}" has no value at "${where}"` }),
47
+ /** A reference whose getter threw. */
48
+ readThrew: (key: string, where: string): ErrorText => ({ kind: "threw", message: `reading "${where}" at "${key}" threw an exception` }),
49
+ /** Two or more arguments or fields that failed (CALL.ARGS, REC.FIELDS). */
50
+ args: (count: number, what: string): ErrorText => ({ kind: "args", message: `${String(count)} ${what} failed` }),
51
+ /** The axis table of an evaluation without that table. */
52
+ noTable: (name: string): ErrorText => ({ kind: "no-table", message: `the evaluation has no table "${name}"` }),
53
+ /** The test `until` of `iterate`, with a value that is not a boolean. */
54
+ untilKind: (value: unknown): ErrorText => ({ kind: "kind-mismatch", message: `the test "until" of "iterate" gave a ${typeof value}, not a boolean` }),
55
+ /** The limit of `iterate` with a test that is not true. */
56
+ limit: (limit: number): ErrorText => ({ kind: "limit", message: `"iterate" made its ${String(limit)} steps, and its test "until" is not true` }),
57
+ /** A value of a row of `fix` of the wrong kind for its join. */
58
+ fixKind: (name: string, join: string, kind: string, value: unknown): ErrorText => ({ kind: "kind-mismatch", message: `the "fix" "${name}" with the join "${join}" needs a ${kind}, not a ${describeType(value)}` }),
59
+ /** A value of a row of `fix` that is not a finite number. */
60
+ fixNumber: (name: string, value: unknown): ErrorText => ({ kind: "not-finite", message: `the "fix" "${name}" gave the value ${String(value)}, not a finite number` }),
61
+ /** The limit of the rounds of `fix`. */
62
+ fixLimit: (name: string, rounds: number): ErrorText => ({ kind: "limit", message: `the "fix" "${name}" made its ${String(rounds)} rounds, and its values still change` }),
63
+ /** A read of `last` at a key that is not a row. */
64
+ lastKey: (name: string, key: string): ErrorText => ({ kind: "unknown-key", message: `the "fix" "${name}" has no row "${key}"` }),
65
+ /** The test of `where`, with a value that is not a boolean. */
66
+ whereKind: (value: unknown): ErrorText => ({ kind: "kind-mismatch", message: `the test of "where" gave a ${typeof value}, not a boolean` }),
67
+ /** A domain that accepts the receiver of an op and has no such op. */
68
+ domainNoOp: (domain: string, op: string): ErrorText => ({ kind: "unknown-op", message: `the domain "${domain}" has no op "${op}"`, op }),
69
+ /** An op without arguments and without a free function. */
70
+ noOp: (op: string): ErrorText => ({ kind: "unknown-op", message: `there is no function "${op}"`, op }),
71
+ /** An op whose receiver no domain accepts. */
72
+ noDomain: (op: string, self: unknown): ErrorText => ({ kind: "not-instance", message: `no domain accepts the receiver of "${op}" (${describeType(self)})`, op }),
73
+ /** A special form without the argument at the index `i`. */
74
+ needsArgument: (op: string, i: number): ErrorText => ({ kind: "bad-expression", message: `"${op}" needs argument ${String(i + 1)}`, op }),
75
+ /** `and` or `or` without arguments. */
76
+ needsArguments: (op: string): ErrorText => ({ kind: "bad-expression", message: `"${op}" needs at least 1 argument`, op }),
77
+ /** An argument of a special form that is not a boolean. */
78
+ notBoolean: (op: string, i: number, value: unknown): ErrorText => ({ kind: "kind-mismatch", message: `argument ${String(i + 1)} of "${op}" is a ${describeType(value)}, not a boolean`, op }),
79
+ /** An argument of an op that does not have the kind of its parameter. */
80
+ badParam: (op: string, i: number, value: unknown, kind: ParamKind, domain: string): ErrorText => ({
81
+ kind: kind === "domain" ? "not-instance" : "kind-mismatch",
82
+ message: `argument ${String(i + 1)} of "${op}" is a ${describeType(value)}, not a ${kind === "domain" ? domain : kind}`,
83
+ op,
84
+ }),
85
+ /** An op that gave `undefined` or `null`. */
86
+ noValue: (op: string): ErrorText => ({ kind: "undefined-result", message: `"${op}" gave no value`, op }),
87
+ /** An op that gave a number that is not finite. */
88
+ notFinite: (op: string, value: number): ErrorText => ({ kind: "not-finite", message: `"${op}" gave ${String(value)}`, op }),
89
+ /** An op that gave a value that its domain does not accept as valid. */
90
+ invalid: (op: string, domain: string): ErrorText => ({ kind: "invalid-value", message: `"${op}" gave a value that is not a valid ${domain}`, op }),
91
+ /** A check `valid` of a domain that threw. */
92
+ validThrew: (op: string, domain: string): ErrorText => ({ kind: "threw", message: `the "valid" check of "${domain}" threw an exception`, op }),
93
+ /** A list op whose items must have one kind, with an item of another kind. */
94
+ /** The axis `list` over a value that is not a list (AXIS.LIST). */
95
+ axisList: (value: unknown): ErrorText => ({ kind: "kind-mismatch", message: `the axis "list" needs a list, not a ${describeType(value)}` }),
96
+ needsItems: (op: string, what: "numbers" | "booleans", item: unknown): ErrorText => ({ kind: "kind-mismatch", message: `"${op}" needs ${what}, but an item is a ${describeType(item)}`, op }),
97
+ /** A list op that has no items to work with. */
98
+ empty: (op: string): ErrorText => ({ kind: "empty", message: `"${op}" has no values to work with`, op }),
99
+ /** `reduce` with an op name that is not a text. */
100
+ reduceName: (name: unknown): ErrorText => ({ kind: "kind-mismatch", message: `"reduce" needs an op name, but got a ${describeType(name)}`, op: "reduce" }),
101
+ /** A step of `reduce` or of `sortBy` that no domain gives. */
102
+ noStep: (op: string, value: unknown): ErrorText => ({ kind: "unknown-op", message: `no domain gives "${op}" for a ${describeType(value)}`, op }),
103
+ } as const;
104
+
105
+ /** The details of an error that come from its evaluation, and not from its text. */
106
+ export interface ErrorExtra {
107
+ readonly causes?: readonly VexError[];
108
+ readonly thrown?: unknown;
109
+ }
110
+
111
+ /** This function makes the error of a text at a node: the path of the node, with its origin and its focus. */
112
+ export function errorAt(t: ErrorText, pos: Position, path: readonly number[], extra: ErrorExtra = {}): VexError {
113
+ return vexError(t.kind, t.message, { path, origin: pos.origin, focus: pos.focus, ...(t.op === undefined ? {} : { op: t.op }), ...extra });
114
+ }