@mark1russell7/vex 0.9.1 → 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 +18 -2
- package/build/index.d.ts +123 -62
- package/build/index.d.ts.map +1 -1
- package/build/index.js +1869 -497
- package/build/index.js.map +1 -1
- package/package.json +5 -2
- package/src/builder.ts +54 -13
- package/src/deps.ts +174 -60
- package/src/document.ts +133 -248
- package/src/errors.ts +7 -3
- package/src/evaluate.ts +59 -13
- package/src/index.ts +4 -1
- 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/kernel.ts
ADDED
|
@@ -0,0 +1,897 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Vex in the kernel of coeval (decision D13 of coeval, and decision D13 of Vex in `docs/REVIEW.md`). This module gives
|
|
3
|
+
* the contracts of the kinds of Vex as data, and a machine of the kernel that evaluates the documents of Vex.
|
|
4
|
+
*
|
|
5
|
+
* - The static kit of the kernel checks a document by these contracts (`fromDocument`, DOC.ERROR) and finds its
|
|
6
|
+
* references (`deps`, DEPS.READS).
|
|
7
|
+
* - The machine is the reference tier of Vex. The closure compiler and the loop compiler give its results
|
|
8
|
+
* (EVAL.REFERENCE). It evaluates the shared constructs with the formula kit of the kernel, and a profile gives the
|
|
9
|
+
* rules of Vex. Vex adds only what is its own: the moves, the axes, the loops and the dispatch on the domains.
|
|
10
|
+
*/
|
|
11
|
+
import {
|
|
12
|
+
type Context,
|
|
13
|
+
type Definitions,
|
|
14
|
+
type EvalError,
|
|
15
|
+
type EvalFn,
|
|
16
|
+
type Failed,
|
|
17
|
+
type ExtFn,
|
|
18
|
+
type FormulaProfile,
|
|
19
|
+
type HostThing,
|
|
20
|
+
type Key,
|
|
21
|
+
type Kind,
|
|
22
|
+
type LazyOp,
|
|
23
|
+
type Machine,
|
|
24
|
+
type PartShape,
|
|
25
|
+
type Part,
|
|
26
|
+
type Result as Outcome,
|
|
27
|
+
type Walker,
|
|
28
|
+
type World,
|
|
29
|
+
Failure,
|
|
30
|
+
Held,
|
|
31
|
+
STD_EXT,
|
|
32
|
+
THING,
|
|
33
|
+
formulaDefinitions,
|
|
34
|
+
formulaEvaluators,
|
|
35
|
+
ok,
|
|
36
|
+
} from "@mark1russell7/coeval";
|
|
37
|
+
import { decodeValue } from "./codec.ts";
|
|
38
|
+
import type { AnyDomain } from "./domain.ts";
|
|
39
|
+
import { vexError, type ErrorCode, type ErrorDetails, type ErrorKind, type VexError } from "./errors.ts";
|
|
40
|
+
import type { CompileOptions } from "./evaluate.ts";
|
|
41
|
+
import { MAX_ITERATIONS, type Axis, type FixedMove } from "./ir.ts";
|
|
42
|
+
import { isVexList, LIST_OPS, vexList, type ListItem } from "./list.ts";
|
|
43
|
+
import { fail as vexFail, ok as vexOk, type Result } from "./result.ts";
|
|
44
|
+
import { isVexError } from "./same.ts";
|
|
45
|
+
import { applyMove, axisTargets, type Space } from "./space.ts";
|
|
46
|
+
|
|
47
|
+
// ---------------------------------------------------------------- the contracts
|
|
48
|
+
|
|
49
|
+
/** The kinds of the terms of Vex. A part in the position of a term has one of these kinds (DOC.TERM). */
|
|
50
|
+
export const TERM_KINDS: readonly (readonly string[])[] = [["lit"], ["ref"], ["record"], ["let"], ["call"], ["each"], ["fold"], ["iterate"], ["ops"], ["ext"]];
|
|
51
|
+
|
|
52
|
+
/** A term: an envelope of a term kind, or a bare value, which is a literal. */
|
|
53
|
+
const TERM: PartShape = { shape: "term", of: "lit", kinds: TERM_KINDS };
|
|
54
|
+
const TERMS: PartShape = { shape: "list", item: TERM };
|
|
55
|
+
const NAMES: PartShape = { shape: "map", item: TERM };
|
|
56
|
+
const AXIS: PartShape = { shape: "term", kinds: [["axes"]] };
|
|
57
|
+
/** The address of `each` and `fold`: a reference that gives a key of the space, not a value (DOC.ADDRESS). */
|
|
58
|
+
const ADDRESS: PartShape = { shape: "term", kinds: [["ref"]], address: true };
|
|
59
|
+
const NO_VALUE: PartShape = { shape: "one", values: [null] };
|
|
60
|
+
|
|
61
|
+
/** This function gives the shape of a record with these fields and no other fields (DOC.CONSTRUCT). */
|
|
62
|
+
const closed = (fields: Readonly<Record<string, PartShape>>, required: readonly string[]): PartShape => ({ shape: "record", fields, required, closed: true });
|
|
63
|
+
|
|
64
|
+
/** The axes without parameters. */
|
|
65
|
+
const PLAIN_AXES = ["all", "others", "other", "children", "ancestors", "descendants", "siblings", "successors", "predecessors", "reachable"] as const;
|
|
66
|
+
|
|
67
|
+
/** This function gives the kind of an axis with these parameters (DOC.AXIS). */
|
|
68
|
+
const axisKind = (fields: Readonly<Record<string, PartShape>>): Kind => ({ verbs: { eval: "vex.axis" }, parts: closed(fields, Object.keys(fields)), summary: "An axis of Vex: the targets of a body." });
|
|
69
|
+
|
|
70
|
+
/** This function gives the kind of a move. Its document is a step of a path, and a computed key is its part (DOC.MOVE). */
|
|
71
|
+
const move = (walker: string, parts: PartShape): Kind => ({ verbs: { eval: "formula.step", step: walker }, parts, summary: "A move of Vex: a step to another key of the space." });
|
|
72
|
+
|
|
73
|
+
/** The scope of a loop: the names of `init`, for the steps, the test `until` and the result (LOOP.NAMES). */
|
|
74
|
+
const LOOP_SCOPE = [{ names: { keysAt: ["init"] }, in: [["step", "*"], ["until"], ["result"]] }] as const;
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* This function gives the world of Vex. The module uses it one time, and the annotation `__PURE__` lets a bundler
|
|
78
|
+
* remove the world from a program that does not use it.
|
|
79
|
+
*/
|
|
80
|
+
function worldOfVex(): World {
|
|
81
|
+
/** A binding of a `let`: a term, or a function (FN.BIND). */
|
|
82
|
+
const BIND: PartShape = { shape: "term", of: "lit", kinds: [...TERM_KINDS, ["fn"]] };
|
|
83
|
+
/** The axes that `reverse` can hold: each axis but `where`, `reverse` and `table` (AXIS.REVERSE). */
|
|
84
|
+
const BASE_AXES: readonly string[] = [...PLAIN_AXES, "neighbors", "window", "list"];
|
|
85
|
+
return {
|
|
86
|
+
kinds: {
|
|
87
|
+
lit: { verbs: { eval: "vex.lit" }, summary: "A literal: its value in the JSON form of IR.JSON." },
|
|
88
|
+
ref: { verbs: { eval: "formula.ref" }, parts: { shape: "deep" }, summary: "A reference: the fields of self after its moves, or a name." },
|
|
89
|
+
record: { verbs: { eval: "formula.record" }, parts: NAMES, summary: "A record of the values of its fields." },
|
|
90
|
+
let: {
|
|
91
|
+
verbs: { eval: "formula.let" },
|
|
92
|
+
parts: closed({ bind: { shape: "map", item: BIND }, body: TERM }, ["bind", "body"]),
|
|
93
|
+
scope: [{ names: { keysAt: ["bind"] }, in: [["body"]] }],
|
|
94
|
+
summary: "Names for the body. A binding does not see the other bindings.",
|
|
95
|
+
},
|
|
96
|
+
fn: {
|
|
97
|
+
verbs: { eval: "vex.fn" },
|
|
98
|
+
parts: closed({ params: { shape: "list", item: { shape: "text" }, distinct: true }, body: TERM }, ["params", "body"]),
|
|
99
|
+
scope: [{ names: { listAt: ["params"] }, in: [["body"]] }],
|
|
100
|
+
summary: "A function of a let. Its body evaluates at the position of each call.",
|
|
101
|
+
},
|
|
102
|
+
call: { verbs: { eval: "vex.call" }, parts: closed({ fn: { shape: "term", kinds: [["ref"]] }, args: TERMS }, ["fn", "args"]), summary: "A call of a function of a let." },
|
|
103
|
+
each: { verbs: { eval: "vex.each" }, parts: closed({ axis: AXIS, body: TERM, at: ADDRESS }, ["axis", "body"]), summary: "The body at each target of an axis: a list." },
|
|
104
|
+
fold: {
|
|
105
|
+
verbs: { eval: "vex.fold" },
|
|
106
|
+
parts: closed({ axis: AXIS, init: NAMES, step: NAMES, result: TERM, at: ADDRESS }, ["axis", "init", "step", "result"]),
|
|
107
|
+
scope: LOOP_SCOPE,
|
|
108
|
+
summary: "A step at each target of an axis, in order, and a result.",
|
|
109
|
+
},
|
|
110
|
+
iterate: {
|
|
111
|
+
verbs: { eval: "vex.iterate" },
|
|
112
|
+
parts: closed({ limit: { shape: "number", whole: true, min: 0, max: MAX_ITERATIONS }, init: NAMES, step: NAMES, until: TERM, result: TERM }, ["limit", "init", "step", "result"]),
|
|
113
|
+
scope: LOOP_SCOPE,
|
|
114
|
+
summary: "Up to limit steps, until a test is true, and a result.",
|
|
115
|
+
},
|
|
116
|
+
ops: { kinds: {}, fallback: { verbs: { eval: "formula.op" }, parts: TERMS, summary: "An op, applied to the values of its arguments." } },
|
|
117
|
+
ext: { kinds: {}, fallback: { verbs: { eval: "formula.ext" }, summary: "An extension: its handler gives the value of its data." } },
|
|
118
|
+
axes: {
|
|
119
|
+
kinds: {
|
|
120
|
+
...Object.fromEntries(PLAIN_AXES.map((name) => [name, axisKind({})])),
|
|
121
|
+
neighbors: axisKind({ n: { shape: "one", values: [4, 8] } }),
|
|
122
|
+
window: axisKind({ from: { shape: "number" }, to: { shape: "number" } }),
|
|
123
|
+
table: axisKind({ name: { shape: "text" } }),
|
|
124
|
+
list: axisKind({ list: TERM }),
|
|
125
|
+
reverse: axisKind({ axis: { shape: "term", kinds: BASE_AXES.map((name) => ["axes", name]) } }),
|
|
126
|
+
where: axisKind({ axis: AXIS, test: TERM }),
|
|
127
|
+
},
|
|
128
|
+
},
|
|
129
|
+
moves: {
|
|
130
|
+
kinds: {
|
|
131
|
+
key: move("vex.move.key", TERM),
|
|
132
|
+
index: move("vex.move.index", TERM),
|
|
133
|
+
offset: move("vex.move.offset", { shape: "list", item: { shape: "number" } }),
|
|
134
|
+
other: move("vex.move.other", NO_VALUE),
|
|
135
|
+
origin: move("vex.move.origin", NO_VALUE),
|
|
136
|
+
parent: move("vex.move.parent", NO_VALUE),
|
|
137
|
+
},
|
|
138
|
+
},
|
|
139
|
+
},
|
|
140
|
+
defaults: {},
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* The world of Vex: the contract of each kind of a document of Vex, as data. A contract gives the shape of the parts,
|
|
146
|
+
* the data of the fields and the names that the kind binds. The static kit of the kernel reads it.
|
|
147
|
+
*/
|
|
148
|
+
export const VEX_WORLD: World = /* @__PURE__ */ worldOfVex();
|
|
149
|
+
|
|
150
|
+
/** The deepest nesting of documents that the machine takes. A deeper document gives `#DEPTH!` (DOC.ERROR). */
|
|
151
|
+
export const MAX_DOCUMENT_DEPTH = 4096;
|
|
152
|
+
|
|
153
|
+
// ---------------------------------------------------------------- errors
|
|
154
|
+
|
|
155
|
+
/** The kind of a Vex error for each code of the kernel. Another code is a document that is not valid. */
|
|
156
|
+
const KIND_OF: Readonly<Partial<Record<string, ErrorKind>>> = {
|
|
157
|
+
"#REF!": "unknown-key",
|
|
158
|
+
"#N/A": "missing-field",
|
|
159
|
+
"#VALUE!": "kind-mismatch",
|
|
160
|
+
"#NAME?": "unbound",
|
|
161
|
+
"#NUM!": "not-finite",
|
|
162
|
+
"#CALC!": "threw",
|
|
163
|
+
"#ARGS": "args",
|
|
164
|
+
"#CYCLE!": "cycle",
|
|
165
|
+
"#DEPTH!": "depth",
|
|
166
|
+
};
|
|
167
|
+
|
|
168
|
+
/** This function gives the error of the kernel for a Vex error. The Vex error is its cause, so no detail is lost. */
|
|
169
|
+
export const toKernelError = (e: VexError): EvalError => ({ code: e.code, reason: e.message, cause: e });
|
|
170
|
+
|
|
171
|
+
/** This function gives the Vex error of an error of the kernel. A code that Vex does not have gives `#VALUE!`. */
|
|
172
|
+
export function toVexError(e: EvalError): VexError {
|
|
173
|
+
if (isVexError(e.cause)) return e.cause;
|
|
174
|
+
return vexError(KIND_OF[e.code] ?? "bad-expression", e.reason, e.cause === undefined ? {} : { thrown: e.cause });
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** This function gives the Vex result of a result of the kernel. */
|
|
178
|
+
export const toVexResult = (r: Outcome): Result<unknown> => (r.ok ? vexOk(r.value) : vexFail(toVexError(r.error)));
|
|
179
|
+
|
|
180
|
+
/** This function makes an error of the kernel from a kind of Vex error. */
|
|
181
|
+
const kernelError = (kind: ErrorKind, message: string, details: ErrorDetails = {}): EvalError => toKernelError(vexError(kind, message, details));
|
|
182
|
+
|
|
183
|
+
/** This function makes a failed result of the kernel. */
|
|
184
|
+
const failed = (kind: ErrorKind, message: string): Failed => ({ ok: false, error: kernelError(kind, message) });
|
|
185
|
+
|
|
186
|
+
/** This function stops host code with an error of the kernel. The kernel catches the `Failure` and gives its error. */
|
|
187
|
+
const stop = (kind: ErrorKind, message: string): never => {
|
|
188
|
+
throw new Failure(kernelError(kind, message));
|
|
189
|
+
};
|
|
190
|
+
|
|
191
|
+
/** This function tells if an error is `#DEPTH!`. Some rules do not hide it (EVAL.DEPTH). */
|
|
192
|
+
const isDepth = (e: EvalError): boolean => e.code === ("#DEPTH!" satisfies ErrorCode);
|
|
193
|
+
|
|
194
|
+
// ---------------------------------------------------------------- the position
|
|
195
|
+
|
|
196
|
+
/** The segments that are not fields (REF.FORBIDDEN). */
|
|
197
|
+
const FORBIDDEN: ReadonlySet<string> = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* A position of an evaluation, as a host thing of the kernel: the space, the tables, the origin and the focus. It is the
|
|
201
|
+
* root `self` of the context. A move gives a new position, and a field step reads the record at the focus. A move that
|
|
202
|
+
* fails gives a position with the failure. The failure is the result when a reader uses the position, so the checks of
|
|
203
|
+
* the computed keys come first (NAV.COMPUTED).
|
|
204
|
+
*/
|
|
205
|
+
class Place implements HostThing {
|
|
206
|
+
// The constructor sets the brand. A computed field of the class makes a bundler keep the class in each program.
|
|
207
|
+
declare readonly [THING]: true;
|
|
208
|
+
readonly space: Space;
|
|
209
|
+
readonly tables: Readonly<Record<string, Space>>;
|
|
210
|
+
readonly origin: string;
|
|
211
|
+
readonly focus: string;
|
|
212
|
+
readonly failure: EvalError | undefined;
|
|
213
|
+
|
|
214
|
+
constructor(space: Space, tables: Readonly<Record<string, Space>>, origin: string, focus: string, failure?: EvalError) {
|
|
215
|
+
(this as { [THING]: true })[THING] = true;
|
|
216
|
+
this.space = space;
|
|
217
|
+
this.tables = tables;
|
|
218
|
+
this.origin = origin;
|
|
219
|
+
this.focus = focus;
|
|
220
|
+
this.failure = failure;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** The text of the position for a trace. */
|
|
224
|
+
get label(): string {
|
|
225
|
+
return `key ${this.focus}`;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** This method gives the position of a key of the same space, with the same origin. */
|
|
229
|
+
to(focus: string): Place {
|
|
230
|
+
return new Place(this.space, this.tables, this.origin, focus);
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/** This method gives the position with a failure, for a move that failed. */
|
|
234
|
+
failed(failure: EvalError): Place {
|
|
235
|
+
return new Place(this.space, this.tables, this.origin, this.focus, failure);
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/** This method reads one field of the record at the focus. */
|
|
239
|
+
deref(key: Key): unknown {
|
|
240
|
+
return this.resolve([key])?.thing;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* This method reads the fields of a path in the record at the focus (REF.PATH). A missing field, `null` and a segment
|
|
245
|
+
* that is not a field reach nothing, and the kernel gives `#N/A` (REF.MISSING, REF.FORBIDDEN). A getter that throws
|
|
246
|
+
* gives `#CALC!`, because the kernel catches the exception.
|
|
247
|
+
*/
|
|
248
|
+
resolve(keys: readonly Key[]): { readonly thing: unknown } | undefined {
|
|
249
|
+
if (this.failure !== undefined) throw new Failure(this.failure);
|
|
250
|
+
let value: unknown = this.space.get(this.focus);
|
|
251
|
+
if (value === undefined || value === null) return undefined;
|
|
252
|
+
for (const key of keys) {
|
|
253
|
+
const seg = String(key);
|
|
254
|
+
if ((typeof value !== "object" && typeof value !== "function") || seg === "" || FORBIDDEN.has(seg)) return undefined;
|
|
255
|
+
value = Reflect.get(value, seg);
|
|
256
|
+
if (value === undefined || value === null) return undefined;
|
|
257
|
+
}
|
|
258
|
+
return { thing: value };
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/** This method gives the record at the focus: the value of a reference without fields. */
|
|
262
|
+
toJson(): unknown {
|
|
263
|
+
if (this.failure !== undefined) throw new Failure(this.failure);
|
|
264
|
+
const record = this.space.get(this.focus);
|
|
265
|
+
return record === undefined || record === null ? stop("missing-field", `the record at "${this.focus}" has no value`) : record;
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/**
|
|
270
|
+
* This function gives the root `self` of an evaluation in the kernel. It is the position at the origin of a space,
|
|
271
|
+
* with the tables of the axis table (AXIS.TABLE).
|
|
272
|
+
*/
|
|
273
|
+
export function vexSelf(space: Space, origin: string, tables: Readonly<Record<string, Space>> = {}): HostThing {
|
|
274
|
+
return new Place(space, tables, origin, origin);
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/**
|
|
278
|
+
* This function gives the walker of a kind of move. `fix` gives the fixed move of the value of the step, or the reason
|
|
279
|
+
* why the value is not valid, which gives `#VALUE!` (NAV.COMPUTED).
|
|
280
|
+
*/
|
|
281
|
+
function moveWalker(fix: (data: unknown) => FixedMove | string): Walker {
|
|
282
|
+
return ({ data, here }) => {
|
|
283
|
+
if (!(here instanceof Place)) return { ok: false, reason: "a move starts at a key of a space", code: "#REF!" };
|
|
284
|
+
const fixed = fix(data);
|
|
285
|
+
if (typeof fixed === "string") return { ok: false, reason: fixed, code: "#VALUE!" };
|
|
286
|
+
// A move after a failed move keeps the first failure, as the address of the closure compiler does (NAV.SEQUENCE).
|
|
287
|
+
if (here.failure !== undefined) return { ok: true, thing: here };
|
|
288
|
+
const r = applyMove(here.space, here, fixed);
|
|
289
|
+
return { ok: true, thing: r.ok ? here.to(r.value) : here.failed(toKernelError(r.error)) };
|
|
290
|
+
};
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/** The walkers of the moves of Vex. */
|
|
294
|
+
const WALKERS: Readonly<Record<string, Walker>> = {
|
|
295
|
+
"vex.move.key": /* @__PURE__ */ moveWalker((d) => (typeof d === "string" ? { t: "key", key: d } : `the key of a move is a ${typeof d}, not a text`)),
|
|
296
|
+
"vex.move.index": /* @__PURE__ */ moveWalker((d) => (typeof d === "number" ? { t: "index", i: d } : `the position of a move is a ${typeof d}, not a number`)),
|
|
297
|
+
"vex.move.offset": /* @__PURE__ */ moveWalker((d) => ({ t: "offset", d: d as readonly number[] })),
|
|
298
|
+
"vex.move.other": /* @__PURE__ */ moveWalker(() => ({ t: "other" })),
|
|
299
|
+
"vex.move.origin": /* @__PURE__ */ moveWalker(() => ({ t: "origin" })),
|
|
300
|
+
"vex.move.parent": /* @__PURE__ */ moveWalker(() => ({ t: "parent" })),
|
|
301
|
+
};
|
|
302
|
+
|
|
303
|
+
// ---------------------------------------------------------------- the axes and the loops
|
|
304
|
+
|
|
305
|
+
/*
|
|
306
|
+
* The evaluators of Vex are functions of their input, not compilers. Thus a plan of the kernel and the reference
|
|
307
|
+
* interpreter of the kernel use the same code for them, and the reference needs a definition only for the formula kit
|
|
308
|
+
* (`vexDefinitions`).
|
|
309
|
+
*/
|
|
310
|
+
|
|
311
|
+
/** A target of an axis: its key, or its key and an error (AXIS.WHERE, AXIS.LIST). */
|
|
312
|
+
interface Target {
|
|
313
|
+
readonly key: string;
|
|
314
|
+
readonly error?: VexError;
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/** The value of an axis document: the targets from a position. `table` names the table of the axis table. */
|
|
318
|
+
interface Targets {
|
|
319
|
+
readonly table: string | undefined;
|
|
320
|
+
targets(from: Place): Outcome<readonly Target[]>;
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
/** This function gives the position of a target. In the space of the axis table, the origin is the target (AXIS.TABLE). */
|
|
324
|
+
const placeOf = (axis: Targets, from: Place, key: string): Place => (axis.table === undefined ? from.to(key) : new Place(from.space, from.tables, key, key));
|
|
325
|
+
|
|
326
|
+
/** This function gives the parts of a record value, by name. */
|
|
327
|
+
const partsOf = (value: unknown): Readonly<Record<string, Part | undefined>> => (value ?? {}) as Readonly<Record<string, Part | undefined>>;
|
|
328
|
+
|
|
329
|
+
/** This function gives the part of a field that the contract makes necessary. */
|
|
330
|
+
const partAt = (value: unknown, name: string): Part => partsOf(value)[name] as Part;
|
|
331
|
+
|
|
332
|
+
/** This function gives the position of a context. A context without a position gives an error. */
|
|
333
|
+
function selfOf(ctx: Context): Place | EvalError {
|
|
334
|
+
return ctx.self instanceof Place ? ctx.self : kernelError("unknown-key", "the context has no key of a space");
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
/** This function gives the position where an axis finds its targets: the key of the address, or the focus (AXIS.ADDRESS). */
|
|
338
|
+
function startOf(at: Part | undefined, ctx: Context): Place | EvalError {
|
|
339
|
+
if (at === undefined) return selfOf(ctx);
|
|
340
|
+
const r = at.evaluate();
|
|
341
|
+
if (!r.ok) return r.error;
|
|
342
|
+
const where = r.value as Place;
|
|
343
|
+
return where.failure ?? where;
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/** This function gives the position in the space of the axis: the space of its table for the axis table (AXIS.TABLE). */
|
|
347
|
+
function spaceOf(axis: Targets, from: Place): Place | EvalError {
|
|
348
|
+
if (axis.table === undefined) return from;
|
|
349
|
+
const space = Object.hasOwn(from.tables, axis.table) ? from.tables[axis.table] : undefined;
|
|
350
|
+
return space === undefined ? kernelError("no-table", `the evaluation has no table "${axis.table}"`) : new Place(space, from.tables, from.origin, from.focus);
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
/**
|
|
354
|
+
* This function is the evaluator of the axes. An axis document gives a value that finds the targets from a position.
|
|
355
|
+
* The list of `list` evaluates at that position, and the test of `where` at each target (AXIS.LIST, AXIS.WHERE).
|
|
356
|
+
*/
|
|
357
|
+
const axisEvaluator: EvalFn = ({ typePath, value, context }) => {
|
|
358
|
+
const name = String(typePath[1]);
|
|
359
|
+
const fields = partsOf(value);
|
|
360
|
+
if (name === "table") {
|
|
361
|
+
const table = (value as { readonly name: string }).name;
|
|
362
|
+
return ok<Targets>({ table, targets: (from) => ok(from.space.keys.map((key) => ({ key }))) });
|
|
363
|
+
}
|
|
364
|
+
if (name === "list") {
|
|
365
|
+
const list = fields["list"] as Part;
|
|
366
|
+
return ok<Targets>({
|
|
367
|
+
table: undefined,
|
|
368
|
+
targets: (from) => {
|
|
369
|
+
const r = list.evaluate({ ...context, self: from });
|
|
370
|
+
if (!r.ok) return r;
|
|
371
|
+
if (!isVexList(r.value)) return failed("kind-mismatch", `the axis "list" needs a list, not a ${describe(r.value)}`);
|
|
372
|
+
return ok(r.value.items.map(({ key, result }) => (result.ok ? { key } : { key, error: result.error })));
|
|
373
|
+
},
|
|
374
|
+
});
|
|
375
|
+
}
|
|
376
|
+
if (name === "reverse" || name === "where") {
|
|
377
|
+
const r = (fields["axis"] as Part).evaluate();
|
|
378
|
+
// Stryker disable next-line ConditionalExpression: an axis document fails only when the call stack of the engine is full
|
|
379
|
+
if (!r.ok) return r;
|
|
380
|
+
const base = r.value as Targets;
|
|
381
|
+
const test = fields["test"];
|
|
382
|
+
if (test === undefined) {
|
|
383
|
+
return ok<Targets>({
|
|
384
|
+
table: base.table,
|
|
385
|
+
targets: (from) => {
|
|
386
|
+
const ts = base.targets(from);
|
|
387
|
+
return ts.ok ? ok(ts.value.toReversed()) : ts;
|
|
388
|
+
},
|
|
389
|
+
});
|
|
390
|
+
}
|
|
391
|
+
return ok<Targets>({ table: base.table, targets: (from) => whereTargets(base, test, context, from) });
|
|
392
|
+
}
|
|
393
|
+
const ir = { t: name, ...(value as object) } as Exclude<Axis, { readonly t: "where" }>;
|
|
394
|
+
return ok<Targets>({
|
|
395
|
+
table: undefined,
|
|
396
|
+
targets: (from) => {
|
|
397
|
+
const keys = axisTargets(from.space, from, ir);
|
|
398
|
+
return keys.ok ? ok(keys.value.map((key) => ({ key }))) : { ok: false, error: toKernelError(keys.error) };
|
|
399
|
+
},
|
|
400
|
+
});
|
|
401
|
+
};
|
|
402
|
+
|
|
403
|
+
/** This function keeps the targets where the test gives `true`. A failed test, or a value that is not a boolean, gives an error item. */
|
|
404
|
+
function whereTargets(base: Targets, test: Part, ctx: Context, from: Place): Outcome<readonly Target[]> {
|
|
405
|
+
const ts = base.targets(from);
|
|
406
|
+
if (!ts.ok) return ts;
|
|
407
|
+
const out: Target[] = [];
|
|
408
|
+
for (const t of ts.value) {
|
|
409
|
+
if (t.error !== undefined) {
|
|
410
|
+
out.push(t);
|
|
411
|
+
continue;
|
|
412
|
+
}
|
|
413
|
+
const r = test.evaluate({ ...ctx, self: placeOf(base, from, t.key) });
|
|
414
|
+
if (!r.ok) out.push({ key: t.key, error: toVexError(r.error) });
|
|
415
|
+
else if (r.value === true) out.push({ key: t.key });
|
|
416
|
+
else if (r.value !== false) out.push({ key: t.key, error: vexError("kind-mismatch", `the test of "where" gave a ${typeof r.value}, not a boolean`) });
|
|
417
|
+
}
|
|
418
|
+
return ok(out);
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
/** This function finds the targets of the axis of a loop, from the address or the focus, in the space of the axis. */
|
|
422
|
+
function targetsOf(value: unknown, ctx: Context): Outcome<{ readonly axis: Targets; readonly from: Place; readonly targets: readonly Target[] }> {
|
|
423
|
+
const start = startOf(partsOf(value)["at"], ctx);
|
|
424
|
+
if (!(start instanceof Place)) return { ok: false, error: start };
|
|
425
|
+
const a = partAt(value, "axis").evaluate();
|
|
426
|
+
// Stryker disable next-line ConditionalExpression: an axis document fails only when the call stack of the engine is full
|
|
427
|
+
if (!a.ok) return a;
|
|
428
|
+
const axis = a.value as Targets;
|
|
429
|
+
const from = spaceOf(axis, start);
|
|
430
|
+
if (!(from instanceof Place)) return { ok: false, error: from };
|
|
431
|
+
const ts = axis.targets(from);
|
|
432
|
+
return ts.ok ? ok({ axis, from, targets: ts.value }) : ts;
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
/**
|
|
436
|
+
* This function sets a name of a new record of names, also the name `__proto__`. The record is new and gets each
|
|
437
|
+
* name one time, so the property needs no other attributes. A later record copies it with a spread, so it is enumerable.
|
|
438
|
+
*/
|
|
439
|
+
function setName(names: Record<string, unknown>, name: string, value: unknown): void {
|
|
440
|
+
Object.defineProperty(names, name, { value, enumerable: true });
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
/**
|
|
444
|
+
* This function evaluates the parts of a record of names in order (LOOP.NAMES). It gives the names with their new
|
|
445
|
+
* values, or the first error. Each value reads the names before the step, so the names change only after all values.
|
|
446
|
+
*/
|
|
447
|
+
function bindAll(record: Part | undefined, ctx: Context, names: Readonly<Record<string, unknown>>): Outcome<Readonly<Record<string, unknown>>> {
|
|
448
|
+
const values: [string, unknown][] = [];
|
|
449
|
+
for (const [name, part] of Object.entries(partsOf(record))) {
|
|
450
|
+
const r = (part as Part).evaluate(ctx);
|
|
451
|
+
if (!r.ok) return r;
|
|
452
|
+
values.push([name, r.value]);
|
|
453
|
+
}
|
|
454
|
+
const out: Record<string, unknown> = { ...names };
|
|
455
|
+
for (const [name, v] of values) setName(out, name, v);
|
|
456
|
+
return ok(out);
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
/** The evaluators of the loops: each, fold and iterate (LOOP.NAMES, FOLD.ORDER, ITERATE.LIMIT). */
|
|
460
|
+
const LOOPS: Readonly<Record<string, EvalFn>> = {
|
|
461
|
+
"vex.each": ({ value, context }) => {
|
|
462
|
+
const found = targetsOf(value, context);
|
|
463
|
+
if (!found.ok) return found;
|
|
464
|
+
const { axis, from, targets } = found.value;
|
|
465
|
+
const body = partAt(value, "body");
|
|
466
|
+
const items: ListItem[] = targets.map(({ key, error }) => ({ key, result: error === undefined ? toVexResult(body.evaluate({ ...context, self: placeOf(axis, from, key) })) : vexFail(error) }));
|
|
467
|
+
return ok(vexList(items));
|
|
468
|
+
},
|
|
469
|
+
|
|
470
|
+
"vex.fold": ({ value, context }) => {
|
|
471
|
+
const { init, step } = partsOf(value);
|
|
472
|
+
// The first values come at the node, before the address and the targets (FOLD.ORDER).
|
|
473
|
+
const first = bindAll(init, context, context.names);
|
|
474
|
+
if (!first.ok) return first;
|
|
475
|
+
let names = first.value;
|
|
476
|
+
const found = targetsOf(value, context);
|
|
477
|
+
if (!found.ok) return found;
|
|
478
|
+
const { axis, from, targets } = found.value;
|
|
479
|
+
for (const { key, error } of targets) {
|
|
480
|
+
if (error !== undefined) return { ok: false, error: toKernelError(error) };
|
|
481
|
+
const next = bindAll(step, { ...context, self: placeOf(axis, from, key), names }, names);
|
|
482
|
+
if (!next.ok) return next;
|
|
483
|
+
names = next.value;
|
|
484
|
+
}
|
|
485
|
+
return partAt(value, "result").evaluate({ ...context, names });
|
|
486
|
+
},
|
|
487
|
+
|
|
488
|
+
"vex.iterate": ({ value, context }) => {
|
|
489
|
+
const { init, step, until } = partsOf(value);
|
|
490
|
+
const limit = (value as { readonly limit: number }).limit;
|
|
491
|
+
const first = bindAll(init, context, context.names);
|
|
492
|
+
if (!first.ok) return first;
|
|
493
|
+
let names = first.value;
|
|
494
|
+
for (let k = 0; ; k++) {
|
|
495
|
+
const here: Context = { ...context, names };
|
|
496
|
+
if (until !== undefined) {
|
|
497
|
+
const t = until.evaluate(here);
|
|
498
|
+
if (!t.ok) return t;
|
|
499
|
+
if (t.value === true) break;
|
|
500
|
+
if (t.value !== false) return failed("kind-mismatch", `the test "until" of "iterate" gave a ${typeof t.value}, not a boolean`);
|
|
501
|
+
}
|
|
502
|
+
if (k === limit) {
|
|
503
|
+
if (until !== undefined) return failed("limit", `"iterate" made its ${String(limit)} steps, and its test "until" is not true`);
|
|
504
|
+
break;
|
|
505
|
+
}
|
|
506
|
+
const next = bindAll(step, here, names);
|
|
507
|
+
if (!next.ok) return next;
|
|
508
|
+
names = next.value;
|
|
509
|
+
}
|
|
510
|
+
return partAt(value, "result").evaluate({ ...context, names });
|
|
511
|
+
},
|
|
512
|
+
};
|
|
513
|
+
|
|
514
|
+
// ---------------------------------------------------------------- functions
|
|
515
|
+
|
|
516
|
+
/**
|
|
517
|
+
* A function of a `let` (FN.BIND). A reference to its name is an error, because a function is not a value (FN.VALUE).
|
|
518
|
+
* It keeps the names of the place of its binding, and its body evaluates at the position of each call (FN.CALL).
|
|
519
|
+
*/
|
|
520
|
+
class Bound extends Held {
|
|
521
|
+
readonly params: readonly string[];
|
|
522
|
+
readonly body: Part;
|
|
523
|
+
readonly names: Readonly<Record<string, unknown>>;
|
|
524
|
+
|
|
525
|
+
constructor(params: readonly string[], body: Part, names: Readonly<Record<string, unknown>>) {
|
|
526
|
+
super(kernelError("kind-mismatch", "the name is a function, not a value"));
|
|
527
|
+
this.params = params;
|
|
528
|
+
this.body = body;
|
|
529
|
+
this.names = names;
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
/** The evaluators of the functions of Vex (FN.BIND, FN.CALL, FN.ARGS). */
|
|
534
|
+
const FUNCTIONS: Readonly<Record<string, EvalFn>> = {
|
|
535
|
+
"vex.fn": ({ value, context }) => ok(new Bound((value as { readonly params: readonly string[] }).params, partAt(value, "body"), context.names)),
|
|
536
|
+
|
|
537
|
+
"vex.call": ({ doc, value, context }) => {
|
|
538
|
+
// The contract and fromDocument make the function a reference to a name: ["names", name] (DOC.CALL).
|
|
539
|
+
const name = String((doc.value as { readonly fn: { readonly value: readonly unknown[] } }).fn.value[1]);
|
|
540
|
+
const args = partsOf(value)["args"] as unknown as readonly Part[];
|
|
541
|
+
if (!Object.hasOwn(context.names, name)) return failed("unbound", `the function "${name}" has no binding`);
|
|
542
|
+
const bound = context.names[name];
|
|
543
|
+
if (!(bound instanceof Bound)) return bound instanceof Held ? { ok: false, error: bound.error } : failed("kind-mismatch", `the name "${name}" is a value, not a function`);
|
|
544
|
+
if (bound.params.length !== args.length) return failed("bad-expression", `the function "${name}" takes ${String(bound.params.length)} arguments, not ${String(args.length)}`);
|
|
545
|
+
// Each parameter gets the result of its argument at the call. An error has an effect only where the body reads it.
|
|
546
|
+
const names: Record<string, unknown> = { ...bound.names };
|
|
547
|
+
bound.params.forEach((p, i) => {
|
|
548
|
+
const r = (args[i] as Part).evaluate();
|
|
549
|
+
setName(names, p, r.ok ? r.value : new Held(r.error));
|
|
550
|
+
});
|
|
551
|
+
return bound.body.evaluate({ ...context, names });
|
|
552
|
+
},
|
|
553
|
+
};
|
|
554
|
+
|
|
555
|
+
// ---------------------------------------------------------------- ops
|
|
556
|
+
|
|
557
|
+
/** This function gives a short name for the type of a value, for a message. */
|
|
558
|
+
function describe(u: unknown): string {
|
|
559
|
+
if (u === null) return "null";
|
|
560
|
+
if (Array.isArray(u)) return "array";
|
|
561
|
+
if (isVexList(u)) return "list";
|
|
562
|
+
return typeof u;
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
/** This function applies the test of a domain to a value. A test that throws rejects the value. */
|
|
566
|
+
function accepts(d: AnyDomain, x: unknown): boolean {
|
|
567
|
+
let accepted = false;
|
|
568
|
+
try {
|
|
569
|
+
accepted = d.is(x);
|
|
570
|
+
} catch {
|
|
571
|
+
// The value stays rejected.
|
|
572
|
+
}
|
|
573
|
+
return accepted;
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
/** This function finds an own method of a receiver or of its prototypes, but not of `Object` or `Function` (CALL.METHOD). */
|
|
577
|
+
function methodOf(self: unknown, name: string): ((...a: unknown[]) => unknown) | undefined {
|
|
578
|
+
// The loop stops at null, so a null receiver gives undefined too.
|
|
579
|
+
if (FORBIDDEN.has(name) || (typeof self !== "object" && typeof self !== "function")) return undefined;
|
|
580
|
+
for (let o: object | null = self; o !== null && o !== Object.prototype && o !== Function.prototype; o = Object.getPrototypeOf(o) as object | null) {
|
|
581
|
+
const d = Object.getOwnPropertyDescriptor(o, name);
|
|
582
|
+
if (d !== undefined) return typeof d.value === "function" ? (d.value as (...a: unknown[]) => unknown) : undefined;
|
|
583
|
+
}
|
|
584
|
+
return undefined;
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
/** This function checks the value of an op (CALL.RESULT): a value, a finite number, and a valid value of its domain. */
|
|
588
|
+
function checked(x: unknown, op: string, domains: readonly AnyDomain[]): unknown {
|
|
589
|
+
if (x === undefined || x === null) return stop("undefined-result", `"${op}" gave no value`);
|
|
590
|
+
if (typeof x === "number" && !Number.isFinite(x)) return stop("not-finite", `"${op}" gave ${String(x)}`);
|
|
591
|
+
const d = domains.find((dom) => accepts(dom, x));
|
|
592
|
+
if (d?.valid !== undefined && !d.valid(x)) return stop("invalid-value", `"${op}" gave a value that is not a valid ${d.name}`);
|
|
593
|
+
return x;
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
/** The op of a domain for a receiver: its spec, and the method of the receiver for an op without `fn`. */
|
|
597
|
+
interface Found {
|
|
598
|
+
readonly domain: AnyDomain;
|
|
599
|
+
readonly spec: { readonly fn?: (...a: unknown[]) => unknown; readonly liftScalar?: boolean | readonly boolean[]; readonly params?: readonly string[] } | undefined;
|
|
600
|
+
readonly method: ((...a: unknown[]) => unknown) | undefined;
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
/** This function finds the op of a domain for a receiver, or `undefined` (CALL.UNKNOWN-OP). */
|
|
604
|
+
function opOf(d: AnyDomain, self: unknown, op: string): Found | undefined {
|
|
605
|
+
const spec = Object.hasOwn(d.ops, op) && !FORBIDDEN.has(op) ? (d.ops[op] as Found["spec"]) : undefined;
|
|
606
|
+
// An op with a function does not use the method, so the search of the method only adds work there.
|
|
607
|
+
const method = spec !== undefined || d.methods === "all" ? methodOf(self, op) : undefined;
|
|
608
|
+
return spec?.fn === undefined && method === undefined ? undefined : { domain: d, spec, method };
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
/** This function applies the op of a domain: it lifts the numbers, checks the kinds of the arguments and checks the value. */
|
|
612
|
+
function callFound(found: Found, op: string, self: unknown, args: readonly unknown[], domains: readonly AnyDomain[]): unknown {
|
|
613
|
+
const { domain, spec } = found;
|
|
614
|
+
const lift = spec?.liftScalar;
|
|
615
|
+
const from = domain.fromScalar;
|
|
616
|
+
const rest = from === undefined ? args : args.map((a, i): unknown => (typeof a === "number" && (lift === true || (Array.isArray(lift) && lift[i] === true)) ? from(a) : a));
|
|
617
|
+
const params = spec?.params;
|
|
618
|
+
if (params !== undefined) {
|
|
619
|
+
rest.forEach((a, i) => {
|
|
620
|
+
const k = params[i] ?? "any";
|
|
621
|
+
if (k !== "any" && !(k === "domain" ? accepts(domain, a) : typeof a === k)) {
|
|
622
|
+
stop(k === "domain" ? "not-instance" : "kind-mismatch", `argument ${String(i + 1)} of "${op}" is a ${describe(a)}, not a ${k === "domain" ? domain.name : k}`);
|
|
623
|
+
}
|
|
624
|
+
});
|
|
625
|
+
}
|
|
626
|
+
const out = spec?.fn !== undefined ? spec.fn(self, ...rest) : (found.method as (...a: unknown[]) => unknown).call(self, ...rest);
|
|
627
|
+
return checked(out, op, domains);
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
/** The list ops with a second argument before their options: a count, a position, an op name or a list. */
|
|
631
|
+
const WITH_ARGUMENT: ReadonlySet<string> = /* @__PURE__ */ new Set(["reduce", "take", "nth", "drop", "append", "without"]);
|
|
632
|
+
|
|
633
|
+
/**
|
|
634
|
+
* This function gives the items of a list that have a value (LIST.LENIENT). A list op does not skip `#DEPTH!`, so that
|
|
635
|
+
* error comes first (EVAL.DEPTH). With `strict`, the first error item is the result.
|
|
636
|
+
*/
|
|
637
|
+
function goodOf(items: readonly ListItem[], strict: boolean): readonly ListItem[] {
|
|
638
|
+
const depth = items.find((it) => !it.result.ok && it.result.error.code === "#DEPTH!");
|
|
639
|
+
if (depth !== undefined && !depth.result.ok) throw new Failure(toKernelError(depth.result.error));
|
|
640
|
+
const firstBad = items.find((it) => !it.result.ok);
|
|
641
|
+
if (strict && firstBad !== undefined && !firstBad.result.ok) throw new Failure(toKernelError(firstBad.result.error));
|
|
642
|
+
return items.filter((it) => it.result.ok);
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
/** This function gives the items of the list `other` of `append` and `without` (LIST.BUILD). Another value gives `#VALUE!`. */
|
|
646
|
+
function otherOf(op: string, other: unknown, strict: boolean): readonly ListItem[] {
|
|
647
|
+
return isVexList(other) ? goodOf(other.items, strict) : stop("kind-mismatch", `"${op}" needs a list as its second argument, not a ${describe(other)}`);
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
/** This function joins the lists that are the values of the items, in order (LIST.FLAT). Each list follows LIST.BUILD. */
|
|
651
|
+
function flat(vs: readonly unknown[], strict: boolean): unknown {
|
|
652
|
+
const out: ListItem[] = [];
|
|
653
|
+
for (const inner of vs) {
|
|
654
|
+
if (!isVexList(inner)) return stop("kind-mismatch", `"flat" needs a list as the value of each item, but an item is a ${describe(inner)}`);
|
|
655
|
+
out.push(...goodOf(inner.items, strict));
|
|
656
|
+
}
|
|
657
|
+
return vexList(out);
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
/** This function applies a list op (LIST.*). The error items are skipped, except with `{ strict: true }`, and except `#DEPTH!`. */
|
|
661
|
+
function listOp(op: string, items: readonly ListItem[], rest: readonly unknown[], domains: readonly AnyDomain[]): unknown {
|
|
662
|
+
const o = WITH_ARGUMENT.has(op) ? rest[1] : rest[0];
|
|
663
|
+
const strict = (o as { strict?: unknown } | null | undefined)?.strict === true;
|
|
664
|
+
const good = goodOf(items, strict);
|
|
665
|
+
const vs = good.map((it) => (it.result.ok ? it.result.value : undefined));
|
|
666
|
+
const nums = (): readonly number[] => (vs.every((x) => typeof x === "number") ? vs : stop("kind-mismatch", `"${op}" needs numbers`));
|
|
667
|
+
const bools = (): readonly boolean[] => (vs.every((x) => typeof x === "boolean") ? vs : stop("kind-mismatch", `"${op}" needs booleans`));
|
|
668
|
+
const empty = (): never => stop("empty", `"${op}" has no values to work with`);
|
|
669
|
+
switch (op) {
|
|
670
|
+
case "count":
|
|
671
|
+
return vs.length;
|
|
672
|
+
case "values":
|
|
673
|
+
return Object.freeze([...vs]);
|
|
674
|
+
case "keys":
|
|
675
|
+
return Object.freeze(good.map((it) => it.key));
|
|
676
|
+
case "errors":
|
|
677
|
+
return Object.freeze(items.flatMap((it) => (it.result.ok ? [] : [it.result.error])));
|
|
678
|
+
case "first":
|
|
679
|
+
return vs.length > 0 ? vs[0] : empty();
|
|
680
|
+
case "sortBy": {
|
|
681
|
+
const kind = typeof vs[0];
|
|
682
|
+
if (vs.some((x) => typeof x !== kind || (kind !== "number" && kind !== "string") || Number.isNaN(x))) stop("kind-mismatch", '"sortBy" needs numbers without NaN or texts, all of one kind');
|
|
683
|
+
return vexList(good.map((it, i) => ({ it, i })).toSorted((a, b) => compare(vs[a.i], vs[b.i])).map(({ it }) => it));
|
|
684
|
+
}
|
|
685
|
+
case "take":
|
|
686
|
+
case "drop":
|
|
687
|
+
case "nth": {
|
|
688
|
+
const n = rest[0] as number;
|
|
689
|
+
if (!Number.isSafeInteger(n) || n < 0) return stop("kind-mismatch", `"${op}" needs a whole number from 0`);
|
|
690
|
+
if (op === "take") return vexList(good.slice(0, n));
|
|
691
|
+
if (op === "drop") return vexList(good.slice(n));
|
|
692
|
+
return n < vs.length ? vs[n] : stop("empty", `"nth" has no item at the position ${String(n)}`);
|
|
693
|
+
}
|
|
694
|
+
case "append":
|
|
695
|
+
return vexList([...good, ...otherOf(op, rest[0], strict)]);
|
|
696
|
+
case "without": {
|
|
697
|
+
const gone = new Set(otherOf(op, rest[0], strict).map((it) => it.key));
|
|
698
|
+
return vexList(good.filter((it) => !gone.has(it.key)));
|
|
699
|
+
}
|
|
700
|
+
case "flat":
|
|
701
|
+
return flat(vs, strict);
|
|
702
|
+
case "sum":
|
|
703
|
+
// Stryker disable next-line ArrayDeclaration: a sum needs no domain, and a text in the list accepts no value
|
|
704
|
+
return checked(nums().reduce((s, x) => s + x, 0), op, []);
|
|
705
|
+
case "mean": {
|
|
706
|
+
const n = nums();
|
|
707
|
+
// Stryker disable next-line ArrayDeclaration: a mean needs no domain, and a text in the list accepts no value
|
|
708
|
+
return n.length === 0 ? empty() : checked(n.reduce((s, x) => s + x, 0) / n.length, op, []);
|
|
709
|
+
}
|
|
710
|
+
case "min":
|
|
711
|
+
case "max": {
|
|
712
|
+
const n = nums();
|
|
713
|
+
return n.length === 0 ? empty() : n.reduce((best, x) => (op === "min" ? Math.min(best, x) : Math.max(best, x)));
|
|
714
|
+
}
|
|
715
|
+
case "any":
|
|
716
|
+
return bools().some(Boolean);
|
|
717
|
+
case "all":
|
|
718
|
+
return bools().every(Boolean);
|
|
719
|
+
case "none":
|
|
720
|
+
return !bools().some(Boolean);
|
|
721
|
+
default:
|
|
722
|
+
return reduce(rest[0], vs, o, domains);
|
|
723
|
+
}
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
/** This function compares two numbers or two texts for `sortBy`. Equal values keep their order (LIST.SORT). */
|
|
727
|
+
const compare = (a: unknown, b: unknown): number => ((a as number) < (b as number) ? -1 : (a as number) > (b as number) ? 1 : 0);
|
|
728
|
+
|
|
729
|
+
/** This function folds the values of a list with a domain op, from the left (LIST.REDUCE, LIST.REDUCE.EMPTY). */
|
|
730
|
+
function reduce(name: unknown, vs: readonly unknown[], o: unknown, domains: readonly AnyDomain[]): unknown {
|
|
731
|
+
if (typeof name !== "string") return stop("kind-mismatch", '"reduce" needs an op name');
|
|
732
|
+
if (vs.length === 0) {
|
|
733
|
+
const named = (o as { domain?: unknown } | null | undefined)?.domain;
|
|
734
|
+
if (named !== undefined && !domains.some((d) => d.name === named)) return stop("unknown-op", `"reduce" names the domain ${JSON.stringify(named) ?? "?"}, but the program has no such domain`);
|
|
735
|
+
const ds = domains.filter((d) => Object.hasOwn(d.ops, name) && (d.ops[name] as { identity?: unknown }).identity !== undefined && (named === undefined || d.name === named));
|
|
736
|
+
const only = ds.length === 1 ? (ds[0]?.ops[name] as { identity: () => unknown }) : undefined;
|
|
737
|
+
return only === undefined ? stop("empty", `"reduce" with "${name}" has no values, and no one identity`) : only.identity();
|
|
738
|
+
}
|
|
739
|
+
let acc: unknown = vs[0];
|
|
740
|
+
for (const x of vs.slice(1)) {
|
|
741
|
+
const found = domains.filter((d) => accepts(d, acc)).map((d) => opOf(d, acc, name)).find((f) => f !== undefined);
|
|
742
|
+
if (found === undefined) return stop("unknown-op", `no domain gives "${name}" for a ${describe(acc)}`);
|
|
743
|
+
acc = callFound(found, name, acc, [x], domains);
|
|
744
|
+
}
|
|
745
|
+
return acc;
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
/**
|
|
749
|
+
* This function gives the op of a name: the dispatch of Vex at run time. A list op applies to a list. Else the first
|
|
750
|
+
* domain that accepts the receiver and has the op applies it. Else a free function applies (CALL.FREE).
|
|
751
|
+
*/
|
|
752
|
+
function dispatch(op: string, domains: readonly AnyDomain[], fns: Readonly<Record<string, (...a: readonly unknown[]) => unknown>>): (...values: unknown[]) => unknown {
|
|
753
|
+
const free = Object.hasOwn(fns, op) ? fns[op] : undefined;
|
|
754
|
+
const listed = LIST_OPS.has(op);
|
|
755
|
+
return (...values) => {
|
|
756
|
+
const self = values[0];
|
|
757
|
+
if (listed && isVexList(self)) return listOp(op, self.items, values.slice(1), domains);
|
|
758
|
+
let accepted = false;
|
|
759
|
+
if (values.length > 0) {
|
|
760
|
+
for (const d of domains) {
|
|
761
|
+
if (!accepts(d, self)) continue;
|
|
762
|
+
accepted = true;
|
|
763
|
+
const found = opOf(d, self, op);
|
|
764
|
+
if (found !== undefined) return callFound(found, op, self, values.slice(1), domains);
|
|
765
|
+
}
|
|
766
|
+
}
|
|
767
|
+
if (free !== undefined) return checked(free(...values), op, domains);
|
|
768
|
+
if (accepted || values.length === 0) return stop("unknown-op", accepted ? `the domain of the receiver has no op "${op}"` : `there is no function "${op}"`);
|
|
769
|
+
return stop("not-instance", `no domain accepts the receiver of "${op}" (${describe(self)})`);
|
|
770
|
+
};
|
|
771
|
+
}
|
|
772
|
+
|
|
773
|
+
/** This function gives an argument of a special form. A missing argument gives `#VALUE!`. */
|
|
774
|
+
const argOf = (args: readonly (() => Outcome)[], i: number, op: string): Outcome => args[i]?.() ?? failed("bad-expression", `"${op}" needs argument ${String(i + 1)}`);
|
|
775
|
+
|
|
776
|
+
/** This function gives an argument of a special form that must be a boolean (FORM.IF, FORM.AND-OR). */
|
|
777
|
+
function boolOf(args: readonly (() => Outcome)[], i: number, op: string): Outcome {
|
|
778
|
+
const r = argOf(args, i, op);
|
|
779
|
+
return !r.ok || typeof r.value === "boolean" ? r : failed("kind-mismatch", `argument ${String(i + 1)} of "${op}" is a ${describe(r.value)}, not a boolean`);
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
/** This function gives `and` or `or`: they stop at the first argument that decides (FORM.AND-OR). */
|
|
783
|
+
const logic = (op: "and" | "or"): LazyOp => (args) => {
|
|
784
|
+
if (args.length === 0) return failed("bad-expression", `"${op}" needs at least 1 argument`);
|
|
785
|
+
for (let i = 0; i < args.length; i++) {
|
|
786
|
+
const b = boolOf(args, i, op);
|
|
787
|
+
if (!b.ok || b.value === (op === "or")) return b;
|
|
788
|
+
}
|
|
789
|
+
return ok(op === "and");
|
|
790
|
+
};
|
|
791
|
+
|
|
792
|
+
/** The special forms of Vex: lazy ops of the formula kit (FORM.IF, FORM.AND-OR, FORM.IFERROR). */
|
|
793
|
+
const FORMS: Readonly<Record<string, LazyOp>> = {
|
|
794
|
+
if: (args) => {
|
|
795
|
+
const c = boolOf(args, 0, "if");
|
|
796
|
+
return c.ok ? argOf(args, c.value === true ? 1 : 2, "if") : c;
|
|
797
|
+
},
|
|
798
|
+
and: /* @__PURE__ */ logic("and"),
|
|
799
|
+
or: /* @__PURE__ */ logic("or"),
|
|
800
|
+
// EVAL.DEPTH: ifError does not hide #DEPTH!, because the engine failed, not the data.
|
|
801
|
+
ifError: (args) => {
|
|
802
|
+
// Stryker disable next-line StringLiteral: ifError replaces the error of a missing first argument, so no one sees this name
|
|
803
|
+
const first = argOf(args, 0, "ifError");
|
|
804
|
+
return first.ok || isDepth(first.error) ? first : argOf(args, 1, "ifError");
|
|
805
|
+
},
|
|
806
|
+
};
|
|
807
|
+
|
|
808
|
+
/**
|
|
809
|
+
* This function gives the profile of Vex for the formula kit: the dispatch of the ops, the special forms and the
|
|
810
|
+
* extensions. Two or more failed arguments or fields give `#ARGS` (CALL.ARGS, REC.FIELDS).
|
|
811
|
+
*/
|
|
812
|
+
function profileOf(opts: CompileOptions): FormulaProfile {
|
|
813
|
+
// Stryker disable next-line ArrayDeclaration: a list with a value that is not a domain matches no value
|
|
814
|
+
const domains = opts.domains ?? [];
|
|
815
|
+
const fns = opts.fns ?? {};
|
|
816
|
+
const extensions = opts.extensions ?? {};
|
|
817
|
+
// Vex has no standard extension: each extension kind needs its handler, so the standard names give #NAME? too.
|
|
818
|
+
// A record without a prototype, so an extension kind such as `__proto__` is an own entry too.
|
|
819
|
+
const ext = Object.create(null) as Record<string, ExtFn>;
|
|
820
|
+
for (const name of Object.keys(STD_EXT)) ext[name] = () => failed("unknown-op", `no handler for the extension kind "${name}"`);
|
|
821
|
+
for (const [name, handler] of Object.entries(extensions)) {
|
|
822
|
+
ext[name] = (data, ctx) => {
|
|
823
|
+
const self = selfOf(ctx);
|
|
824
|
+
if (!(self instanceof Place)) return { ok: false, error: self };
|
|
825
|
+
// The kernel does not know the path of a node in the tagged IR, so the path is empty.
|
|
826
|
+
const r = handler(data, { space: self.space, position: { origin: self.origin, focus: self.focus }, path: [] });
|
|
827
|
+
if (r.ok) return r;
|
|
828
|
+
// An error without an origin gets the position of the extension (EVAL.LOCATION).
|
|
829
|
+
return { ok: false, error: toKernelError(r.error.origin === undefined ? { ...r.error, origin: self.origin, focus: self.focus } : r.error) };
|
|
830
|
+
};
|
|
831
|
+
}
|
|
832
|
+
return {
|
|
833
|
+
ops: (name) => dispatch(name, domains, fns),
|
|
834
|
+
lazy: FORMS,
|
|
835
|
+
ext,
|
|
836
|
+
// A #DEPTH! argument is the result: #ARGS does not wrap it (EVAL.DEPTH).
|
|
837
|
+
combine: (errors) => errors.find(isDepth) ?? kernelError("args", `${String(errors.length)} arguments failed`, { causes: errors.map(toVexError) }),
|
|
838
|
+
};
|
|
839
|
+
}
|
|
840
|
+
|
|
841
|
+
/** The evaluators of the literals: the JSON form of IR.JSON, and a value of the host (DOC.LITERAL). */
|
|
842
|
+
function literals(domains: readonly AnyDomain[]): Readonly<Record<string, EvalFn>> {
|
|
843
|
+
return {
|
|
844
|
+
// The kernel catches a decoder that throws, and gives #CALC! (CALL.THROW) or #DEPTH! (EVAL.DEPTH).
|
|
845
|
+
"vex.lit": ({ doc }) => {
|
|
846
|
+
const decoded = decodeValue(doc.value, domains);
|
|
847
|
+
return decoded.ok ? ok(decoded.value) : { ok: false, error: toKernelError(decoded.error) };
|
|
848
|
+
},
|
|
849
|
+
// A literal of an expression without a JSON form: its document holds the value of the host, with this own entry.
|
|
850
|
+
"vex.host": ({ doc }) => ok(doc.value),
|
|
851
|
+
};
|
|
852
|
+
}
|
|
853
|
+
|
|
854
|
+
/**
|
|
855
|
+
* The rules of the machines of Vex. The values of a space are data, so a field that has the shape of a reference stays
|
|
856
|
+
* a value. A reference starts at `self` or `names`, and a document has a limit of nesting.
|
|
857
|
+
*/
|
|
858
|
+
const RULES = { plain: true, roots: ["self", "names"], maxDepth: MAX_DOCUMENT_DEPTH } as const;
|
|
859
|
+
|
|
860
|
+
/**
|
|
861
|
+
* This function makes the machine of the kernel for Vex: the world of Vex, and the formula kit with the profile of
|
|
862
|
+
* Vex. Vex adds its evaluators and its walkers. It is the reference tier of Vex (EVAL.REFERENCE).
|
|
863
|
+
*/
|
|
864
|
+
export function vexMachine(opts: CompileOptions = {}): Machine {
|
|
865
|
+
// Stryker disable next-line ArrayDeclaration: a list with a value that is not a domain matches no value
|
|
866
|
+
return { world: VEX_WORLD, evaluators: { ...formulaEvaluators(profileOf(opts)), ...literals(opts.domains ?? []), ...LOOPS, ...FUNCTIONS, "vex.axis": axisEvaluator }, walkers: WALKERS, ...RULES };
|
|
867
|
+
}
|
|
868
|
+
|
|
869
|
+
/** The code of each evaluator and walker of the machine of the checks. A check uses only their names. */
|
|
870
|
+
const NO_CODE = (): never => stop("bad-expression", "the machine of the checks evaluates nothing");
|
|
871
|
+
|
|
872
|
+
/**
|
|
873
|
+
* This function makes the machine of the checks (DOC.CHECK). It has the world of Vex, and the names of the evaluators
|
|
874
|
+
* and the walkers of `vexMachine` without their code. The static kit of the kernel needs only the names. Thus a
|
|
875
|
+
* program that only reads documents does not hold the evaluators.
|
|
876
|
+
*/
|
|
877
|
+
export function vexChecker(): Machine {
|
|
878
|
+
const evaluators: Record<string, EvalFn> = {};
|
|
879
|
+
const walkers: Record<string, Walker> = {};
|
|
880
|
+
const todo: unknown[] = Object.values(VEX_WORLD.kinds);
|
|
881
|
+
for (let x = todo.pop(); x !== undefined; x = todo.pop()) {
|
|
882
|
+
const kind = x as { readonly verbs?: Readonly<Record<string, string>>; readonly kinds?: Readonly<Record<string, unknown>>; readonly fallback?: unknown };
|
|
883
|
+
const { eval: name, step } = kind.verbs ?? {};
|
|
884
|
+
if (name !== undefined) evaluators[name] = NO_CODE;
|
|
885
|
+
if (step !== undefined) walkers[step] = NO_CODE;
|
|
886
|
+
todo.push(...Object.values(kind.kinds ?? {}), ...(kind.fallback === undefined ? [] : [kind.fallback]));
|
|
887
|
+
}
|
|
888
|
+
return { world: VEX_WORLD, evaluators, walkers, ...RULES };
|
|
889
|
+
}
|
|
890
|
+
|
|
891
|
+
/**
|
|
892
|
+
* This function gives the definitions of the machine of Vex for the reference interpreter of the kernel. The formula
|
|
893
|
+
* kit gets its definitions with the profile of Vex. The evaluators of Vex are functions, so they need no definition.
|
|
894
|
+
*/
|
|
895
|
+
export function vexDefinitions(opts: CompileOptions = {}): Definitions {
|
|
896
|
+
return formulaDefinitions(profileOf(opts));
|
|
897
|
+
}
|