@mark1russell7/vex 0.9.0 → 0.9.1

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.9.0",
4
+ "version": "0.9.1",
5
5
  "description": "Vex: typed spreadsheet formulas over domain objects. The kernel and the typed builder.",
6
6
  "keywords": [
7
7
  "typescript",
@@ -48,6 +48,7 @@
48
48
  "access": "public"
49
49
  },
50
50
  "devDependencies": {
51
+ "@mark1russell7/coeval": "^0.1.0",
51
52
  "@mark1russell7/cue": "github:mark1russell7/cue",
52
53
  "@mark1russell7/optional": "github:mark1russell7/optional",
53
54
  "@types/node": "^26.6.4",
package/src/codec.ts ADDED
@@ -0,0 +1,104 @@
1
+ /**
2
+ * The JSON form of the values of a literal. `serialize`, `parse`, `toDocument` and `fromDocument` share it. The package
3
+ * index does not export this module.
4
+ */
5
+ import type { AnyDomain } from "./domain.ts";
6
+ import { vexError } from "./errors.ts";
7
+ import { fail, ok, type Result } from "./result.ts";
8
+
9
+ /**
10
+ * The JSON form of the values in a literal. JSON data stays as it is, with three exceptions. Each exception is a record
11
+ * with the key `$vex`:
12
+ *
13
+ * - `{ "$vex": "domain", "domain": name, "value": v }`: a value of a domain, with the `encode` of the domain.
14
+ * - `{ "$vex": "number", "value": "-0" }`: a number that JSON has no text for: `-0`, `NaN`, `Infinity` or `-Infinity`.
15
+ * - `{ "$vex": "escape", "value": record }`: a record of the data that has the key `$vex` itself (IR.JSON.ESCAPE).
16
+ *
17
+ * A record with the key `$vex` and another form stays data, so a file from an older version reads as before.
18
+ *
19
+ * The functions walk the tree of the expression, so only the value of a literal gets this form. A field of a literal
20
+ * that looks like an expression stays data. The data of an extension is plain JSON, as before. A document has the same
21
+ * form for the value of a literal (DOC.LITERAL).
22
+ */
23
+ type Encoded =
24
+ | { readonly $vex: "domain"; readonly domain: string; readonly value: unknown }
25
+ | { readonly $vex: "number"; readonly value: "-0" | "NaN" | "Infinity" | "-Infinity" }
26
+ | { readonly $vex: "escape"; readonly value: Readonly<Record<string, unknown>> };
27
+
28
+ /** This function tells if a value is a record: an object that is not an array. */
29
+ export const isRecord = (u: unknown): u is Readonly<Record<string, unknown>> => typeof u === "object" && u !== null && !Array.isArray(u);
30
+
31
+ const isPlainRecord = (u: unknown): u is Readonly<Record<string, unknown>> => {
32
+ if (!isRecord(u)) return false;
33
+ const proto: unknown = Object.getPrototypeOf(u);
34
+ return proto === Object.prototype || proto === null;
35
+ };
36
+
37
+ /** This function gives the JSON form of a value, or the reason why the value has no JSON form. */
38
+ export function encodeValue(u: unknown, domains: readonly AnyDomain[]): Result<unknown> {
39
+ if (u === null || typeof u === "string" || typeof u === "boolean") return ok(u);
40
+ if (typeof u === "number") {
41
+ if (Object.is(u, -0)) return ok({ $vex: "number", value: "-0" } satisfies Encoded);
42
+ // Stryker disable next-line EqualityOperator: here u is an infinity, so u > 0 and u >= 0 are the same test
43
+ return Number.isFinite(u) ? ok(u) : ok({ $vex: "number", value: Number.isNaN(u) ? "NaN" : u > 0 ? "Infinity" : "-Infinity" } satisfies Encoded);
44
+ }
45
+ if (Array.isArray(u)) {
46
+ const out: unknown[] = [];
47
+ for (const x of u) {
48
+ const r = encodeValue(x, domains);
49
+ if (!r.ok) return r;
50
+ out.push(r.value);
51
+ }
52
+ return ok(out);
53
+ }
54
+ if (isPlainRecord(u)) {
55
+ const out: Record<string, unknown> = {};
56
+ for (const [k, x] of Object.entries(u)) {
57
+ const r = encodeValue(x, domains);
58
+ if (!r.ok) return r;
59
+ out[k] = r.value;
60
+ }
61
+ return ok(Object.hasOwn(u, "$vex") ? ({ $vex: "escape", value: out } satisfies Encoded) : out);
62
+ }
63
+ // A plain array or record stays data. Another object is a value of a domain, or it has no JSON form.
64
+ const d = domains.find((dom) => dom.encode !== undefined && dom.is(u));
65
+ if (d?.encode !== undefined) return ok({ $vex: "domain", domain: d.name, value: d.encode(u) } satisfies Encoded);
66
+ return fail(vexError("bad-expression", "a literal value is not JSON data and no domain encodes it"));
67
+ }
68
+
69
+ const NUMBERS: Readonly<Record<string, number>> = { "-0": -0, NaN: Number.NaN, Infinity: Number.POSITIVE_INFINITY, "-Infinity": Number.NEGATIVE_INFINITY };
70
+
71
+ /** This function reads a value from its JSON form. */
72
+ export function decodeValue(u: unknown, domains: readonly AnyDomain[]): Result<unknown> {
73
+ if (Array.isArray(u)) {
74
+ const out: unknown[] = [];
75
+ for (const x of u) {
76
+ const r = decodeValue(x, domains);
77
+ if (!r.ok) return r;
78
+ out.push(r.value);
79
+ }
80
+ return ok(out);
81
+ }
82
+ if (!isRecord(u)) return ok(u);
83
+ const fields = (record: Readonly<Record<string, unknown>>): Result<unknown> => {
84
+ const out: Record<string, unknown> = {};
85
+ for (const [k, x] of Object.entries(record)) {
86
+ const r = decodeValue(x, domains);
87
+ if (!r.ok) return r;
88
+ out[k] = r.value;
89
+ }
90
+ return ok(out);
91
+ };
92
+ // A record without the key $vex matches none of the forms below, so it stays data too.
93
+ const kind = u["$vex"];
94
+ if (kind === "escape" && isRecord(u["value"])) return fields(u["value"]);
95
+ if (kind === "number" && typeof u["value"] === "string" && Object.hasOwn(NUMBERS, u["value"])) return ok(NUMBERS[u["value"]]);
96
+ if (kind === "domain" && typeof u["domain"] === "string") {
97
+ const name = u["domain"];
98
+ const d = domains.find((dom) => dom.name === name);
99
+ if (d?.decode === undefined) return fail(vexError("bad-expression", `no domain "${name}" decodes a literal`));
100
+ return ok(d.decode(u["value"]));
101
+ }
102
+ // A form that this version does not know stays data, so a file from an older version reads as before.
103
+ return fields(u);
104
+ }
@@ -0,0 +1,416 @@
1
+ /**
2
+ * The documents of Vex. A document is the form of an expression in coeval, the language base of the family. Each term
3
+ * is an envelope `{ type, value }`, and a reference is a path from a root. The rules are decision D12 of coeval:
4
+ * <https://github.com/mark1russell7/coeval/blob/main/docs/DECISIONS.md>.
5
+ *
6
+ * | Expression | Document |
7
+ * |---|---|
8
+ * | `lit` | the JSON value of the literal. A value with the shape of an envelope is `{ "type": "lit", "value": x }`. |
9
+ * | `ref` | `{ "type": "ref", "value": ["self", ...moves, ...fields] }` |
10
+ * | `var` | `{ "type": "ref", "value": ["names", name] }` |
11
+ * | `app` | `{ "type": ["ops", ...keys], "value": [...args] }`. The keys are the name of the op, split at its dots. |
12
+ * | `let` | `{ "type": "let", "value": { "bind", "body" } }` |
13
+ * | `fn` | `{ "type": "fn", "value": { "params", "body" } }` |
14
+ * | `call` | `{ "type": "call", "value": { "fn": { "type": "ref", "value": ["names", name] }, "args" } }` |
15
+ * | `rec` | `{ "type": "record", "value": { ...fields } }` |
16
+ * | `each` | `{ "type": "each", "value": { "axis", "body", "at"? } }` |
17
+ * | `fold` | `{ "type": "fold", "value": { "axis", "init", "step", "result", "at"? } }` |
18
+ * | `iterate` | `{ "type": "iterate", "value": { "limit", "init", "step", "until"?, "result" } }` |
19
+ * | `ext` | `{ "type": ["ext", ...keys], "value": data }` |
20
+ * | a move | `{ "type": ["moves", kind], "value": v }` |
21
+ * | an axis | `{ "type": ["axes", name], "value": { ...parameters } }` |
22
+ *
23
+ * The address `at` of `each` and `fold` is a reference from `self` with moves only. An empty address is no address.
24
+ */
25
+ import { isEnvelope, ref as path, typed, typeName, typePath, type Envelope, type Json, type JsonRecord } from "@mark1russell7/coeval";
26
+ import { decodeValue, encodeValue, isRecord } from "./codec.ts";
27
+ import type { AnyDomain } from "./domain.ts";
28
+ import { isStackOverflow, vexError, type VexError } from "./errors.ts";
29
+ 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 Move, type Names } from "./ir.ts";
30
+ import { fail, ok, type Result } from "./result.ts";
31
+
32
+ export type { Envelope, Json } from "@mark1russell7/coeval";
33
+
34
+ /** The axes without parameters. */
35
+ const PLAIN_AXES: ReadonlySet<string> = new Set(["all", "others", "other", "children", "ancestors", "descendants", "siblings", "successors", "predecessors", "reachable"]);
36
+
37
+ /** The moves without a value. */
38
+ const PLAIN_MOVES: ReadonlyMap<string, Move> = new Map([
39
+ ["other", other],
40
+ ["origin", origin],
41
+ ["parent", parent],
42
+ ]);
43
+
44
+ /** The stop of a conversion. The functions of this module throw it, and the top of the conversion gives its error. */
45
+ class Stop {
46
+ readonly error: VexError;
47
+
48
+ constructor(error: VexError) {
49
+ this.error = error;
50
+ }
51
+ }
52
+
53
+ /** This function gives the location of a child: a JSON Pointer, with the escapes of RFC 6901. */
54
+ const into = (where: string, step: string | number): string => `${where}/${String(step).replaceAll("~", "~0").replaceAll("/", "~1")}`;
55
+
56
+ /** This function stops the reading of a document that is not valid at `where`. */
57
+ function bad(where: string, reason: string): never {
58
+ throw new Stop(vexError("bad-expression", `the document is not valid at ${where === "" ? "its root" : `"${where}"`}: ${reason}`));
59
+ }
60
+
61
+ /** This function does a conversion. It gives its value, or the error of the conversion. It does not throw. */
62
+ function attempt<T>(work: () => T, threw: string, deep: string): Result<T> {
63
+ try {
64
+ return ok(work());
65
+ } catch (thrown) {
66
+ if (thrown instanceof Stop) return fail(thrown.error);
67
+ if (isStackOverflow(thrown)) return fail(vexError("depth", deep, { thrown }));
68
+ return fail(vexError("threw", threw, { thrown }));
69
+ }
70
+ }
71
+
72
+ /**
73
+ * This function tells if a value is a document: an envelope `{ type, value }`. A node of the tagged IR is not an
74
+ * envelope, because it has the key `tag`. Thus `compile` and `evaluate` can take either one (DOC.ENTRY).
75
+ */
76
+ export function isDocument(u: unknown): u is Envelope {
77
+ return isEnvelope(u as Json);
78
+ }
79
+
80
+ /**
81
+ * This function gives the document of an expression (DOC.TERM). The root is always an envelope, so `compile` can tell a
82
+ * document from the tagged IR. A literal value has the JSON form of IR.JSON, so a domain value needs `encode` (DOC.LITERAL).
83
+ * An expression that is not valid, or a literal without a JSON form, gives the error `#VALUE!` (DOC.ERROR).
84
+ */
85
+ // Stryker disable next-line ArrayDeclaration: a list with a value that is not a domain encodes no value
86
+ export function toDocument(e: Expr, domains: readonly AnyDomain[] = []): Result<Envelope> {
87
+ const shape = shapeError(e);
88
+ if (shape !== undefined) return fail(vexError("bad-expression", shape));
89
+ // A getter of a literal value can throw, so the conversion is inside the attempt.
90
+ return attempt(() => new Writer(domains).envelope(e), "the expression has no document", "the expression is too deep for the call stack of the engine");
91
+ }
92
+
93
+ /**
94
+ * This function reads an expression from a document (DOC.TERM). It is the inverse of `toDocument`. It checks the
95
+ * expression as `compile` does (EVAL.SHAPE). A document that is not valid gives `#VALUE!` with its location (DOC.ERROR).
96
+ */
97
+ // Stryker disable next-line ArrayDeclaration: a list with a value that is not a domain decodes no value
98
+ export function fromDocument(doc: unknown, domains: readonly AnyDomain[] = []): Result<Expr> {
99
+ const read = attempt(() => new Reader(domains).term(doc, ""), "a decoder of a domain threw an exception", "the document is too deep for the call stack of the engine");
100
+ if (!read.ok) return read;
101
+ const shape = shapeError(read.value);
102
+ return shape === undefined ? read : fail(vexError("bad-expression", `the document gives an expression that is not valid: ${shape}`));
103
+ }
104
+
105
+ /** The writer of documents. Its methods throw a `Stop` for a literal without a JSON form. */
106
+ class Writer {
107
+ readonly #domains: readonly AnyDomain[];
108
+
109
+ constructor(domains: readonly AnyDomain[]) {
110
+ this.#domains = domains;
111
+ }
112
+
113
+ /** This method gives the document of a term. A literal is its JSON value, except a value with the shape of an envelope. */
114
+ term(e: Expr): Json {
115
+ if (e.tag !== "lit") return this.envelope(e);
116
+ const value = this.#value(e.value);
117
+ return isEnvelope(value) ? typed("lit", value) : value;
118
+ }
119
+
120
+ /** This method gives the document of a term as an envelope. Here a literal is an envelope too. */
121
+ envelope(e: Expr): Envelope {
122
+ switch (e.tag) {
123
+ case "lit":
124
+ return typed("lit", this.#value(e.value));
125
+ case "ref":
126
+ return path("self", ...this.#moves(e.at), ...e.path);
127
+ case "var":
128
+ return path("names", e.name);
129
+ case "app":
130
+ return typed(["ops", ...e.op.split(".")], e.args.map((a) => this.term(a)));
131
+ case "let":
132
+ return typed("let", { bind: this.#names(e.bind), body: this.term(e.body) });
133
+ case "fn":
134
+ return typed("fn", { params: [...e.params], body: this.term(e.body) });
135
+ case "call":
136
+ return typed("call", { fn: path("names", e.fn), args: e.args.map((a) => this.term(a)) });
137
+ case "rec":
138
+ return typed("record", this.#names(e.fields));
139
+ case "each":
140
+ return typed("each", { axis: this.#axis(e.axis), body: this.term(e.body), ...this.#at(e.at) });
141
+ case "fold":
142
+ return typed("fold", { axis: this.#axis(e.axis), init: this.#names(e.init), step: this.#names(e.step), result: this.term(e.result), ...this.#at(e.at) });
143
+ case "iterate":
144
+ return typed("iterate", {
145
+ limit: e.limit,
146
+ init: this.#names(e.init),
147
+ step: this.#names(e.step),
148
+ ...(e.until === undefined ? {} : { until: this.term(e.until) }),
149
+ result: this.term(e.result),
150
+ });
151
+ case "ext":
152
+ return typed(["ext", ...e.kind.split(".")], e.data as Json);
153
+ }
154
+ }
155
+
156
+ /** This method gives the JSON form of a literal value (IR.JSON). */
157
+ #value(u: unknown): Json {
158
+ const r = encodeValue(u, this.#domains);
159
+ if (!r.ok) throw new Stop(r.error);
160
+ return r.value as Json;
161
+ }
162
+
163
+ /** This method gives the documents of the terms of a record of names. */
164
+ #names(names: Names): JsonRecord {
165
+ return Object.fromEntries(Object.entries(names).map(([name, x]) => [name, this.term(x)]));
166
+ }
167
+
168
+ /** This method gives the step documents of the moves of an address. */
169
+ #moves(at: Addr | undefined): Json[] {
170
+ return (at ?? []).map((m) => this.#move(m));
171
+ }
172
+
173
+ /** This method gives the step document of a move. A computed key or position is an envelope (DOC.MOVE). */
174
+ #move(m: Move): Envelope {
175
+ switch (m.t) {
176
+ case "key":
177
+ return typed(["moves", "key"], typeof m.key === "string" ? m.key : this.envelope(m.key));
178
+ case "index":
179
+ return typed(["moves", "index"], typeof m.i === "number" ? m.i : this.envelope(m.i));
180
+ case "offset":
181
+ return typed(["moves", "offset"], [...m.d]);
182
+ case "other":
183
+ case "origin":
184
+ case "parent":
185
+ return typed(["moves", m.t], null);
186
+ }
187
+ }
188
+
189
+ /** This method gives the field `at` of `each` and `fold`: a reference from `self` with moves only, or no field. */
190
+ #at(at: Addr | undefined): { readonly at?: Envelope } {
191
+ return at === undefined || at.length === 0 ? {} : { at: path("self", ...this.#moves(at)) };
192
+ }
193
+
194
+ /** This method gives the document of an axis (DOC.AXIS). */
195
+ #axis(a: Axis): Envelope {
196
+ const name = ["axes", a.t];
197
+ switch (a.t) {
198
+ case "neighbors":
199
+ return typed(name, { n: a.n });
200
+ case "window":
201
+ return typed(name, { from: a.from, to: a.to });
202
+ case "table":
203
+ return typed(name, { name: a.name });
204
+ case "list":
205
+ return typed(name, { list: this.term(a.list) });
206
+ case "reverse":
207
+ return typed(name, { axis: this.#axis(a.axis) });
208
+ case "where":
209
+ return typed(name, { axis: this.#axis(a.axis), test: this.term(a.test) });
210
+ case "all":
211
+ case "others":
212
+ case "other":
213
+ case "children":
214
+ case "ancestors":
215
+ case "descendants":
216
+ case "siblings":
217
+ case "successors":
218
+ case "predecessors":
219
+ case "reachable":
220
+ return typed(name, {});
221
+ }
222
+ }
223
+ }
224
+
225
+ /** The reader of documents. Its methods throw a `Stop` at the first part that is not valid. */
226
+ class Reader {
227
+ readonly #domains: readonly AnyDomain[];
228
+
229
+ constructor(domains: readonly AnyDomain[]) {
230
+ this.#domains = domains;
231
+ }
232
+
233
+ /** This method reads a term. An envelope is a term, and another value is a literal (DOC.TERM). */
234
+ term(u: unknown, where: string): Expr {
235
+ return isDocument(u) ? this.#envelope(u, where) : lit(this.#value(u, where));
236
+ }
237
+
238
+ /** This method reads a term in an envelope. */
239
+ #envelope(u: Envelope, where: string): Expr {
240
+ const at = into(where, "value");
241
+ const [head, ...rest] = this.#type(u, where);
242
+ if (rest.length > 0 && (head === "ops" || head === "ext")) {
243
+ const name = this.#name(rest, into(where, "type"));
244
+ return head === "ops" ? app(name, ...this.#list(u.value, at).map((x, i) => this.term(x, into(at, i)))) : ext(name, u.value);
245
+ }
246
+ if (rest.length > 0) return bad(where, `the type "${typeName(u.type)}" is not a term of Vex`);
247
+ switch (head) {
248
+ case "lit":
249
+ return lit(this.#value(u.value, at));
250
+ case "ref":
251
+ return this.#ref(u.value, at);
252
+ case "let": {
253
+ const f = fields(u.value, at, ["bind", "body"]);
254
+ return let_(this.#names(f["bind"], into(at, "bind")), this.term(f["body"], into(at, "body")));
255
+ }
256
+ case "fn": {
257
+ const f = fields(u.value, at, ["params", "body"]);
258
+ const params = this.#list(f["params"], into(at, "params"));
259
+ if (!params.every((p) => typeof p === "string")) return bad(into(at, "params"), "a parameter is not a text");
260
+ return fn(params, this.term(f["body"], into(at, "body")));
261
+ }
262
+ case "call": {
263
+ const f = fields(u.value, at, ["fn", "args"]);
264
+ const name = this.#function(f["fn"], into(at, "fn"));
265
+ return call(name, ...this.#list(f["args"], into(at, "args")).map((x, i) => this.term(x, into(into(at, "args"), i))));
266
+ }
267
+ case "record":
268
+ return rec(this.#names(u.value, at));
269
+ case "each": {
270
+ const f = fields(u.value, at, ["axis", "body"], ["at"]);
271
+ return each(this.#axis(f["axis"], into(at, "axis")), this.term(f["body"], into(at, "body")), this.#address(f["at"], into(at, "at")));
272
+ }
273
+ case "fold": {
274
+ const f = fields(u.value, at, ["axis", "init", "step", "result"], ["at"]);
275
+ const axis = this.#axis(f["axis"], into(at, "axis"));
276
+ const init = this.#names(f["init"], into(at, "init"));
277
+ const step = this.#names(f["step"], into(at, "step"));
278
+ return fold(axis, init, step, this.term(f["result"], into(at, "result")), this.#address(f["at"], into(at, "at")));
279
+ }
280
+ case "iterate": {
281
+ const f = fields(u.value, at, ["limit", "init", "step", "result"], ["until"]);
282
+ const init = this.#names(f["init"], into(at, "init"));
283
+ const step = this.#names(f["step"], into(at, "step"));
284
+ const until = f["until"] === undefined ? undefined : this.term(f["until"], into(at, "until"));
285
+ // The limit is a number of the IR. The check of the expression tells a bad limit (ITERATE.LIMIT).
286
+ return iterate(f["limit"] as number, init, step, this.term(f["result"], into(at, "result")), until);
287
+ }
288
+ default:
289
+ // A construct of a newer version of Vex, or of another language.
290
+ return bad(where, `the type "${typeName(u.type)}" is not a term of Vex`);
291
+ }
292
+ }
293
+
294
+ /** This method gives the keys of the type of an envelope. An envelope of a term has no header (DOC.TERM). */
295
+ #type(u: Envelope, where: string): readonly [string | number, ...(string | number)[]] {
296
+ if (u.name !== undefined || u.own !== undefined) return bad(where, "a term of Vex has no name and no own entries");
297
+ const keys = typePath(u.type);
298
+ if (keys === undefined) return bad(into(where, "type"), "the type has a computed step");
299
+ // A type is a text, or a list with one key or more, so its path has a first key.
300
+ return keys as readonly [string | number, ...(string | number)[]];
301
+ }
302
+
303
+ /** This method gives the name of an op or an extension: its keys, joined with dots (DOC.OPS, DOC.EXT). */
304
+ #name(keys: readonly (string | number)[], where: string): string {
305
+ return keys.every((k) => typeof k === "string") ? keys.join(".") : bad(where, "a key of the name is not a text");
306
+ }
307
+
308
+ /** This method gives the value of a literal from its JSON form (DOC.LITERAL). */
309
+ #value(u: unknown, where: string): unknown {
310
+ const r = decodeValue(u, this.#domains);
311
+ return r.ok ? r.value : bad(where, r.error.message);
312
+ }
313
+
314
+ /** This method reads a list. */
315
+ #list(u: unknown, where: string): readonly unknown[] {
316
+ return Array.isArray(u) ? (u as readonly unknown[]) : bad(where, "the value is not a list");
317
+ }
318
+
319
+ /** This method reads a record of names and the term of each name. */
320
+ #names(u: unknown, where: string): Names {
321
+ if (!isRecord(u)) return bad(where, "the value is not a record");
322
+ return Object.fromEntries(Object.entries(u).map(([name, x]) => [name, this.term(x, into(where, name))]));
323
+ }
324
+
325
+ /** This method reads a reference: the fields of `self` after its moves, or a name of `names` (DOC.REF). */
326
+ #ref(u: unknown, where: string): Expr {
327
+ const [root, ...steps] = this.#list(u, where);
328
+ if (root === "names") return steps.length === 1 && typeof steps[0] === "string" ? v(steps[0]) : bad(where, "a reference to a name has one step: the name");
329
+ if (root !== "self") return bad(into(where, 0), `Vex reads only from the roots "self" and "names", and this reference starts at ${JSON.stringify(root) ?? "nothing"}`);
330
+ const moves: Move[] = [];
331
+ const names: string[] = [];
332
+ steps.forEach((step, i) => {
333
+ const at = into(where, i + 1);
334
+ if (typeof step === "string") names.push(step);
335
+ else if (!isDocument(step)) bad(at, "a step is not a text and not a move");
336
+ else if (names.length > 0) bad(at, "a move comes after a field. Vex reads the fields at the end of the path");
337
+ else moves.push(this.#move(step, at));
338
+ });
339
+ return ref(names, moves);
340
+ }
341
+
342
+ /** This method reads the function of a call: a reference to a name (DOC.CALL). */
343
+ #function(u: unknown, where: string): string {
344
+ const e = isDocument(u) ? this.#envelope(u, where) : undefined;
345
+ return e?.tag === "var" ? e.name : bad(where, 'the function of a call is a reference to a name: { "type": "ref", "value": ["names", name] }');
346
+ }
347
+
348
+ /** This method reads the field `at` of `each` and `fold`: a reference from `self` with moves only (DOC.ADDRESS). */
349
+ #address(u: unknown, where: string): Addr | undefined {
350
+ if (u === undefined) return undefined;
351
+ const e = isDocument(u) ? this.#envelope(u, where) : undefined;
352
+ return e?.tag === "ref" && e.path.length === 0 ? (e.at ?? []) : bad(where, 'the address is a reference from "self" with moves only: { "type": "ref", "value": ["self", ...moves] }');
353
+ }
354
+
355
+ /** This method reads a move (DOC.MOVE). A fixed key is a text, a fixed position is a number, and an envelope is a term. */
356
+ #move(u: Envelope, where: string): Move {
357
+ const [head, kind, ...rest] = this.#type(u, where);
358
+ const at = into(where, "value");
359
+ if (head !== "moves" || typeof kind !== "string" || rest.length > 0) return bad(where, `Vex has no step of the type "${typeName(u.type)}"`);
360
+ const value = u.value;
361
+ switch (kind) {
362
+ case "key":
363
+ return typeof value === "string" ? key(value) : isDocument(value) ? key(this.#envelope(value, at)) : bad(at, "the key is not a text or a term in an envelope");
364
+ case "index":
365
+ return typeof value === "number" ? index(value) : isDocument(value) ? index(this.#envelope(value, at)) : bad(at, "the position is not a number or a term in an envelope");
366
+ case "offset":
367
+ return Array.isArray(value) && value.every((d) => typeof d === "number") ? offset(...(value as readonly number[])) : bad(at, "the offset is not a list of numbers");
368
+ default: {
369
+ const plain = PLAIN_MOVES.get(kind);
370
+ if (plain === undefined) return bad(where, `Vex has no move "${kind}"`);
371
+ return value === null ? plain : bad(at, `the value of the move "${kind}" is not null`);
372
+ }
373
+ }
374
+ }
375
+
376
+ /** This method reads an axis (DOC.AXIS). The check of the expression tells a bad parameter. */
377
+ #axis(u: unknown, where: string): Axis {
378
+ if (!isDocument(u)) return bad(where, "the axis is not an envelope");
379
+ const [head, name, ...rest] = this.#type(u, where);
380
+ if (head !== "axes" || typeof name !== "string" || rest.length > 0) return bad(where, `the type "${typeName(u.type)}" is not an axis`);
381
+ const at = into(where, "value");
382
+ switch (name) {
383
+ case "neighbors":
384
+ return { t: name, n: fields(u.value, at, ["n"])["n"] as 4 | 8 };
385
+ case "window": {
386
+ const f = fields(u.value, at, ["from", "to"]);
387
+ return { t: name, from: f["from"] as number, to: f["to"] as number };
388
+ }
389
+ case "table":
390
+ return { t: name, name: fields(u.value, at, ["name"])["name"] as string };
391
+ case "list":
392
+ return { t: name, list: this.term(fields(u.value, at, ["list"])["list"], into(at, "list")) };
393
+ case "reverse":
394
+ return { t: name, axis: this.#axis(fields(u.value, at, ["axis"])["axis"], into(at, "axis")) };
395
+ case "where": {
396
+ const f = fields(u.value, at, ["axis", "test"]);
397
+ return { t: name, axis: this.#axis(f["axis"], into(at, "axis")), test: this.term(f["test"], into(at, "test")) };
398
+ }
399
+ default:
400
+ if (!PLAIN_AXES.has(name)) return bad(where, `Vex has no axis "${name}"`);
401
+ fields(u.value, at, []);
402
+ return { t: name } as Axis;
403
+ }
404
+ }
405
+ }
406
+
407
+ /**
408
+ * This function reads the value of a construct: a record with each necessary field, and no field outside the necessary
409
+ * and the optional fields. Thus a wrong name of a field gives an error, and the round trip keeps each field.
410
+ */
411
+ function fields(u: unknown, where: string, required: readonly string[], optional: readonly string[] = []): Readonly<Record<string, unknown>> {
412
+ if (!isRecord(u)) return bad(where, "the value is not a record");
413
+ for (const name of required) if (!Object.hasOwn(u, name)) bad(where, `the value has no field "${name}"`);
414
+ for (const name of Object.keys(u)) if (!required.includes(name) && !optional.includes(name)) bad(into(where, name), `the field "${name}" is not a field of this term`);
415
+ return u;
416
+ }
package/src/evaluate.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { fromDocument, isDocument, type Envelope } from "./document.ts";
1
2
  import { liftsAt, resolveOp, type AnyDomain, type ParamKind, type ResolvedOp } from "./domain.ts";
2
3
  import { formatError, isDepthError, isStackOverflow, vexError, type ErrorKind, type VexError } from "./errors.ts";
3
4
  import { addrExprs, children, shapeError, type Addr, type Axis, type Expr, type ExprOf, type FixedMove, type Move } from "./ir.ts";
@@ -65,7 +66,10 @@ export type RunOptions = Pick<EvalOptions, "space" | "origin" | "vars" | "trace"
65
66
  * and over different spaces, without a new walk of the expression.
66
67
  */
67
68
  export interface Program {
68
- /** The expression of the program. */
69
+ /**
70
+ * The expression of the program. For a document, it is the expression of the document. A document that is not valid
71
+ * stays as it is, as an expression that is not valid stays (DOC.ENTRY).
72
+ */
69
73
  readonly expr: Expr;
70
74
  /** This method evaluates the program at an origin. It does not throw. */
71
75
  run(opts: RunOptions): Result<unknown>;
@@ -73,10 +77,6 @@ export interface Program {
73
77
  explain(opts: Omit<RunOptions, "trace">): Trace;
74
78
  }
75
79
 
76
- /**
77
- * This function compiles an expression. The result gives the same results and the same traces as `evaluate`,
78
- * because `evaluate` uses it too.
79
- */
80
80
  /** A bound function (FN.BIND): its parameters, its compiled body and the names of the place of its binding. */
81
81
  class Closure {
82
82
  readonly params: readonly string[];
@@ -107,13 +107,21 @@ export function nestingOf(e: Expr): number {
107
107
  return deepest;
108
108
  }
109
109
 
110
- export function compile(expr: Expr, opts: CompileOptions = {}): Program {
110
+ /**
111
+ * This function compiles an expression or a document (DOC.ENTRY). The result gives the same results and the same traces
112
+ * as `evaluate`, because `evaluate` uses it too.
113
+ */
114
+ export function compile(source: Expr | Envelope, opts: CompileOptions = {}): Program {
115
+ // DOC.ENTRY: a document gives its expression first. A document that is not valid gives the error of fromDocument.
116
+ const read = isDocument(source) ? fromDocument(source, opts.domains) : ok(source);
117
+ const expr = read.ok ? read.value : (source as unknown as Expr);
111
118
  // EVAL.SHAPE: an expression that is not valid, for example from a newer version of Vex, gives an error before a walk.
112
119
  // EVAL.NESTING: a program nested too deep gives an error before the compiler walks it with recursion.
113
- const shape = shapeError(expr);
120
+ const shape = read.ok ? shapeError(expr) : read.error.message;
114
121
  const nesting = shape === undefined ? nestingOf(expr) : 0;
115
122
  const bad = shape ?? (nesting > MAX_NESTING ? `the expression is nested ${nesting} levels deep, and the limit is ${MAX_NESTING}` : undefined);
116
- 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 }));
123
+ const kind = read.ok ? "bad-expression" : read.error.kind;
124
+ const root: Node = bad === undefined ? new Compiler(opts).node(expr, []) : (f) => fail(vexError(kind, bad, { path: [], origin: f.pos.origin, focus: f.pos.focus }));
117
125
  const run = (r: RunOptions): Result<unknown> => {
118
126
  const { space, origin } = r;
119
127
  if (!space.has(origin)) return fail(vexError("unknown-key", `the space has no key "${origin}"`, { origin, focus: origin }));
@@ -137,10 +145,10 @@ export function compile(expr: Expr, opts: CompileOptions = {}): Program {
137
145
  };
138
146
  }
139
147
 
140
- // The cache of compiled programs: one entry for each expression object, for the last options.
141
- const CACHE = new WeakMap<Expr, { readonly domains: unknown; readonly fns: unknown; readonly extensions: unknown; readonly program: Program }>();
148
+ // The cache of compiled programs: one entry for each expression object or document, for the last options.
149
+ const CACHE = new WeakMap<Expr | Envelope, { readonly domains: unknown; readonly fns: unknown; readonly extensions: unknown; readonly program: Program }>();
142
150
 
143
- function compiled(expr: Expr, opts: CompileOptions): Program {
151
+ function compiled(expr: Expr | Envelope, opts: CompileOptions): Program {
144
152
  const hit = CACHE.get(expr);
145
153
  // Without the cache, each evaluation compiles again: the result is the same, so a mutant that removes a hit is
146
154
  // equivalent. A false hit changes results, and the tests find it.
@@ -151,13 +159,13 @@ function compiled(expr: Expr, opts: CompileOptions): Program {
151
159
  return program;
152
160
  }
153
161
 
154
- /** This function evaluates an expression at the origin of a space. It does not throw. */
155
- export function evaluate(expr: Expr, opts: EvalOptions): Result<unknown> {
162
+ /** This function evaluates an expression or a document at the origin of a space. It does not throw. */
163
+ export function evaluate(expr: Expr | Envelope, opts: EvalOptions): Result<unknown> {
156
164
  return compiled(expr, opts).run(opts);
157
165
  }
158
166
 
159
- /** This function evaluates an expression and records a trace of each node. */
160
- export function explain(expr: Expr, opts: Omit<EvalOptions, "trace">): Trace {
167
+ /** This function evaluates an expression or a document and records a trace of each node. */
168
+ export function explain(expr: Expr | Envelope, opts: Omit<EvalOptions, "trace">): Trace {
161
169
  return compiled(expr, opts).explain(opts);
162
170
  }
163
171
 
package/src/index.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * The kernel of Vex: spaces, addresses, the expression IR, domains, the interpreter and its folds.
2
+ * The kernel of Vex: spaces, addresses, the expression IR and its documents, domains, the interpreter and its folds.
3
3
  */
4
4
  export * from "./result.ts";
5
5
  export * from "./errors.ts";
@@ -11,6 +11,7 @@ export * from "./trace.ts";
11
11
  export * from "./evaluate.ts";
12
12
  export * from "./deps.ts";
13
13
  export * from "./json.ts";
14
+ export * from "./document.ts";
14
15
  export * from "./traversal.ts";
15
16
  export * from "./sheet.ts";
16
17
  export * from "./builder.ts";