@mark1russell7/vex 0.9.1 → 0.11.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/src/list.ts CHANGED
@@ -15,15 +15,50 @@ export interface VexList<T = unknown> {
15
15
  /** This function makes a list. */
16
16
  export const vexList = <T>(items: readonly ListItem<T>[]): VexList<T> => Object.freeze({ kind: "vex.list", items: Object.freeze([...items]) });
17
17
 
18
- /** This function tells if a value is a Vex list. */
19
- export const isVexList = (u: unknown): u is VexList =>
20
- (u as { kind?: unknown } | null | undefined)?.kind === "vex.list" && Array.isArray((u as { items?: unknown }).items);
18
+ /** The lists that passed the check of `isVexList` and cannot change. Each list of `vexList` is frozen. */
19
+ const CHECKED = new WeakSet<object>();
21
20
 
22
- /** The name of a core list op. `sortBy` and `take` give a list, and the other ops give a value. */
23
- export type ListOp = "count" | "sum" | "min" | "max" | "mean" | "any" | "all" | "none" | "values" | "keys" | "reduce" | "first" | "errors" | "sortBy" | "take" | "nth";
21
+ /** This function tells if a value is an error value: a text `code`, `kind` and `message`, and a `path` (LIST.SHAPE). */
22
+ const isErrorValue = (u: unknown): boolean => {
23
+ if (typeof u !== "object" || u === null) return false;
24
+ const e = u as { code?: unknown; kind?: unknown; message?: unknown; path?: unknown };
25
+ return typeof e.code === "string" && typeof e.kind === "string" && typeof e.message === "string" && Array.isArray(e.path);
26
+ };
27
+
28
+ /** This function tells if a value is an item of a list: a text key, and a value or an error value (LIST.SHAPE). */
29
+ const isListItem = (u: unknown): boolean => {
30
+ if (typeof u !== "object" || u === null) return false;
31
+ const { key, result } = u as { key?: unknown; result?: unknown };
32
+ if (typeof key !== "string" || typeof result !== "object" || result === null) return false;
33
+ const r = result as { ok?: unknown; value?: unknown; error?: unknown };
34
+ return r.ok === true ? r.value !== undefined : r.ok === false && isErrorValue(r.error);
35
+ };
36
+
37
+ /**
38
+ * This function tells if a value is a Vex list (LIST.SHAPE). A list has the kind `vex.list`, and each item has a text key
39
+ * and a result. Another value with the kind `vex.list` is a record, so no list op applies to it. A frozen
40
+ * list passes the check once.
41
+ */
42
+ export const isVexList = (u: unknown): u is VexList => {
43
+ if (typeof u !== "object" || u === null) return false;
44
+ // Stryker disable next-line ConditionalExpression,BlockStatement: the cache holds only lists that pass the check again
45
+ if (CHECKED.has(u)) return true;
46
+ const { kind, items } = u as { kind?: unknown; items?: unknown };
47
+ if (kind !== "vex.list" || !Array.isArray(items)) return false;
48
+ // A loop over the positions, not `every`, so a hole of a sparse array is not an item.
49
+ for (let i = 0; i < items.length; i++) if (!isListItem(items[i])) return false;
50
+ if (Object.isFrozen(u) && Object.isFrozen(items)) CHECKED.add(u);
51
+ return true;
52
+ };
53
+
54
+ /**
55
+ * The name of a core list op. `sortBy`, `take`, `drop`, `append`, `flat` and `without` give a list (LIST.BUILD), and
56
+ * the other ops give a value. `get` gives the value at a key (LIST.GET).
57
+ */
58
+ export type ListOp = "count" | "sum" | "min" | "max" | "mean" | "any" | "all" | "none" | "values" | "keys" | "reduce" | "first" | "errors" | "sortBy" | "take" | "nth" | "drop" | "append" | "flat" | "without" | "get";
24
59
 
25
60
  /** The names of the core list ops. They apply when the first argument is a list. */
26
- export const LIST_OPS: ReadonlySet<string> = new Set<ListOp>(["count", "sum", "min", "max", "mean", "any", "all", "none", "values", "keys", "reduce", "first", "errors", "sortBy", "take", "nth"]);
61
+ export const LIST_OPS: ReadonlySet<string> = new Set<ListOp>(["count", "sum", "min", "max", "mean", "any", "all", "none", "values", "keys", "reduce", "first", "errors", "sortBy", "take", "nth", "drop", "append", "flat", "without", "get"]);
27
62
 
28
63
  /** This function tells if a name is the name of a core list op. */
29
64
  export const isListOp = (op: string): op is ListOp => LIST_OPS.has(op);
package/src/plan.ts ADDED
@@ -0,0 +1,88 @@
1
+ /**
2
+ * The reference tier of Vex: a program as a plan of the kernel of coeval (decision D13 of coeval). The kernel evaluates
3
+ * the document of the program with the machine of `kernel.ts`. The closure compiler and the loop compiler give its
4
+ * results (EVAL.REFERENCE), and the test kit compares them on random programs.
5
+ */
6
+ import { agree as kernelAgree, context, prepare, reference as kernelReference, type Agreement, type Context, type Failed, type Result as Outcome } from "@mark1russell7/coeval";
7
+ import { fromDocument, isDocument, type Envelope } from "./document.ts";
8
+ import { vexError, type VexError } from "./errors.ts";
9
+ import { MAX_NESTING, nestingOf, type CompileOptions, type RunOptions } from "./evaluate.ts";
10
+ import { shapeError, type Expr } from "./ir.ts";
11
+ import { toKernelError, toVexResult, vexDefinitions, vexMachine, vexSelf } from "./kernel.ts";
12
+ import type { Result } from "./result.ts";
13
+ import { sameVex } from "./same.ts";
14
+ import { writeDocument } from "./write.ts";
15
+
16
+ /** The options of a run of a plan of the kernel: the options of a run without a trace. */
17
+ export type KernelRunOptions = Omit<RunOptions, "trace">;
18
+
19
+ /** A program in the kernel: its document, and a run at an origin of a space. */
20
+ export interface KernelPlan {
21
+ /** The document that the kernel evaluates, or `undefined` for a program that is not valid. */
22
+ readonly doc: Envelope | undefined;
23
+ /** This method evaluates the program at an origin. It does not throw. */
24
+ run(opts: KernelRunOptions): Result<unknown>;
25
+ /** This method evaluates the program at an origin, and gives the result of the kernel with its own code. */
26
+ evaluate(opts: KernelRunOptions): Outcome;
27
+ /**
28
+ * This method evaluates the program at an origin with the reference interpreter of the kernel. The reference reads
29
+ * the document by the rules of the kernel, and it compiles nothing. Thus it shares no compiler with `evaluate`.
30
+ */
31
+ reference(opts: KernelRunOptions): Outcome;
32
+ /**
33
+ * This method compares the tiers of the kernel at an origin (`agree` of coeval). The tiers are `evaluate`, the
34
+ * reference interpreter, the traced evaluation and a second evaluation. The tier `other` of the caller is the last
35
+ * tier. The method gives the result, or the first tier that gives another result. Two errors agree when they have the
36
+ * same code.
37
+ */
38
+ agree(opts: KernelRunOptions, other?: () => Result<unknown>): Agreement;
39
+ }
40
+
41
+ /** This function gives the context of the kernel at an origin: the position of the origin, and the names of the caller. */
42
+ const contextOf = ({ space, origin, vars, tables }: KernelRunOptions): Context => context({ self: vexSelf(space, origin, tables), names: vars ?? {} });
43
+
44
+ /** This function gives the result of the kernel for a result of Vex. */
45
+ const toOutcome = (r: Result<unknown>): Outcome => (r.ok ? { ok: true, value: r.value } : { ok: false, error: toKernelError(r.error) });
46
+
47
+ /**
48
+ * This function gives the plan of a program in the kernel (EVAL.REFERENCE). A document stays as it is, after the check
49
+ * of `fromDocument`. An expression gets its document: a literal has its JSON form, or the value of the host when it has
50
+ * no JSON form. A program that is not valid gives the error of `compile` at each run (EVAL.SHAPE, EVAL.NESTING).
51
+ */
52
+ export function kernelPlan(source: Expr | Envelope, opts: CompileOptions = {}): KernelPlan {
53
+ // Stryker disable next-line ArrayDeclaration: a list with a value that is not a domain matches no value
54
+ const domains = opts.domains ?? [];
55
+ let doc: Envelope | undefined;
56
+ let bad: VexError | undefined;
57
+ if (isDocument(source)) {
58
+ const read = fromDocument(source, domains);
59
+ if (read.ok) doc = source;
60
+ else bad = read.error;
61
+ } else {
62
+ const shape = shapeError(source);
63
+ const nesting = shape === undefined ? nestingOf(source) : 0;
64
+ const reason = shape ?? (nesting > MAX_NESTING ? `the expression is nested ${String(nesting)} levels deep, and the limit is ${String(MAX_NESTING)}` : undefined);
65
+ // Stryker disable next-line StringLiteral: the writer tests only the mode "json" and the order "reads"
66
+ if (reason === undefined) doc = writeDocument(source, { domains, literals: "host", order: "document" });
67
+ else bad = vexError("bad-expression", reason);
68
+ }
69
+ const machine = vexMachine(opts);
70
+ // A program that is not valid has no document. Its plan does not run, because each run fails before the kernel.
71
+ const plan = prepare(machine, doc);
72
+ // An origin outside the space and a program that is not valid fail before the kernel (EVAL.ORIGIN, EVAL.SHAPE).
73
+ const early = ({ space, origin }: KernelRunOptions): Failed | undefined => {
74
+ if (!space.has(origin)) return { ok: false, error: toKernelError(vexError("unknown-key", `the space has no key "${origin}"`, { origin, focus: origin })) };
75
+ return bad === undefined ? undefined : { ok: false, error: toKernelError(bad) };
76
+ };
77
+ const evaluate = (r: KernelRunOptions): Outcome => early(r) ?? plan.evaluate(contextOf(r));
78
+ const reference = (r: KernelRunOptions): Outcome => early(r) ?? kernelReference(machine, doc, contextOf(r), { definitions: vexDefinitions(opts) });
79
+ const agree = (r: KernelRunOptions, other?: () => Result<unknown>): Agreement => {
80
+ const tier = other === undefined ? {} : { other: (): Outcome => toOutcome(other()) };
81
+ const first = early(r);
82
+ if (first === undefined) return kernelAgree(machine, doc, contextOf(r), { definitions: vexDefinitions(opts), equal: sameVex, ...tier });
83
+ // The kernel does not evaluate the program, so only the tier can give another result.
84
+ const second = tier.other?.() ?? first;
85
+ return !second.ok && second.error.code === first.error.code ? { ok: true, result: first, effects: [] } : { ok: false, tier: "other", plan: first, other: second, reason: "The plan does not evaluate the program, and the tier gives another result." };
86
+ };
87
+ return { doc, evaluate, reference, agree, run: (r) => toVexResult(evaluate(r)) };
88
+ }
package/src/same.ts ADDED
@@ -0,0 +1,31 @@
1
+ /**
2
+ * The comparison of the values of Vex for `agree` of the kernel (EVAL.AGREE), and the test of a Vex error. The package
3
+ * index does not export this module: `kernel.ts` and `plan.ts` use it.
4
+ */
5
+ import { sameValue } from "@mark1russell7/coeval";
6
+ import type { VexError } from "./errors.ts";
7
+
8
+ /** This function tells if a value is a Vex error: it has a code, a kind, a message and a path. */
9
+ export function isVexError(u: unknown): u is VexError {
10
+ const e = u as Partial<VexError> | null | undefined;
11
+ return typeof e?.code === "string" && typeof e.kind === "string" && typeof e.message === "string" && Array.isArray(e.path);
12
+ }
13
+
14
+ /** This function tells if a value is a value of a class: an object that is not a plain record and not an array. */
15
+ function isInstance(u: unknown): u is object {
16
+ if (typeof u !== "object" || u === null || Array.isArray(u)) return false;
17
+ const proto: unknown = Object.getPrototypeOf(u);
18
+ return proto !== Object.prototype && proto !== null;
19
+ }
20
+
21
+ /**
22
+ * This function compares two values of Vex for `agree`. Two Vex errors agree when they have the same code, because
23
+ * only the closure compiler gives the location of an error (EVAL.LOCATION). Two values of one class agree when their
24
+ * fields agree, for example two values of a domain from two decodes of a literal. The rules of `sameValue` compare
25
+ * each other pair.
26
+ */
27
+ export function sameVex(a: unknown, b: unknown): boolean | undefined {
28
+ if (isVexError(a) && isVexError(b)) return a.code === b.code;
29
+ if (!isInstance(a) || !isInstance(b)) return undefined;
30
+ return Object.getPrototypeOf(a) === Object.getPrototypeOf(b) && sameValue({ ...a }, { ...b }, sameVex);
31
+ }
package/src/sheet.ts CHANGED
@@ -447,7 +447,8 @@ export class SheetRun {
447
447
  #compiled(t: Table, column: string, program: Expr): Program | undefined {
448
448
  const compile = this.#compile;
449
449
  // The formula of a cell evaluates once in a run, so the run compiles only the formulas of the columns.
450
- if (compile === undefined || t.columns.get(column) !== program) return undefined;
450
+ // V-056: a formula that is not an object cannot be a key of the cache, so the interpreter gives its error.
451
+ if (compile === undefined || t.columns.get(column) !== program || typeof program !== "object" || program === null) return undefined;
451
452
  const { domains, fns, extensions } = this.#compileOptions;
452
453
  const hit = PROGRAMS.get(program);
453
454
  if (hit !== undefined && hit.compile === compile && hit.domains === domains && hit.fns === fns && hit.extensions === extensions) return hit.program;
package/src/write.ts ADDED
@@ -0,0 +1,257 @@
1
+ /**
2
+ * The writer of the documents of Vex: the coeval document of an expression (DOC.TERM). It uses a stack, not recursion,
3
+ * so an expression of any depth has a document. The package index does not export this module: `toDocument`, `deps`
4
+ * and `kernelPlan` use it.
5
+ */
6
+ import { isEnvelope, ref as path, typed, type Envelope, type Json, type JsonRecord } from "@mark1russell7/coeval";
7
+ import { encodeValue } from "./codec.ts";
8
+ import type { AnyDomain } from "./domain.ts";
9
+ import type { VexError } from "./errors.ts";
10
+ import type { Axis, Expr, Move } from "./ir.ts";
11
+
12
+ /** The options of the writer. */
13
+ export interface WriteOptions {
14
+ /** The domains that encode the values of the literals. */
15
+ readonly domains: readonly AnyDomain[];
16
+ /**
17
+ * The form of a literal without a JSON form. `"json"` stops the writer with its error. `"host"` keeps the value of the
18
+ * host in a literal with the own entry `vex.host`, for an evaluation in the kernel.
19
+ */
20
+ readonly literals: "json" | "host";
21
+ /**
22
+ * The order of the fields of `each` and `fold`. `"document"` is the order of DOC.CONSTRUCT. `"reads"` puts the body or
23
+ * the steps before the axis, in the order of the reads of `deps`.
24
+ */
25
+ readonly order: "document" | "reads";
26
+ /** A map that gets the expression of each envelope of a reference, an axis loop and a call. */
27
+ readonly nodes?: Map<object, Expr>;
28
+ }
29
+
30
+ /** The stop of a write: a literal without a JSON form. The caller gives its error. */
31
+ export class WriteStop {
32
+ readonly error: VexError;
33
+
34
+ constructor(error: VexError) {
35
+ this.error = error;
36
+ }
37
+ }
38
+
39
+ /** A job of the writer: an expression in the position of a term or of an envelope, an axis or a move. */
40
+ type Job = { readonly t: "term" | "envelope"; readonly e: Expr } | { readonly t: "axis"; readonly a: Axis } | { readonly t: "move"; readonly m: Move };
41
+
42
+ /** The plan of a job: the jobs of its parts, and the function that makes its document from their documents. */
43
+ interface Plan {
44
+ readonly jobs: readonly Job[];
45
+ readonly make: (docs: readonly Json[]) => Json;
46
+ }
47
+
48
+ const NONE: readonly Job[] = [];
49
+ // Stryker disable next-line StringLiteral: the writer tests only the kind "envelope", so each other kind is the kind "term"
50
+ const term = (e: Expr): Job => ({ t: "term", e });
51
+ const envelope = (e: Expr): Job => ({ t: "envelope", e });
52
+
53
+ /** This function gives a record from names and the documents of their values, from an index of the documents. */
54
+ function namesOf(names: readonly string[], docs: readonly Json[], from: number): JsonRecord {
55
+ const out: Record<string, Json> = {};
56
+ names.forEach((name, i) => {
57
+ Object.defineProperty(out, name, { value: docs[from + i], enumerable: true, writable: true, configurable: true });
58
+ });
59
+ return out;
60
+ }
61
+
62
+ /** The writer of one document. */
63
+ class Writer {
64
+ readonly #opts: WriteOptions;
65
+
66
+ constructor(opts: WriteOptions) {
67
+ this.#opts = opts;
68
+ }
69
+
70
+ /** This method writes the document of a job, with a stack of plans. */
71
+ write(root: Job): Json {
72
+ const stack: { readonly plan: Plan; readonly docs: Json[] }[] = [{ plan: this.#plan(root), docs: [] }];
73
+ for (;;) {
74
+ const top = stack[stack.length - 1] as (typeof stack)[number];
75
+ const next = top.plan.jobs[top.docs.length];
76
+ if (next !== undefined) {
77
+ stack.push({ plan: this.#plan(next), docs: [] });
78
+ continue;
79
+ }
80
+ const doc = top.plan.make(top.docs);
81
+ stack.pop();
82
+ const parent = stack[stack.length - 1];
83
+ if (parent === undefined) return doc;
84
+ parent.docs.push(doc);
85
+ }
86
+ }
87
+
88
+ /** This method keeps the expression of an envelope, for `deps`. */
89
+ #keep<T extends Json>(doc: T, e: Expr): T {
90
+ this.#opts.nodes?.set(doc as object, e);
91
+ return doc;
92
+ }
93
+
94
+ /** This method gives the document of a literal: its JSON form, or a value of the host (DOC.LITERAL). */
95
+ #literal(value: unknown, root: boolean): Json {
96
+ const host: Json = { type: "lit", value: value as Json, own: { eval: "vex.host" } };
97
+ let r: ReturnType<typeof encodeValue>;
98
+ try {
99
+ r = encodeValue(value, this.#opts.domains);
100
+ } catch (thrown) {
101
+ // A getter of the value threw. In the mode "host", the literal keeps the value of the host.
102
+ if (this.#opts.literals === "json") throw thrown;
103
+ return host;
104
+ }
105
+ if (!r.ok) {
106
+ if (this.#opts.literals === "json") throw new WriteStop(r.error);
107
+ return host;
108
+ }
109
+ const json = r.value as Json;
110
+ // In the position of a term, a literal is its JSON value, except a value with the shape of an envelope (DOC.TERM).
111
+ return root || isEnvelope(json) ? typed("lit", json) : json;
112
+ }
113
+
114
+ #plan(job: Job): Plan {
115
+ if (job.t === "axis") return this.#axis(job.a);
116
+ if (job.t === "move") return this.#move(job.m);
117
+ const e = job.e;
118
+ if (e.tag === "lit") return { jobs: NONE, make: () => this.#literal(e.value, job.t === "envelope") };
119
+ return this.#envelope(e);
120
+ }
121
+
122
+ #envelope(e: Exclude<Expr, { readonly tag: "lit" }>): Plan {
123
+ const reads = this.#opts.order === "reads";
124
+ switch (e.tag) {
125
+ case "ref":
126
+ return { jobs: (e.at ?? []).map((m): Job => ({ t: "move", m })), make: (docs) => this.#keep(path("self", ...docs, ...e.path), e) };
127
+ case "var":
128
+ return { jobs: NONE, make: () => path("names", e.name) };
129
+ case "app":
130
+ return { jobs: e.args.map(term), make: (docs) => typed(["ops", ...e.op.split(".")], [...docs]) };
131
+ case "let": {
132
+ const names = Object.keys(e.bind);
133
+ return { jobs: [...Object.values(e.bind).map(term), term(e.body)], make: (docs) => typed("let", { bind: namesOf(names, docs, 0), body: docs[names.length] as Json }) };
134
+ }
135
+ case "fn":
136
+ return { jobs: [term(e.body)], make: (docs) => typed("fn", { params: [...e.params], body: docs[0] as Json }) };
137
+ case "call":
138
+ return { jobs: e.args.map(term), make: (docs) => this.#keep(typed("call", { fn: path("names", e.fn), args: [...docs] }), e) };
139
+ case "rec": {
140
+ const names = Object.keys(e.fields);
141
+ return { jobs: Object.values(e.fields).map(term), make: (docs) => typed("record", namesOf(names, docs, 0)) };
142
+ }
143
+ case "each": {
144
+ const at = this.#at(e.at);
145
+ return {
146
+ jobs: [{ t: "axis", a: e.axis }, term(e.body), ...at.jobs],
147
+ make: (docs) => {
148
+ const axis = docs[0] as Json;
149
+ const body = docs[1] as Json;
150
+ const address = at.make(docs.slice(2));
151
+ return this.#keep(typed("each", reads ? { body, axis, ...address } : { axis, body, ...address }), e);
152
+ },
153
+ };
154
+ }
155
+ case "fold": {
156
+ const init = Object.keys(e.init);
157
+ const step = Object.keys(e.step);
158
+ const at = this.#at(e.at);
159
+ const after = 1 + init.length + step.length;
160
+ return {
161
+ jobs: [{ t: "axis", a: e.axis }, ...Object.values(e.init).map(term), ...Object.values(e.step).map(term), term(e.result), ...at.jobs],
162
+ make: (docs) => {
163
+ const axis = docs[0] as Json;
164
+ const names = { init: namesOf(init, docs, 1), step: namesOf(step, docs, 1 + init.length) };
165
+ const result = docs[after] as Json;
166
+ const address = at.make(docs.slice(after + 1));
167
+ return this.#keep(typed("fold", reads ? { ...names, axis, ...address, result } : { axis, ...names, result, ...address }), e);
168
+ },
169
+ };
170
+ }
171
+ case "iterate": {
172
+ const init = Object.keys(e.init);
173
+ const step = Object.keys(e.step);
174
+ const until = e.until === undefined ? NONE : [term(e.until)];
175
+ const after = init.length + step.length;
176
+ return {
177
+ jobs: [...Object.values(e.init).map(term), ...Object.values(e.step).map(term), ...until, term(e.result)],
178
+ make: (docs) =>
179
+ typed("iterate", {
180
+ limit: e.limit,
181
+ init: namesOf(init, docs, 0),
182
+ step: namesOf(step, docs, init.length),
183
+ ...(e.until === undefined ? {} : { until: docs[after] as Json }),
184
+ result: docs[after + until.length] as Json,
185
+ }),
186
+ };
187
+ }
188
+ case "ext":
189
+ return { jobs: NONE, make: () => typed(["ext", ...e.kind.split(".")], e.data as Json) };
190
+ }
191
+ }
192
+
193
+ /** This method gives the plan of the field `at` of `each` and `fold`: a reference from `self` with moves only (DOC.ADDRESS). */
194
+ #at(at: readonly Move[] | undefined): { readonly jobs: readonly Job[]; readonly make: (docs: readonly Json[]) => { readonly at?: Envelope } } {
195
+ // Stryker disable next-line ArrowFunction: a spread of no value adds no fields, as a spread of an empty record does
196
+ if (at === undefined || at.length === 0) return { jobs: NONE, make: () => ({}) };
197
+ return { jobs: at.map((m): Job => ({ t: "move", m })), make: (docs) => ({ at: path("self", ...docs) }) };
198
+ }
199
+
200
+ /** This method gives the plan of a move. A computed key or position is an envelope (DOC.MOVE). */
201
+ #move(m: Move): Plan {
202
+ switch (m.t) {
203
+ case "key":
204
+ return typeof m.key === "string" ? this.#fixed(["moves", "key"], m.key) : { jobs: [envelope(m.key)], make: (docs) => typed(["moves", "key"], docs[0] as Json) };
205
+ case "index":
206
+ return typeof m.i === "number" ? this.#fixed(["moves", "index"], m.i) : { jobs: [envelope(m.i)], make: (docs) => typed(["moves", "index"], docs[0] as Json) };
207
+ case "offset":
208
+ return this.#fixed(["moves", "offset"], [...m.d]);
209
+ case "other":
210
+ case "origin":
211
+ case "parent":
212
+ return this.#fixed(["moves", m.t], null);
213
+ }
214
+ }
215
+
216
+ #fixed(type: readonly string[], value: Json): Plan {
217
+ return { jobs: NONE, make: () => typed(type, value) };
218
+ }
219
+
220
+ /** This method gives the plan of an axis (DOC.AXIS). */
221
+ #axis(a: Axis): Plan {
222
+ const type = ["axes", a.t];
223
+ switch (a.t) {
224
+ case "neighbors":
225
+ return this.#fixed(type, { n: a.n });
226
+ case "window":
227
+ return this.#fixed(type, { from: a.from, to: a.to });
228
+ case "table":
229
+ return this.#fixed(type, { name: a.name });
230
+ case "list":
231
+ return { jobs: [term(a.list)], make: (docs) => typed(type, { list: docs[0] as Json }) };
232
+ case "reverse":
233
+ return { jobs: [{ t: "axis", a: a.axis }], make: (docs) => typed(type, { axis: docs[0] as Json }) };
234
+ case "where":
235
+ return { jobs: [{ t: "axis", a: a.axis }, term(a.test)], make: (docs) => typed(type, { axis: docs[0] as Json, test: docs[1] as Json }) };
236
+ case "all":
237
+ case "others":
238
+ case "other":
239
+ case "children":
240
+ case "ancestors":
241
+ case "descendants":
242
+ case "siblings":
243
+ case "successors":
244
+ case "predecessors":
245
+ case "reachable":
246
+ return this.#fixed(type, {});
247
+ }
248
+ }
249
+ }
250
+
251
+ /**
252
+ * This function writes the document of a valid expression. The root is always an envelope. It throws a `WriteStop` for
253
+ * a literal without a JSON form in the mode `"json"`, and an exception of a getter of a literal value.
254
+ */
255
+ export function writeDocument(e: Expr, opts: WriteOptions): Envelope {
256
+ return new Writer(opts).write({ t: "envelope", e }) as Envelope;
257
+ }