@mark1russell7/vex 0.14.0 → 0.16.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 +16 -3
- package/build/index.d.ts.map +1 -1
- package/build/index.js +257 -59
- package/build/index.js.map +1 -1
- package/package.json +2 -2
- package/src/builder.ts +18 -0
- package/src/checked.ts +6 -0
- package/src/evaluate.ts +234 -64
- package/src/kernel.ts +34 -1
- package/src/list.ts +4 -6
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.16.0",
|
|
5
5
|
"description": "Vex: typed spreadsheet formulas over domain objects. The kernel and the typed builder.",
|
|
6
6
|
"keywords": [
|
|
7
7
|
"typescript",
|
|
@@ -49,7 +49,7 @@
|
|
|
49
49
|
"access": "public"
|
|
50
50
|
},
|
|
51
51
|
"dependencies": {
|
|
52
|
-
"@mark1russell7/coeval": "^0.
|
|
52
|
+
"@mark1russell7/coeval": "^0.14.0"
|
|
53
53
|
},
|
|
54
54
|
"devDependencies": {
|
|
55
55
|
"@mark1russell7/cue": "github:mark1russell7/cue",
|
package/src/builder.ts
CHANGED
|
@@ -432,6 +432,15 @@ export interface ListChain<Ctx extends ChainContext, U> {
|
|
|
432
432
|
without<V>(other: ListChain<Ctx, V>, opts?: ListOpts): ListChain<Ctx, U>;
|
|
433
433
|
/** The items of the lists that are the values of the items, in order (LIST.FLAT). The values must be lists. */
|
|
434
434
|
flat<V>(this: ListChain<Ctx, VexList<V>>, opts?: ListOpts): ListChain<Ctx, V>;
|
|
435
|
+
/** The first item of each value, in the order of the list (LIST.DISTINCT). The values are numbers, texts or booleans. */
|
|
436
|
+
distinct(opts?: ListOpts): ListChain<Ctx, U>;
|
|
437
|
+
/**
|
|
438
|
+
* The groups of the items by the text keys of `keys` (LIST.GROUP). The key at a position is the key of the item at
|
|
439
|
+
* the same position. Each key gives one item, and its value is the list of its items (BUILD.LIST.GROUP).
|
|
440
|
+
*/
|
|
441
|
+
group(keys: ListChain<Ctx, string>, opts?: ListOpts): ListChain<Ctx, VexList<U>>;
|
|
442
|
+
/** The texts of the items with the text `sep` between them (LIST.JOIN). A chain of a text gives the separator. */
|
|
443
|
+
join(this: ListChain<Ctx, string>, sep: string | ChainBase<Ctx, string>, opts?: ListOpts): ChainOf<Ctx, string>;
|
|
435
444
|
/**
|
|
436
445
|
* The axis list (AXIS.LIST): the body evaluates at the key of each item, in the order of the list. The body reads the
|
|
437
446
|
* fields of the record of the item. The chain of the body has no value of its own. The body also gets a chain of the
|
|
@@ -995,6 +1004,15 @@ class ListChainImpl {
|
|
|
995
1004
|
flat(opts?: ListOpts): ListChainImpl {
|
|
996
1005
|
return this.#list("flat", [], opts);
|
|
997
1006
|
}
|
|
1007
|
+
distinct(opts?: ListOpts): ListChainImpl {
|
|
1008
|
+
return this.#list("distinct", [], opts);
|
|
1009
|
+
}
|
|
1010
|
+
group(keys: unknown, opts?: ListOpts): ListChainImpl {
|
|
1011
|
+
return this.#list("group", [listProgram("group", keys)], opts);
|
|
1012
|
+
}
|
|
1013
|
+
join(sep: string | { readonly program: Expr }, opts?: ListOpts): ChainImpl {
|
|
1014
|
+
return this.#op("join", [typeof sep === "string" ? lit(sep) : sep.program], opts);
|
|
1015
|
+
}
|
|
998
1016
|
each(body: (c: ChainImpl, item: ChainImpl, index: ChainImpl) => { readonly program: Expr }, opts?: AxisOptsImpl): ListChainImpl {
|
|
999
1017
|
// The chains of the body are at the key of the item. The chain of the body has no value of its own.
|
|
1000
1018
|
const inner: State = { ...this.#s, addr: [], depth: this.#s.depth + 1 };
|
package/src/checked.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The cache of the lists that passed the check of LIST.SHAPE. `isVexList` adds each frozen list that passes its check.
|
|
3
|
+
* The interpreter adds each list that it makes from the items of such lists, because these items passed the check.
|
|
4
|
+
* The package index does not export this module.
|
|
5
|
+
*/
|
|
6
|
+
export const CHECKED: WeakSet<object> = new WeakSet<object>();
|
package/src/evaluate.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
+
import { CHECKED } from "./checked.ts";
|
|
1
2
|
import { fromDocument, isDocument, type Envelope } from "./document.ts";
|
|
2
|
-
import { liftsAt, resolveOp, type AnyDomain, type ParamKind, type ResolvedOp } from "./domain.ts";
|
|
3
|
+
import { findMethod, isOpName, liftsAt, resolveOp, type AnyDomain, type OpSpec, type ParamKind, type PrimitiveKind, type ResolvedOp } from "./domain.ts";
|
|
3
4
|
import { formatError, isDepthError, isStackOverflow, vexError, type ErrorKind, type VexError } from "./errors.ts";
|
|
4
5
|
import { addrExprs, children, shapeError, type Addr, type Axis, type Expr, type ExprOf, type FixedMove, type ItemNames, type Move } from "./ir.ts";
|
|
5
6
|
import { asList, fillList, isFillCount, isIndexValue, listOfArray } from "./array-list.ts";
|
|
@@ -41,7 +42,41 @@ export interface EvalOptions {
|
|
|
41
42
|
readonly trace?: TraceSink;
|
|
42
43
|
}
|
|
43
44
|
|
|
44
|
-
|
|
45
|
+
/** The names of a frame: a map of the variables of the caller, or a scope inside it. */
|
|
46
|
+
interface Env {
|
|
47
|
+
get(name: string): Result<unknown> | undefined;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* A scope: the names of one `let`, a function, an item or a loop. It is in front of the outer names, and it does not
|
|
52
|
+
* copy them. A name of a scope hides an outer name of the same name. The names of one
|
|
53
|
+
* scope are distinct (FN.BIND, LOOP.NAMES, AXIS.LIST.SCOPE).
|
|
54
|
+
*/
|
|
55
|
+
class Scope implements Env {
|
|
56
|
+
readonly #outer: Env;
|
|
57
|
+
readonly #names: readonly string[];
|
|
58
|
+
readonly #values: readonly Result<unknown>[];
|
|
59
|
+
|
|
60
|
+
constructor(outer: Env, names: readonly string[], values: readonly Result<unknown>[]) {
|
|
61
|
+
this.#outer = outer;
|
|
62
|
+
this.#names = names;
|
|
63
|
+
this.#values = values;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
get(name: string): Result<unknown> | undefined {
|
|
67
|
+
const at = this.#names.indexOf(name);
|
|
68
|
+
return at >= 0 ? this.#values[at] : this.#outer.get(name);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** This method gives a copy of this scope with the values `values` at the positions `at` (LOOP.NAMES). */
|
|
72
|
+
with(at: readonly number[], values: readonly Result<unknown>[]): Scope {
|
|
73
|
+
const next = [...this.#values];
|
|
74
|
+
at.forEach((position, i) => {
|
|
75
|
+
next[position] = values[i] as Result<unknown>;
|
|
76
|
+
});
|
|
77
|
+
return new Scope(this.#outer, this.#names, next);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
45
80
|
|
|
46
81
|
interface Frame {
|
|
47
82
|
readonly pos: Position;
|
|
@@ -82,9 +117,9 @@ export interface Program {
|
|
|
82
117
|
class Closure {
|
|
83
118
|
readonly params: readonly string[];
|
|
84
119
|
readonly body: Node;
|
|
85
|
-
readonly env:
|
|
120
|
+
readonly env: Env;
|
|
86
121
|
|
|
87
|
-
constructor(params: readonly string[], body: Node, env:
|
|
122
|
+
constructor(params: readonly string[], body: Node, env: Env) {
|
|
88
123
|
this.params = params;
|
|
89
124
|
this.body = body;
|
|
90
125
|
this.env = env;
|
|
@@ -185,6 +220,26 @@ const baseAxis = (a: Axis): Exclude<Axis, { readonly t: "where" }> => (a.t === "
|
|
|
185
220
|
/** A compiled node: it evaluates in a frame of a run. */
|
|
186
221
|
type Node = (f: Frame, c: Ctx) => Result<unknown>;
|
|
187
222
|
|
|
223
|
+
/** This function evaluates the nodes in order. The first error stops it and is the result. */
|
|
224
|
+
function allValues(ns: readonly Node[], f: Frame, c: Ctx): Result<Result<unknown>[]> {
|
|
225
|
+
const values: Result<unknown>[] = [];
|
|
226
|
+
for (const n of ns) {
|
|
227
|
+
const r = n(f, c);
|
|
228
|
+
if (!r.ok) return r;
|
|
229
|
+
values.push(r);
|
|
230
|
+
}
|
|
231
|
+
return ok(values);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** The primitive types of KIND.PRIMITIVE. */
|
|
235
|
+
const PRIMITIVE_TYPES: readonly PrimitiveKind[] = ["number", "string", "boolean"];
|
|
236
|
+
|
|
237
|
+
/** The spec of an op without an entry in the op table of a domain with `methods: "all"`. */
|
|
238
|
+
const NO_SPEC: OpSpec<unknown> = Object.freeze({});
|
|
239
|
+
|
|
240
|
+
/** The function of an op: the receiver comes first, then the arguments. */
|
|
241
|
+
type OpFn = (self: unknown, ...args: readonly unknown[]) => unknown;
|
|
242
|
+
|
|
188
243
|
/**
|
|
189
244
|
* A target of an axis: its key, and the error of a test of `where` or of an error item. A target of the axis `list` also
|
|
190
245
|
* has the value of its item and its position as `nth` counts it (AXIS.LIST.ITEM, AXIS.LIST.INDEX).
|
|
@@ -204,12 +259,8 @@ type Targets = (f: Frame, c: Ctx) => Result<readonly Target[]>;
|
|
|
204
259
|
* the item, and the second its index (AXIS.LIST.ITEM, AXIS.LIST.INDEX). A loop without `as` keeps its names.
|
|
205
260
|
*/
|
|
206
261
|
function withItem(env: Env, as: ItemNames | undefined, t: Target): Env {
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
const [item, index] = as;
|
|
210
|
-
out.set(item, ok(t.value));
|
|
211
|
-
if (index !== undefined) out.set(index, ok(t.index));
|
|
212
|
-
return out;
|
|
262
|
+
// A scope with one name reads only the first value.
|
|
263
|
+
return as === undefined ? env : new Scope(env, as, [ok(t.value), ok(t.index)]);
|
|
213
264
|
}
|
|
214
265
|
|
|
215
266
|
/** The static facts of a node for its trace events. */
|
|
@@ -225,12 +276,21 @@ class Compiler {
|
|
|
225
276
|
readonly #extensions: Readonly<Record<string, ExtHandler>> | undefined;
|
|
226
277
|
/** The index of the keys of each list that `get` read (LIST.GET). A list does not change, so its index stays right. */
|
|
227
278
|
readonly #keyIndex = new WeakMap<VexList, KeyIndex>();
|
|
279
|
+
/**
|
|
280
|
+
* The domains that can accept a value of each primitive type, in order (KIND.PRIMITIVE). These are the domains of
|
|
281
|
+
* that type and the domains without a primitive type.
|
|
282
|
+
*/
|
|
283
|
+
readonly #ofType = new Map<string, readonly AnyDomain[]>();
|
|
284
|
+
/** The domains without a primitive type. Only they can accept a value of another type, for example an object. */
|
|
285
|
+
readonly #open: readonly AnyDomain[];
|
|
228
286
|
|
|
229
287
|
constructor(opts: CompileOptions) {
|
|
230
288
|
// Stryker disable next-line ArrayDeclaration: a list with a value that is not a domain matches no value
|
|
231
289
|
this.#domains = opts.domains ?? [];
|
|
232
290
|
this.#fns = opts.fns;
|
|
233
291
|
this.#extensions = opts.extensions;
|
|
292
|
+
this.#open = this.#domains.filter((d) => d.primitive === undefined);
|
|
293
|
+
for (const t of PRIMITIVE_TYPES) this.#ofType.set(t, this.#domains.filter((d) => d.primitive === undefined || d.primitive === t));
|
|
234
294
|
}
|
|
235
295
|
|
|
236
296
|
#err(kind: ErrorKind, message: string, f: Frame, path: readonly number[], extra: { op?: string; causes?: readonly VexError[]; thrown?: unknown } = {}): Result<never> {
|
|
@@ -246,7 +306,11 @@ class Compiler {
|
|
|
246
306
|
#fill(values: readonly unknown[], f: Frame, path: readonly number[]): Result<VexList> {
|
|
247
307
|
const [n, value] = values;
|
|
248
308
|
if (!isFillCount(n)) return this.#err("kind-mismatch", `"fill" needs a whole number from 0 to 100000, not ${describeType(n)}`, f, path, { op: "fill" });
|
|
249
|
-
|
|
309
|
+
if (value === undefined) return this.#err("bad-expression", '"fill" needs argument 2', f, path, { op: "fill" });
|
|
310
|
+
// Each item of the list has the value, so the list has the shape of LIST.SHAPE.
|
|
311
|
+
const list = fillList(n, value);
|
|
312
|
+
CHECKED.add(list);
|
|
313
|
+
return ok(list);
|
|
250
314
|
}
|
|
251
315
|
|
|
252
316
|
#emit(c: Ctx, info: Info, f: Frame, result: Result<unknown>, reads?: readonly Read[]): Result<unknown> {
|
|
@@ -289,12 +353,14 @@ class Compiler {
|
|
|
289
353
|
case "call":
|
|
290
354
|
return this.#callFn(e, info);
|
|
291
355
|
case "let": {
|
|
292
|
-
const
|
|
356
|
+
const names = Object.keys(e.bind);
|
|
357
|
+
const binds = this.#nodes(Object.values(e.bind), path);
|
|
293
358
|
const body = this.node(e.body, [...path, binds.length]);
|
|
294
359
|
return (f, c) => {
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
360
|
+
// Each binding evaluates with the outer names, so a binding does not see the other bindings.
|
|
361
|
+
const values: Result<unknown>[] = [];
|
|
362
|
+
for (const n of binds) values.push(n(f, c));
|
|
363
|
+
return this.#emit(c, info, f, body({ pos: f.pos, env: new Scope(f.env, names, values) }, c));
|
|
298
364
|
};
|
|
299
365
|
}
|
|
300
366
|
case "rec": {
|
|
@@ -354,9 +420,9 @@ class Compiler {
|
|
|
354
420
|
const callee = bound.value;
|
|
355
421
|
if (!(callee instanceof Closure)) return this.#emit(c, info, f, this.#err("kind-mismatch", `the name "${e.fn}" is a value, not a function`, f, path));
|
|
356
422
|
if (callee.params.length !== args.length) return this.#emit(c, info, f, this.#err("bad-expression", `the function "${e.fn}" takes ${String(callee.params.length)} arguments, not ${String(args.length)}`, f, path));
|
|
357
|
-
const
|
|
358
|
-
|
|
359
|
-
return this.#emit(c, info, f, callee.body({ pos: f.pos, env }, c));
|
|
423
|
+
const values: Result<unknown>[] = [];
|
|
424
|
+
for (const n of args) values.push(n(f, c));
|
|
425
|
+
return this.#emit(c, info, f, callee.body({ pos: f.pos, env: new Scope(callee.env, callee.params, values) }, c));
|
|
360
426
|
};
|
|
361
427
|
}
|
|
362
428
|
|
|
@@ -492,33 +558,25 @@ class Compiler {
|
|
|
492
558
|
* functions give the first values, and the values after one step. The first error stops each of them.
|
|
493
559
|
*/
|
|
494
560
|
#names(e: ExprOf<"fold"> | ExprOf<"iterate">, path: readonly number[]): {
|
|
495
|
-
readonly first: (f: Frame, c: Ctx) => Result<
|
|
496
|
-
readonly next: (f: Frame, c: Ctx,
|
|
561
|
+
readonly first: (f: Frame, c: Ctx) => Result<Scope>;
|
|
562
|
+
readonly next: (f: Frame, c: Ctx, scope: Scope) => Result<Scope>;
|
|
497
563
|
} {
|
|
498
|
-
const
|
|
499
|
-
const
|
|
564
|
+
const names = Object.keys(e.init);
|
|
565
|
+
const inits = this.#nodes(Object.values(e.init), path);
|
|
566
|
+
const steps = Object.values(e.step).map((x, i) => this.node(x, [...path, inits.length + i]));
|
|
567
|
+
// Each name of a step is a name of init (LOOP.NAMES), so a step changes the value at a position of the scope.
|
|
568
|
+
const at = Object.keys(e.step).map((name) => names.indexOf(name));
|
|
500
569
|
return {
|
|
501
570
|
first: (f, c) => {
|
|
502
|
-
const
|
|
503
|
-
|
|
504
|
-
const r = n(f, c);
|
|
505
|
-
if (!r.ok) return r;
|
|
506
|
-
env.set(name, r);
|
|
507
|
-
}
|
|
508
|
-
return ok(env);
|
|
571
|
+
const values = allValues(inits, f, c);
|
|
572
|
+
return values.ok ? ok(new Scope(f.env, names, values.value)) : values;
|
|
509
573
|
},
|
|
510
574
|
// Each value of a step reads the values before the step, so the names change only after all the values. The new
|
|
511
|
-
// names come from `
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
if (!r.ok) return r;
|
|
517
|
-
values.push([name, r]);
|
|
518
|
-
}
|
|
519
|
-
const env = new Map(names);
|
|
520
|
-
for (const [name, r] of values) env.set(name, r);
|
|
521
|
-
return ok(env);
|
|
575
|
+
// names come from `scope`, the scope of the loop, because the frame can have more names, for example the names of
|
|
576
|
+
// an item (AXIS.LIST.SCOPE).
|
|
577
|
+
next: (f, c, scope) => {
|
|
578
|
+
const values = allValues(steps, f, c);
|
|
579
|
+
return values.ok ? ok(scope.with(at, values.value)) : values;
|
|
522
580
|
},
|
|
523
581
|
};
|
|
524
582
|
}
|
|
@@ -594,7 +652,7 @@ class Compiler {
|
|
|
594
652
|
if (until !== undefined) return this.#emit(c, info, f, this.#err("limit", `"iterate" made its ${String(limit)} steps, and its test "until" is not true`, f, path));
|
|
595
653
|
break;
|
|
596
654
|
}
|
|
597
|
-
const after = names.next(frame, c);
|
|
655
|
+
const after = names.next(frame, c, env);
|
|
598
656
|
if (!after.ok) return this.#emit(c, info, f, after);
|
|
599
657
|
env = after.value;
|
|
600
658
|
}
|
|
@@ -663,6 +721,8 @@ class Compiler {
|
|
|
663
721
|
const { path } = info;
|
|
664
722
|
const listOp = isListOp(op) ? op : undefined;
|
|
665
723
|
const fn = this.#fns !== undefined && Object.hasOwn(this.#fns, op) ? this.#fns[op] : undefined;
|
|
724
|
+
// A name that cannot be an op name has no op, also with an own entry in an op table (resolveOp).
|
|
725
|
+
const named = isOpName(op);
|
|
666
726
|
return (f, c) => {
|
|
667
727
|
const all = this.#all(args, f, c, path, "arguments");
|
|
668
728
|
if (!all.ok) return this.#emit(c, info, f, all);
|
|
@@ -676,8 +736,12 @@ class Compiler {
|
|
|
676
736
|
for (const d of this.#domains) {
|
|
677
737
|
if (!safeIs(d, self)) continue;
|
|
678
738
|
accepted ??= d;
|
|
679
|
-
|
|
680
|
-
|
|
739
|
+
// The rules of resolveOp, without a closure for each call: the function of the spec, or a method of the
|
|
740
|
+
// receiver for a declared op without a function, or for each op of a domain with `methods: "all"`.
|
|
741
|
+
const spec = named && Object.hasOwn(d.ops, op) ? (d.ops[op] as OpSpec<unknown>) : undefined;
|
|
742
|
+
if (spec?.fn !== undefined) return this.#emit(c, info, f, this.#call(d, spec, spec.fn as OpFn, self, op, values.slice(1), f, path));
|
|
743
|
+
const method = spec !== undefined || d.methods === "all" ? findMethod(self, op) : undefined;
|
|
744
|
+
if (method !== undefined) return this.#emit(c, info, f, this.#call(d, spec ?? NO_SPEC, (receiver, ...given) => method.apply(receiver, [...given]), self, op, values.slice(1), f, path));
|
|
681
745
|
}
|
|
682
746
|
}
|
|
683
747
|
if (fn !== undefined) return this.#emit(c, info, f, this.#checkResult(this.#invoke(() => fn(...values), op, f, path), f, path, op));
|
|
@@ -729,8 +793,16 @@ class Compiler {
|
|
|
729
793
|
}
|
|
730
794
|
}
|
|
731
795
|
|
|
732
|
-
|
|
733
|
-
|
|
796
|
+
/** This method starts an op that resolveOp found, for example a method of the receiver. */
|
|
797
|
+
#callResolved(op: ResolvedOp, self: unknown, name: string, rest: readonly unknown[], f: Frame, path: readonly number[]): Result<unknown> {
|
|
798
|
+
return this.#call(op.domain, op.spec, (_self, ...args) => op.call(args), self, name, rest, f, path);
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
/**
|
|
802
|
+
* This method starts the op `name` of the domain `domain` with the receiver `self` and the arguments `rest`. It lifts
|
|
803
|
+
* the numbers, checks the arguments and checks the result.
|
|
804
|
+
*/
|
|
805
|
+
#call(domain: AnyDomain, spec: OpSpec<unknown>, run: OpFn, self: unknown, name: string, rest: readonly unknown[], f: Frame, path: readonly number[]): Result<unknown> {
|
|
734
806
|
const lift = spec.liftScalar;
|
|
735
807
|
const from = domain.fromScalar;
|
|
736
808
|
let callArgs: readonly unknown[] = rest;
|
|
@@ -748,7 +820,13 @@ class Compiler {
|
|
|
748
820
|
}
|
|
749
821
|
}
|
|
750
822
|
}
|
|
751
|
-
|
|
823
|
+
let value: unknown;
|
|
824
|
+
try {
|
|
825
|
+
value = run(self, ...callArgs);
|
|
826
|
+
} catch (thrown) {
|
|
827
|
+
return this.#threw(thrown, `"${name}" threw an exception`, f, path, { op: name });
|
|
828
|
+
}
|
|
829
|
+
return this.#checkResult(ok(value), f, path, name);
|
|
752
830
|
}
|
|
753
831
|
|
|
754
832
|
#invoke(run: () => unknown, op: string, f: Frame, path: readonly number[]): Result<unknown> {
|
|
@@ -759,6 +837,16 @@ class Compiler {
|
|
|
759
837
|
}
|
|
760
838
|
}
|
|
761
839
|
|
|
840
|
+
/**
|
|
841
|
+
* This method gives the first domain that accepts a value. It starts only the tests of the domains without a primitive
|
|
842
|
+
* type: a domain of the type of the value accepts it (KIND.PRIMITIVE).
|
|
843
|
+
*/
|
|
844
|
+
#domainOf(value: unknown): AnyDomain | undefined {
|
|
845
|
+
const candidates = this.#ofType.get(typeof value) ?? this.#open;
|
|
846
|
+
for (const d of candidates) if (d.primitive !== undefined || testIs(d, value)) return d;
|
|
847
|
+
return undefined;
|
|
848
|
+
}
|
|
849
|
+
|
|
762
850
|
/** This method checks the value that an op gave: no `undefined`, finite numbers, and valid domain values. */
|
|
763
851
|
#checkResult(r: Result<unknown>, f: Frame, path: readonly number[], op: string): Result<unknown> {
|
|
764
852
|
if (!r.ok) return r;
|
|
@@ -766,7 +854,7 @@ class Compiler {
|
|
|
766
854
|
const extra = { op };
|
|
767
855
|
if (value === undefined || value === null) return this.#err("undefined-result", `"${op}" gave no value`, f, path, extra);
|
|
768
856
|
if (typeof value === "number" && !Number.isFinite(value)) return this.#err("not-finite", `"${op}" gave ${value}`, f, path, extra);
|
|
769
|
-
const d = this.#
|
|
857
|
+
const d = this.#domainOf(value);
|
|
770
858
|
if (d?.valid !== undefined) {
|
|
771
859
|
let valid: boolean;
|
|
772
860
|
try {
|
|
@@ -784,11 +872,12 @@ class Compiler {
|
|
|
784
872
|
const optsArg = WITH_ARGUMENT.has(op) ? rest[1] : rest[0];
|
|
785
873
|
const strict = (optsArg as ListOptions | null | undefined)?.strict === true;
|
|
786
874
|
if (op === "get") return this.#get(list, rest[0], strict, f, path);
|
|
875
|
+
if (op === "group") return this.#group(list, rest[0], strict, f, path);
|
|
787
876
|
const good = goodItems(list, strict);
|
|
788
877
|
if (!good.ok) return good;
|
|
789
878
|
const okItems = good.value;
|
|
790
|
-
|
|
791
|
-
const
|
|
879
|
+
const okValues: unknown[] = [];
|
|
880
|
+
for (const it of okItems) okValues.push(valueOf(it));
|
|
792
881
|
const numbers = (): Result<readonly number[]> => {
|
|
793
882
|
const bad = okValues.find((x) => typeof x !== "number");
|
|
794
883
|
return bad === undefined ? ok(okValues as readonly number[]) : this.#err("kind-mismatch", `"${op}" needs numbers, but an item is a ${describeType(bad)}`, f, path, { op });
|
|
@@ -815,20 +904,40 @@ class Compiler {
|
|
|
815
904
|
case "drop": {
|
|
816
905
|
const n = whole();
|
|
817
906
|
if (!n.ok) return n;
|
|
818
|
-
return ok(
|
|
907
|
+
return ok(checkedList(op === "take" ? okItems.slice(0, n.value) : okItems.slice(n.value)));
|
|
819
908
|
}
|
|
820
909
|
case "append": {
|
|
821
910
|
const more = other();
|
|
822
|
-
return more.ok ? ok(
|
|
911
|
+
return more.ok ? ok(checkedList([...okItems, ...more.value])) : more;
|
|
823
912
|
}
|
|
824
913
|
case "without": {
|
|
825
914
|
const more = other();
|
|
826
915
|
if (!more.ok) return more;
|
|
827
916
|
const gone = new Set(more.value.map((it) => it.key));
|
|
828
|
-
return ok(
|
|
917
|
+
return ok(checkedList(okItems.filter((it) => !gone.has(it.key))));
|
|
829
918
|
}
|
|
830
919
|
case "flat":
|
|
831
920
|
return this.#flat(okValues, strict, f, path);
|
|
921
|
+
case "distinct": {
|
|
922
|
+
// The first item of each value, in the order of the list (LIST.DISTINCT). === compares the values, as for
|
|
923
|
+
// indexOf, so each NaN stays.
|
|
924
|
+
const seen = new Set<unknown>();
|
|
925
|
+
const out: ListItem[] = [];
|
|
926
|
+
for (let i = 0; i < okValues.length; i++) {
|
|
927
|
+
const x = okValues[i];
|
|
928
|
+
if (!isIndexValue(x)) return this.#err("kind-mismatch", `"distinct" needs numbers, texts or booleans, but an item is a ${describeType(x)}`, f, path, { op });
|
|
929
|
+
if (Number.isNaN(x) || !seen.has(x)) out.push(okItems[i] as ListItem);
|
|
930
|
+
seen.add(x);
|
|
931
|
+
}
|
|
932
|
+
return ok(checkedList(out));
|
|
933
|
+
}
|
|
934
|
+
case "join": {
|
|
935
|
+
// The texts of the items with the text sep between them (LIST.JOIN).
|
|
936
|
+
const sep = rest[0];
|
|
937
|
+
if (typeof sep !== "string") return this.#err("kind-mismatch", `"join" needs a text separator, not a ${describeType(sep)}`, f, path, { op });
|
|
938
|
+
const bad = okValues.find((x) => typeof x !== "string");
|
|
939
|
+
return bad === undefined ? ok(okValues.join(sep)) : this.#err("kind-mismatch", `"join" needs texts, but an item is a ${describeType(bad)}`, f, path, { op });
|
|
940
|
+
}
|
|
832
941
|
case "indexOf": {
|
|
833
942
|
const x = rest[0];
|
|
834
943
|
if (!isIndexValue(x)) return this.#err("kind-mismatch", `"indexOf" needs a number, a text or a boolean, not a ${describeType(x)}`, f, path, { op });
|
|
@@ -898,6 +1007,36 @@ class Compiler {
|
|
|
898
1007
|
return index.values.has(key) ? ok(index.values.get(key)) : this.#err("missing-field", `the list has no item with the key ${JSON.stringify(key)}`, f, path, { op: "get" });
|
|
899
1008
|
}
|
|
900
1009
|
|
|
1010
|
+
/**
|
|
1011
|
+
* This method gives the groups of a list (LIST.GROUP). The item at a position has the key at the same position of
|
|
1012
|
+
* `keys`, so the two lists must have the same number of items. A pair with an error item or an error key is not in a
|
|
1013
|
+
* group (LIST.LENIENT). Each key gives one item, in the order of its first pair, and its value is a list of its items.
|
|
1014
|
+
*/
|
|
1015
|
+
#group(list: VexList, keys: unknown, strict: boolean, f: Frame, path: readonly number[]): Result<VexList> {
|
|
1016
|
+
const good = goodItems(list, strict);
|
|
1017
|
+
if (!good.ok) return good;
|
|
1018
|
+
const listed = asList(keys, this.#missing(f, path));
|
|
1019
|
+
if (listed === undefined) return this.#err("kind-mismatch", `"group" needs a list of keys as its second argument, not a ${describeType(keys)}`, f, path, { op: "group" });
|
|
1020
|
+
const goodKeys = goodItems(listed, strict);
|
|
1021
|
+
if (!goodKeys.ok) return goodKeys;
|
|
1022
|
+
const { items } = list;
|
|
1023
|
+
const keyItems = listed.items;
|
|
1024
|
+
if (keyItems.length !== items.length) return this.#err("kind-mismatch", `"group" needs one key for each item, but the list has ${String(items.length)} items and ${String(keyItems.length)} keys`, f, path, { op: "group" });
|
|
1025
|
+
const groups = new Map<string, ListItem[]>();
|
|
1026
|
+
for (let i = 0; i < items.length; i++) {
|
|
1027
|
+
const it = items[i] as ListItem;
|
|
1028
|
+
const k = (keyItems[i] as ListItem).result;
|
|
1029
|
+
if (!it.result.ok || !k.ok) continue;
|
|
1030
|
+
if (typeof k.value !== "string") return this.#err("kind-mismatch", `"group" needs text keys, but a key is a ${describeType(k.value)}`, f, path, { op: "group" });
|
|
1031
|
+
const g = groups.get(k.value);
|
|
1032
|
+
if (g === undefined) groups.set(k.value, [it]);
|
|
1033
|
+
else g.push(it);
|
|
1034
|
+
}
|
|
1035
|
+
const out: ListItem[] = [];
|
|
1036
|
+
for (const [key, g] of groups) out.push({ key, result: ok(checkedList(g)) });
|
|
1037
|
+
return ok(checkedList(out));
|
|
1038
|
+
}
|
|
1039
|
+
|
|
901
1040
|
/**
|
|
902
1041
|
* This method joins the lists that are the values of the items of a list, in order (LIST.FLAT). Each list follows the
|
|
903
1042
|
* rules of LIST.BUILD. A value that is not a list gives `#VALUE!`.
|
|
@@ -911,7 +1050,7 @@ class Compiler {
|
|
|
911
1050
|
if (!good.ok) return good;
|
|
912
1051
|
out.push(...good.value);
|
|
913
1052
|
}
|
|
914
|
-
return ok(
|
|
1053
|
+
return ok(checkedList(out));
|
|
915
1054
|
}
|
|
916
1055
|
|
|
917
1056
|
/**
|
|
@@ -937,7 +1076,7 @@ class Compiler {
|
|
|
937
1076
|
// Stryker disable next-line ConditionalExpression,EqualityOperator: see the comment above
|
|
938
1077
|
return a < b ? -1 : a > b ? 1 : 0;
|
|
939
1078
|
});
|
|
940
|
-
return ok(
|
|
1079
|
+
return ok(checkedList(order.map((i) => items[i] as ListItem)));
|
|
941
1080
|
}
|
|
942
1081
|
|
|
943
1082
|
/**
|
|
@@ -954,7 +1093,7 @@ class Compiler {
|
|
|
954
1093
|
if (op !== undefined) break;
|
|
955
1094
|
}
|
|
956
1095
|
if (op === undefined) return this.#err("unknown-op", `no domain gives "${by}" for a ${describeType(x)}`, f, path, { op: by });
|
|
957
|
-
const r = this.#
|
|
1096
|
+
const r = this.#callResolved(op, x, by, [], f, path);
|
|
958
1097
|
if (!r.ok) return r;
|
|
959
1098
|
out.push(r.value);
|
|
960
1099
|
}
|
|
@@ -986,7 +1125,7 @@ class Compiler {
|
|
|
986
1125
|
const d = this.#domains.find((dom) => safeIs(dom, acc) && resolveOp(dom, acc, opName) !== undefined);
|
|
987
1126
|
const op = d === undefined ? undefined : resolveOp(d, acc, opName);
|
|
988
1127
|
if (op === undefined) return this.#err("unknown-op", `no domain gives "${opName}" for a ${describeType(acc)}`, f, path, { op: opName });
|
|
989
|
-
const r = this.#
|
|
1128
|
+
const r = this.#callResolved(op, acc, opName, [values[i]], f, path);
|
|
990
1129
|
if (!r.ok) return r;
|
|
991
1130
|
acc = r.value;
|
|
992
1131
|
}
|
|
@@ -995,20 +1134,42 @@ class Compiler {
|
|
|
995
1134
|
}
|
|
996
1135
|
|
|
997
1136
|
/** The list ops with a second argument before their options: a count, a position, an op name or a list. */
|
|
998
|
-
const WITH_ARGUMENT: ReadonlySet<ListOp> = new Set<ListOp>(["reduce", "take", "nth", "drop", "append", "without", "get", "indexOf"]);
|
|
1137
|
+
const WITH_ARGUMENT: ReadonlySet<ListOp> = new Set<ListOp>(["reduce", "take", "nth", "drop", "append", "without", "get", "indexOf", "group", "join"]);
|
|
999
1138
|
|
|
1000
1139
|
/**
|
|
1001
1140
|
* This function gives the items of a list that have a value (LIST.LENIENT). A list op does not skip `#DEPTH!`, so that
|
|
1002
1141
|
* error comes first (EVAL.DEPTH). With `strict`, the first error item is the result.
|
|
1003
1142
|
*/
|
|
1004
1143
|
function goodItems(list: VexList, strict: boolean): Result<readonly ListItem[]> {
|
|
1005
|
-
const
|
|
1006
|
-
|
|
1007
|
-
const
|
|
1008
|
-
|
|
1009
|
-
|
|
1144
|
+
const { items } = list;
|
|
1145
|
+
let first: VexError | undefined;
|
|
1146
|
+
for (const it of items) {
|
|
1147
|
+
if (it.result.ok) continue;
|
|
1148
|
+
if (isDepthError(it.result.error)) return fail(it.result.error);
|
|
1149
|
+
first ??= it.result.error;
|
|
1150
|
+
}
|
|
1151
|
+
// A list without error items gives its own items: no copy. Nothing changes them: the items of `vexList` are frozen,
|
|
1152
|
+
// and each list op makes a new array.
|
|
1153
|
+
if (first === undefined) return ok(items);
|
|
1154
|
+
if (strict) return fail(first);
|
|
1155
|
+
const out: ListItem[] = [];
|
|
1156
|
+
for (const it of items) if (it.result.ok) out.push(it);
|
|
1157
|
+
return ok(out);
|
|
1158
|
+
}
|
|
1159
|
+
|
|
1160
|
+
/**
|
|
1161
|
+
* This function makes a list from the items of lists that passed the check of LIST.SHAPE, or from items of the same
|
|
1162
|
+
* shape. Thus the list skips the check of `isVexList`.
|
|
1163
|
+
*/
|
|
1164
|
+
function checkedList(items: readonly ListItem[]): VexList {
|
|
1165
|
+
const list = vexList(items);
|
|
1166
|
+
CHECKED.add(list);
|
|
1167
|
+
return list;
|
|
1010
1168
|
}
|
|
1011
1169
|
|
|
1170
|
+
/** This function gives the value of an item with a value. */
|
|
1171
|
+
const valueOf = (it: ListItem): unknown => (it.result as { readonly value: unknown }).value;
|
|
1172
|
+
|
|
1012
1173
|
/** The index of the keys of a list (LIST.GET): the value of the first item of each key, and the first errors. */
|
|
1013
1174
|
interface KeyIndex {
|
|
1014
1175
|
readonly values: ReadonlyMap<string, unknown>;
|
|
@@ -1039,9 +1200,18 @@ const FORBIDDEN_FIELDS = new Set(["__proto__", "constructor", "prototype"]);
|
|
|
1039
1200
|
/** This function tells if a segment of a path can name a field. A compiler uses the same rule as the interpreter. */
|
|
1040
1201
|
export const isFieldName = (seg: string): boolean => seg.length > 0 && !FORBIDDEN_FIELDS.has(seg);
|
|
1041
1202
|
|
|
1042
|
-
/**
|
|
1043
|
-
|
|
1203
|
+
/**
|
|
1204
|
+
* This function tells if a domain accepts a value. A domain with a primitive type accepts each value of that type and
|
|
1205
|
+
* no other value (KIND.PRIMITIVE), so its test `is` does not start. For another domain, a test that throws counts as
|
|
1206
|
+
* `false`.
|
|
1207
|
+
*/
|
|
1044
1208
|
export function safeIs(d: AnyDomain, value: unknown): boolean {
|
|
1209
|
+
return d.primitive !== undefined ? typeof value === d.primitive : testIs(d, value);
|
|
1210
|
+
}
|
|
1211
|
+
|
|
1212
|
+
/** This function starts the `is` test of a domain. A test that throws counts as `false`. */
|
|
1213
|
+
// Stryker disable BlockStatement: an empty catch gives undefined, which also counts as false
|
|
1214
|
+
function testIs(d: AnyDomain, value: unknown): boolean {
|
|
1045
1215
|
try {
|
|
1046
1216
|
return d.is(value);
|
|
1047
1217
|
} catch {
|
package/src/kernel.ts
CHANGED
|
@@ -673,7 +673,7 @@ function callFound(found: Found, op: string, self: unknown, args: readonly unkno
|
|
|
673
673
|
}
|
|
674
674
|
|
|
675
675
|
/** The list ops with a second argument before their options: a count, a position, an op name or a list. */
|
|
676
|
-
const WITH_ARGUMENT: ReadonlySet<string> = /* @__PURE__ */ new Set(["reduce", "take", "nth", "drop", "append", "without", "get", "indexOf"]);
|
|
676
|
+
const WITH_ARGUMENT: ReadonlySet<string> = /* @__PURE__ */ new Set(["reduce", "take", "nth", "drop", "append", "without", "get", "indexOf", "group", "join"]);
|
|
677
677
|
|
|
678
678
|
/**
|
|
679
679
|
* This function gives the items of a list that have a value (LIST.LENIENT). A list op does not skip `#DEPTH!`, so that
|
|
@@ -704,10 +704,31 @@ function flat(vs: readonly unknown[], strict: boolean): unknown {
|
|
|
704
704
|
return vexList(out);
|
|
705
705
|
}
|
|
706
706
|
|
|
707
|
+
/**
|
|
708
|
+
* This function gives the groups of `group(list, keys)` (LIST.GROUP). The item at a position has the key at the same
|
|
709
|
+
* position. A pair with an error item or an error key is not in a group.
|
|
710
|
+
*/
|
|
711
|
+
function group(items: readonly ListItem[], keys: unknown, strict: boolean): unknown {
|
|
712
|
+
goodOf(items, strict);
|
|
713
|
+
const list = asList(keys, missing);
|
|
714
|
+
if (list === undefined) return stop("kind-mismatch", `"group" needs a list of keys, not a ${describe(keys)}`);
|
|
715
|
+
goodOf(list.items, strict);
|
|
716
|
+
if (list.items.length !== items.length) return stop("kind-mismatch", '"group" needs one key for each item');
|
|
717
|
+
const groups = new Map<string, ListItem[]>();
|
|
718
|
+
items.forEach((it, i) => {
|
|
719
|
+
const k = (list.items[i] as ListItem).result;
|
|
720
|
+
if (!it.result.ok || !k.ok) return;
|
|
721
|
+
if (typeof k.value !== "string") stop("kind-mismatch", '"group" needs text keys');
|
|
722
|
+
groups.set(k.value as string, [...(groups.get(k.value as string) ?? []), it]);
|
|
723
|
+
});
|
|
724
|
+
return vexList([...groups].map(([key, g]): ListItem => ({ key, result: vexOk(vexList(g)) })));
|
|
725
|
+
}
|
|
726
|
+
|
|
707
727
|
/** This function applies a list op (LIST.*). The error items are skipped, except with `{ strict: true }`, and except `#DEPTH!`. */
|
|
708
728
|
function listOp(op: string, items: readonly ListItem[], rest: readonly unknown[], domains: readonly AnyDomain[]): unknown {
|
|
709
729
|
const o = WITH_ARGUMENT.has(op) ? rest[1] : rest[0];
|
|
710
730
|
const strict = (o as { strict?: unknown } | null | undefined)?.strict === true;
|
|
731
|
+
if (op === "group") return group(items, rest[0], strict);
|
|
711
732
|
const good = goodOf(items, strict);
|
|
712
733
|
const vs = good.map((it) => (it.result.ok ? it.result.value : undefined));
|
|
713
734
|
const nums = (): readonly number[] => (vs.every((x) => typeof x === "number") ? vs : stop("kind-mismatch", `"${op}" needs numbers`));
|
|
@@ -754,6 +775,18 @@ function listOp(op: string, items: readonly ListItem[], rest: readonly unknown[]
|
|
|
754
775
|
const i = good.findIndex((it) => it.key === key);
|
|
755
776
|
return i >= 0 ? vs[i] : stop("missing-field", `the list has no item with the key ${JSON.stringify(key)}`);
|
|
756
777
|
}
|
|
778
|
+
case "distinct": {
|
|
779
|
+
// The first item of each value, by ===, as for indexOf. Thus each NaN stays (LIST.DISTINCT).
|
|
780
|
+
if (!vs.every(isIndexValue)) return stop("kind-mismatch", '"distinct" needs numbers, texts or booleans');
|
|
781
|
+
const keep = vs.map((x, i) => vs.indexOf(x) === i || Number.isNaN(x));
|
|
782
|
+
return vexList(good.filter((_it, i) => keep[i]));
|
|
783
|
+
}
|
|
784
|
+
case "join": {
|
|
785
|
+
// The texts of the items with the text sep between them (LIST.JOIN).
|
|
786
|
+
const sep = rest[0];
|
|
787
|
+
if (typeof sep !== "string") return stop("kind-mismatch", `"join" needs a text separator, not a ${describe(sep)}`);
|
|
788
|
+
return vs.every((x) => typeof x === "string") ? vs.join(sep) : stop("kind-mismatch", '"join" needs texts');
|
|
789
|
+
}
|
|
757
790
|
case "indexOf": {
|
|
758
791
|
// The position of the first value, among the items with a value (LIST.INDEXOF).
|
|
759
792
|
const x = rest[0];
|