@mark1russell7/vex 0.0.0-stage → 0.2.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/LICENSE +21 -0
- package/build/index.d.ts +884 -0
- package/build/index.d.ts.map +1 -0
- package/build/index.js +1839 -0
- package/build/index.js.map +1 -0
- package/package.json +44 -3
- package/src/builder.ts +649 -0
- package/src/deps.ts +33 -0
- package/src/domain.ts +135 -0
- package/src/errors.ts +102 -0
- package/src/evaluate.ts +628 -0
- package/src/index.ts +16 -0
- package/src/ir.ts +212 -0
- package/src/json.ts +76 -0
- package/src/list.ts +35 -0
- package/src/result.ts +44 -0
- package/src/sheet.ts +141 -0
- package/src/space.ts +322 -0
- package/src/trace.ts +37 -0
- package/src/traversal.ts +126 -0
- package/README.md +0 -3
package/src/ir.ts
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The expression IR of Vex. It is plain JSON data. Its first three kinds (`lit`, `ref`, `app`) have the same
|
|
3
|
+
* shape as the expressions of `render`.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/** One move of an address. The moves of an address apply in order, from the focus of the evaluation. */
|
|
7
|
+
export type Move =
|
|
8
|
+
| { readonly t: "key"; readonly key: string }
|
|
9
|
+
| { readonly t: "index"; readonly i: number }
|
|
10
|
+
| { readonly t: "other" }
|
|
11
|
+
| { readonly t: "offset"; readonly d: readonly number[] }
|
|
12
|
+
| { readonly t: "origin" }
|
|
13
|
+
| { readonly t: "parent" };
|
|
14
|
+
|
|
15
|
+
/** An address: a list of moves. The empty list is the focus. */
|
|
16
|
+
export type Addr = readonly Move[];
|
|
17
|
+
|
|
18
|
+
/** An axis: the relation between a position and the targets that a body reads. */
|
|
19
|
+
export type Axis =
|
|
20
|
+
| { readonly t: "all" }
|
|
21
|
+
| { readonly t: "others" }
|
|
22
|
+
| { readonly t: "other" }
|
|
23
|
+
| { readonly t: "neighbors"; readonly n: 4 | 8 }
|
|
24
|
+
| { readonly t: "children" }
|
|
25
|
+
| { readonly t: "ancestors" }
|
|
26
|
+
| { readonly t: "descendants" }
|
|
27
|
+
| { readonly t: "siblings" }
|
|
28
|
+
| { readonly t: "where"; readonly axis: Axis; readonly test: Expr };
|
|
29
|
+
|
|
30
|
+
/** A Vex expression. */
|
|
31
|
+
export type Expr =
|
|
32
|
+
| { readonly tag: "lit"; readonly value: unknown }
|
|
33
|
+
| { readonly tag: "ref"; readonly path: readonly string[]; readonly at?: Addr }
|
|
34
|
+
| { readonly tag: "app"; readonly op: string; readonly args: readonly Expr[] }
|
|
35
|
+
| { readonly tag: "let"; readonly bind: Readonly<Record<string, Expr>>; readonly body: Expr }
|
|
36
|
+
| { readonly tag: "var"; readonly name: string }
|
|
37
|
+
| { readonly tag: "rec"; readonly fields: Readonly<Record<string, Expr>> }
|
|
38
|
+
| { readonly tag: "each"; readonly axis: Axis; readonly body: Expr }
|
|
39
|
+
| { readonly tag: "ext"; readonly kind: string; readonly data: unknown };
|
|
40
|
+
|
|
41
|
+
/** The tag of an expression kind. */
|
|
42
|
+
export type ExprTag = Expr["tag"];
|
|
43
|
+
|
|
44
|
+
/** An expression of one kind. */
|
|
45
|
+
export type ExprOf<T extends ExprTag> = Extract<Expr, { readonly tag: T }>;
|
|
46
|
+
|
|
47
|
+
// ---------------------------------------------------------------- constructors
|
|
48
|
+
|
|
49
|
+
/** This function makes a literal. */
|
|
50
|
+
export const lit = (value: unknown): ExprOf<"lit"> => ({ tag: "lit", value });
|
|
51
|
+
|
|
52
|
+
/** This function splits a dotted path, for example `"pos.x"`, into its segments. */
|
|
53
|
+
export const toPath = (path: string | readonly string[]): readonly string[] =>
|
|
54
|
+
typeof path === "string" ? path.split(".").filter((s) => s.length > 0) : path;
|
|
55
|
+
|
|
56
|
+
/** This function makes a reference to a field path. With `at`, the reference reads at that address. */
|
|
57
|
+
export function ref(path: string | readonly string[], at?: Addr): ExprOf<"ref"> {
|
|
58
|
+
const segments = toPath(path);
|
|
59
|
+
return at === undefined || at.length === 0 ? { tag: "ref", path: segments } : { tag: "ref", path: segments, at };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** This function makes the application of an op to arguments. For a method op, the first argument is the receiver. */
|
|
63
|
+
export const app = (op: string, ...args: readonly Expr[]): ExprOf<"app"> => ({ tag: "app", op, args });
|
|
64
|
+
|
|
65
|
+
/** This function binds names to expressions for the body. */
|
|
66
|
+
export const let_ = (bind: Readonly<Record<string, Expr>>, body: Expr): ExprOf<"let"> => ({ tag: "let", bind, body });
|
|
67
|
+
|
|
68
|
+
/** This function makes a reference to a bound name. */
|
|
69
|
+
export const v = (name: string): ExprOf<"var"> => ({ tag: "var", name });
|
|
70
|
+
|
|
71
|
+
/** This function makes a record from field expressions. */
|
|
72
|
+
export const rec = (fields: Readonly<Record<string, Expr>>): ExprOf<"rec"> => ({ tag: "rec", fields });
|
|
73
|
+
|
|
74
|
+
/** This function evaluates `body` once for each target of `axis`. The result is a list. */
|
|
75
|
+
export const each = (axis: Axis, body: Expr): ExprOf<"each"> => ({ tag: "each", axis, body });
|
|
76
|
+
|
|
77
|
+
/** This function makes an expression of an extension kind. */
|
|
78
|
+
export const ext = (kind: string, data: unknown): ExprOf<"ext"> => ({ tag: "ext", kind, data });
|
|
79
|
+
|
|
80
|
+
// ---------------------------------------------------------------- moves and axes
|
|
81
|
+
|
|
82
|
+
/** The move to an absolute key. */
|
|
83
|
+
export const key = (k: string): Move => ({ t: "key", key: k });
|
|
84
|
+
/** The move to a position in the key order. */
|
|
85
|
+
export const index = (i: number): Move => ({ t: "index", i });
|
|
86
|
+
/** The move to the other key of a space with two keys. */
|
|
87
|
+
export const other: Move = Object.freeze({ t: "other" });
|
|
88
|
+
/** The relative move in an array (one number) or a grid (two numbers). */
|
|
89
|
+
export const offset = (...d: readonly number[]): Move => ({ t: "offset", d });
|
|
90
|
+
/** The move back to the origin of the evaluation. */
|
|
91
|
+
export const origin: Move = Object.freeze({ t: "origin" });
|
|
92
|
+
/** The move to the parent of the focus in a tree space. */
|
|
93
|
+
export const parent: Move = Object.freeze({ t: "parent" });
|
|
94
|
+
|
|
95
|
+
/** The axes. */
|
|
96
|
+
export const axes = {
|
|
97
|
+
/** Each key of the space. */
|
|
98
|
+
all: Object.freeze({ t: "all" }) as Axis,
|
|
99
|
+
/** Each key except the focus. */
|
|
100
|
+
others: Object.freeze({ t: "others" }) as Axis,
|
|
101
|
+
/** The other key of a pair. */
|
|
102
|
+
other: Object.freeze({ t: "other" }) as Axis,
|
|
103
|
+
/** The neighbors of the focus in a grid. */
|
|
104
|
+
neighbors: (n: 4 | 8 = 8): Axis => ({ t: "neighbors", n }),
|
|
105
|
+
/** The children of the focus in a tree, in key order. */
|
|
106
|
+
children: Object.freeze({ t: "children" }) as Axis,
|
|
107
|
+
/** The ancestors of the focus in a tree: the parent first, the root last. */
|
|
108
|
+
ancestors: Object.freeze({ t: "ancestors" }) as Axis,
|
|
109
|
+
/** The descendants of the focus in a tree, depth first, each parent before its children. */
|
|
110
|
+
descendants: Object.freeze({ t: "descendants" }) as Axis,
|
|
111
|
+
/** The other children of the parent of the focus. For a root, the other roots. */
|
|
112
|
+
siblings: Object.freeze({ t: "siblings" }) as Axis,
|
|
113
|
+
/** The targets of `axis` where `test` gives `true`. */
|
|
114
|
+
where: (axis: Axis, test: Expr): Axis => ({ t: "where", axis, test }),
|
|
115
|
+
} as const;
|
|
116
|
+
|
|
117
|
+
// ---------------------------------------------------------------- validation
|
|
118
|
+
|
|
119
|
+
const isObject = (u: unknown): u is Readonly<Record<string, unknown>> => typeof u === "object" && u !== null;
|
|
120
|
+
|
|
121
|
+
const isStringArray = (u: unknown): u is readonly string[] => Array.isArray(u) && u.every((s) => typeof s === "string");
|
|
122
|
+
|
|
123
|
+
/** This function tells if a value is a valid move. */
|
|
124
|
+
export function isMove(u: unknown): u is Move {
|
|
125
|
+
if (!isObject(u)) return false;
|
|
126
|
+
switch (u["t"]) {
|
|
127
|
+
case "key":
|
|
128
|
+
return typeof u["key"] === "string";
|
|
129
|
+
case "index":
|
|
130
|
+
return typeof u["i"] === "number" && Number.isInteger(u["i"]);
|
|
131
|
+
case "offset":
|
|
132
|
+
return Array.isArray(u["d"]) && u["d"].every((n) => typeof n === "number" && Number.isInteger(n));
|
|
133
|
+
case "other":
|
|
134
|
+
case "origin":
|
|
135
|
+
case "parent":
|
|
136
|
+
return true;
|
|
137
|
+
default:
|
|
138
|
+
return false;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** This function tells if a value is a valid axis. */
|
|
143
|
+
export function isAxis(u: unknown): u is Axis {
|
|
144
|
+
if (!isObject(u)) return false;
|
|
145
|
+
switch (u["t"]) {
|
|
146
|
+
case "all":
|
|
147
|
+
case "others":
|
|
148
|
+
case "other":
|
|
149
|
+
case "children":
|
|
150
|
+
case "ancestors":
|
|
151
|
+
case "descendants":
|
|
152
|
+
case "siblings":
|
|
153
|
+
return true;
|
|
154
|
+
case "neighbors":
|
|
155
|
+
return u["n"] === 4 || u["n"] === 8;
|
|
156
|
+
case "where":
|
|
157
|
+
return isAxis(u["axis"]) && isExpr(u["test"]);
|
|
158
|
+
default:
|
|
159
|
+
return false;
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
const isExprRecord = (u: unknown): u is Readonly<Record<string, Expr>> =>
|
|
164
|
+
isObject(u) && !Array.isArray(u) && Object.values(u).every((e) => isExpr(e));
|
|
165
|
+
|
|
166
|
+
/** This function tells if a value is a valid expression. It checks the whole tree. */
|
|
167
|
+
export function isExpr(u: unknown): u is Expr {
|
|
168
|
+
if (!isObject(u)) return false;
|
|
169
|
+
switch (u["tag"]) {
|
|
170
|
+
case "lit":
|
|
171
|
+
return "value" in u;
|
|
172
|
+
case "ref":
|
|
173
|
+
return isStringArray(u["path"]) && (u["at"] === undefined || (Array.isArray(u["at"]) && u["at"].every(isMove)));
|
|
174
|
+
case "app":
|
|
175
|
+
return typeof u["op"] === "string" && Array.isArray(u["args"]) && u["args"].every((a) => isExpr(a));
|
|
176
|
+
case "let":
|
|
177
|
+
return isExprRecord(u["bind"]) && isExpr(u["body"]);
|
|
178
|
+
case "var":
|
|
179
|
+
return typeof u["name"] === "string";
|
|
180
|
+
case "rec":
|
|
181
|
+
return isExprRecord(u["fields"]);
|
|
182
|
+
case "each":
|
|
183
|
+
return isAxis(u["axis"]) && isExpr(u["body"]);
|
|
184
|
+
case "ext":
|
|
185
|
+
return typeof u["kind"] === "string" && "data" in u;
|
|
186
|
+
default:
|
|
187
|
+
return false;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** This function gives the child expressions of an expression, in the order of their child index. */
|
|
192
|
+
export function children(e: Expr): readonly Expr[] {
|
|
193
|
+
switch (e.tag) {
|
|
194
|
+
case "app":
|
|
195
|
+
return e.args;
|
|
196
|
+
case "let":
|
|
197
|
+
return [...Object.values(e.bind), e.body];
|
|
198
|
+
case "rec":
|
|
199
|
+
return Object.values(e.fields);
|
|
200
|
+
case "each":
|
|
201
|
+
return e.axis.t === "where" ? [e.body, ...whereTests(e.axis)] : [e.body];
|
|
202
|
+
case "lit":
|
|
203
|
+
case "ref":
|
|
204
|
+
case "var":
|
|
205
|
+
case "ext":
|
|
206
|
+
return [];
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
function whereTests(a: Axis): readonly Expr[] {
|
|
211
|
+
return a.t === "where" ? [...whereTests(a.axis), a.test] : [];
|
|
212
|
+
}
|
package/src/json.ts
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import type { AnyDomain } from "./domain.ts";
|
|
2
|
+
import { vexError } from "./errors.ts";
|
|
3
|
+
import { isExpr, type Expr } from "./ir.ts";
|
|
4
|
+
import { fail, ok, type Result } from "./result.ts";
|
|
5
|
+
|
|
6
|
+
/** The JSON form of a domain value inside a literal. */
|
|
7
|
+
interface EncodedValue {
|
|
8
|
+
readonly $vex: "domain";
|
|
9
|
+
readonly domain: string;
|
|
10
|
+
readonly value: unknown;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
const isPlainJson = (u: unknown): boolean => {
|
|
14
|
+
if (u === null || typeof u === "string" || typeof u === "boolean") return true;
|
|
15
|
+
if (typeof u === "number") return Number.isFinite(u);
|
|
16
|
+
if (Array.isArray(u)) return u.every(isPlainJson);
|
|
17
|
+
if (typeof u === "object") {
|
|
18
|
+
const proto: unknown = Object.getPrototypeOf(u);
|
|
19
|
+
return (proto === Object.prototype || proto === null) && Object.values(u).every(isPlainJson);
|
|
20
|
+
}
|
|
21
|
+
return false;
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* This function gives the JSON text of an expression. A literal that is a domain value needs a domain with
|
|
26
|
+
* `encode`. A literal that is not JSON data and has no such domain gives the error `#VALUE!`.
|
|
27
|
+
*/
|
|
28
|
+
export function serialize(e: Expr, domains: readonly AnyDomain[] = []): Result<string> {
|
|
29
|
+
const failure: { message: string }[] = [];
|
|
30
|
+
const replacer = function (this: unknown, k: string, value: unknown): unknown {
|
|
31
|
+
const holder = this as Record<string, unknown> | null;
|
|
32
|
+
if (k !== "value" || holder === null || holder["tag"] !== "lit") return value;
|
|
33
|
+
if (isPlainJson(value)) return value;
|
|
34
|
+
const d = domains.find((dom) => dom.encode !== undefined && dom.is(value));
|
|
35
|
+
if (d?.encode !== undefined) {
|
|
36
|
+
const encoded: EncodedValue = { $vex: "domain", domain: d.name, value: d.encode(value) };
|
|
37
|
+
return encoded;
|
|
38
|
+
}
|
|
39
|
+
failure.push({ message: `a literal value is not JSON data and no domain encodes it` });
|
|
40
|
+
return null;
|
|
41
|
+
};
|
|
42
|
+
let text: string;
|
|
43
|
+
try {
|
|
44
|
+
text = JSON.stringify(e, replacer);
|
|
45
|
+
} catch (thrown) {
|
|
46
|
+
return fail(vexError("threw", "the expression has no JSON form", { thrown }));
|
|
47
|
+
}
|
|
48
|
+
const first = failure[0];
|
|
49
|
+
return first === undefined ? ok(text) : fail(vexError("bad-expression", first.message));
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const isEncoded = (u: unknown): u is EncodedValue =>
|
|
53
|
+
typeof u === "object" && u !== null && (u as { $vex?: unknown }).$vex === "domain" && typeof (u as { domain?: unknown }).domain === "string";
|
|
54
|
+
|
|
55
|
+
/** This function reads an expression from JSON text. It checks the whole tree. */
|
|
56
|
+
export function parse(text: string, domains: readonly AnyDomain[] = []): Result<Expr> {
|
|
57
|
+
let raw: unknown;
|
|
58
|
+
const failure: string[] = [];
|
|
59
|
+
try {
|
|
60
|
+
raw = JSON.parse(text, (_k, value: unknown) => {
|
|
61
|
+
if (!isEncoded(value)) return value;
|
|
62
|
+
const d = domains.find((dom) => dom.name === value.domain);
|
|
63
|
+
if (d?.decode === undefined) {
|
|
64
|
+
failure.push(`no domain "${value.domain}" decodes a literal`);
|
|
65
|
+
return value;
|
|
66
|
+
}
|
|
67
|
+
const decoded: unknown = d.decode(value.value);
|
|
68
|
+
return decoded;
|
|
69
|
+
});
|
|
70
|
+
} catch (thrown) {
|
|
71
|
+
return fail(vexError("bad-expression", "the text is not JSON", { thrown }));
|
|
72
|
+
}
|
|
73
|
+
const first = failure[0];
|
|
74
|
+
if (first !== undefined) return fail(vexError("bad-expression", first));
|
|
75
|
+
return isExpr(raw) ? ok(raw) : fail(vexError("bad-expression", "the JSON is not a valid Vex expression"));
|
|
76
|
+
}
|
package/src/list.ts
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { Result } from "./result.ts";
|
|
2
|
+
|
|
3
|
+
/** One item of a list: the key of the target and the result of the body there. */
|
|
4
|
+
export interface ListItem<T = unknown> {
|
|
5
|
+
readonly key: string;
|
|
6
|
+
readonly result: Result<T>;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/** The value of an `each` expression: one item for each target of the axis. */
|
|
10
|
+
export interface VexList<T = unknown> {
|
|
11
|
+
readonly kind: "vex.list";
|
|
12
|
+
readonly items: readonly ListItem<T>[];
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** This function makes a list. */
|
|
16
|
+
export const vexList = <T>(items: readonly ListItem<T>[]): VexList<T> => Object.freeze({ kind: "vex.list", items: Object.freeze([...items]) });
|
|
17
|
+
|
|
18
|
+
/** This function tells if a value is a Vex list. */
|
|
19
|
+
export const isVexList = (u: unknown): u is VexList =>
|
|
20
|
+
typeof u === "object" && u !== null && (u as { kind?: unknown }).kind === "vex.list" && Array.isArray((u as { items?: unknown }).items);
|
|
21
|
+
|
|
22
|
+
/** The name of a core list op. */
|
|
23
|
+
export type ListOp = "count" | "sum" | "min" | "max" | "mean" | "any" | "all" | "none" | "values" | "keys" | "reduce" | "first" | "errors";
|
|
24
|
+
|
|
25
|
+
/** 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"]);
|
|
27
|
+
|
|
28
|
+
/** This function tells if a name is the name of a core list op. */
|
|
29
|
+
export const isListOp = (op: string): op is ListOp => LIST_OPS.has(op);
|
|
30
|
+
|
|
31
|
+
/** The options of a list op. */
|
|
32
|
+
export interface ListOptions {
|
|
33
|
+
/** With `true`, any error item makes the result that error. The default skips error items. */
|
|
34
|
+
readonly strict?: boolean;
|
|
35
|
+
}
|
package/src/result.ts
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import type { Optional as FamilyOptional } from "@mark1russell7/optional";
|
|
2
|
+
import type { VexError } from "./errors.ts";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* A value that is there, or not there. This is the public result of a Vex program. It is the Optional of the
|
|
6
|
+
* family (`@mark1russell7/optional`), so render and Vex give and take the same values. The import is a type import
|
|
7
|
+
* only: the build copies the type into the declarations, so the package has no runtime dependency.
|
|
8
|
+
*/
|
|
9
|
+
export type Optional<T> = FamilyOptional<T>;
|
|
10
|
+
|
|
11
|
+
/** A value, or the error that tells why there is no value. The interpreter uses this type. */
|
|
12
|
+
export type Result<T> = { readonly ok: true; readonly value: T } | { readonly ok: false; readonly error: VexError };
|
|
13
|
+
|
|
14
|
+
const NONE: Optional<never> = Object.freeze({ tag: "none" });
|
|
15
|
+
|
|
16
|
+
/** This function makes an `Optional` that holds `value`. */
|
|
17
|
+
export const some = <T>(value: T): Optional<T> => ({ tag: "some", value });
|
|
18
|
+
|
|
19
|
+
/** This function gives the shared empty `Optional`. */
|
|
20
|
+
export const none = <T = never>(): Optional<T> => NONE;
|
|
21
|
+
|
|
22
|
+
/** This function makes a successful `Result`. */
|
|
23
|
+
export const ok = <T>(value: T): Result<T> => ({ ok: true, value });
|
|
24
|
+
|
|
25
|
+
/** This function makes a failed `Result`. */
|
|
26
|
+
export const fail = <T = never>(error: VexError): Result<T> => ({ ok: false, error });
|
|
27
|
+
|
|
28
|
+
/** This function tells if an `Optional` holds a value. */
|
|
29
|
+
export const isSome = <T>(o: Optional<T>): o is { readonly tag: "some"; readonly value: T } => o.tag === "some";
|
|
30
|
+
|
|
31
|
+
/** This function tells if an `Optional` is empty. */
|
|
32
|
+
export const isNone = <T>(o: Optional<T>): o is { readonly tag: "none" } => o.tag === "none";
|
|
33
|
+
|
|
34
|
+
/** This function changes a `Result` into an `Optional`. The error is lost. */
|
|
35
|
+
export const toOptional = <T>(r: Result<T>): Optional<T> => (r.ok ? some(r.value) : none());
|
|
36
|
+
|
|
37
|
+
/** This function gives the value of an `Optional`, or `fallback` if it is empty. */
|
|
38
|
+
export const getOr = <T, U>(o: Optional<T>, fallback: U): T | U => (o.tag === "some" ? o.value : fallback);
|
|
39
|
+
|
|
40
|
+
/** This function applies `f` to the value of a `Result`. An error stays the same. */
|
|
41
|
+
export const mapResult = <T, U>(r: Result<T>, f: (value: T) => U): Result<U> => (r.ok ? ok(f(r.value)) : r);
|
|
42
|
+
|
|
43
|
+
/** This function applies `f` to the value of a `Result`, and `f` gives a `Result`. An error stays the same. */
|
|
44
|
+
export const chainResult = <T, U>(r: Result<T>, f: (value: T) => Result<U>): Result<U> => (r.ok ? f(r.value) : r);
|
package/src/sheet.ts
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Sheets: named columns of formulas over a space. A formula can read a column at an address, like a cell
|
|
3
|
+
* reference of a spreadsheet. A cell is one column at one key. A run evaluates each cell once, and each cell on a
|
|
4
|
+
* cycle of reads gives `#CYCLE!`.
|
|
5
|
+
*
|
|
6
|
+
* A cell reference is the extension node `ext("vex.cell", { column, at })`. Thus the IR has no new kind, and the
|
|
7
|
+
* JSON form, `deps` and the traces work without a change.
|
|
8
|
+
*/
|
|
9
|
+
import { vexError } from "./errors.ts";
|
|
10
|
+
import { evaluate, explain, type EvalOptions, type ExtHandler } from "./evaluate.ts";
|
|
11
|
+
import { ext, isMove, type Addr, type Expr } from "./ir.ts";
|
|
12
|
+
import { fail, type Result } from "./result.ts";
|
|
13
|
+
import { resolveAddr } from "./space.ts";
|
|
14
|
+
import type { Trace } from "./trace.ts";
|
|
15
|
+
|
|
16
|
+
/** The extension kind of a cell reference. */
|
|
17
|
+
export const CELL_KIND = "vex.cell";
|
|
18
|
+
|
|
19
|
+
/** The data of a cell reference: the column, and the address from the focus. */
|
|
20
|
+
export interface CellRef {
|
|
21
|
+
readonly column: string;
|
|
22
|
+
readonly at: Addr;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** This function makes a cell reference: the column `column` at the address `at` from the focus. */
|
|
26
|
+
export const cell = (column: string, at: Addr = []): Expr => ext(CELL_KIND, { column, at } satisfies CellRef);
|
|
27
|
+
|
|
28
|
+
const isCellRef = (u: unknown): u is CellRef =>
|
|
29
|
+
typeof u === "object" &&
|
|
30
|
+
u !== null &&
|
|
31
|
+
typeof (u as { column?: unknown }).column === "string" &&
|
|
32
|
+
Array.isArray((u as { at?: unknown }).at) &&
|
|
33
|
+
(u as { at: readonly unknown[] }).at.every(isMove);
|
|
34
|
+
|
|
35
|
+
/** The options of a sheet run: the evaluation options without the origin and the trace. */
|
|
36
|
+
export type SheetOptions = Omit<EvalOptions, "origin" | "trace">;
|
|
37
|
+
|
|
38
|
+
const cycleError = (column: string, key: string): Result<never> =>
|
|
39
|
+
fail(vexError("cycle", `the cell "${column}" at "${key}" is on a cycle of cell references`, { origin: key, focus: key }));
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* One run of a sheet. It keeps the result of each cell that it evaluated. The space does not change, so a cell has
|
|
43
|
+
* one result in a run.
|
|
44
|
+
*
|
|
45
|
+
* The run is a depth-first search with the algorithm of Tarjan for strongly connected components. A cell finishes
|
|
46
|
+
* when its component finishes. Each cell of a component with two or more cells, or with a reference to itself,
|
|
47
|
+
* gives `#CYCLE!`. A read of a cell that is not finished gives `#CYCLE!` too. Thus the order of the evaluations
|
|
48
|
+
* does not change a result, also when `ifError` catches the error of a cycle.
|
|
49
|
+
*/
|
|
50
|
+
/** The state of one cell in the search. */
|
|
51
|
+
interface Visit {
|
|
52
|
+
readonly id: string;
|
|
53
|
+
readonly column: string;
|
|
54
|
+
readonly key: string;
|
|
55
|
+
readonly index: number;
|
|
56
|
+
low: number;
|
|
57
|
+
selfLoop: boolean;
|
|
58
|
+
result: Result<unknown>;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export class SheetRun {
|
|
62
|
+
readonly #columns: ReadonlyMap<string, Expr>;
|
|
63
|
+
readonly #opts: SheetOptions;
|
|
64
|
+
readonly #done = new Map<string, Result<unknown>>();
|
|
65
|
+
// The cells on the stack of the search: started, but their component is not finished.
|
|
66
|
+
readonly #visits = new Map<string, Visit>();
|
|
67
|
+
readonly #stack: Visit[] = [];
|
|
68
|
+
// The cell whose formula is in evaluation. At the top level, it is a placeholder that is not a cell.
|
|
69
|
+
#top: Visit = { id: "", column: "", key: "", index: -1, low: -1, selfLoop: false, result: cycleError("", "") };
|
|
70
|
+
#next = 0;
|
|
71
|
+
|
|
72
|
+
constructor(columns: ReadonlyMap<string, Expr>, opts: SheetOptions) {
|
|
73
|
+
this.#columns = columns;
|
|
74
|
+
this.#opts = { ...opts, extensions: { ...opts.extensions, [CELL_KIND]: this.#handler } };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
readonly #handler: ExtHandler = (data, ctx) => {
|
|
78
|
+
if (!isCellRef(data)) return fail(vexError("bad-expression", "a cell reference needs a column name and an address", { path: ctx.path }));
|
|
79
|
+
const where = resolveAddr(ctx.space, ctx.position, data.at);
|
|
80
|
+
if (!where.ok) return fail({ ...where.error, path: ctx.path });
|
|
81
|
+
return this.cell(data.column, where.value);
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
/** This method gives the result of one cell: the column `column` at the key `key`. */
|
|
85
|
+
cell(column: string, key: string): Result<unknown> {
|
|
86
|
+
const id = `${column}\u0000${key}`;
|
|
87
|
+
const done = this.#done.get(id);
|
|
88
|
+
if (done !== undefined) return done;
|
|
89
|
+
const caller = this.#top;
|
|
90
|
+
const seen = this.#visits.get(id);
|
|
91
|
+
if (seen !== undefined) {
|
|
92
|
+
// A read of a cell that is not finished: the caller and this cell are on one cycle.
|
|
93
|
+
caller.low = Math.min(caller.low, seen.index);
|
|
94
|
+
if (caller === seen) seen.selfLoop = true;
|
|
95
|
+
return cycleError(column, key);
|
|
96
|
+
}
|
|
97
|
+
const program = this.#columns.get(column);
|
|
98
|
+
if (program === undefined) return fail(vexError("unbound", `the sheet has no column "${column}"`, { origin: key, focus: key }));
|
|
99
|
+
|
|
100
|
+
const n = this.#next++;
|
|
101
|
+
const visit: Visit = { id, column, key, index: n, low: n, selfLoop: false, result: cycleError(column, key) };
|
|
102
|
+
this.#visits.set(id, visit);
|
|
103
|
+
this.#stack.push(visit);
|
|
104
|
+
this.#top = visit;
|
|
105
|
+
visit.result = evaluate(program, { ...this.#opts, origin: key });
|
|
106
|
+
this.#top = caller;
|
|
107
|
+
|
|
108
|
+
if (visit.low === visit.index) this.#finish(visit);
|
|
109
|
+
else caller.low = Math.min(caller.low, visit.low);
|
|
110
|
+
return this.#done.get(id) ?? cycleError(column, key);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** This method takes the component of `root` from the stack, and sets the final result of each of its cells. */
|
|
114
|
+
#finish(root: Visit): void {
|
|
115
|
+
const members = this.#stack.splice(this.#stack.indexOf(root));
|
|
116
|
+
const cyclic = members.length > 1 || root.selfLoop;
|
|
117
|
+
for (const m of members) {
|
|
118
|
+
this.#visits.delete(m.id);
|
|
119
|
+
this.#done.set(m.id, cyclic ? cycleError(m.column, m.key) : m.result);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** This method evaluates one cell with a trace of the nodes of its column. The result is the result of the cell. */
|
|
124
|
+
explain(column: string, key: string): Trace {
|
|
125
|
+
const result = this.cell(column, key);
|
|
126
|
+
const program = this.#columns.get(column);
|
|
127
|
+
if (program === undefined) return { events: [], result };
|
|
128
|
+
return { events: explain(program, { ...this.#opts, origin: key }).events, result };
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* This method evaluates the column `column` at each key before `key`, in key order. A recurrence over the keys,
|
|
133
|
+
* for example a running total, then reads finished cells and does not go deep into the call stack.
|
|
134
|
+
*/
|
|
135
|
+
warm(column: string, key: string): void {
|
|
136
|
+
for (const k of this.#opts.space.keys) {
|
|
137
|
+
if (k === key) return;
|
|
138
|
+
this.cell(column, k);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
}
|