@mark1russell7/vex 0.9.0 → 0.10.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/README.md +36 -1
- package/build/index.d.ts +155 -28
- package/build/index.d.ts.map +1 -1
- package/build/index.js +2124 -227
- package/build/index.js.map +1 -1
- package/package.json +5 -1
- package/src/builder.ts +54 -13
- package/src/codec.ts +104 -0
- package/src/deps.ts +174 -60
- package/src/document.ts +301 -0
- package/src/errors.ts +7 -3
- package/src/evaluate.ts +82 -28
- package/src/index.ts +5 -1
- package/src/json.ts +11 -96
- package/src/kernel.ts +897 -0
- package/src/list.ts +6 -3
- package/src/plan.ts +88 -0
- package/src/same.ts +31 -0
- package/src/sheet.ts +2 -1
- package/src/write.ts +257 -0
package/src/document.ts
ADDED
|
@@ -0,0 +1,301 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The documents of Vex. A document is the form of an expression in coeval, the kernel of the family. Each term is an
|
|
3
|
+
* 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
|
+
* The kernel checks a document by the contracts of `VEX_WORLD` (DOC.CHECK). A contract gives the shape of a kind, the
|
|
26
|
+
* data of its fields and the kinds of each position. Then `fromDocument` reads the expression. It checks only the grammar
|
|
27
|
+
* of Vex: the steps of a reference, the address, the function of a call and the names of a loop.
|
|
28
|
+
*/
|
|
29
|
+
import { check, isEnvelope, typeName, typePath, type Envelope, type Issue, type Key, type Machine } from "@mark1russell7/coeval";
|
|
30
|
+
import { decodeValue } from "./codec.ts";
|
|
31
|
+
import type { AnyDomain } from "./domain.ts";
|
|
32
|
+
import { isStackOverflow, vexError, type VexError } from "./errors.ts";
|
|
33
|
+
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";
|
|
34
|
+
import { MAX_DOCUMENT_DEPTH, TERM_KINDS, vexChecker } from "./kernel.ts";
|
|
35
|
+
import { fail, ok, type Result } from "./result.ts";
|
|
36
|
+
import { WriteStop, writeDocument, type WriteOptions } from "./write.ts";
|
|
37
|
+
|
|
38
|
+
export type { Envelope, Json } from "@mark1russell7/coeval";
|
|
39
|
+
|
|
40
|
+
/** The stop of a reading. The functions of this module throw it, and the top of the reading gives its error. */
|
|
41
|
+
class Stop {
|
|
42
|
+
readonly error: VexError;
|
|
43
|
+
|
|
44
|
+
constructor(error: VexError) {
|
|
45
|
+
this.error = error;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** This function gives the location of a child: a JSON Pointer, with the escapes of RFC 6901. */
|
|
50
|
+
const into = (where: string, step: Key): string => `${where}/${String(step).replaceAll("~", "~0").replaceAll("/", "~1")}`;
|
|
51
|
+
|
|
52
|
+
/** This function gives the JSON Pointer of a path of keys. */
|
|
53
|
+
const pointer = (keys: readonly Key[]): string => keys.reduce<string>(into, "");
|
|
54
|
+
|
|
55
|
+
/** This function gives the message of a document that is not valid at `where`. */
|
|
56
|
+
const notValid = (where: string, reason: string): string => `the document is not valid at ${where === "" ? "its root" : `"${where}"`}: ${reason}`;
|
|
57
|
+
|
|
58
|
+
/** This function stops the reading of a document that is not valid at `where`. */
|
|
59
|
+
function bad(where: string, reason: string): never {
|
|
60
|
+
throw new Stop(vexError("bad-expression", notValid(where, reason)));
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** This function does a conversion. It gives its value, or the error of the conversion. It does not throw. */
|
|
64
|
+
function attempt<T>(work: () => T, threw: string, deep: string): Result<T> {
|
|
65
|
+
try {
|
|
66
|
+
return ok(work());
|
|
67
|
+
} catch (thrown) {
|
|
68
|
+
if (thrown instanceof Stop || thrown instanceof WriteStop) return fail(thrown.error);
|
|
69
|
+
if (isStackOverflow(thrown)) return fail(vexError("depth", deep, { thrown }));
|
|
70
|
+
return fail(vexError("threw", threw, { thrown }));
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* This function tells if a value is a document: an envelope `{ type, value }`. A node of the tagged IR is not an
|
|
76
|
+
* envelope, because it has the key `tag`. Thus `compile` and `evaluate` can take either one (DOC.ENTRY).
|
|
77
|
+
*/
|
|
78
|
+
export function isDocument(u: unknown): u is Envelope {
|
|
79
|
+
return isEnvelope(u);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* This function gives the document of an expression (DOC.TERM). The root is always an envelope, so `compile` can tell a
|
|
84
|
+
* document from the tagged IR. A literal value has the JSON form of IR.JSON, so a domain value needs `encode` (DOC.LITERAL).
|
|
85
|
+
* An expression that is not valid, or a literal without a JSON form, gives the error `#VALUE!` (DOC.ERROR).
|
|
86
|
+
*/
|
|
87
|
+
// Stryker disable next-line ArrayDeclaration: a list with a value that is not a domain encodes no value
|
|
88
|
+
export function toDocument(e: Expr, domains: readonly AnyDomain[] = []): Result<Envelope> {
|
|
89
|
+
const shape = shapeError(e);
|
|
90
|
+
if (shape !== undefined) return fail(vexError("bad-expression", shape));
|
|
91
|
+
const options: WriteOptions = {
|
|
92
|
+
domains,
|
|
93
|
+
literals: "json",
|
|
94
|
+
// Stryker disable next-line StringLiteral: the writer tests only the order "reads", and each other order is the order of DOC.CONSTRUCT
|
|
95
|
+
order: "document",
|
|
96
|
+
};
|
|
97
|
+
// A getter of a literal value can throw, so the conversion is inside the attempt.
|
|
98
|
+
return attempt(() => writeDocument(e, options), "the expression has no document", "a literal value is too deep for the call stack of the engine");
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// The machine of the checks: the contracts of Vex, and the names of its evaluators and walkers, without their code.
|
|
102
|
+
let checker: Machine | undefined;
|
|
103
|
+
|
|
104
|
+
/** This function gives the first problem of a document that the kernel finds by the contracts of Vex (DOC.CHECK). */
|
|
105
|
+
function problemOf(doc: unknown): Issue | undefined {
|
|
106
|
+
checker ??= vexChecker();
|
|
107
|
+
// A bare value at the root is a literal. The names of a let, a function, a loop and the caller are free names.
|
|
108
|
+
return check(checker, doc, { declaredType: "lit", names: "any" })[0];
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* This function reads an expression from a document (DOC.TERM). It is the inverse of `toDocument`. The kernel checks
|
|
113
|
+
* the document first (DOC.CHECK). A document that is not valid gives `#VALUE!` with its location, and a document nested
|
|
114
|
+
* deeper than the kernel takes gives `#DEPTH!` (DOC.ERROR). The expression of a valid document is valid (EVAL.SHAPE).
|
|
115
|
+
*/
|
|
116
|
+
// Stryker disable next-line ArrayDeclaration: a list with a value that is not a domain decodes no value
|
|
117
|
+
export function fromDocument(doc: unknown, domains: readonly AnyDomain[] = []): Result<Expr> {
|
|
118
|
+
const problem = attempt(() => problemOf(doc), "the check of the document threw an exception", "the document is too deep for the call stack of the engine");
|
|
119
|
+
if (!problem.ok) return problem;
|
|
120
|
+
const issue = problem.value;
|
|
121
|
+
if (issue?.code === "#DEPTH!") return fail(vexError("depth", `the document is nested deeper than ${String(MAX_DOCUMENT_DEPTH)} documents`));
|
|
122
|
+
// Stryker disable next-line ArrayDeclaration: the check of coeval gives each issue the keys of its value
|
|
123
|
+
if (issue !== undefined) return fail(vexError("bad-expression", notValid(pointer(issue.at ?? []), issue.reason)));
|
|
124
|
+
return 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");
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** The kinds of the terms, as the first key of their type. */
|
|
128
|
+
const TERMS: ReadonlySet<string> = /* @__PURE__ */ new Set(/* @__PURE__ */ TERM_KINDS.map((k) => k[0] as string));
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* The reader of documents. The kernel checked the document, so each kind has the shape of its contract. The reader
|
|
132
|
+
* checks the grammar of Vex, and its methods throw a `Stop` at the first part that is not valid.
|
|
133
|
+
*/
|
|
134
|
+
class Reader {
|
|
135
|
+
readonly #domains: readonly AnyDomain[];
|
|
136
|
+
|
|
137
|
+
constructor(domains: readonly AnyDomain[]) {
|
|
138
|
+
this.#domains = domains;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** This method reads a term. An envelope is a term, and another value is a literal (DOC.TERM). */
|
|
142
|
+
term(u: unknown, where: string): Expr {
|
|
143
|
+
return isDocument(u) ? this.#envelope(u, where) : lit(this.#value(u, where));
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** This method reads a term in an envelope. */
|
|
147
|
+
#envelope(u: Envelope, where: string): Expr {
|
|
148
|
+
const at = into(where, "value");
|
|
149
|
+
const keys = this.#type(u, where);
|
|
150
|
+
const head = String(keys[0]);
|
|
151
|
+
// The contracts permit only the kinds of the terms in the position of a term. The root has no position. The check gave
|
|
152
|
+
// the type a kind of the world, so the first key tells if the type is a term.
|
|
153
|
+
if (!TERMS.has(head)) return bad(where, `the type "${typeName(u.type)}" is not a term of Vex`);
|
|
154
|
+
if (head === "ops" || head === "ext") {
|
|
155
|
+
const name = this.#name(keys.slice(1), into(where, "type"));
|
|
156
|
+
return head === "ops" ? app(name, ...(u.value as readonly unknown[]).map((x, i) => this.term(x, into(at, i)))) : ext(name, u.value);
|
|
157
|
+
}
|
|
158
|
+
const f = u.value as Readonly<Record<string, unknown>>;
|
|
159
|
+
switch (head) {
|
|
160
|
+
case "lit":
|
|
161
|
+
return lit(this.#value(u.value, at));
|
|
162
|
+
case "ref":
|
|
163
|
+
return this.#ref(u.value as readonly unknown[], at);
|
|
164
|
+
case "let":
|
|
165
|
+
return let_(this.#binds(f["bind"], into(at, "bind")), this.term(f["body"], into(at, "body")));
|
|
166
|
+
case "call": {
|
|
167
|
+
const name = this.#function(f["fn"] as Envelope, into(at, "fn"));
|
|
168
|
+
return call(name, ...(f["args"] as readonly unknown[]).map((x, i) => this.term(x, into(into(at, "args"), i))));
|
|
169
|
+
}
|
|
170
|
+
case "record":
|
|
171
|
+
return rec(this.#names(u.value, at));
|
|
172
|
+
case "each":
|
|
173
|
+
return each(this.#axis(f["axis"] as Envelope, into(at, "axis")), this.term(f["body"], into(at, "body")), this.#address(f["at"], into(at, "at")));
|
|
174
|
+
case "fold": {
|
|
175
|
+
const [init, step] = this.#loop(f, at);
|
|
176
|
+
return fold(this.#axis(f["axis"] as Envelope, into(at, "axis")), init, step, this.term(f["result"], into(at, "result")), this.#address(f["at"], into(at, "at")));
|
|
177
|
+
}
|
|
178
|
+
default: {
|
|
179
|
+
// iterate: the contract gives a whole number from 0 to MAX_ITERATIONS for the limit (ITERATE.LIMIT).
|
|
180
|
+
const [init, step] = this.#loop(f, at);
|
|
181
|
+
const until = f["until"] === undefined ? undefined : this.term(f["until"], into(at, "until"));
|
|
182
|
+
return iterate(f["limit"] as number, init, step, this.term(f["result"], into(at, "result")), until);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** This method gives the keys of the type of an envelope. A term of Vex has no header (DOC.TERM). */
|
|
188
|
+
#type(u: Envelope, where: string): readonly Key[] {
|
|
189
|
+
if (u.name !== undefined || u.own !== undefined) return bad(where, "a term of Vex has no name and no own entries");
|
|
190
|
+
// The check found the kind of the type, so the type has no computed step.
|
|
191
|
+
return typePath(u.type) as readonly Key[];
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** This method gives the name of an op or an extension: its keys, joined with dots (DOC.OPS, DOC.EXT). */
|
|
195
|
+
#name(keys: readonly Key[], where: string): string {
|
|
196
|
+
return keys.every((k) => typeof k === "string") ? keys.join(".") : bad(where, "a key of the name is not a text");
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** This method gives the value of a literal from its JSON form (DOC.LITERAL). */
|
|
200
|
+
#value(u: unknown, where: string): unknown {
|
|
201
|
+
const r = decodeValue(u, this.#domains);
|
|
202
|
+
return r.ok ? r.value : bad(where, r.error.message);
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** This method reads a record of names and the term of each name. */
|
|
206
|
+
#names(u: unknown, where: string): Names {
|
|
207
|
+
return Object.fromEntries(Object.entries(u as Readonly<Record<string, unknown>>).map(([name, x]) => [name, this.term(x, into(where, name))]));
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** This method reads the bindings of a let. A binding can be a function (FN.BIND). */
|
|
211
|
+
#binds(u: unknown, where: string): Names {
|
|
212
|
+
return Object.fromEntries(
|
|
213
|
+
Object.entries(u as Readonly<Record<string, unknown>>).map(([name, x]) => {
|
|
214
|
+
const at = into(where, name);
|
|
215
|
+
if (!isDocument(x) || typeName(x.type) !== "fn") return [name, this.term(x, at)];
|
|
216
|
+
this.#type(x, at);
|
|
217
|
+
const f = x.value as { readonly params: readonly string[]; readonly body: unknown };
|
|
218
|
+
return [name, fn(f.params, this.term(f.body, into(into(at, "value"), "body")))];
|
|
219
|
+
}),
|
|
220
|
+
);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** This method reads the names of a loop. Each name of `step` is a name of `init` (LOOP.NAMES). */
|
|
224
|
+
#loop(f: Readonly<Record<string, unknown>>, at: string): readonly [Names, Names] {
|
|
225
|
+
const init = this.#names(f["init"], into(at, "init"));
|
|
226
|
+
const step = this.#names(f["step"], into(at, "step"));
|
|
227
|
+
const extra = Object.keys(step).find((name) => !Object.hasOwn(init, name));
|
|
228
|
+
return extra === undefined ? [init, step] : bad(into(into(at, "step"), extra), `the name "${extra}" of step is not a name of init`);
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/** This method reads a reference: the fields of `self` after its moves, or a name of `names` (DOC.REF). */
|
|
232
|
+
#ref(path: readonly unknown[], where: string): Expr {
|
|
233
|
+
const [root, ...steps] = path;
|
|
234
|
+
// The check gives each reference a root that Vex reads: "self" or "names".
|
|
235
|
+
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");
|
|
236
|
+
const moves: Move[] = [];
|
|
237
|
+
const names: string[] = [];
|
|
238
|
+
steps.forEach((step, i) => {
|
|
239
|
+
const at = into(where, i + 1);
|
|
240
|
+
if (typeof step === "string") names.push(step);
|
|
241
|
+
else if (!isDocument(step)) bad(at, "a step is not a text and not a move");
|
|
242
|
+
else if (names.length > 0) bad(at, "a move comes after a field. Vex reads the fields at the end of the path");
|
|
243
|
+
else moves.push(this.#move(step, at));
|
|
244
|
+
});
|
|
245
|
+
return ref(names, moves);
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/** This method reads the function of a call: a reference to a name (DOC.CALL). */
|
|
249
|
+
#function(u: Envelope, where: string): string {
|
|
250
|
+
const steps = u.value as readonly unknown[];
|
|
251
|
+
return steps[0] === "names" && steps.length === 2 && typeof steps[1] === "string" ? steps[1] : bad(where, 'the function of a call is a reference to a name: { "type": "ref", "value": ["names", name] }');
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/** This method reads the field `at` of `each` and `fold`: a reference from `self` with moves only (DOC.ADDRESS). */
|
|
255
|
+
#address(u: unknown, where: string): Addr | undefined {
|
|
256
|
+
if (u === undefined) return undefined;
|
|
257
|
+
const e = this.#envelope(u as Envelope, where);
|
|
258
|
+
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] }');
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/**
|
|
262
|
+
* This method reads a move (DOC.MOVE). The value of `key` and `index` is a term: a text key and a number position are
|
|
263
|
+
* fixed, and another term is computed. The check gave the other moves their values.
|
|
264
|
+
*/
|
|
265
|
+
#move(u: Envelope, where: string): Move {
|
|
266
|
+
const kind = String(this.#type(u, where)[1]);
|
|
267
|
+
const at = into(where, "value");
|
|
268
|
+
const value = u.value;
|
|
269
|
+
switch (kind) {
|
|
270
|
+
case "key":
|
|
271
|
+
return typeof value === "string" ? key(value) : key(this.term(value, at));
|
|
272
|
+
case "index":
|
|
273
|
+
return typeof value === "number" ? index(value) : index(this.term(value, at));
|
|
274
|
+
case "offset":
|
|
275
|
+
return offset(...(value as readonly number[]));
|
|
276
|
+
case "other":
|
|
277
|
+
return other;
|
|
278
|
+
case "origin":
|
|
279
|
+
return origin;
|
|
280
|
+
default:
|
|
281
|
+
return parent;
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/** This method reads an axis (DOC.AXIS). The check gave it the parameters of its kind. */
|
|
286
|
+
#axis(u: Envelope, where: string): Axis {
|
|
287
|
+
const name = String(this.#type(u, where)[1]);
|
|
288
|
+
const at = into(where, "value");
|
|
289
|
+
const f = u.value as Readonly<Record<string, unknown>>;
|
|
290
|
+
switch (name) {
|
|
291
|
+
case "list":
|
|
292
|
+
return { t: name, list: this.term(f["list"], into(at, "list")) };
|
|
293
|
+
case "reverse":
|
|
294
|
+
return { t: name, axis: this.#axis(f["axis"] as Envelope, into(at, "axis")) };
|
|
295
|
+
case "where":
|
|
296
|
+
return { t: name, axis: this.#axis(f["axis"] as Envelope, into(at, "axis")), test: this.term(f["test"], into(at, "test")) };
|
|
297
|
+
default:
|
|
298
|
+
return { t: name, ...f } as Axis;
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
}
|
package/src/errors.ts
CHANGED
|
@@ -1,8 +1,12 @@
|
|
|
1
|
+
import type { KernelCode } from "@mark1russell7/coeval";
|
|
2
|
+
|
|
1
3
|
/**
|
|
2
|
-
* The error codes of Vex. The names come from the spreadsheet error values, because a Vex program is a
|
|
3
|
-
*
|
|
4
|
+
* The error codes of Vex. The names come from the spreadsheet error values, because a Vex program is a spreadsheet
|
|
5
|
+
* formula over records. Each code is a code of the kernel of coeval with the same meaning. For example, `#N/A` is a step
|
|
6
|
+
* that reaches nothing, and `#DEPTH!` is a full call stack. The type checks it: a code that the kernel does not have is
|
|
7
|
+
* not a member.
|
|
4
8
|
*/
|
|
5
|
-
export type ErrorCode = "#REF!" | "#N/A" | "#VALUE!" | "#NAME?" | "#NUM!" | "#CALC!" | "#ARGS" | "#CYCLE!" | "#DEPTH!"
|
|
9
|
+
export type ErrorCode = Extract<KernelCode, "#REF!" | "#N/A" | "#VALUE!" | "#NAME?" | "#NUM!" | "#CALC!" | "#ARGS" | "#CYCLE!" | "#DEPTH!">;
|
|
6
10
|
|
|
7
11
|
/** The cause of an error, in more detail than the code. */
|
|
8
12
|
export type ErrorKind =
|
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
|
-
/**
|
|
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
|
-
|
|
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
|
|
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,12 @@ 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 {
|
|
152
|
+
// V-056: a program that is not an object cannot be a key of the cache. Its compilation gives #VALUE! (EVAL.SHAPE).
|
|
153
|
+
if (typeof expr !== "object" || expr === null) return compile(expr, opts);
|
|
144
154
|
const hit = CACHE.get(expr);
|
|
145
155
|
// Without the cache, each evaluation compiles again: the result is the same, so a mutant that removes a hit is
|
|
146
156
|
// equivalent. A false hit changes results, and the tests find it.
|
|
@@ -151,13 +161,13 @@ function compiled(expr: Expr, opts: CompileOptions): Program {
|
|
|
151
161
|
return program;
|
|
152
162
|
}
|
|
153
163
|
|
|
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> {
|
|
164
|
+
/** This function evaluates an expression or a document at the origin of a space. It does not throw. */
|
|
165
|
+
export function evaluate(expr: Expr | Envelope, opts: EvalOptions): Result<unknown> {
|
|
156
166
|
return compiled(expr, opts).run(opts);
|
|
157
167
|
}
|
|
158
168
|
|
|
159
|
-
/** This function evaluates an expression and records a trace of each node. */
|
|
160
|
-
export function explain(expr: Expr, opts: Omit<EvalOptions, "trace">): Trace {
|
|
169
|
+
/** This function evaluates an expression or a document and records a trace of each node. */
|
|
170
|
+
export function explain(expr: Expr | Envelope, opts: Omit<EvalOptions, "trace">): Trace {
|
|
161
171
|
return compiled(expr, opts).explain(opts);
|
|
162
172
|
}
|
|
163
173
|
|
|
@@ -719,15 +729,14 @@ class Compiler {
|
|
|
719
729
|
}
|
|
720
730
|
|
|
721
731
|
#listOp(op: ListOp, list: VexList, rest: readonly unknown[], f: Frame, path: readonly number[]): Result<unknown> {
|
|
722
|
-
// The options come after the
|
|
723
|
-
const optsArg = op
|
|
724
|
-
// A reduction that skips error items does not skip #DEPTH! (EVAL.DEPTH).
|
|
725
|
-
const depth = list.items.find((it) => !it.result.ok && isDepthError(it.result.error))?.result;
|
|
726
|
-
if (depth !== undefined && !depth.ok) return fail(depth.error);
|
|
732
|
+
// The options come after the second argument of an op with one, for example the count of take.
|
|
733
|
+
const optsArg = WITH_ARGUMENT.has(op) ? rest[1] : rest[0];
|
|
727
734
|
const strict = (optsArg as ListOptions | null | undefined)?.strict === true;
|
|
728
|
-
const
|
|
729
|
-
if (
|
|
730
|
-
const
|
|
735
|
+
const good = goodItems(list, strict);
|
|
736
|
+
if (!good.ok) return good;
|
|
737
|
+
const okItems = good.value;
|
|
738
|
+
// Stryker disable next-line ConditionalExpression,ArrayDeclaration: each item of okItems has a value
|
|
739
|
+
const okValues = okItems.flatMap((it) => (it.result.ok ? [it.result.value] : []));
|
|
731
740
|
const numbers = (): Result<readonly number[]> => {
|
|
732
741
|
const bad = okValues.find((x) => typeof x !== "number");
|
|
733
742
|
return bad === undefined ? ok(okValues as readonly number[]) : this.#err("kind-mismatch", `"${op}" needs numbers, but an item is a ${describeType(bad)}`, f, path, { op });
|
|
@@ -737,19 +746,34 @@ class Compiler {
|
|
|
737
746
|
return bad === undefined ? ok(okValues as readonly boolean[]) : this.#err("kind-mismatch", `"${op}" needs booleans, but an item is a ${describeType(bad)}`, f, path, { op });
|
|
738
747
|
};
|
|
739
748
|
const empty = (): Result<never> => this.#err("empty", `"${op}" has no values to work with`, f, path, { op });
|
|
740
|
-
// A count or a position of take and nth is a whole number from 0.
|
|
749
|
+
// A count or a position of take, drop and nth is a whole number from 0.
|
|
741
750
|
const whole = (): Result<number> => {
|
|
742
751
|
const n = rest[0] as number;
|
|
743
752
|
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 });
|
|
744
753
|
};
|
|
745
|
-
|
|
754
|
+
// The second list of append and without follows the rules of the first list (LIST.BUILD).
|
|
755
|
+
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 }));
|
|
746
756
|
switch (op) {
|
|
747
757
|
case "sortBy":
|
|
748
758
|
return this.#sortBy(okItems, okValues, f, path);
|
|
749
|
-
case "take":
|
|
759
|
+
case "take":
|
|
760
|
+
case "drop": {
|
|
750
761
|
const n = whole();
|
|
751
|
-
|
|
762
|
+
if (!n.ok) return n;
|
|
763
|
+
return ok(vexList(op === "take" ? okItems.slice(0, n.value) : okItems.slice(n.value)));
|
|
764
|
+
}
|
|
765
|
+
case "append": {
|
|
766
|
+
const more = other();
|
|
767
|
+
return more.ok ? ok(vexList([...okItems, ...more.value])) : more;
|
|
752
768
|
}
|
|
769
|
+
case "without": {
|
|
770
|
+
const more = other();
|
|
771
|
+
if (!more.ok) return more;
|
|
772
|
+
const gone = new Set(more.value.map((it) => it.key));
|
|
773
|
+
return ok(vexList(okItems.filter((it) => !gone.has(it.key))));
|
|
774
|
+
}
|
|
775
|
+
case "flat":
|
|
776
|
+
return this.#flat(okValues, strict, f, path);
|
|
753
777
|
case "nth": {
|
|
754
778
|
const i = whole();
|
|
755
779
|
if (!i.ok) return i;
|
|
@@ -760,7 +784,7 @@ class Compiler {
|
|
|
760
784
|
case "values":
|
|
761
785
|
return ok(Object.freeze([...okValues]));
|
|
762
786
|
case "keys":
|
|
763
|
-
return ok(Object.freeze(
|
|
787
|
+
return ok(Object.freeze(okItems.map((it) => it.key)));
|
|
764
788
|
case "errors":
|
|
765
789
|
return ok(Object.freeze(list.items.flatMap((it) => (it.result.ok ? [] : [it.result.error]))));
|
|
766
790
|
case "first":
|
|
@@ -795,6 +819,21 @@ class Compiler {
|
|
|
795
819
|
}
|
|
796
820
|
}
|
|
797
821
|
|
|
822
|
+
/**
|
|
823
|
+
* This method joins the lists that are the values of the items of a list, in order (LIST.FLAT). Each list follows the
|
|
824
|
+
* rules of LIST.BUILD. A value that is not a list gives `#VALUE!`.
|
|
825
|
+
*/
|
|
826
|
+
#flat(values: readonly unknown[], strict: boolean, f: Frame, path: readonly number[]): Result<VexList> {
|
|
827
|
+
const out: ListItem[] = [];
|
|
828
|
+
for (const inner of values) {
|
|
829
|
+
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" });
|
|
830
|
+
const good = goodItems(inner, strict);
|
|
831
|
+
if (!good.ok) return good;
|
|
832
|
+
out.push(...good.value);
|
|
833
|
+
}
|
|
834
|
+
return ok(vexList(out));
|
|
835
|
+
}
|
|
836
|
+
|
|
798
837
|
/**
|
|
799
838
|
* This method sorts the items of a list by their values, from the smallest (LIST.SORT). The sort is stable. The values
|
|
800
839
|
* are all numbers without NaN, or all texts. Texts compare by their UTF-16 code units.
|
|
@@ -846,6 +885,21 @@ class Compiler {
|
|
|
846
885
|
}
|
|
847
886
|
}
|
|
848
887
|
|
|
888
|
+
/** The list ops with a second argument before their options: a count, a position, an op name or a list. */
|
|
889
|
+
const WITH_ARGUMENT: ReadonlySet<ListOp> = new Set<ListOp>(["reduce", "take", "nth", "drop", "append", "without"]);
|
|
890
|
+
|
|
891
|
+
/**
|
|
892
|
+
* This function gives the items of a list that have a value (LIST.LENIENT). A list op does not skip `#DEPTH!`, so that
|
|
893
|
+
* error comes first (EVAL.DEPTH). With `strict`, the first error item is the result.
|
|
894
|
+
*/
|
|
895
|
+
function goodItems(list: VexList, strict: boolean): Result<readonly ListItem[]> {
|
|
896
|
+
const depth = list.items.find((it) => !it.result.ok && isDepthError(it.result.error))?.result;
|
|
897
|
+
if (depth !== undefined && !depth.ok) return fail(depth.error);
|
|
898
|
+
const firstError = list.items.find((it) => !it.result.ok)?.result;
|
|
899
|
+
if (strict && firstError !== undefined && !firstError.ok) return fail(firstError.error);
|
|
900
|
+
return ok(list.items.filter((it) => it.result.ok));
|
|
901
|
+
}
|
|
902
|
+
|
|
849
903
|
const FORBIDDEN_FIELDS = new Set(["__proto__", "constructor", "prototype"]);
|
|
850
904
|
/** This function tells if a segment of a path can name a field. A compiler uses the same rule as the interpreter. */
|
|
851
905
|
export const isFieldName = (seg: string): boolean => seg.length > 0 && !FORBIDDEN_FIELDS.has(seg);
|
package/src/index.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* The
|
|
2
|
+
* The core of Vex: spaces, addresses, the expression IR and its documents, domains, the interpreter and its folds. It
|
|
3
|
+
* also has Vex in the kernel of coeval: the contracts of its kinds and the reference tier.
|
|
3
4
|
*/
|
|
4
5
|
export * from "./result.ts";
|
|
5
6
|
export * from "./errors.ts";
|
|
@@ -11,6 +12,9 @@ export * from "./trace.ts";
|
|
|
11
12
|
export * from "./evaluate.ts";
|
|
12
13
|
export * from "./deps.ts";
|
|
13
14
|
export * from "./json.ts";
|
|
15
|
+
export * from "./document.ts";
|
|
16
|
+
export * from "./kernel.ts";
|
|
17
|
+
export * from "./plan.ts";
|
|
14
18
|
export * from "./traversal.ts";
|
|
15
19
|
export * from "./sheet.ts";
|
|
16
20
|
export * from "./builder.ts";
|