@mark1russell7/vex 0.2.0 → 0.3.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 +42 -11
- package/build/index.d.ts.map +1 -1
- package/build/index.js +40 -29
- package/build/index.js.map +1 -1
- package/package.json +18 -1
- package/src/builder.ts +94 -20
- package/src/domain.ts +2 -1
- package/src/evaluate.ts +20 -6
- package/src/ir.ts +3 -3
- package/src/json.ts +6 -3
- package/src/list.ts +1 -1
- package/src/sheet.ts +11 -6
- package/src/space.ts +10 -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.3.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",
|
package/src/builder.ts
CHANGED
|
@@ -112,13 +112,38 @@ export type ArgInput<P, Ctx extends ChainContext, Lift extends boolean> =
|
|
|
112
112
|
|
|
113
113
|
type MapArgs<P extends readonly unknown[], Ctx extends ChainContext, Lift extends boolean> = { [I in keyof P]: ArgInput<P[I], Ctx, Lift> };
|
|
114
114
|
|
|
115
|
-
/** The
|
|
115
|
+
/** A table of free functions. The first parameter of a function gets the current value of the chain. */
|
|
116
|
+
export type FnTable = Readonly<Record<string, (...args: never[]) => unknown>>;
|
|
117
|
+
|
|
118
|
+
/** The free functions of a builder without `withOptions`: none, so `call` accepts no name. */
|
|
119
|
+
// oxlint-disable-next-line typescript/no-generated-empty-object-type -- an empty table is the intent.
|
|
120
|
+
export type NoFns = Record<never, never>;
|
|
121
|
+
|
|
122
|
+
/** The static context of a chain: its domains, its key type, its record type and its free functions. */
|
|
116
123
|
export interface ChainContext {
|
|
117
124
|
readonly domains: readonly AnyDomain[];
|
|
118
125
|
readonly keys: string;
|
|
119
126
|
readonly record: unknown;
|
|
127
|
+
readonly fns?: FnTable;
|
|
120
128
|
}
|
|
121
129
|
|
|
130
|
+
type FnsOf<Ctx extends ChainContext> = NonNullable<Ctx["fns"]>;
|
|
131
|
+
type FnParams<F> = F extends (...args: infer P) => unknown ? P : never;
|
|
132
|
+
type FirstParam<P> = P extends readonly [infer A, ...unknown[]] ? A : unknown;
|
|
133
|
+
type RestParams<P> = P extends readonly [unknown, ...infer R] ? R : [];
|
|
134
|
+
|
|
135
|
+
/** The names of the free functions whose first parameter accepts a value of type `T`. */
|
|
136
|
+
export type CallableFns<Ctx extends ChainContext, T> = {
|
|
137
|
+
[K in keyof FnsOf<Ctx>]: [T] extends [FirstParam<FnParams<FnsOf<Ctx>[K]>>] ? K : never;
|
|
138
|
+
}[keyof FnsOf<Ctx>] &
|
|
139
|
+
string;
|
|
140
|
+
|
|
141
|
+
/** The inputs for the parameters of the free function `N` after its first parameter. */
|
|
142
|
+
export type CallArgs<Ctx extends ChainContext, N extends keyof FnsOf<Ctx>> = MapArgs<RestParams<FnParams<FnsOf<Ctx>[N]>>, Ctx, false>;
|
|
143
|
+
|
|
144
|
+
/** The return type of the free function `N`. */
|
|
145
|
+
export type CallReturn<Ctx extends ChainContext, N extends keyof FnsOf<Ctx>> = FnsOf<Ctx>[N] extends (...args: never[]) => infer R ? R : unknown;
|
|
146
|
+
|
|
122
147
|
/** The ops section `._` of a chain whose value has domain `Dm`. */
|
|
123
148
|
export type OpsProxy<Ctx extends ChainContext, Dm> = {
|
|
124
149
|
readonly [M in OpNames<Dm>]: (...args: MapArgs<OpParams<Dm, M>, Ctx, Lifts<Dm, M>>) => ChainOf<Ctx, OpReturn<Dm, M>>;
|
|
@@ -157,6 +182,11 @@ export interface ChainBase<Ctx extends ChainContext, T> {
|
|
|
157
182
|
parent(): ChainOf<Ctx, T>;
|
|
158
183
|
/** This method uses `fallback` when the chain gives an error. */
|
|
159
184
|
ifError<U>(fallback: ArgInput<U, Ctx, false> | T): ChainOf<Ctx, T | U>;
|
|
185
|
+
/**
|
|
186
|
+
* This method applies the free function `name` of `withOptions`. The function gets the current value as its first
|
|
187
|
+
* argument, then `args`. The types accept only the functions whose first parameter accepts the current value.
|
|
188
|
+
*/
|
|
189
|
+
call<N extends CallableFns<Ctx, T>>(name: N, ...args: CallArgs<Ctx, N>): ChainOf<Ctx, CallReturn<Ctx, N>>;
|
|
160
190
|
/** This method evaluates each branch with the current value, and gives a record of the results. */
|
|
161
191
|
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
192
|
/** This method binds names for the body. The body gets a variable token for each name. */
|
|
@@ -288,9 +318,20 @@ export interface SheetRow<K extends string, Cols> {
|
|
|
288
318
|
* other columns with `cell`. Each evaluation evaluates a cell once, and each cell on a cycle of references gives
|
|
289
319
|
* `#CYCLE!`. A sheet is immutable: `column` gives a new sheet.
|
|
290
320
|
*/
|
|
291
|
-
export interface Sheet<Ctx extends ChainContext, Cols> {
|
|
292
|
-
/**
|
|
293
|
-
|
|
321
|
+
export interface Sheet<Ctx extends ChainContext, Cols, Decl = object> {
|
|
322
|
+
/**
|
|
323
|
+
* This method gives a new sheet with one more column. The formula gets a root with `cell`. If `declare` gave the
|
|
324
|
+
* column a type, the formula must give a value of that type.
|
|
325
|
+
*/
|
|
326
|
+
column<const N extends string, C extends ChainBase<Ctx, DeclaredType<Decl, N>>>(
|
|
327
|
+
name: N,
|
|
328
|
+
formula: (r: SheetRoot<Ctx, Cols & Decl>) => C,
|
|
329
|
+
): Sheet<Ctx, Cols & { readonly [P in N]: ValueOf<C> }, Decl>;
|
|
330
|
+
/**
|
|
331
|
+
* This method gives the types of columns before their formulas. A formula can then read a declared column with
|
|
332
|
+
* `cell` and its type: the column itself (a recurrence) or a later column. It has no effect at run time.
|
|
333
|
+
*/
|
|
334
|
+
declare<D extends Readonly<Record<string, unknown>>>(): Sheet<Ctx, Cols, Decl & D>;
|
|
294
335
|
/** The program of each column. */
|
|
295
336
|
readonly columns: Readonly<Record<string, Expr>>;
|
|
296
337
|
/** This method evaluates one cell, and gives the error if there is one. */
|
|
@@ -303,28 +344,45 @@ export interface Sheet<Ctx extends ChainContext, Cols> {
|
|
|
303
344
|
table(): readonly SheetRow<Ctx["keys"], Cols>[];
|
|
304
345
|
}
|
|
305
346
|
|
|
347
|
+
/** The declared type of the column `N`, or `unknown` for a column without a declaration. */
|
|
348
|
+
export type DeclaredType<Decl, N extends string> = N extends keyof Decl ? Decl[N] : unknown;
|
|
349
|
+
|
|
306
350
|
/** The options of the builder. */
|
|
307
|
-
export interface VexOptions {
|
|
308
|
-
/** Free function ops. */
|
|
309
|
-
readonly fns?:
|
|
351
|
+
export interface VexOptions<F extends FnTable = FnTable> {
|
|
352
|
+
/** Free function ops. A chain applies them with `call`. */
|
|
353
|
+
readonly fns?: F;
|
|
310
354
|
/** Handlers of extension expression kinds. */
|
|
311
355
|
readonly extensions?: Readonly<Record<string, ExtHandler>>;
|
|
312
356
|
}
|
|
313
357
|
|
|
314
358
|
/** The entry point for a list of domains. */
|
|
315
|
-
export interface VexEntry<Dms extends readonly AnyDomain[]> {
|
|
359
|
+
export interface VexEntry<Dms extends readonly AnyDomain[], F extends FnTable = NoFns> {
|
|
316
360
|
/** 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
|
|
361
|
+
over<K extends string, O>(s: Space<K, O>): Root<{ readonly domains: Dms; readonly keys: K; readonly record: Merge<O>; readonly fns: F }>;
|
|
318
362
|
/** The domains. */
|
|
319
363
|
readonly domains: Dms;
|
|
320
364
|
}
|
|
321
365
|
|
|
322
366
|
// ---------------------------------------------------------------- run time
|
|
323
367
|
|
|
368
|
+
/** The options as the interpreter takes them: free functions get untyped arguments at run time. */
|
|
369
|
+
interface RuntimeOptions {
|
|
370
|
+
readonly fns?: Readonly<Record<string, FreeFn>>;
|
|
371
|
+
readonly extensions?: Readonly<Record<string, ExtHandler>>;
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/** This function gives the run-time form of the options. A typed free function gets the values that the types promise. */
|
|
375
|
+
const runtimeOptions = (options: VexOptions): RuntimeOptions => ({
|
|
376
|
+
// Stryker disable next-line ConditionalExpression: an undefined option and an absent option are the same
|
|
377
|
+
...(options.fns === undefined ? {} : { fns: options.fns as Readonly<Record<string, FreeFn>> }),
|
|
378
|
+
// Stryker disable next-line ConditionalExpression: an undefined option and an absent option are the same
|
|
379
|
+
...(options.extensions === undefined ? {} : { extensions: options.extensions }),
|
|
380
|
+
});
|
|
381
|
+
|
|
324
382
|
interface Env {
|
|
325
383
|
readonly space: Space;
|
|
326
384
|
readonly domains: readonly AnyDomain[];
|
|
327
|
-
readonly options:
|
|
385
|
+
readonly options: RuntimeOptions;
|
|
328
386
|
}
|
|
329
387
|
|
|
330
388
|
interface State {
|
|
@@ -337,9 +395,9 @@ interface State {
|
|
|
337
395
|
readonly depth: number;
|
|
338
396
|
}
|
|
339
397
|
|
|
340
|
-
const
|
|
341
|
-
const
|
|
342
|
-
|
|
398
|
+
const kindOf = (u: unknown): unknown => (u as { kind?: unknown } | null | undefined)?.kind;
|
|
399
|
+
const isArg = (u: unknown): u is Arg<unknown> => kindOf(u) === "vex.arg";
|
|
400
|
+
const isChainLike = (u: unknown): u is { readonly program: Expr } => kindOf(u) === "vex.chain" || kindOf(u) === "vex.list-chain";
|
|
343
401
|
|
|
344
402
|
/** This function turns a builder argument into an expression. A bare string is a field reference at `addr`. */
|
|
345
403
|
function toExpr(a: unknown, addr: readonly Move[]): Expr {
|
|
@@ -379,7 +437,9 @@ class ChainImpl {
|
|
|
379
437
|
space: env.space,
|
|
380
438
|
origin: k,
|
|
381
439
|
domains: env.domains,
|
|
440
|
+
// Stryker disable next-line ConditionalExpression: an undefined option and an absent option are the same
|
|
382
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
|
|
383
443
|
...(env.options.extensions === undefined ? {} : { extensions: env.options.extensions }),
|
|
384
444
|
};
|
|
385
445
|
}
|
|
@@ -428,6 +488,9 @@ class ChainImpl {
|
|
|
428
488
|
return this.#move(parentMove);
|
|
429
489
|
}
|
|
430
490
|
|
|
491
|
+
call(name: string, ...args: readonly unknown[]): ChainImpl {
|
|
492
|
+
return new ChainImpl({ ...this.#s, expr: app(name, this.#s.expr, ...args.map((a) => toExpr(a, this.#s.addr))) });
|
|
493
|
+
}
|
|
431
494
|
ifError(fallback: unknown): ChainImpl {
|
|
432
495
|
return new ChainImpl({ ...this.#s, expr: app("ifError", this.#s.expr, toExpr(fallback, this.#s.addr)) });
|
|
433
496
|
}
|
|
@@ -581,8 +644,7 @@ class RootImpl {
|
|
|
581
644
|
|
|
582
645
|
class SheetRootImpl extends RootImpl {
|
|
583
646
|
cell(column: string, at?: string | Addr): Arg<unknown> {
|
|
584
|
-
|
|
585
|
-
return argToken(cellRef(column, addr));
|
|
647
|
+
return argToken(cellRef(column, typeof at === "string" ? [keyMove(at)] : at));
|
|
586
648
|
}
|
|
587
649
|
}
|
|
588
650
|
|
|
@@ -596,6 +658,9 @@ class SheetImpl {
|
|
|
596
658
|
get columns(): Readonly<Record<string, Expr>> {
|
|
597
659
|
return Object.freeze(Object.fromEntries(this.#columns));
|
|
598
660
|
}
|
|
661
|
+
declare(): SheetImpl {
|
|
662
|
+
return this;
|
|
663
|
+
}
|
|
599
664
|
column(name: string, formula: (r: SheetRootImpl) => { readonly program: Expr }): SheetImpl {
|
|
600
665
|
const program = formula(new SheetRootImpl(this.#env)).program;
|
|
601
666
|
return new SheetImpl(this.#env, new Map([...this.#columns, [name, program]]));
|
|
@@ -605,7 +670,9 @@ class SheetImpl {
|
|
|
605
670
|
return new SheetRun(this.#columns, {
|
|
606
671
|
space: s,
|
|
607
672
|
domains,
|
|
673
|
+
// Stryker disable next-line ConditionalExpression: an undefined option and an absent option are the same
|
|
608
674
|
...(options.fns === undefined ? {} : { fns: options.fns }),
|
|
675
|
+
// Stryker disable next-line ConditionalExpression: an undefined option and an absent option are the same
|
|
609
676
|
...(options.extensions === undefined ? {} : { extensions: options.extensions }),
|
|
610
677
|
});
|
|
611
678
|
}
|
|
@@ -633,13 +700,20 @@ class SheetImpl {
|
|
|
633
700
|
* This function gives the entry point of the builder for a list of domains. The interpreter finds the op of a
|
|
634
701
|
* value in the first domain that accepts the value.
|
|
635
702
|
*/
|
|
636
|
-
export function vex<const Dms extends readonly AnyDomain[]>(
|
|
637
|
-
|
|
703
|
+
export function vex<const Dms extends readonly AnyDomain[]>(
|
|
704
|
+
...domains: Dms
|
|
705
|
+
): VexEntry<Dms> & { withOptions<const F extends FnTable = NoFns>(options: VexOptions<F>): VexEntry<Dms, F> } {
|
|
706
|
+
const make = <F extends FnTable>(options: VexOptions<F>): VexEntry<Dms, F> => ({
|
|
638
707
|
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<{
|
|
708
|
+
over: <K extends string, O>(s: Space<K, O>): Root<{ readonly domains: Dms; readonly keys: K; readonly record: Merge<O>; readonly fns: F }> =>
|
|
709
|
+
new RootImpl({ space: s, domains, options: runtimeOptions(options) }) as unknown as Root<{
|
|
710
|
+
readonly domains: Dms;
|
|
711
|
+
readonly keys: K;
|
|
712
|
+
readonly record: Merge<O>;
|
|
713
|
+
readonly fns: F;
|
|
714
|
+
}>,
|
|
641
715
|
});
|
|
642
|
-
return { ...make({}), withOptions: make };
|
|
716
|
+
return { ...make<NoFns>({}), withOptions: make };
|
|
643
717
|
}
|
|
644
718
|
|
|
645
719
|
/** The type of a domain value, from the domain object. */
|
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
|
@@ -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 }));
|
|
@@ -338,6 +345,8 @@ class Compiler {
|
|
|
338
345
|
const self = values[0];
|
|
339
346
|
if (listOp !== undefined && isVexList(self)) return this.#emit(c, info, f, this.#listOp(listOp, self, values.slice(1), f, path));
|
|
340
347
|
let accepted: AnyDomain | undefined;
|
|
348
|
+
// Without arguments, the receiver is undefined, and no domain of a test accepts it.
|
|
349
|
+
// Stryker disable next-line ConditionalExpression,EqualityOperator: the loop finds no domain for undefined
|
|
341
350
|
if (values.length > 0) {
|
|
342
351
|
for (const d of this.#domains) {
|
|
343
352
|
if (!safeIs(d, self)) continue;
|
|
@@ -396,7 +405,7 @@ class Compiler {
|
|
|
396
405
|
const lift = spec.liftScalar;
|
|
397
406
|
const from = domain.fromScalar;
|
|
398
407
|
let callArgs: readonly unknown[] = rest;
|
|
399
|
-
if (lift
|
|
408
|
+
if (lift && from !== undefined) {
|
|
400
409
|
const lifted = this.#invoke(() => rest.map((a, i): unknown => (typeof a === "number" && liftsAt(lift, i) ? from(a) : a)), `${domain.name}.fromScalar`, f, path);
|
|
401
410
|
if (!lifted.ok) return lifted;
|
|
402
411
|
callArgs = lifted.value as readonly unknown[];
|
|
@@ -443,7 +452,7 @@ class Compiler {
|
|
|
443
452
|
|
|
444
453
|
#listOp(op: ListOp, list: VexList, rest: readonly unknown[], f: Frame, path: readonly number[]): Result<unknown> {
|
|
445
454
|
const optsArg = op === "reduce" ? rest[1] : rest[0];
|
|
446
|
-
const strict =
|
|
455
|
+
const strict = (optsArg as ListOptions | null | undefined)?.strict === true;
|
|
447
456
|
const firstError = list.items.find((it) => !it.result.ok)?.result;
|
|
448
457
|
if (strict && firstError !== undefined && !firstError.ok) return fail(firstError.error);
|
|
449
458
|
const okValues = list.items.flatMap((it) => (it.result.ok ? [it.result.value] : []));
|
|
@@ -524,6 +533,7 @@ const FORBIDDEN_FIELDS = new Set(["__proto__", "constructor", "prototype"]);
|
|
|
524
533
|
const isFieldName = (seg: string): boolean => seg.length > 0 && !FORBIDDEN_FIELDS.has(seg);
|
|
525
534
|
|
|
526
535
|
/** This function runs the `is` test of a domain. A test that throws counts as `false`. */
|
|
536
|
+
// Stryker disable BlockStatement: an empty catch gives undefined, which also counts as false
|
|
527
537
|
function safeIs(d: AnyDomain, value: unknown): boolean {
|
|
528
538
|
try {
|
|
529
539
|
return d.is(value);
|
|
@@ -531,8 +541,8 @@ function safeIs(d: AnyDomain, value: unknown): boolean {
|
|
|
531
541
|
return false;
|
|
532
542
|
}
|
|
533
543
|
}
|
|
544
|
+
// Stryker restore BlockStatement
|
|
534
545
|
|
|
535
|
-
const isOptions = (u: unknown): u is ListOptions => typeof u === "object" && u !== null && !Array.isArray(u) && !isVexList(u);
|
|
536
546
|
|
|
537
547
|
function matchesKind(kind: ParamKind, value: unknown, domain: AnyDomain): boolean {
|
|
538
548
|
switch (kind) {
|
|
@@ -585,11 +595,13 @@ export function labelOf(e: Expr): string {
|
|
|
585
595
|
|
|
586
596
|
/** This function gives a short text for a value. */
|
|
587
597
|
export function previewValue(u: unknown): string {
|
|
588
|
-
|
|
589
|
-
if (typeof u === "number"
|
|
598
|
+
// JSON has no NaN and no Infinity, so a number gets its own text. JSON gives the text of the other primitives.
|
|
599
|
+
if (typeof u === "number") return String(u);
|
|
590
600
|
if (isVexList(u)) return `list(${u.items.length})`;
|
|
591
601
|
try {
|
|
592
602
|
const json = JSON.stringify(u);
|
|
603
|
+
// A function, a symbol and undefined have no JSON form.
|
|
604
|
+
// Stryker disable next-line ConditionalExpression: without the test, undefined.length throws, and the catch gives the same text
|
|
593
605
|
if (json !== undefined) return json.length > 60 ? `${json.slice(0, 57)}...` : json;
|
|
594
606
|
} catch {
|
|
595
607
|
// A value with cycles has no JSON form.
|
|
@@ -604,11 +616,13 @@ const formatRead = (r: Read): string => `${r.ok ? "read" : "no value at"} ${r.ke
|
|
|
604
616
|
* This function gives a text form of a trace. Each event has one line, in finish order. The indent of a line
|
|
605
617
|
* shows the depth of the node. A domain with `show` gives the text of its values. The golden tests compare this text.
|
|
606
618
|
*/
|
|
619
|
+
// Stryker disable next-line ArrayDeclaration: a list with a value that is not a domain shows no value
|
|
607
620
|
export function formatTrace(trace: Trace, domains: readonly AnyDomain[] = []): string {
|
|
608
621
|
const show = (u: unknown): string => {
|
|
609
622
|
if (isVexList(u)) return `[${u.items.map((it) => `${it.key}: ${result(it.result)}`).join(", ")}]`;
|
|
610
623
|
const d = domains.find((dom) => dom.show !== undefined && safeIs(dom, u));
|
|
611
624
|
try {
|
|
625
|
+
// Stryker disable next-line ConditionalExpression,OptionalChaining: without a domain, d.show throws, and the catch gives the same text
|
|
612
626
|
if (d?.show !== undefined) return d.show(u);
|
|
613
627
|
} catch {
|
|
614
628
|
// A show function that throws gives the default text.
|
package/src/ir.ts
CHANGED
|
@@ -127,9 +127,9 @@ export function isMove(u: unknown): u is Move {
|
|
|
127
127
|
case "key":
|
|
128
128
|
return typeof u["key"] === "string";
|
|
129
129
|
case "index":
|
|
130
|
-
return
|
|
130
|
+
return Number.isInteger(u["i"]);
|
|
131
131
|
case "offset":
|
|
132
|
-
return Array.isArray(u["d"]) && u["d"].every((n) =>
|
|
132
|
+
return Array.isArray(u["d"]) && u["d"].every((n) => Number.isInteger(n));
|
|
133
133
|
case "other":
|
|
134
134
|
case "origin":
|
|
135
135
|
case "parent":
|
|
@@ -198,7 +198,7 @@ export function children(e: Expr): readonly Expr[] {
|
|
|
198
198
|
case "rec":
|
|
199
199
|
return Object.values(e.fields);
|
|
200
200
|
case "each":
|
|
201
|
-
return
|
|
201
|
+
return [e.body, ...whereTests(e.axis)];
|
|
202
202
|
case "lit":
|
|
203
203
|
case "ref":
|
|
204
204
|
case "var":
|
package/src/json.ts
CHANGED
|
@@ -25,11 +25,13 @@ const isPlainJson = (u: unknown): boolean => {
|
|
|
25
25
|
* This function gives the JSON text of an expression. A literal that is a domain value needs a domain with
|
|
26
26
|
* `encode`. A literal that is not JSON data and has no such domain gives the error `#VALUE!`.
|
|
27
27
|
*/
|
|
28
|
+
// Stryker disable next-line ArrayDeclaration: a list with a value that is not a domain encodes no value
|
|
28
29
|
export function serialize(e: Expr, domains: readonly AnyDomain[] = []): Result<string> {
|
|
29
30
|
const failure: { message: string }[] = [];
|
|
30
31
|
const replacer = function (this: unknown, k: string, value: unknown): unknown {
|
|
31
|
-
|
|
32
|
-
|
|
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;
|
|
33
35
|
if (isPlainJson(value)) return value;
|
|
34
36
|
const d = domains.find((dom) => dom.encode !== undefined && dom.is(value));
|
|
35
37
|
if (d?.encode !== undefined) {
|
|
@@ -50,9 +52,10 @@ export function serialize(e: Expr, domains: readonly AnyDomain[] = []): Result<s
|
|
|
50
52
|
}
|
|
51
53
|
|
|
52
54
|
const isEncoded = (u: unknown): u is EncodedValue =>
|
|
53
|
-
|
|
55
|
+
(u as { $vex?: unknown } | null)?.$vex === "domain" && typeof (u as { domain?: unknown }).domain === "string";
|
|
54
56
|
|
|
55
57
|
/** This function reads an expression from JSON text. It checks the whole tree. */
|
|
58
|
+
// Stryker disable next-line ArrayDeclaration: a list with a value that is not a domain decodes no value
|
|
56
59
|
export function parse(text: string, domains: readonly AnyDomain[] = []): Result<Expr> {
|
|
57
60
|
let raw: unknown;
|
|
58
61
|
const failure: string[] = [];
|
package/src/list.ts
CHANGED
|
@@ -17,7 +17,7 @@ export const vexList = <T>(items: readonly ListItem<T>[]): VexList<T> => Object.
|
|
|
17
17
|
|
|
18
18
|
/** This function tells if a value is a Vex list. */
|
|
19
19
|
export const isVexList = (u: unknown): u is VexList =>
|
|
20
|
-
|
|
20
|
+
(u as { kind?: unknown } | null | undefined)?.kind === "vex.list" && Array.isArray((u as { items?: unknown }).items);
|
|
21
21
|
|
|
22
22
|
/** The name of a core list op. */
|
|
23
23
|
export type ListOp = "count" | "sum" | "min" | "max" | "mean" | "any" | "all" | "none" | "values" | "keys" | "reduce" | "first" | "errors";
|
package/src/sheet.ts
CHANGED
|
@@ -54,7 +54,7 @@ interface Visit {
|
|
|
54
54
|
readonly key: string;
|
|
55
55
|
readonly index: number;
|
|
56
56
|
low: number;
|
|
57
|
-
|
|
57
|
+
reread: boolean;
|
|
58
58
|
result: Result<unknown>;
|
|
59
59
|
}
|
|
60
60
|
|
|
@@ -64,9 +64,11 @@ export class SheetRun {
|
|
|
64
64
|
readonly #done = new Map<string, Result<unknown>>();
|
|
65
65
|
// The cells on the stack of the search: started, but their component is not finished.
|
|
66
66
|
readonly #visits = new Map<string, Visit>();
|
|
67
|
+
// Stryker disable next-line ArrayDeclaration: the search never reads below the root of a component
|
|
67
68
|
readonly #stack: Visit[] = [];
|
|
68
69
|
// The cell whose formula is in evaluation. At the top level, it is a placeholder that is not a cell.
|
|
69
|
-
|
|
70
|
+
// Stryker disable next-line all: the placeholder is not a cell, so the search reads none of its fields
|
|
71
|
+
#top: Visit = { id: "", column: "", key: "", index: -1, low: -1, reread: false, result: cycleError("", "") };
|
|
70
72
|
#next = 0;
|
|
71
73
|
|
|
72
74
|
constructor(columns: ReadonlyMap<string, Expr>, opts: SheetOptions) {
|
|
@@ -89,16 +91,18 @@ export class SheetRun {
|
|
|
89
91
|
const caller = this.#top;
|
|
90
92
|
const seen = this.#visits.get(id);
|
|
91
93
|
if (seen !== undefined) {
|
|
92
|
-
// A read of a cell that is not finished: the caller and this cell are on one cycle.
|
|
94
|
+
// A read of a cell that is not finished: the caller and this cell are on one cycle. The cell is on the
|
|
95
|
+
// stack of the search, so it is in the component of the caller. Thus a component with one cell is cyclic
|
|
96
|
+
// only if that cell reads itself.
|
|
93
97
|
caller.low = Math.min(caller.low, seen.index);
|
|
94
|
-
|
|
98
|
+
seen.reread = true;
|
|
95
99
|
return cycleError(column, key);
|
|
96
100
|
}
|
|
97
101
|
const program = this.#columns.get(column);
|
|
98
102
|
if (program === undefined) return fail(vexError("unbound", `the sheet has no column "${column}"`, { origin: key, focus: key }));
|
|
99
103
|
|
|
100
104
|
const n = this.#next++;
|
|
101
|
-
const visit: Visit = { id, column, key, index: n, low: n,
|
|
105
|
+
const visit: Visit = { id, column, key, index: n, low: n, reread: false, result: cycleError(column, key) };
|
|
102
106
|
this.#visits.set(id, visit);
|
|
103
107
|
this.#stack.push(visit);
|
|
104
108
|
this.#top = visit;
|
|
@@ -113,8 +117,9 @@ export class SheetRun {
|
|
|
113
117
|
/** This method takes the component of `root` from the stack, and sets the final result of each of its cells. */
|
|
114
118
|
#finish(root: Visit): void {
|
|
115
119
|
const members = this.#stack.splice(this.#stack.indexOf(root));
|
|
116
|
-
const cyclic = members.length > 1 || root.
|
|
120
|
+
const cyclic = members.length > 1 || root.reread;
|
|
117
121
|
for (const m of members) {
|
|
122
|
+
// Stryker disable next-line CallExpression: a finished cell is in #done, and cell() reads #done first
|
|
118
123
|
this.#visits.delete(m.id);
|
|
119
124
|
this.#done.set(m.id, cyclic ? cycleError(m.column, m.key) : m.result);
|
|
120
125
|
}
|
package/src/space.ts
CHANGED
|
@@ -50,9 +50,11 @@ class RecordSpace<K extends string, O> implements Space<K, O> {
|
|
|
50
50
|
get(k: string): O | undefined {
|
|
51
51
|
return this.#records.get(k);
|
|
52
52
|
}
|
|
53
|
+
// Stryker disable next-line BlockStatement: the body gives undefined, and an empty body gives undefined too
|
|
53
54
|
coords(): readonly number[] | undefined {
|
|
54
55
|
return undefined;
|
|
55
56
|
}
|
|
57
|
+
// Stryker disable next-line BlockStatement: the body gives undefined, and an empty body gives undefined too
|
|
56
58
|
keyAt(): K | undefined {
|
|
57
59
|
return undefined;
|
|
58
60
|
}
|
|
@@ -79,7 +81,7 @@ class ArraySpace<O> implements Space<ArrayKey, O> {
|
|
|
79
81
|
return this.has(k) ? [Number(k)] : undefined;
|
|
80
82
|
}
|
|
81
83
|
keyAt(coords: readonly number[]): ArrayKey | undefined {
|
|
82
|
-
const k = coords
|
|
84
|
+
const k = String(coords[0]);
|
|
83
85
|
return coords.length === 1 && this.has(k) ? k : undefined;
|
|
84
86
|
}
|
|
85
87
|
}
|
|
@@ -107,8 +109,9 @@ class GridSpace<O> implements Space<GridKey, O> {
|
|
|
107
109
|
return this.#coords.get(k);
|
|
108
110
|
}
|
|
109
111
|
keyAt(coords: readonly number[]): GridKey | undefined {
|
|
112
|
+
// Each key has two coordinates, so a list with more or fewer coordinates gives no key.
|
|
110
113
|
const k = coords.join(",");
|
|
111
|
-
return
|
|
114
|
+
return this.has(k) ? k : undefined;
|
|
112
115
|
}
|
|
113
116
|
}
|
|
114
117
|
|
|
@@ -145,6 +148,8 @@ class TreeSpace<K extends string, O> implements Space<K, O> {
|
|
|
145
148
|
const children = new Map<string, K[]>(this.keys.map((k) => [k, []]));
|
|
146
149
|
for (const k of this.keys) {
|
|
147
150
|
const p = parentOf.get(k);
|
|
151
|
+
// Each parent is a key, so its list exists, and the test of p only skips the roots.
|
|
152
|
+
// Stryker disable next-line ConditionalExpression,OptionalChaining: a root has no list to push to
|
|
148
153
|
if (p !== undefined) children.get(p)?.push(k);
|
|
149
154
|
}
|
|
150
155
|
this.#children = new Map([...children].map(([k, c]) => [k, Object.freeze(c)]));
|
|
@@ -156,9 +161,11 @@ class TreeSpace<K extends string, O> implements Space<K, O> {
|
|
|
156
161
|
get(k: string): O | undefined {
|
|
157
162
|
return this.#records.get(k);
|
|
158
163
|
}
|
|
164
|
+
// Stryker disable next-line BlockStatement: the body gives undefined, and an empty body gives undefined too
|
|
159
165
|
coords(): readonly number[] | undefined {
|
|
160
166
|
return undefined;
|
|
161
167
|
}
|
|
168
|
+
// Stryker disable next-line BlockStatement: the body gives undefined, and an empty body gives undefined too
|
|
162
169
|
keyAt(): K | undefined {
|
|
163
170
|
return undefined;
|
|
164
171
|
}
|
|
@@ -208,7 +215,7 @@ export function applyMove(s: Space, at: Position, m: Move): Result<string> {
|
|
|
208
215
|
return s.has(m.key) ? ok(m.key) : refError("unknown-key", `the space has no key "${m.key}"`);
|
|
209
216
|
case "index": {
|
|
210
217
|
const k = s.keys[m.i];
|
|
211
|
-
return
|
|
218
|
+
return k !== undefined ? ok(k) : refError("out-of-bounds", `the space has no key at index ${m.i}`);
|
|
212
219
|
}
|
|
213
220
|
case "other": {
|
|
214
221
|
if (s.keys.length !== 2) return refError("not-a-pair", `"other" needs a space with 2 keys, but this space has ${s.keys.length}`);
|
package/src/traversal.ts
CHANGED
|
@@ -3,7 +3,7 @@ import { vexError, type VexError } from "./errors.ts";
|
|
|
3
3
|
import { evaluate, type FreeFn } from "./evaluate.ts";
|
|
4
4
|
import { app, lit, v } from "./ir.ts";
|
|
5
5
|
import { vexList, type ListItem } from "./list.ts";
|
|
6
|
-
import { fail, ok, toOptional, type Optional, type Result } from "./result.ts";
|
|
6
|
+
import { fail, none, ok, toOptional, type Optional, type Result } from "./result.ts";
|
|
7
7
|
import { space as spaces, type Space } from "./space.ts";
|
|
8
8
|
|
|
9
9
|
/** A monoid: an associative `concat` with an identity element `empty`. */
|
|
@@ -84,7 +84,6 @@ export function traversal<K extends string, T>(items: readonly TraversalItem<K,
|
|
|
84
84
|
origin: "$",
|
|
85
85
|
domains: env.domains,
|
|
86
86
|
vars: { $list: list },
|
|
87
|
-
...(env.options?.fns === undefined ? {} : { fns: env.options.fns }),
|
|
88
87
|
});
|
|
89
88
|
};
|
|
90
89
|
const t: Traversal<K, T> = {
|
|
@@ -92,7 +91,7 @@ export function traversal<K extends string, T>(items: readonly TraversalItem<K,
|
|
|
92
91
|
strict: () => traversal(items, env, true),
|
|
93
92
|
get: (k) => {
|
|
94
93
|
const item = items.find((it) => it.key === k);
|
|
95
|
-
return item === undefined ?
|
|
94
|
+
return item === undefined ? none() : toOptional(item.result);
|
|
96
95
|
},
|
|
97
96
|
values: () => items.flatMap((it) => (it.result.ok ? [it.result.value] : [])),
|
|
98
97
|
keys: () => items.flatMap((it) => (it.result.ok ? [it.key] : [])),
|