@mark1russell7/vex 0.2.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/LICENSE +21 -21
- package/README.md +53 -0
- package/build/index.d.ts +83 -18
- package/build/index.d.ts.map +1 -1
- package/build/index.js +329 -104
- package/build/index.js.map +1 -1
- package/package.json +20 -2
- package/src/builder.ts +161 -34
- package/src/deps.ts +8 -5
- package/src/domain.ts +2 -1
- package/src/evaluate.ts +65 -16
- package/src/ir.ts +12 -7
- package/src/json.ts +164 -50
- package/src/list.ts +1 -1
- package/src/sheet.ts +41 -11
- package/src/space.ts +20 -3
- package/src/traversal.ts +2 -3
package/package.json
CHANGED
|
@@ -1,8 +1,25 @@
|
|
|
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
|
+
"keywords": [
|
|
7
|
+
"typescript",
|
|
8
|
+
"spreadsheet",
|
|
9
|
+
"formulas",
|
|
10
|
+
"expression-language",
|
|
11
|
+
"dsl",
|
|
12
|
+
"computed-fields",
|
|
13
|
+
"rules-engine",
|
|
14
|
+
"declarative",
|
|
15
|
+
"layout",
|
|
16
|
+
"functional-programming"
|
|
17
|
+
],
|
|
18
|
+
"homepage": "https://mark1russell7.github.io/vex/",
|
|
19
|
+
"bugs": {
|
|
20
|
+
"url": "https://github.com/mark1russell7/vex/issues"
|
|
21
|
+
},
|
|
22
|
+
"author": "Mark Russell (https://github.com/mark1russell7)",
|
|
6
23
|
"license": "MIT",
|
|
7
24
|
"repository": {
|
|
8
25
|
"type": "git",
|
|
@@ -42,6 +59,7 @@
|
|
|
42
59
|
"test": "vitest run",
|
|
43
60
|
"test:watch": "vitest",
|
|
44
61
|
"bench": "vitest bench --run -c vitest.bench.config.ts --reporter=verbose",
|
|
45
|
-
"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"
|
|
46
64
|
}
|
|
47
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,17 +110,48 @@ 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
|
|
|
115
|
-
/** The
|
|
123
|
+
/** A table of free functions. The first parameter of a function gets the current value of the chain. */
|
|
124
|
+
export type FnTable = Readonly<Record<string, (...args: never[]) => unknown>>;
|
|
125
|
+
|
|
126
|
+
/** The free functions of a builder without `withOptions`: none, so `call` accepts no name. */
|
|
127
|
+
// oxlint-disable-next-line typescript/no-generated-empty-object-type -- an empty table is the intent.
|
|
128
|
+
export type NoFns = Record<never, never>;
|
|
129
|
+
|
|
130
|
+
/** The static context of a chain: its domains, its key type, its record type and its free functions. */
|
|
116
131
|
export interface ChainContext {
|
|
117
132
|
readonly domains: readonly AnyDomain[];
|
|
118
133
|
readonly keys: string;
|
|
119
134
|
readonly record: unknown;
|
|
135
|
+
readonly fns?: FnTable;
|
|
120
136
|
}
|
|
121
137
|
|
|
138
|
+
type FnsOf<Ctx extends ChainContext> = NonNullable<Ctx["fns"]>;
|
|
139
|
+
type FnParams<F> = F extends (...args: infer P) => unknown ? P : never;
|
|
140
|
+
type FirstParam<P> = P extends readonly [infer A, ...unknown[]] ? A : unknown;
|
|
141
|
+
type RestParams<P> = P extends readonly [unknown, ...infer R] ? R : [];
|
|
142
|
+
|
|
143
|
+
/** The names of the free functions whose first parameter accepts a value of type `T`. */
|
|
144
|
+
export type CallableFns<Ctx extends ChainContext, T> = {
|
|
145
|
+
[K in keyof FnsOf<Ctx>]: [T] extends [FirstParam<FnParams<FnsOf<Ctx>[K]>>] ? K : never;
|
|
146
|
+
}[keyof FnsOf<Ctx>] &
|
|
147
|
+
string;
|
|
148
|
+
|
|
149
|
+
/** The inputs for the parameters of the free function `N` after its first parameter. */
|
|
150
|
+
export type CallArgs<Ctx extends ChainContext, N extends keyof FnsOf<Ctx>> = MapArgs<RestParams<FnParams<FnsOf<Ctx>[N]>>, Ctx, false>;
|
|
151
|
+
|
|
152
|
+
/** The return type of the free function `N`. */
|
|
153
|
+
export type CallReturn<Ctx extends ChainContext, N extends keyof FnsOf<Ctx>> = FnsOf<Ctx>[N] extends (...args: never[]) => infer R ? R : unknown;
|
|
154
|
+
|
|
122
155
|
/** The ops section `._` of a chain whose value has domain `Dm`. */
|
|
123
156
|
export type OpsProxy<Ctx extends ChainContext, Dm> = {
|
|
124
157
|
readonly [M in OpNames<Dm>]: (...args: MapArgs<OpParams<Dm, M>, Ctx, Lifts<Dm, M>>) => ChainOf<Ctx, OpReturn<Dm, M>>;
|
|
@@ -157,6 +190,16 @@ export interface ChainBase<Ctx extends ChainContext, T> {
|
|
|
157
190
|
parent(): ChainOf<Ctx, T>;
|
|
158
191
|
/** This method uses `fallback` when the chain gives an error. */
|
|
159
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>;
|
|
198
|
+
/**
|
|
199
|
+
* This method applies the free function `name` of `withOptions`. The function gets the current value as its first
|
|
200
|
+
* argument, then `args`. The types accept only the functions whose first parameter accepts the current value.
|
|
201
|
+
*/
|
|
202
|
+
call<N extends CallableFns<Ctx, T>>(name: N, ...args: CallArgs<Ctx, N>): ChainOf<Ctx, CallReturn<Ctx, N>>;
|
|
160
203
|
/** This method evaluates each branch with the current value, and gives a record of the results. */
|
|
161
204
|
fork<const B extends Readonly<Record<string, (c: ChainOf<Ctx, T>) => ChainBase<Ctx, unknown>>>>(branches: B): ChainOf<Ctx, { readonly [N in keyof B]: ValueOf<ReturnType<B[N]>> }>;
|
|
162
205
|
/** This method binds names for the body. The body gets a variable token for each name. */
|
|
@@ -229,8 +272,18 @@ export interface ListChain<Ctx extends ChainContext, U> {
|
|
|
229
272
|
all(this: ListChain<Ctx, boolean>, opts?: ListOpts): ChainOf<Ctx, boolean>;
|
|
230
273
|
none(this: ListChain<Ctx, boolean>, opts?: ListOpts): ChainOf<Ctx, boolean>;
|
|
231
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[]>;
|
|
232
279
|
first(opts?: ListOpts): ChainOf<Ctx, U>;
|
|
233
|
-
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;
|
|
234
287
|
}
|
|
235
288
|
|
|
236
289
|
/** The options of a list reduction. */
|
|
@@ -239,6 +292,11 @@ export interface ListOpts {
|
|
|
239
292
|
readonly strict?: boolean;
|
|
240
293
|
}
|
|
241
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
|
+
|
|
242
300
|
/** The root of the builder for one space. */
|
|
243
301
|
export interface Root<Ctx extends ChainContext> {
|
|
244
302
|
/** This method starts a chain with a field of the record at the focus. */
|
|
@@ -288,9 +346,20 @@ export interface SheetRow<K extends string, Cols> {
|
|
|
288
346
|
* other columns with `cell`. Each evaluation evaluates a cell once, and each cell on a cycle of references gives
|
|
289
347
|
* `#CYCLE!`. A sheet is immutable: `column` gives a new sheet.
|
|
290
348
|
*/
|
|
291
|
-
export interface Sheet<Ctx extends ChainContext, Cols> {
|
|
292
|
-
/**
|
|
293
|
-
|
|
349
|
+
export interface Sheet<Ctx extends ChainContext, Cols, Decl = object> {
|
|
350
|
+
/**
|
|
351
|
+
* This method gives a new sheet with one more column. The formula gets a root with `cell`. If `declare` gave the
|
|
352
|
+
* column a type, the formula must give a value of that type.
|
|
353
|
+
*/
|
|
354
|
+
column<const N extends string, C extends ChainBase<Ctx, DeclaredType<Decl, N>>>(
|
|
355
|
+
name: N,
|
|
356
|
+
formula: (r: SheetRoot<Ctx, Cols & Decl>) => C,
|
|
357
|
+
): Sheet<Ctx, Cols & { readonly [P in N]: ValueOf<C> }, Decl>;
|
|
358
|
+
/**
|
|
359
|
+
* This method gives the types of columns before their formulas. A formula can then read a declared column with
|
|
360
|
+
* `cell` and its type: the column itself (a recurrence) or a later column. It has no effect at run time.
|
|
361
|
+
*/
|
|
362
|
+
declare<D extends Readonly<Record<string, unknown>>>(): Sheet<Ctx, Cols, Decl & D>;
|
|
294
363
|
/** The program of each column. */
|
|
295
364
|
readonly columns: Readonly<Record<string, Expr>>;
|
|
296
365
|
/** This method evaluates one cell, and gives the error if there is one. */
|
|
@@ -303,28 +372,45 @@ export interface Sheet<Ctx extends ChainContext, Cols> {
|
|
|
303
372
|
table(): readonly SheetRow<Ctx["keys"], Cols>[];
|
|
304
373
|
}
|
|
305
374
|
|
|
375
|
+
/** The declared type of the column `N`, or `unknown` for a column without a declaration. */
|
|
376
|
+
export type DeclaredType<Decl, N extends string> = N extends keyof Decl ? Decl[N] : unknown;
|
|
377
|
+
|
|
306
378
|
/** The options of the builder. */
|
|
307
|
-
export interface VexOptions {
|
|
308
|
-
/** Free function ops. */
|
|
309
|
-
readonly fns?:
|
|
379
|
+
export interface VexOptions<F extends FnTable = FnTable> {
|
|
380
|
+
/** Free function ops. A chain applies them with `call`. */
|
|
381
|
+
readonly fns?: F;
|
|
310
382
|
/** Handlers of extension expression kinds. */
|
|
311
383
|
readonly extensions?: Readonly<Record<string, ExtHandler>>;
|
|
312
384
|
}
|
|
313
385
|
|
|
314
386
|
/** The entry point for a list of domains. */
|
|
315
|
-
export interface VexEntry<Dms extends readonly AnyDomain[]> {
|
|
387
|
+
export interface VexEntry<Dms extends readonly AnyDomain[], F extends FnTable = NoFns> {
|
|
316
388
|
/** This method gives the root of the builder for a space. */
|
|
317
|
-
over<K extends string, O>(s: Space<K, O>): Root<{ readonly domains: Dms; readonly keys: K; readonly record: Merge<O
|
|
389
|
+
over<K extends string, O>(s: Space<K, O>): Root<{ readonly domains: Dms; readonly keys: K; readonly record: Merge<O>; readonly fns: F }>;
|
|
318
390
|
/** The domains. */
|
|
319
391
|
readonly domains: Dms;
|
|
320
392
|
}
|
|
321
393
|
|
|
322
394
|
// ---------------------------------------------------------------- run time
|
|
323
395
|
|
|
396
|
+
/** The options as the interpreter takes them: free functions get untyped arguments at run time. */
|
|
397
|
+
interface RuntimeOptions {
|
|
398
|
+
readonly fns?: Readonly<Record<string, FreeFn>>;
|
|
399
|
+
readonly extensions?: Readonly<Record<string, ExtHandler>>;
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
/** This function gives the run-time form of the options. A typed free function gets the values that the types promise. */
|
|
403
|
+
const runtimeOptions = (options: VexOptions): RuntimeOptions => ({
|
|
404
|
+
// Stryker disable next-line ConditionalExpression: an undefined option and an absent option are the same
|
|
405
|
+
...(options.fns === undefined ? {} : { fns: options.fns as Readonly<Record<string, FreeFn>> }),
|
|
406
|
+
// Stryker disable next-line ConditionalExpression: an undefined option and an absent option are the same
|
|
407
|
+
...(options.extensions === undefined ? {} : { extensions: options.extensions }),
|
|
408
|
+
});
|
|
409
|
+
|
|
324
410
|
interface Env {
|
|
325
411
|
readonly space: Space;
|
|
326
412
|
readonly domains: readonly AnyDomain[];
|
|
327
|
-
readonly options:
|
|
413
|
+
readonly options: RuntimeOptions;
|
|
328
414
|
}
|
|
329
415
|
|
|
330
416
|
interface State {
|
|
@@ -337,9 +423,9 @@ interface State {
|
|
|
337
423
|
readonly depth: number;
|
|
338
424
|
}
|
|
339
425
|
|
|
340
|
-
const
|
|
341
|
-
const
|
|
342
|
-
|
|
426
|
+
const kindOf = (u: unknown): unknown => (u as { kind?: unknown } | null | undefined)?.kind;
|
|
427
|
+
const isArg = (u: unknown): u is Arg<unknown> => kindOf(u) === "vex.arg";
|
|
428
|
+
const isChainLike = (u: unknown): u is { readonly program: Expr } => kindOf(u) === "vex.chain" || kindOf(u) === "vex.list-chain";
|
|
343
429
|
|
|
344
430
|
/** This function turns a builder argument into an expression. A bare string is a field reference at `addr`. */
|
|
345
431
|
function toExpr(a: unknown, addr: readonly Move[]): Expr {
|
|
@@ -374,14 +460,7 @@ class ChainImpl {
|
|
|
374
460
|
}
|
|
375
461
|
|
|
376
462
|
#opts(k: string): EvalOptions {
|
|
377
|
-
|
|
378
|
-
return {
|
|
379
|
-
space: env.space,
|
|
380
|
-
origin: k,
|
|
381
|
-
domains: env.domains,
|
|
382
|
-
...(env.options.fns === undefined ? {} : { fns: env.options.fns }),
|
|
383
|
-
...(env.options.extensions === undefined ? {} : { extensions: env.options.extensions }),
|
|
384
|
-
};
|
|
463
|
+
return evalOptions(this.#s, k);
|
|
385
464
|
}
|
|
386
465
|
|
|
387
466
|
result(k: string): Result<unknown> {
|
|
@@ -428,6 +507,12 @@ class ChainImpl {
|
|
|
428
507
|
return this.#move(parentMove);
|
|
429
508
|
}
|
|
430
509
|
|
|
510
|
+
call(name: string, ...args: readonly unknown[]): ChainImpl {
|
|
511
|
+
return new ChainImpl({ ...this.#s, expr: app(name, this.#s.expr, ...args.map((a) => toExpr(a, this.#s.addr))) });
|
|
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
|
+
}
|
|
431
516
|
ifError(fallback: unknown): ChainImpl {
|
|
432
517
|
return new ChainImpl({ ...this.#s, expr: app("ifError", this.#s.expr, toExpr(fallback, this.#s.addr)) });
|
|
433
518
|
}
|
|
@@ -464,7 +549,8 @@ class ChainImpl {
|
|
|
464
549
|
const inTarget = new ChainImpl({ ...start.#s, addr: [] });
|
|
465
550
|
const inner = body(inTarget);
|
|
466
551
|
const axis: Axis = opts?.where === undefined ? a : { t: "where", axis: a, test: opts.where(inTarget).program };
|
|
467
|
-
|
|
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)) });
|
|
468
554
|
}
|
|
469
555
|
others(body: (c: ChainImpl) => { readonly program: Expr }, opts?: { readonly where?: (c: ChainImpl) => { readonly program: Expr } }): ListChainImpl {
|
|
470
556
|
return this.#axis({ t: "others" }, body, opts);
|
|
@@ -489,6 +575,20 @@ class ChainImpl {
|
|
|
489
575
|
}
|
|
490
576
|
}
|
|
491
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
|
+
|
|
492
592
|
class ListChainImpl {
|
|
493
593
|
readonly kind = "vex.list-chain" as const;
|
|
494
594
|
readonly #s: State;
|
|
@@ -498,8 +598,9 @@ class ListChainImpl {
|
|
|
498
598
|
get program(): Expr {
|
|
499
599
|
return this.#s.expr;
|
|
500
600
|
}
|
|
501
|
-
#op(op: string, extra: readonly Expr[], opts?: ListOpts): ChainImpl {
|
|
502
|
-
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;
|
|
503
604
|
return new ChainImpl({ ...this.#s, expr: app(op, this.#s.expr, ...args) });
|
|
504
605
|
}
|
|
505
606
|
count(opts?: ListOpts): ChainImpl {
|
|
@@ -529,12 +630,27 @@ class ListChainImpl {
|
|
|
529
630
|
values(opts?: ListOpts): ChainImpl {
|
|
530
631
|
return this.#op("values", [], opts);
|
|
531
632
|
}
|
|
633
|
+
keys(opts?: ListOpts): ChainImpl {
|
|
634
|
+
return this.#op("keys", [], opts);
|
|
635
|
+
}
|
|
636
|
+
errors(): ChainImpl {
|
|
637
|
+
return this.#op("errors", []);
|
|
638
|
+
}
|
|
532
639
|
first(opts?: ListOpts): ChainImpl {
|
|
533
640
|
return this.#op("first", [], opts);
|
|
534
641
|
}
|
|
535
|
-
reduce(op: string, opts?: ListOpts): ChainImpl {
|
|
642
|
+
reduce(op: string, opts?: ListOpts & { readonly domain?: string }): ChainImpl {
|
|
536
643
|
return this.#op("reduce", [lit(op)], opts);
|
|
537
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
|
+
}
|
|
538
654
|
}
|
|
539
655
|
|
|
540
656
|
class RootImpl {
|
|
@@ -581,8 +697,7 @@ class RootImpl {
|
|
|
581
697
|
|
|
582
698
|
class SheetRootImpl extends RootImpl {
|
|
583
699
|
cell(column: string, at?: string | Addr): Arg<unknown> {
|
|
584
|
-
|
|
585
|
-
return argToken(cellRef(column, addr));
|
|
700
|
+
return argToken(cellRef(column, typeof at === "string" ? [keyMove(at)] : at));
|
|
586
701
|
}
|
|
587
702
|
}
|
|
588
703
|
|
|
@@ -596,6 +711,9 @@ class SheetImpl {
|
|
|
596
711
|
get columns(): Readonly<Record<string, Expr>> {
|
|
597
712
|
return Object.freeze(Object.fromEntries(this.#columns));
|
|
598
713
|
}
|
|
714
|
+
declare(): SheetImpl {
|
|
715
|
+
return this;
|
|
716
|
+
}
|
|
599
717
|
column(name: string, formula: (r: SheetRootImpl) => { readonly program: Expr }): SheetImpl {
|
|
600
718
|
const program = formula(new SheetRootImpl(this.#env)).program;
|
|
601
719
|
return new SheetImpl(this.#env, new Map([...this.#columns, [name, program]]));
|
|
@@ -605,7 +723,9 @@ class SheetImpl {
|
|
|
605
723
|
return new SheetRun(this.#columns, {
|
|
606
724
|
space: s,
|
|
607
725
|
domains,
|
|
726
|
+
// Stryker disable next-line ConditionalExpression: an undefined option and an absent option are the same
|
|
608
727
|
...(options.fns === undefined ? {} : { fns: options.fns }),
|
|
728
|
+
// Stryker disable next-line ConditionalExpression: an undefined option and an absent option are the same
|
|
609
729
|
...(options.extensions === undefined ? {} : { extensions: options.extensions }),
|
|
610
730
|
});
|
|
611
731
|
}
|
|
@@ -633,13 +753,20 @@ class SheetImpl {
|
|
|
633
753
|
* This function gives the entry point of the builder for a list of domains. The interpreter finds the op of a
|
|
634
754
|
* value in the first domain that accepts the value.
|
|
635
755
|
*/
|
|
636
|
-
export function vex<const Dms extends readonly AnyDomain[]>(
|
|
637
|
-
|
|
756
|
+
export function vex<const Dms extends readonly AnyDomain[]>(
|
|
757
|
+
...domains: Dms
|
|
758
|
+
): VexEntry<Dms> & { withOptions<const F extends FnTable = NoFns>(options: VexOptions<F>): VexEntry<Dms, F> } {
|
|
759
|
+
const make = <F extends FnTable>(options: VexOptions<F>): VexEntry<Dms, F> => ({
|
|
638
760
|
domains,
|
|
639
|
-
over: <K extends string, O>(s: Space<K, O>): Root<{ readonly domains: Dms; readonly keys: K; readonly record: Merge<O
|
|
640
|
-
new RootImpl({ space: s, domains, options }) as unknown as Root<{
|
|
761
|
+
over: <K extends string, O>(s: Space<K, O>): Root<{ readonly domains: Dms; readonly keys: K; readonly record: Merge<O>; readonly fns: F }> =>
|
|
762
|
+
new RootImpl({ space: s, domains, options: runtimeOptions(options) }) as unknown as Root<{
|
|
763
|
+
readonly domains: Dms;
|
|
764
|
+
readonly keys: K;
|
|
765
|
+
readonly record: Merge<O>;
|
|
766
|
+
readonly fns: F;
|
|
767
|
+
}>,
|
|
641
768
|
});
|
|
642
|
-
return { ...make({}), withOptions: make };
|
|
769
|
+
return { ...make<NoFns>({}), withOptions: make };
|
|
643
770
|
}
|
|
644
771
|
|
|
645
772
|
/** The type of a domain value, from the domain object. */
|
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/domain.ts
CHANGED
|
@@ -89,7 +89,8 @@ export const isOpName = (name: string): boolean => name.length > 0 && !FORBIDDEN
|
|
|
89
89
|
* It stops at `Object.prototype` and `Function.prototype`, so inherited members (for example `toString`) are not ops.
|
|
90
90
|
*/
|
|
91
91
|
export function findMethod(self: unknown, name: string): ((...args: unknown[]) => unknown) | undefined {
|
|
92
|
-
if (!isOpName(name)
|
|
92
|
+
if (!isOpName(name)) return undefined;
|
|
93
|
+
// A primitive has no own methods. The loop below stops at null, so null needs no test here.
|
|
93
94
|
if (typeof self !== "object" && typeof self !== "function") return undefined;
|
|
94
95
|
let o: object | null = self;
|
|
95
96
|
while (o !== null && o !== Object.prototype && o !== Function.prototype) {
|
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";
|
|
@@ -104,6 +104,9 @@ const CACHE = new WeakMap<Expr, { readonly domains: unknown; readonly fns: unkno
|
|
|
104
104
|
|
|
105
105
|
function compiled(expr: Expr, opts: CompileOptions): Program {
|
|
106
106
|
const hit = CACHE.get(expr);
|
|
107
|
+
// Without the cache, each evaluation compiles again: the result is the same, so a mutant that removes a hit is
|
|
108
|
+
// equivalent. A false hit changes results, and the tests find it.
|
|
109
|
+
// Stryker disable next-line ConditionalExpression: a missed hit only compiles again
|
|
107
110
|
if (hit !== undefined && hit.domains === opts.domains && hit.fns === opts.fns && hit.extensions === opts.extensions) return hit.program;
|
|
108
111
|
const program = compile(expr, opts);
|
|
109
112
|
CACHE.set(expr, { domains: opts.domains, fns: opts.fns, extensions: opts.extensions, program });
|
|
@@ -142,6 +145,7 @@ class Compiler {
|
|
|
142
145
|
readonly #extensions: Readonly<Record<string, ExtHandler>> | undefined;
|
|
143
146
|
|
|
144
147
|
constructor(opts: CompileOptions) {
|
|
148
|
+
// Stryker disable next-line ArrayDeclaration: a list with a value that is not a domain matches no value
|
|
145
149
|
this.#domains = opts.domains ?? [];
|
|
146
150
|
this.#fns = opts.fns;
|
|
147
151
|
this.#extensions = opts.extensions;
|
|
@@ -208,7 +212,8 @@ class Compiler {
|
|
|
208
212
|
case "each":
|
|
209
213
|
return this.#each(e, info);
|
|
210
214
|
case "ext": {
|
|
211
|
-
const
|
|
215
|
+
const extensions = this.#extensions ?? {};
|
|
216
|
+
const handler = Object.hasOwn(extensions, e.kind) ? extensions[e.kind] : undefined;
|
|
212
217
|
const { kind, data } = e;
|
|
213
218
|
if (handler === undefined) return (f, c) => this.#emit(c, info, f, this.#err("unknown-op", `no handler for the extension kind "${kind}"`, f, path));
|
|
214
219
|
return (f, c) =>
|
|
@@ -243,6 +248,8 @@ class Compiler {
|
|
|
243
248
|
const steps = segs.map((seg, i) => ({ seg, where: segs.slice(0, i + 1).join("."), valid: isFieldName(seg) }));
|
|
244
249
|
return (f, c) => {
|
|
245
250
|
let key = f.pos.focus;
|
|
251
|
+
// The empty address resolves to the focus, so this fast path changes no result.
|
|
252
|
+
// Stryker disable next-line ConditionalExpression,EqualityOperator: resolveAddr of [] gives the focus too
|
|
246
253
|
if (at.length > 0) {
|
|
247
254
|
const where = resolveAddr(c.space, f.pos, at);
|
|
248
255
|
if (!where.ok) return this.#emit(c, info, f, fail({ ...where.error, path }));
|
|
@@ -282,10 +289,19 @@ class Compiler {
|
|
|
282
289
|
|
|
283
290
|
#each(e: ExprOf<"each">, info: Info): Node {
|
|
284
291
|
const { path } = info;
|
|
292
|
+
const at = e.at ?? [];
|
|
285
293
|
const targets = this.#targets(e.axis, path, { next: 1 });
|
|
286
294
|
const body = this.node(e.body, [...path, 0]);
|
|
287
295
|
return (f, c) => {
|
|
288
|
-
|
|
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);
|
|
289
305
|
if (!ts.ok) return this.#emit(c, info, f, ts);
|
|
290
306
|
const items: ListItem[] = ts.value.map(({ key, test }) => {
|
|
291
307
|
if (test !== undefined && !test.ok) return { key, result: test };
|
|
@@ -338,6 +354,8 @@ class Compiler {
|
|
|
338
354
|
const self = values[0];
|
|
339
355
|
if (listOp !== undefined && isVexList(self)) return this.#emit(c, info, f, this.#listOp(listOp, self, values.slice(1), f, path));
|
|
340
356
|
let accepted: AnyDomain | undefined;
|
|
357
|
+
// Without arguments, the receiver is undefined, and no domain of a test accepts it.
|
|
358
|
+
// Stryker disable next-line ConditionalExpression,EqualityOperator: the loop finds no domain for undefined
|
|
341
359
|
if (values.length > 0) {
|
|
342
360
|
for (const d of this.#domains) {
|
|
343
361
|
if (!safeIs(d, self)) continue;
|
|
@@ -396,7 +414,7 @@ class Compiler {
|
|
|
396
414
|
const lift = spec.liftScalar;
|
|
397
415
|
const from = domain.fromScalar;
|
|
398
416
|
let callArgs: readonly unknown[] = rest;
|
|
399
|
-
if (lift
|
|
417
|
+
if (lift && from !== undefined) {
|
|
400
418
|
const lifted = this.#invoke(() => rest.map((a, i): unknown => (typeof a === "number" && liftsAt(lift, i) ? from(a) : a)), `${domain.name}.fromScalar`, f, path);
|
|
401
419
|
if (!lifted.ok) return lifted;
|
|
402
420
|
callArgs = lifted.value as readonly unknown[];
|
|
@@ -443,7 +461,7 @@ class Compiler {
|
|
|
443
461
|
|
|
444
462
|
#listOp(op: ListOp, list: VexList, rest: readonly unknown[], f: Frame, path: readonly number[]): Result<unknown> {
|
|
445
463
|
const optsArg = op === "reduce" ? rest[1] : rest[0];
|
|
446
|
-
const strict =
|
|
464
|
+
const strict = (optsArg as ListOptions | null | undefined)?.strict === true;
|
|
447
465
|
const firstError = list.items.find((it) => !it.result.ok)?.result;
|
|
448
466
|
if (strict && firstError !== undefined && !firstError.ok) return fail(firstError.error);
|
|
449
467
|
const okValues = list.items.flatMap((it) => (it.result.ok ? [it.result.value] : []));
|
|
@@ -493,19 +511,29 @@ class Compiler {
|
|
|
493
511
|
return ok(!b.value.some((x) => x));
|
|
494
512
|
}
|
|
495
513
|
case "reduce":
|
|
496
|
-
return this.#reduce(rest[0], okValues, f, path);
|
|
514
|
+
return this.#reduce(rest[0], okValues, f, path, optsArg);
|
|
497
515
|
}
|
|
498
516
|
}
|
|
499
517
|
|
|
500
|
-
/**
|
|
501
|
-
|
|
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> {
|
|
502
523
|
if (typeof opName !== "string") return this.#err("kind-mismatch", `"reduce" needs an op name, but got a ${describeType(opName)}`, f, path, { op: "reduce" });
|
|
503
524
|
if (values.length === 0) {
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
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 });
|
|
507
529
|
}
|
|
508
|
-
|
|
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 });
|
|
535
|
+
}
|
|
536
|
+
return this.#invoke((only.ops[opName] as { identity: () => unknown }).identity, opName, f, path);
|
|
509
537
|
}
|
|
510
538
|
let acc: unknown = values[0];
|
|
511
539
|
for (let i = 1; i < values.length; i++) {
|
|
@@ -524,6 +552,7 @@ const FORBIDDEN_FIELDS = new Set(["__proto__", "constructor", "prototype"]);
|
|
|
524
552
|
const isFieldName = (seg: string): boolean => seg.length > 0 && !FORBIDDEN_FIELDS.has(seg);
|
|
525
553
|
|
|
526
554
|
/** This function runs the `is` test of a domain. A test that throws counts as `false`. */
|
|
555
|
+
// Stryker disable BlockStatement: an empty catch gives undefined, which also counts as false
|
|
527
556
|
function safeIs(d: AnyDomain, value: unknown): boolean {
|
|
528
557
|
try {
|
|
529
558
|
return d.is(value);
|
|
@@ -531,8 +560,8 @@ function safeIs(d: AnyDomain, value: unknown): boolean {
|
|
|
531
560
|
return false;
|
|
532
561
|
}
|
|
533
562
|
}
|
|
563
|
+
// Stryker restore BlockStatement
|
|
534
564
|
|
|
535
|
-
const isOptions = (u: unknown): u is ListOptions => typeof u === "object" && u !== null && !Array.isArray(u) && !isVexList(u);
|
|
536
565
|
|
|
537
566
|
function matchesKind(kind: ParamKind, value: unknown, domain: AnyDomain): boolean {
|
|
538
567
|
switch (kind) {
|
|
@@ -577,19 +606,37 @@ export function labelOf(e: Expr): string {
|
|
|
577
606
|
case "rec":
|
|
578
607
|
return `{ ${Object.keys(e.fields).join(", ")} }`;
|
|
579
608
|
case "each":
|
|
580
|
-
return `each ${e.axis.t}`;
|
|
609
|
+
return e.at === undefined ? `each ${e.axis.t}` : `each ${e.axis.t} from ${e.at.map(moveText).join(".")}`;
|
|
581
610
|
case "ext":
|
|
582
611
|
return e.kind;
|
|
583
612
|
}
|
|
584
613
|
}
|
|
585
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
|
+
|
|
586
631
|
/** This function gives a short text for a value. */
|
|
587
632
|
export function previewValue(u: unknown): string {
|
|
588
|
-
|
|
589
|
-
if (typeof u === "number"
|
|
633
|
+
// JSON has no NaN and no Infinity, so a number gets its own text. JSON gives the text of the other primitives.
|
|
634
|
+
if (typeof u === "number") return String(u);
|
|
590
635
|
if (isVexList(u)) return `list(${u.items.length})`;
|
|
591
636
|
try {
|
|
592
637
|
const json = JSON.stringify(u);
|
|
638
|
+
// A function, a symbol and undefined have no JSON form.
|
|
639
|
+
// Stryker disable next-line ConditionalExpression: without the test, undefined.length throws, and the catch gives the same text
|
|
593
640
|
if (json !== undefined) return json.length > 60 ? `${json.slice(0, 57)}...` : json;
|
|
594
641
|
} catch {
|
|
595
642
|
// A value with cycles has no JSON form.
|
|
@@ -604,11 +651,13 @@ const formatRead = (r: Read): string => `${r.ok ? "read" : "no value at"} ${r.ke
|
|
|
604
651
|
* This function gives a text form of a trace. Each event has one line, in finish order. The indent of a line
|
|
605
652
|
* shows the depth of the node. A domain with `show` gives the text of its values. The golden tests compare this text.
|
|
606
653
|
*/
|
|
654
|
+
// Stryker disable next-line ArrayDeclaration: a list with a value that is not a domain shows no value
|
|
607
655
|
export function formatTrace(trace: Trace, domains: readonly AnyDomain[] = []): string {
|
|
608
656
|
const show = (u: unknown): string => {
|
|
609
657
|
if (isVexList(u)) return `[${u.items.map((it) => `${it.key}: ${result(it.result)}`).join(", ")}]`;
|
|
610
658
|
const d = domains.find((dom) => dom.show !== undefined && safeIs(dom, u));
|
|
611
659
|
try {
|
|
660
|
+
// Stryker disable next-line ConditionalExpression,OptionalChaining: without a domain, d.show throws, and the catch gives the same text
|
|
612
661
|
if (d?.show !== undefined) return d.show(u);
|
|
613
662
|
} catch {
|
|
614
663
|
// A show function that throws gives the default text.
|