@mark1russell7/vex 0.3.0 → 0.4.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/build/index.d.ts +41 -7
- package/build/index.d.ts.map +1 -1
- package/build/index.js +293 -79
- package/build/index.js.map +1 -1
- package/package.json +3 -2
- package/src/builder.ts +69 -16
- package/src/deps.ts +8 -5
- package/src/evaluate.ts +45 -10
- package/src/ir.ts +9 -4
- package/src/json.ts +162 -51
- package/src/sheet.ts +30 -5
- package/src/space.ts +10 -0
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://json.schemastore.org/package",
|
|
3
3
|
"name": "@mark1russell7/vex",
|
|
4
|
-
"version": "0.
|
|
4
|
+
"version": "0.4.0",
|
|
5
5
|
"description": "Vex: typed spreadsheet formulas over domain objects. The kernel and the typed builder.",
|
|
6
6
|
"keywords": [
|
|
7
7
|
"typescript",
|
|
@@ -59,6 +59,7 @@
|
|
|
59
59
|
"test": "vitest run",
|
|
60
60
|
"test:watch": "vitest",
|
|
61
61
|
"bench": "vitest bench --run -c vitest.bench.config.ts --reporter=verbose",
|
|
62
|
-
"typecheck": "tsc -p tsconfig.json && tsc -p tsconfig.test.json"
|
|
62
|
+
"typecheck": "tsc -p tsconfig.json && tsc -p tsconfig.test.json",
|
|
63
|
+
"bench:gate": "node bench/gate.ts"
|
|
63
64
|
}
|
|
64
65
|
}
|
package/src/builder.ts
CHANGED
|
@@ -3,12 +3,14 @@
|
|
|
3
3
|
* evaluate anything until a caller asks for a value.
|
|
4
4
|
*/
|
|
5
5
|
import type { AnyDomain, Domain, OpSpec } from "./domain.ts";
|
|
6
|
+
import type { VexError } from "./errors.ts";
|
|
6
7
|
import { evaluate, explain, type EvalOptions, type ExtHandler, type FreeFn } from "./evaluate.ts";
|
|
7
8
|
import { app, each, ext, index as indexMove, key as keyMove, let_, lit, offset as offsetMove, other as otherMove, origin as originMove, parent as parentMove, rec, ref, toPath, v, type Addr, type Axis, type Expr, type Move } from "./ir.ts";
|
|
8
9
|
import { cell as cellRef, SheetRun } from "./sheet.ts";
|
|
9
10
|
import { toOptional, type Optional, type Result } from "./result.ts";
|
|
10
11
|
import type { Space } from "./space.ts";
|
|
11
12
|
import type { Trace } from "./trace.ts";
|
|
13
|
+
import type { VexList } from "./list.ts";
|
|
12
14
|
import { traversal, type Traversal } from "./traversal.ts";
|
|
13
15
|
|
|
14
16
|
// ---------------------------------------------------------------- argument tokens
|
|
@@ -108,7 +110,13 @@ export type ArgInput<P, Ctx extends ChainContext, Lift extends boolean> =
|
|
|
108
110
|
| KeysOfType<Ctx["record"], P>
|
|
109
111
|
| Arg<P>
|
|
110
112
|
| ChainOf<Ctx, P>
|
|
111
|
-
| (Lift extends true ? ([P] extends [DomainValue<DomainFor<Ctx["domains"], P>>] ?
|
|
113
|
+
| (Lift extends true ? ([P] extends [DomainValue<DomainFor<Ctx["domains"], P>>] ? LiftedNumber<Ctx> : never) : never);
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* A number argument for a domain parameter of an op with `liftScalar` (TYPE.LIFT): a number, a field with numbers, an
|
|
117
|
+
* argument or a chain. The interpreter lifts each of them with `fromScalar` (CALL.LIFT).
|
|
118
|
+
*/
|
|
119
|
+
type LiftedNumber<Ctx extends ChainContext> = number | KeysOfType<Ctx["record"], number> | Arg<number> | ChainOf<Ctx, number>;
|
|
112
120
|
|
|
113
121
|
type MapArgs<P extends readonly unknown[], Ctx extends ChainContext, Lift extends boolean> = { [I in keyof P]: ArgInput<P[I], Ctx, Lift> };
|
|
114
122
|
|
|
@@ -182,6 +190,11 @@ export interface ChainBase<Ctx extends ChainContext, T> {
|
|
|
182
190
|
parent(): ChainOf<Ctx, T>;
|
|
183
191
|
/** This method uses `fallback` when the chain gives an error. */
|
|
184
192
|
ifError<U>(fallback: ArgInput<U, Ctx, false> | T): ChainOf<Ctx, T | U>;
|
|
193
|
+
/**
|
|
194
|
+
* This method gives `then` when the boolean value is true, and `otherwise` when it is false (the form `if`). Only
|
|
195
|
+
* the selected branch evaluates.
|
|
196
|
+
*/
|
|
197
|
+
if<U, V>(this: ChainBase<Ctx, boolean>, then: ArgInput<U, Ctx, false>, otherwise: ArgInput<V, Ctx, false>): ChainOf<Ctx, U | V>;
|
|
185
198
|
/**
|
|
186
199
|
* This method applies the free function `name` of `withOptions`. The function gets the current value as its first
|
|
187
200
|
* argument, then `args`. The types accept only the functions whose first parameter accepts the current value.
|
|
@@ -259,8 +272,18 @@ export interface ListChain<Ctx extends ChainContext, U> {
|
|
|
259
272
|
all(this: ListChain<Ctx, boolean>, opts?: ListOpts): ChainOf<Ctx, boolean>;
|
|
260
273
|
none(this: ListChain<Ctx, boolean>, opts?: ListOpts): ChainOf<Ctx, boolean>;
|
|
261
274
|
values(opts?: ListOpts): ChainOf<Ctx, readonly U[]>;
|
|
275
|
+
/** The keys of the items with a value, in the order of the axis. */
|
|
276
|
+
keys(opts?: ListOpts): ChainOf<Ctx, readonly Ctx["keys"][]>;
|
|
277
|
+
/** The error of each item that failed, in the order of the axis. */
|
|
278
|
+
errors(): ChainOf<Ctx, readonly VexError[]>;
|
|
262
279
|
first(opts?: ListOpts): ChainOf<Ctx, U>;
|
|
263
|
-
reduce(op: OpNames<DomainFor<Ctx["domains"], U>>, opts?:
|
|
280
|
+
reduce(op: OpNames<DomainFor<Ctx["domains"], U>>, opts?: ReduceOpts<Ctx>): ChainOf<Ctx, U>;
|
|
281
|
+
/** The list at the origin `k`: one item for each target of the axis, with its key and its result. */
|
|
282
|
+
result(k: Ctx["keys"]): Result<VexList<U>>;
|
|
283
|
+
/** The list at the origin `k`, as an `Optional`. */
|
|
284
|
+
at(k: Ctx["keys"]): Optional<VexList<U>>;
|
|
285
|
+
/** The trace of the evaluation of the list at the origin `k`. */
|
|
286
|
+
explain(k: Ctx["keys"]): Trace;
|
|
264
287
|
}
|
|
265
288
|
|
|
266
289
|
/** The options of a list reduction. */
|
|
@@ -269,6 +292,11 @@ export interface ListOpts {
|
|
|
269
292
|
readonly strict?: boolean;
|
|
270
293
|
}
|
|
271
294
|
|
|
295
|
+
/** The options of `reduce`. `domain` names the domain whose identity an empty list gives (LIST.EMPTY). */
|
|
296
|
+
export interface ReduceOpts<Ctx extends ChainContext> extends ListOpts {
|
|
297
|
+
readonly domain?: Ctx["domains"][number]["name"];
|
|
298
|
+
}
|
|
299
|
+
|
|
272
300
|
/** The root of the builder for one space. */
|
|
273
301
|
export interface Root<Ctx extends ChainContext> {
|
|
274
302
|
/** This method starts a chain with a field of the record at the focus. */
|
|
@@ -432,16 +460,7 @@ class ChainImpl {
|
|
|
432
460
|
}
|
|
433
461
|
|
|
434
462
|
#opts(k: string): EvalOptions {
|
|
435
|
-
|
|
436
|
-
return {
|
|
437
|
-
space: env.space,
|
|
438
|
-
origin: k,
|
|
439
|
-
domains: env.domains,
|
|
440
|
-
// Stryker disable next-line ConditionalExpression: an undefined option and an absent option are the same
|
|
441
|
-
...(env.options.fns === undefined ? {} : { fns: env.options.fns }),
|
|
442
|
-
// Stryker disable next-line ConditionalExpression: an undefined option and an absent option are the same
|
|
443
|
-
...(env.options.extensions === undefined ? {} : { extensions: env.options.extensions }),
|
|
444
|
-
};
|
|
463
|
+
return evalOptions(this.#s, k);
|
|
445
464
|
}
|
|
446
465
|
|
|
447
466
|
result(k: string): Result<unknown> {
|
|
@@ -491,6 +510,9 @@ class ChainImpl {
|
|
|
491
510
|
call(name: string, ...args: readonly unknown[]): ChainImpl {
|
|
492
511
|
return new ChainImpl({ ...this.#s, expr: app(name, this.#s.expr, ...args.map((a) => toExpr(a, this.#s.addr))) });
|
|
493
512
|
}
|
|
513
|
+
if(then: unknown, otherwise: unknown): ChainImpl {
|
|
514
|
+
return new ChainImpl({ ...this.#s, expr: app("if", this.#s.expr, toExpr(then, this.#s.addr), toExpr(otherwise, this.#s.addr)) });
|
|
515
|
+
}
|
|
494
516
|
ifError(fallback: unknown): ChainImpl {
|
|
495
517
|
return new ChainImpl({ ...this.#s, expr: app("ifError", this.#s.expr, toExpr(fallback, this.#s.addr)) });
|
|
496
518
|
}
|
|
@@ -527,7 +549,8 @@ class ChainImpl {
|
|
|
527
549
|
const inTarget = new ChainImpl({ ...start.#s, addr: [] });
|
|
528
550
|
const inner = body(inTarget);
|
|
529
551
|
const axis: Axis = opts?.where === undefined ? a : { t: "where", axis: a, test: opts.where(inTarget).program };
|
|
530
|
-
|
|
552
|
+
// The moves before the axis are its address: parent().children(f) gives f at each child of the parent.
|
|
553
|
+
return new ListChainImpl({ ...this.#s, expr: let_({ [name]: this.#s.expr }, each(axis, inner.program, this.#s.addr)) });
|
|
531
554
|
}
|
|
532
555
|
others(body: (c: ChainImpl) => { readonly program: Expr }, opts?: { readonly where?: (c: ChainImpl) => { readonly program: Expr } }): ListChainImpl {
|
|
533
556
|
return this.#axis({ t: "others" }, body, opts);
|
|
@@ -552,6 +575,20 @@ class ChainImpl {
|
|
|
552
575
|
}
|
|
553
576
|
}
|
|
554
577
|
|
|
578
|
+
/** This function gives the options of an evaluation of a chain or a list chain at the origin `k`. */
|
|
579
|
+
function evalOptions(s: State, k: string): EvalOptions {
|
|
580
|
+
const { env } = s;
|
|
581
|
+
return {
|
|
582
|
+
space: env.space,
|
|
583
|
+
origin: k,
|
|
584
|
+
domains: env.domains,
|
|
585
|
+
// Stryker disable next-line ConditionalExpression: an undefined option and an absent option are the same
|
|
586
|
+
...(env.options.fns === undefined ? {} : { fns: env.options.fns }),
|
|
587
|
+
// Stryker disable next-line ConditionalExpression: an undefined option and an absent option are the same
|
|
588
|
+
...(env.options.extensions === undefined ? {} : { extensions: env.options.extensions }),
|
|
589
|
+
};
|
|
590
|
+
}
|
|
591
|
+
|
|
555
592
|
class ListChainImpl {
|
|
556
593
|
readonly kind = "vex.list-chain" as const;
|
|
557
594
|
readonly #s: State;
|
|
@@ -561,8 +598,9 @@ class ListChainImpl {
|
|
|
561
598
|
get program(): Expr {
|
|
562
599
|
return this.#s.expr;
|
|
563
600
|
}
|
|
564
|
-
#op(op: string, extra: readonly Expr[], opts?: ListOpts): ChainImpl {
|
|
565
|
-
const
|
|
601
|
+
#op(op: string, extra: readonly Expr[], opts?: ListOpts & { readonly domain?: string }): ChainImpl {
|
|
602
|
+
const options = { ...(opts?.strict === true ? { strict: true } : {}), ...(opts?.domain === undefined ? {} : { domain: opts.domain }) };
|
|
603
|
+
const args = Object.keys(options).length > 0 ? [...extra, lit(options)] : extra;
|
|
566
604
|
return new ChainImpl({ ...this.#s, expr: app(op, this.#s.expr, ...args) });
|
|
567
605
|
}
|
|
568
606
|
count(opts?: ListOpts): ChainImpl {
|
|
@@ -592,12 +630,27 @@ class ListChainImpl {
|
|
|
592
630
|
values(opts?: ListOpts): ChainImpl {
|
|
593
631
|
return this.#op("values", [], opts);
|
|
594
632
|
}
|
|
633
|
+
keys(opts?: ListOpts): ChainImpl {
|
|
634
|
+
return this.#op("keys", [], opts);
|
|
635
|
+
}
|
|
636
|
+
errors(): ChainImpl {
|
|
637
|
+
return this.#op("errors", []);
|
|
638
|
+
}
|
|
595
639
|
first(opts?: ListOpts): ChainImpl {
|
|
596
640
|
return this.#op("first", [], opts);
|
|
597
641
|
}
|
|
598
|
-
reduce(op: string, opts?: ListOpts): ChainImpl {
|
|
642
|
+
reduce(op: string, opts?: ListOpts & { readonly domain?: string }): ChainImpl {
|
|
599
643
|
return this.#op("reduce", [lit(op)], opts);
|
|
600
644
|
}
|
|
645
|
+
result(k: string): Result<unknown> {
|
|
646
|
+
return evaluate(this.#s.expr, evalOptions(this.#s, k));
|
|
647
|
+
}
|
|
648
|
+
at(k: string): Optional<unknown> {
|
|
649
|
+
return toOptional(this.result(k));
|
|
650
|
+
}
|
|
651
|
+
explain(k: string): Trace {
|
|
652
|
+
return explain(this.#s.expr, evalOptions(this.#s, k));
|
|
653
|
+
}
|
|
601
654
|
}
|
|
602
655
|
|
|
603
656
|
class RootImpl {
|
package/src/deps.ts
CHANGED
|
@@ -8,6 +8,8 @@ export interface Dependency {
|
|
|
8
8
|
readonly path: readonly string[];
|
|
9
9
|
/** The axes around the read, from the outside to the inside. Inside an axis, the focus is the target. */
|
|
10
10
|
readonly axes: readonly Axis["t"][];
|
|
11
|
+
/** The address of each axis in `axes`, in the same order. The empty address is the focus. */
|
|
12
|
+
readonly axisAt: readonly Addr[];
|
|
11
13
|
}
|
|
12
14
|
|
|
13
15
|
/**
|
|
@@ -16,18 +18,19 @@ export interface Dependency {
|
|
|
16
18
|
*/
|
|
17
19
|
export function deps(e: Expr): readonly Dependency[] {
|
|
18
20
|
const out: Dependency[] = [];
|
|
19
|
-
const walk = (x: Expr, axes: readonly Axis["t"][]): void => {
|
|
21
|
+
const walk = (x: Expr, axes: readonly Axis["t"][], axisAt: readonly Addr[]): void => {
|
|
20
22
|
if (x.tag === "ref") {
|
|
21
|
-
out.push({ at: x.at ?? [], path: x.path, axes });
|
|
23
|
+
out.push({ at: x.at ?? [], path: x.path, axes, axisAt });
|
|
22
24
|
return;
|
|
23
25
|
}
|
|
24
26
|
if (x.tag === "each") {
|
|
25
27
|
const inner = [...axes, x.axis.t];
|
|
26
|
-
|
|
28
|
+
const innerAt = [...axisAt, x.at ?? []];
|
|
29
|
+
children(x).forEach((c) => walk(c, inner, innerAt));
|
|
27
30
|
return;
|
|
28
31
|
}
|
|
29
|
-
children(x).forEach((c) => walk(c, axes));
|
|
32
|
+
children(x).forEach((c) => walk(c, axes, axisAt));
|
|
30
33
|
};
|
|
31
|
-
walk(e, []);
|
|
34
|
+
walk(e, [], []);
|
|
32
35
|
return out;
|
|
33
36
|
}
|
package/src/evaluate.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { liftsAt, resolveOp, type AnyDomain, type ParamKind, type ResolvedOp } from "./domain.ts";
|
|
2
2
|
import { formatError, vexError, type ErrorKind, type VexError } from "./errors.ts";
|
|
3
|
-
import { children, type Axis, type Expr, type ExprOf } from "./ir.ts";
|
|
3
|
+
import { children, type Axis, type Expr, type ExprOf, type Move } from "./ir.ts";
|
|
4
4
|
import { isListOp, isVexList, vexList, type ListItem, type ListOp, type ListOptions, type VexList } from "./list.ts";
|
|
5
5
|
import { fail, ok, type Result } from "./result.ts";
|
|
6
6
|
import { axisTargets, resolveAddr, type Position, type Space } from "./space.ts";
|
|
@@ -289,10 +289,19 @@ class Compiler {
|
|
|
289
289
|
|
|
290
290
|
#each(e: ExprOf<"each">, info: Info): Node {
|
|
291
291
|
const { path } = info;
|
|
292
|
+
const at = e.at ?? [];
|
|
292
293
|
const targets = this.#targets(e.axis, path, { next: 1 });
|
|
293
294
|
const body = this.node(e.body, [...path, 0]);
|
|
294
295
|
return (f, c) => {
|
|
295
|
-
|
|
296
|
+
// An axis with an address finds its targets from the key of the address. The origin does not change.
|
|
297
|
+
let from = f;
|
|
298
|
+
// Stryker disable next-line ConditionalExpression,EqualityOperator: resolveAddr of [] gives the focus too
|
|
299
|
+
if (at.length > 0) {
|
|
300
|
+
const where = resolveAddr(c.space, f.pos, at);
|
|
301
|
+
if (!where.ok) return this.#emit(c, info, f, fail({ ...where.error, path }));
|
|
302
|
+
from = { pos: { origin: f.pos.origin, focus: where.value }, env: f.env };
|
|
303
|
+
}
|
|
304
|
+
const ts = targets(from, c);
|
|
296
305
|
if (!ts.ok) return this.#emit(c, info, f, ts);
|
|
297
306
|
const items: ListItem[] = ts.value.map(({ key, test }) => {
|
|
298
307
|
if (test !== undefined && !test.ok) return { key, result: test };
|
|
@@ -502,19 +511,29 @@ class Compiler {
|
|
|
502
511
|
return ok(!b.value.some((x) => x));
|
|
503
512
|
}
|
|
504
513
|
case "reduce":
|
|
505
|
-
return this.#reduce(rest[0], okValues, f, path);
|
|
514
|
+
return this.#reduce(rest[0], okValues, f, path, optsArg);
|
|
506
515
|
}
|
|
507
516
|
}
|
|
508
517
|
|
|
509
|
-
/**
|
|
510
|
-
|
|
518
|
+
/**
|
|
519
|
+
* This method folds the values with a domain op, from the left. An empty list gives the identity of the op, if one
|
|
520
|
+
* domain has an identity for the op (LIST.EMPTY). The option `domain` names that domain when more domains have one.
|
|
521
|
+
*/
|
|
522
|
+
#reduce(opName: unknown, values: readonly unknown[], f: Frame, path: readonly number[], opts: unknown): Result<unknown> {
|
|
511
523
|
if (typeof opName !== "string") return this.#err("kind-mismatch", `"reduce" needs an op name, but got a ${describeType(opName)}`, f, path, { op: "reduce" });
|
|
512
524
|
if (values.length === 0) {
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
525
|
+
const named = (opts as { domain?: unknown } | null | undefined)?.domain;
|
|
526
|
+
const candidates = this.#domains.filter((d) => Object.hasOwn(d.ops, opName) && (d.ops[opName] as { identity?: () => unknown }).identity !== undefined && (named === undefined || d.name === named));
|
|
527
|
+
if (named !== undefined && !this.#domains.some((d) => d.name === named)) {
|
|
528
|
+
return this.#err("unknown-op", `"reduce" names the domain ${JSON.stringify(named)}, but the program has no such domain`, f, path, { op: opName });
|
|
529
|
+
}
|
|
530
|
+
const [only, second] = candidates;
|
|
531
|
+
if (only === undefined) return this.#err("empty", `"reduce" with "${opName}" has no values and the op has no identity`, f, path, { op: opName });
|
|
532
|
+
if (second !== undefined) {
|
|
533
|
+
const names = candidates.map((d) => d.name).join(", ");
|
|
534
|
+
return this.#err("empty", `"reduce" with "${opName}" has no values, and more domains have an identity for it (${names}). Name one with { domain }`, f, path, { op: opName });
|
|
516
535
|
}
|
|
517
|
-
return this.#
|
|
536
|
+
return this.#invoke((only.ops[opName] as { identity: () => unknown }).identity, opName, f, path);
|
|
518
537
|
}
|
|
519
538
|
let acc: unknown = values[0];
|
|
520
539
|
for (let i = 1; i < values.length; i++) {
|
|
@@ -587,12 +606,28 @@ export function labelOf(e: Expr): string {
|
|
|
587
606
|
case "rec":
|
|
588
607
|
return `{ ${Object.keys(e.fields).join(", ")} }`;
|
|
589
608
|
case "each":
|
|
590
|
-
return `each ${e.axis.t}`;
|
|
609
|
+
return e.at === undefined ? `each ${e.axis.t}` : `each ${e.axis.t} from ${e.at.map(moveText).join(".")}`;
|
|
591
610
|
case "ext":
|
|
592
611
|
return e.kind;
|
|
593
612
|
}
|
|
594
613
|
}
|
|
595
614
|
|
|
615
|
+
/** This function gives a short text for a move, for the label of an axis with an address. */
|
|
616
|
+
function moveText(m: Move): string {
|
|
617
|
+
switch (m.t) {
|
|
618
|
+
case "key":
|
|
619
|
+
return `key(${m.key})`;
|
|
620
|
+
case "index":
|
|
621
|
+
return `index(${m.i})`;
|
|
622
|
+
case "offset":
|
|
623
|
+
return `offset(${m.d.join(", ")})`;
|
|
624
|
+
case "other":
|
|
625
|
+
case "origin":
|
|
626
|
+
case "parent":
|
|
627
|
+
return m.t;
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
|
|
596
631
|
/** This function gives a short text for a value. */
|
|
597
632
|
export function previewValue(u: unknown): string {
|
|
598
633
|
// JSON has no NaN and no Infinity, so a number gets its own text. JSON gives the text of the other primitives.
|
package/src/ir.ts
CHANGED
|
@@ -35,7 +35,7 @@ export type Expr =
|
|
|
35
35
|
| { readonly tag: "let"; readonly bind: Readonly<Record<string, Expr>>; readonly body: Expr }
|
|
36
36
|
| { readonly tag: "var"; readonly name: string }
|
|
37
37
|
| { readonly tag: "rec"; readonly fields: Readonly<Record<string, Expr>> }
|
|
38
|
-
| { readonly tag: "each"; readonly axis: Axis; readonly body: Expr }
|
|
38
|
+
| { readonly tag: "each"; readonly axis: Axis; readonly body: Expr; readonly at?: Addr }
|
|
39
39
|
| { readonly tag: "ext"; readonly kind: string; readonly data: unknown };
|
|
40
40
|
|
|
41
41
|
/** The tag of an expression kind. */
|
|
@@ -71,8 +71,13 @@ export const v = (name: string): ExprOf<"var"> => ({ tag: "var", name });
|
|
|
71
71
|
/** This function makes a record from field expressions. */
|
|
72
72
|
export const rec = (fields: Readonly<Record<string, Expr>>): ExprOf<"rec"> => ({ tag: "rec", fields });
|
|
73
73
|
|
|
74
|
-
/**
|
|
75
|
-
|
|
74
|
+
/**
|
|
75
|
+
* This function evaluates `body` once for each target of `axis`. The result is a list. With `at`, the axis finds its
|
|
76
|
+
* targets from the key of that address, not from the focus.
|
|
77
|
+
*/
|
|
78
|
+
export function each(axis: Axis, body: Expr, at?: Addr): ExprOf<"each"> {
|
|
79
|
+
return at === undefined || at.length === 0 ? { tag: "each", axis, body } : { tag: "each", axis, body, at };
|
|
80
|
+
}
|
|
76
81
|
|
|
77
82
|
/** This function makes an expression of an extension kind. */
|
|
78
83
|
export const ext = (kind: string, data: unknown): ExprOf<"ext"> => ({ tag: "ext", kind, data });
|
|
@@ -180,7 +185,7 @@ export function isExpr(u: unknown): u is Expr {
|
|
|
180
185
|
case "rec":
|
|
181
186
|
return isExprRecord(u["fields"]);
|
|
182
187
|
case "each":
|
|
183
|
-
return isAxis(u["axis"]) && isExpr(u["body"]);
|
|
188
|
+
return isAxis(u["axis"]) && isExpr(u["body"]) && (u["at"] === undefined || (Array.isArray(u["at"]) && u["at"].every(isMove)));
|
|
184
189
|
case "ext":
|
|
185
190
|
return typeof u["kind"] === "string" && "data" in u;
|
|
186
191
|
default:
|
package/src/json.ts
CHANGED
|
@@ -3,77 +3,188 @@ import { vexError } from "./errors.ts";
|
|
|
3
3
|
import { isExpr, type Expr } from "./ir.ts";
|
|
4
4
|
import { fail, ok, type Result } from "./result.ts";
|
|
5
5
|
|
|
6
|
-
/**
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
6
|
+
/**
|
|
7
|
+
* The JSON form of the values in a literal. JSON data stays as it is, with three exceptions. Each exception is a record
|
|
8
|
+
* with the key `$vex`:
|
|
9
|
+
*
|
|
10
|
+
* - `{ "$vex": "domain", "domain": name, "value": v }`: a value of a domain, with the `encode` of the domain.
|
|
11
|
+
* - `{ "$vex": "number", "value": "-0" }`: a number that JSON has no text for: `-0`, `NaN`, `Infinity` or `-Infinity`.
|
|
12
|
+
* - `{ "$vex": "escape", "value": record }`: a record of the data that has the key `$vex` itself (IR.JSON.ESCAPE).
|
|
13
|
+
*
|
|
14
|
+
* A record with the key `$vex` and another form stays data, so a file from an older version reads as before.
|
|
15
|
+
*
|
|
16
|
+
* The functions walk the tree of the expression, so only the value of a literal gets this form. A field of a literal
|
|
17
|
+
* that looks like an expression stays data. The data of an extension is plain JSON, as before.
|
|
18
|
+
*/
|
|
19
|
+
type Encoded =
|
|
20
|
+
| { readonly $vex: "domain"; readonly domain: string; readonly value: unknown }
|
|
21
|
+
| { readonly $vex: "number"; readonly value: "-0" | "NaN" | "Infinity" | "-Infinity" }
|
|
22
|
+
| { readonly $vex: "escape"; readonly value: Readonly<Record<string, unknown>> };
|
|
23
|
+
|
|
24
|
+
const isRecord = (u: unknown): u is Readonly<Record<string, unknown>> => typeof u === "object" && u !== null && !Array.isArray(u);
|
|
25
|
+
|
|
26
|
+
const isPlainRecord = (u: unknown): u is Readonly<Record<string, unknown>> => {
|
|
27
|
+
if (!isRecord(u)) return false;
|
|
28
|
+
const proto: unknown = Object.getPrototypeOf(u);
|
|
29
|
+
return proto === Object.prototype || proto === null;
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
/** This function gives the JSON form of a value, or the reason why the value has no JSON form. */
|
|
33
|
+
function encodeValue(u: unknown, domains: readonly AnyDomain[]): Result<unknown> {
|
|
34
|
+
if (u === null || typeof u === "string" || typeof u === "boolean") return ok(u);
|
|
35
|
+
if (typeof u === "number") {
|
|
36
|
+
if (Object.is(u, -0)) return ok({ $vex: "number", value: "-0" } satisfies Encoded);
|
|
37
|
+
// Stryker disable next-line EqualityOperator: here u is an infinity, so u > 0 and u >= 0 are the same test
|
|
38
|
+
return Number.isFinite(u) ? ok(u) : ok({ $vex: "number", value: Number.isNaN(u) ? "NaN" : u > 0 ? "Infinity" : "-Infinity" } satisfies Encoded);
|
|
39
|
+
}
|
|
40
|
+
if (Array.isArray(u)) {
|
|
41
|
+
const out: unknown[] = [];
|
|
42
|
+
for (const x of u) {
|
|
43
|
+
const r = encodeValue(x, domains);
|
|
44
|
+
if (!r.ok) return r;
|
|
45
|
+
out.push(r.value);
|
|
46
|
+
}
|
|
47
|
+
return ok(out);
|
|
48
|
+
}
|
|
49
|
+
if (isPlainRecord(u)) {
|
|
50
|
+
const out: Record<string, unknown> = {};
|
|
51
|
+
for (const [k, x] of Object.entries(u)) {
|
|
52
|
+
const r = encodeValue(x, domains);
|
|
53
|
+
if (!r.ok) return r;
|
|
54
|
+
out[k] = r.value;
|
|
55
|
+
}
|
|
56
|
+
return ok(Object.hasOwn(u, "$vex") ? ({ $vex: "escape", value: out } satisfies Encoded) : out);
|
|
57
|
+
}
|
|
58
|
+
// A plain array or record stays data. Another object is a value of a domain, or it has no JSON form.
|
|
59
|
+
const d = domains.find((dom) => dom.encode !== undefined && dom.is(u));
|
|
60
|
+
if (d?.encode !== undefined) return ok({ $vex: "domain", domain: d.name, value: d.encode(u) } satisfies Encoded);
|
|
61
|
+
return fail(vexError("bad-expression", "a literal value is not JSON data and no domain encodes it"));
|
|
11
62
|
}
|
|
12
63
|
|
|
13
|
-
const
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
if (
|
|
18
|
-
const
|
|
19
|
-
|
|
64
|
+
const NUMBERS: Readonly<Record<string, number>> = { "-0": -0, NaN: Number.NaN, Infinity: Number.POSITIVE_INFINITY, "-Infinity": Number.NEGATIVE_INFINITY };
|
|
65
|
+
|
|
66
|
+
/** This function reads a value from its JSON form. */
|
|
67
|
+
function decodeValue(u: unknown, domains: readonly AnyDomain[]): Result<unknown> {
|
|
68
|
+
if (Array.isArray(u)) {
|
|
69
|
+
const out: unknown[] = [];
|
|
70
|
+
for (const x of u) {
|
|
71
|
+
const r = decodeValue(x, domains);
|
|
72
|
+
if (!r.ok) return r;
|
|
73
|
+
out.push(r.value);
|
|
74
|
+
}
|
|
75
|
+
return ok(out);
|
|
20
76
|
}
|
|
21
|
-
return
|
|
22
|
-
|
|
77
|
+
if (!isRecord(u)) return ok(u);
|
|
78
|
+
const fields = (record: Readonly<Record<string, unknown>>): Result<unknown> => {
|
|
79
|
+
const out: Record<string, unknown> = {};
|
|
80
|
+
for (const [k, x] of Object.entries(record)) {
|
|
81
|
+
const r = decodeValue(x, domains);
|
|
82
|
+
if (!r.ok) return r;
|
|
83
|
+
out[k] = r.value;
|
|
84
|
+
}
|
|
85
|
+
return ok(out);
|
|
86
|
+
};
|
|
87
|
+
// A record without the key $vex matches none of the forms below, so it stays data too.
|
|
88
|
+
const kind = u["$vex"];
|
|
89
|
+
if (kind === "escape" && isRecord(u["value"])) return fields(u["value"]);
|
|
90
|
+
if (kind === "number" && typeof u["value"] === "string" && Object.hasOwn(NUMBERS, u["value"])) return ok(NUMBERS[u["value"]]);
|
|
91
|
+
if (kind === "domain" && typeof u["domain"] === "string") {
|
|
92
|
+
const name = u["domain"];
|
|
93
|
+
const d = domains.find((dom) => dom.name === name);
|
|
94
|
+
if (d?.decode === undefined) return fail(vexError("bad-expression", `no domain "${name}" decodes a literal`));
|
|
95
|
+
return ok(d.decode(u["value"]));
|
|
96
|
+
}
|
|
97
|
+
// A form that this version does not know stays data, so a file from an older version reads as before.
|
|
98
|
+
return fields(u);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** This function applies `f` to each literal value of a JSON tree of an expression. */
|
|
102
|
+
function mapValues(u: unknown, f: (value: unknown) => Result<unknown>): Result<unknown> {
|
|
103
|
+
if (!isRecord(u)) return ok(u);
|
|
104
|
+
const out: Record<string, unknown> = { ...u };
|
|
105
|
+
const child = (key: string): Result<unknown> | undefined => {
|
|
106
|
+
const r = mapValues(u[key], f);
|
|
107
|
+
if (r.ok) out[key] = r.value;
|
|
108
|
+
return r.ok ? undefined : r;
|
|
109
|
+
};
|
|
110
|
+
const each = (key: string): Result<unknown> | undefined => {
|
|
111
|
+
const list = u[key];
|
|
112
|
+
if (Array.isArray(list)) {
|
|
113
|
+
const items: unknown[] = [];
|
|
114
|
+
for (const x of list) {
|
|
115
|
+
const r = mapValues(x, f);
|
|
116
|
+
if (!r.ok) return r;
|
|
117
|
+
items.push(r.value);
|
|
118
|
+
}
|
|
119
|
+
out[key] = items;
|
|
120
|
+
} else if (isRecord(list)) {
|
|
121
|
+
const rec: Record<string, unknown> = {};
|
|
122
|
+
for (const [k, x] of Object.entries(list)) {
|
|
123
|
+
const r = mapValues(x, f);
|
|
124
|
+
if (!r.ok) return r;
|
|
125
|
+
rec[k] = r.value;
|
|
126
|
+
}
|
|
127
|
+
out[key] = rec;
|
|
128
|
+
}
|
|
129
|
+
return undefined;
|
|
130
|
+
};
|
|
131
|
+
const axis = (a: unknown): Result<unknown> => {
|
|
132
|
+
if (!isRecord(a) || a["t"] !== "where") return ok(a);
|
|
133
|
+
const inner = axis(a["axis"]);
|
|
134
|
+
if (!inner.ok) return inner;
|
|
135
|
+
const test = mapValues(a["test"], f);
|
|
136
|
+
return test.ok ? ok({ ...a, axis: inner.value, test: test.value }) : test;
|
|
137
|
+
};
|
|
138
|
+
switch (u["tag"]) {
|
|
139
|
+
case "lit": {
|
|
140
|
+
if (!Object.hasOwn(u, "value")) return ok(out);
|
|
141
|
+
const r = f(u["value"]);
|
|
142
|
+
if (!r.ok) return r;
|
|
143
|
+
out["value"] = r.value;
|
|
144
|
+
return ok(out);
|
|
145
|
+
}
|
|
146
|
+
case "app":
|
|
147
|
+
return each("args") ?? ok(out);
|
|
148
|
+
case "let":
|
|
149
|
+
return each("bind") ?? child("body") ?? ok(out);
|
|
150
|
+
case "rec":
|
|
151
|
+
return each("fields") ?? ok(out);
|
|
152
|
+
case "each": {
|
|
153
|
+
const a = axis(u["axis"]);
|
|
154
|
+
if (!a.ok) return a;
|
|
155
|
+
out["axis"] = a.value;
|
|
156
|
+
return child("body") ?? ok(out);
|
|
157
|
+
}
|
|
158
|
+
default:
|
|
159
|
+
return ok(out);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
23
162
|
|
|
24
163
|
/**
|
|
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!`.
|
|
164
|
+
* This function gives the JSON text of an expression. A literal value that is a domain value needs a domain with
|
|
165
|
+
* `encode`. A literal value that is not JSON data and has no such domain gives the error `#VALUE!`.
|
|
27
166
|
*/
|
|
28
167
|
// Stryker disable next-line ArrayDeclaration: a list with a value that is not a domain encodes no value
|
|
29
168
|
export function serialize(e: Expr, domains: readonly AnyDomain[] = []): Result<string> {
|
|
30
|
-
const failure: { message: string }[] = [];
|
|
31
|
-
const replacer = function (this: unknown, k: string, value: unknown): unknown {
|
|
32
|
-
// JSON.stringify gives each replacer call an object as this.
|
|
33
|
-
const holder = this as Record<string, unknown>;
|
|
34
|
-
if (k !== "value" || holder["tag"] !== "lit") return value;
|
|
35
|
-
if (isPlainJson(value)) return value;
|
|
36
|
-
const d = domains.find((dom) => dom.encode !== undefined && dom.is(value));
|
|
37
|
-
if (d?.encode !== undefined) {
|
|
38
|
-
const encoded: EncodedValue = { $vex: "domain", domain: d.name, value: d.encode(value) };
|
|
39
|
-
return encoded;
|
|
40
|
-
}
|
|
41
|
-
failure.push({ message: `a literal value is not JSON data and no domain encodes it` });
|
|
42
|
-
return null;
|
|
43
|
-
};
|
|
44
|
-
let text: string;
|
|
45
169
|
try {
|
|
46
|
-
|
|
170
|
+
// A getter of a literal value can throw, so the encoding is inside the try too.
|
|
171
|
+
const tree = mapValues(e, (v) => encodeValue(v, domains));
|
|
172
|
+
return tree.ok ? ok(JSON.stringify(tree.value)) : fail(tree.error);
|
|
47
173
|
} catch (thrown) {
|
|
48
174
|
return fail(vexError("threw", "the expression has no JSON form", { thrown }));
|
|
49
175
|
}
|
|
50
|
-
const first = failure[0];
|
|
51
|
-
return first === undefined ? ok(text) : fail(vexError("bad-expression", first.message));
|
|
52
176
|
}
|
|
53
177
|
|
|
54
|
-
const isEncoded = (u: unknown): u is EncodedValue =>
|
|
55
|
-
(u as { $vex?: unknown } | null)?.$vex === "domain" && typeof (u as { domain?: unknown }).domain === "string";
|
|
56
|
-
|
|
57
178
|
/** This function reads an expression from JSON text. It checks the whole tree. */
|
|
58
179
|
// Stryker disable next-line ArrayDeclaration: a list with a value that is not a domain decodes no value
|
|
59
180
|
export function parse(text: string, domains: readonly AnyDomain[] = []): Result<Expr> {
|
|
60
181
|
let raw: unknown;
|
|
61
|
-
const failure: string[] = [];
|
|
62
182
|
try {
|
|
63
|
-
raw = JSON.parse(text
|
|
64
|
-
if (!isEncoded(value)) return value;
|
|
65
|
-
const d = domains.find((dom) => dom.name === value.domain);
|
|
66
|
-
if (d?.decode === undefined) {
|
|
67
|
-
failure.push(`no domain "${value.domain}" decodes a literal`);
|
|
68
|
-
return value;
|
|
69
|
-
}
|
|
70
|
-
const decoded: unknown = d.decode(value.value);
|
|
71
|
-
return decoded;
|
|
72
|
-
});
|
|
183
|
+
raw = JSON.parse(text);
|
|
73
184
|
} catch (thrown) {
|
|
74
185
|
return fail(vexError("bad-expression", "the text is not JSON", { thrown }));
|
|
75
186
|
}
|
|
76
|
-
const
|
|
77
|
-
if (
|
|
78
|
-
return isExpr(
|
|
187
|
+
const tree = mapValues(raw, (v) => decodeValue(v, domains));
|
|
188
|
+
if (!tree.ok) return fail(tree.error);
|
|
189
|
+
return isExpr(tree.value) ? ok(tree.value) : fail(vexError("bad-expression", "the JSON is not a valid Vex expression"));
|
|
79
190
|
}
|
package/src/sheet.ts
CHANGED
|
@@ -62,6 +62,10 @@ export class SheetRun {
|
|
|
62
62
|
readonly #columns: ReadonlyMap<string, Expr>;
|
|
63
63
|
readonly #opts: SheetOptions;
|
|
64
64
|
readonly #done = new Map<string, Result<unknown>>();
|
|
65
|
+
// For each column, the number of keys at the start of the key order that a warm-up evaluated.
|
|
66
|
+
readonly #warmed = new Map<string, number>();
|
|
67
|
+
// The position of each key in the key order, made at the first warm-up.
|
|
68
|
+
#index: ReadonlyMap<string, number> | undefined;
|
|
65
69
|
// The cells on the stack of the search: started, but their component is not finished.
|
|
66
70
|
readonly #visits = new Map<string, Visit>();
|
|
67
71
|
// Stryker disable next-line ArrayDeclaration: the search never reads below the root of a component
|
|
@@ -83,8 +87,30 @@ export class SheetRun {
|
|
|
83
87
|
return this.cell(data.column, where.value);
|
|
84
88
|
};
|
|
85
89
|
|
|
86
|
-
/**
|
|
90
|
+
/**
|
|
91
|
+
* This method gives the result of one cell: the column `column` at the key `key`. A read from a host first evaluates
|
|
92
|
+
* the column at the keys before `key`, in key order. Thus a recurrence over the keys reads finished cells, and a
|
|
93
|
+
* first read at the last key does not go deep into the call stack.
|
|
94
|
+
*/
|
|
87
95
|
cell(column: string, key: string): Result<unknown> {
|
|
96
|
+
// The placeholder at the top has the index -1. A read inside a formula has a cell at the top, so it does not warm.
|
|
97
|
+
if (this.#top.index < 0) this.#warmTo(column, key);
|
|
98
|
+
return this.#cell(column, key);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** This method evaluates the column `column` at each key before `key` that it did not evaluate before, in key order. */
|
|
102
|
+
#warmTo(column: string, key: string): void {
|
|
103
|
+
if (!this.#columns.has(column)) return;
|
|
104
|
+
const keys = this.#opts.space.keys;
|
|
105
|
+
this.#index ??= new Map(keys.map((k, i) => [k, i]));
|
|
106
|
+
const end = this.#index.get(key) ?? 0;
|
|
107
|
+
const start = this.#warmed.get(column) ?? 0;
|
|
108
|
+
for (let i = start; i < end; i++) this.#cell(column, keys[i] ?? key);
|
|
109
|
+
if (end > start) this.#warmed.set(column, end);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** This method evaluates one cell, without the warm-up of `cell`. */
|
|
113
|
+
#cell(column: string, key: string): Result<unknown> {
|
|
88
114
|
const id = `${column}\u0000${key}`;
|
|
89
115
|
const done = this.#done.get(id);
|
|
90
116
|
if (done !== undefined) return done;
|
|
@@ -117,6 +143,8 @@ export class SheetRun {
|
|
|
117
143
|
/** This method takes the component of `root` from the stack, and sets the final result of each of its cells. */
|
|
118
144
|
#finish(root: Visit): void {
|
|
119
145
|
const members = this.#stack.splice(this.#stack.indexOf(root));
|
|
146
|
+
// A component of two or more cells reads its root again, so root.reread alone decides. The length test is a guard.
|
|
147
|
+
// Stryker disable next-line ConditionalExpression,LogicalOperator: members.length > 1 implies root.reread
|
|
120
148
|
const cyclic = members.length > 1 || root.reread;
|
|
121
149
|
for (const m of members) {
|
|
122
150
|
// Stryker disable next-line CallExpression: a finished cell is in #done, and cell() reads #done first
|
|
@@ -138,9 +166,6 @@ export class SheetRun {
|
|
|
138
166
|
* for example a running total, then reads finished cells and does not go deep into the call stack.
|
|
139
167
|
*/
|
|
140
168
|
warm(column: string, key: string): void {
|
|
141
|
-
|
|
142
|
-
if (k === key) return;
|
|
143
|
-
this.cell(column, k);
|
|
144
|
-
}
|
|
169
|
+
this.#warmTo(column, key);
|
|
145
170
|
}
|
|
146
171
|
}
|