@mark1russell7/vex 0.6.0 → 0.8.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/README.md +1 -0
- package/build/index.d.ts +244 -33
- package/build/index.d.ts.map +1 -1
- package/build/index.js +1093 -122
- package/build/index.js.map +1 -1
- package/package.json +1 -1
- package/src/builder.ts +222 -28
- package/src/deps.ts +57 -8
- package/src/domain.ts +22 -0
- package/src/errors.ts +3 -1
- package/src/evaluate.ts +275 -20
- package/src/ir.ts +238 -51
- package/src/json.ts +44 -2
- package/src/list.ts +3 -3
- package/src/sheet.ts +259 -21
- package/src/space.ts +52 -11
package/src/evaluate.ts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { liftsAt, resolveOp, type AnyDomain, type ParamKind, type ResolvedOp } from "./domain.ts";
|
|
2
2
|
import { formatError, isDepthError, isStackOverflow, vexError, type ErrorKind, type VexError } from "./errors.ts";
|
|
3
|
-
import { children, type Axis, type Expr, type ExprOf, type Move } from "./ir.ts";
|
|
3
|
+
import { addrExprs, children, shapeError, type Addr, type Axis, type Expr, type ExprOf, type FixedMove, 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
|
-
import { axisTargets, resolveAddr, type Position, type Space } from "./space.ts";
|
|
6
|
+
import { axisTargets, fixAddr, resolveAddr, type Position, type Space } from "./space.ts";
|
|
7
7
|
import type { Read, Trace, TraceEvent, TraceSink } from "./trace.ts";
|
|
8
8
|
|
|
9
9
|
/** A free function op. The interpreter gives it the values of all arguments. */
|
|
@@ -77,6 +77,19 @@ export interface Program {
|
|
|
77
77
|
* This function compiles an expression. The result gives the same results and the same traces as `evaluate`,
|
|
78
78
|
* because `evaluate` uses it too.
|
|
79
79
|
*/
|
|
80
|
+
/** A bound function (FN.BIND): its parameters, its compiled body and the names of the place of its binding. */
|
|
81
|
+
class Closure {
|
|
82
|
+
readonly params: readonly string[];
|
|
83
|
+
readonly body: Node;
|
|
84
|
+
readonly env: ReadonlyMap<string, Result<unknown>>;
|
|
85
|
+
|
|
86
|
+
constructor(params: readonly string[], body: Node, env: ReadonlyMap<string, Result<unknown>>) {
|
|
87
|
+
this.params = params;
|
|
88
|
+
this.body = body;
|
|
89
|
+
this.env = env;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
80
93
|
/** The deepest nesting of an expression that `compile` accepts (EVAL.NESTING). */
|
|
81
94
|
export const MAX_NESTING = 500;
|
|
82
95
|
|
|
@@ -95,12 +108,12 @@ export function nestingOf(e: Expr): number {
|
|
|
95
108
|
}
|
|
96
109
|
|
|
97
110
|
export function compile(expr: Expr, opts: CompileOptions = {}): Program {
|
|
111
|
+
// EVAL.SHAPE: an expression that is not valid, for example from a newer version of Vex, gives an error before a walk.
|
|
98
112
|
// EVAL.NESTING: a program nested too deep gives an error before the compiler walks it with recursion.
|
|
99
|
-
const
|
|
100
|
-
const
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
: new Compiler(opts).node(expr, []);
|
|
113
|
+
const shape = shapeError(expr);
|
|
114
|
+
const nesting = shape === undefined ? nestingOf(expr) : 0;
|
|
115
|
+
const bad = shape ?? (nesting > MAX_NESTING ? `the expression is nested ${nesting} levels deep, and the limit is ${MAX_NESTING}` : undefined);
|
|
116
|
+
const root: Node = bad === undefined ? new Compiler(opts).node(expr, []) : (f) => fail(vexError("bad-expression", bad, { path: [], origin: f.pos.origin, focus: f.pos.focus }));
|
|
104
117
|
const run = (r: RunOptions): Result<unknown> => {
|
|
105
118
|
const { space, origin } = r;
|
|
106
119
|
if (!space.has(origin)) return fail(vexError("unknown-key", `the space has no key "${origin}"`, { origin, focus: origin }));
|
|
@@ -212,8 +225,17 @@ class Compiler {
|
|
|
212
225
|
return this.#ref(e, info);
|
|
213
226
|
case "var": {
|
|
214
227
|
const name = e.name;
|
|
215
|
-
return (f, c) =>
|
|
228
|
+
return (f, c) => {
|
|
229
|
+
const bound = f.env.get(name);
|
|
230
|
+
// A function is not a value (FN.VALUE).
|
|
231
|
+
if (bound?.ok === true && bound.value instanceof Closure) return this.#emit(c, info, f, this.#err("kind-mismatch", `the name "${name}" is a function, not a value`, f, path));
|
|
232
|
+
return this.#emit(c, info, f, bound ?? this.#err("unbound", `the name "${name}" has no binding`, f, path));
|
|
233
|
+
};
|
|
216
234
|
}
|
|
235
|
+
case "fn":
|
|
236
|
+
return this.#fn(e, path);
|
|
237
|
+
case "call":
|
|
238
|
+
return this.#callFn(e, info);
|
|
217
239
|
case "let": {
|
|
218
240
|
const binds = Object.entries(e.bind).map(([name, be], i): readonly [string, Node] => [name, this.node(be, [...path, i])]);
|
|
219
241
|
const body = this.node(e.body, [...path, binds.length]);
|
|
@@ -240,6 +262,10 @@ class Compiler {
|
|
|
240
262
|
return isSpecialForm(e.op) ? this.#special(e.op, this.#nodes(e.args, path), info) : this.#app(e.op, this.#nodes(e.args, path), info);
|
|
241
263
|
case "each":
|
|
242
264
|
return this.#each(e, info);
|
|
265
|
+
case "fold":
|
|
266
|
+
return this.#fold(e, info);
|
|
267
|
+
case "iterate":
|
|
268
|
+
return this.#iterate(e, info);
|
|
243
269
|
case "ext": {
|
|
244
270
|
const extensions = this.#extensions ?? {};
|
|
245
271
|
const handler = Object.hasOwn(extensions, e.kind) ? extensions[e.kind] : undefined;
|
|
@@ -255,6 +281,35 @@ class Compiler {
|
|
|
255
281
|
return es.map((x, i) => this.node(x, [...path, i]));
|
|
256
282
|
}
|
|
257
283
|
|
|
284
|
+
/**
|
|
285
|
+
* This method compiles a function (FN.BIND). Its value is a closure: the parameters, the body, and the names of the
|
|
286
|
+
* place of its binding. A binding of `let` does not see the other bindings, so a function cannot call itself.
|
|
287
|
+
*/
|
|
288
|
+
#fn(e: ExprOf<"fn">, path: readonly number[]): Node {
|
|
289
|
+
const body = this.node(e.body, [...path, 0]);
|
|
290
|
+
return (f) => ok(new Closure(e.params, body, f.env));
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/**
|
|
294
|
+
* This method compiles a call (FN.CALL, FN.ARGS). Each parameter gets the result of its argument at the call, so an
|
|
295
|
+
* argument that fails has an effect only where the body reads it. The body evaluates at the position of the call.
|
|
296
|
+
*/
|
|
297
|
+
#callFn(e: ExprOf<"call">, info: Info): Node {
|
|
298
|
+
const { path } = info;
|
|
299
|
+
const args = this.#nodes(e.args, path);
|
|
300
|
+
return (f, c) => {
|
|
301
|
+
const bound = f.env.get(e.fn);
|
|
302
|
+
if (bound === undefined) return this.#emit(c, info, f, this.#err("unbound", `the function "${e.fn}" has no binding`, f, path));
|
|
303
|
+
if (!bound.ok) return this.#emit(c, info, f, bound);
|
|
304
|
+
const callee = bound.value;
|
|
305
|
+
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));
|
|
306
|
+
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));
|
|
307
|
+
const env = new Map(callee.env);
|
|
308
|
+
callee.params.forEach((p, i) => env.set(p, (args[i] as Node)(f, c)));
|
|
309
|
+
return this.#emit(c, info, f, callee.body({ pos: f.pos, env }, c));
|
|
310
|
+
};
|
|
311
|
+
}
|
|
312
|
+
|
|
258
313
|
/** This method gives an error of a handler the path, the origin and the focus of its node, if it has no origin. */
|
|
259
314
|
#locate(r: Result<unknown>, f: Frame, path: readonly number[]): Result<unknown> {
|
|
260
315
|
if (r.ok || r.error.origin !== undefined) return r;
|
|
@@ -274,10 +329,32 @@ class Compiler {
|
|
|
274
329
|
return isStackOverflow(thrown) ? this.#err("depth", DEPTH_MESSAGE, f, path, { ...extra, thrown }) : this.#err("threw", message, f, path, { ...extra, thrown });
|
|
275
330
|
}
|
|
276
331
|
|
|
332
|
+
/**
|
|
333
|
+
* This method compiles an address. Its function gives the key where the address points. The expressions of the
|
|
334
|
+
* computed moves evaluate first, at the position of the node, and their child indexes start at `first`. An error of
|
|
335
|
+
* an expression keeps its path, and an error of a move gets the path of the node.
|
|
336
|
+
*/
|
|
337
|
+
#address(at: Addr, path: readonly number[], first: number): (f: Frame, c: Ctx) => Result<string> {
|
|
338
|
+
const nodes = addrExprs(at).map((x, i) => this.node(x, [...path, first + i]));
|
|
339
|
+
const moved = (r: Result<string>): Result<string> => (r.ok ? r : fail({ ...r.error, path }));
|
|
340
|
+
if (nodes.length === 0) return (f, c) => moved(resolveAddr(c.space, f.pos, at as readonly FixedMove[]));
|
|
341
|
+
return (f, c) => {
|
|
342
|
+
const values: unknown[] = [];
|
|
343
|
+
for (const n of nodes) {
|
|
344
|
+
const r = n(f, c);
|
|
345
|
+
if (!r.ok) return r;
|
|
346
|
+
values.push(r.value);
|
|
347
|
+
}
|
|
348
|
+
const fixed = fixAddr(at, values, f.pos);
|
|
349
|
+
return fixed.ok ? moved(resolveAddr(c.space, f.pos, fixed.value)) : moved(fixed);
|
|
350
|
+
};
|
|
351
|
+
}
|
|
352
|
+
|
|
277
353
|
#ref(e: ExprOf<"ref">, info: Info): Node {
|
|
278
354
|
const { path } = info;
|
|
279
355
|
const segs = e.path;
|
|
280
356
|
const at = e.at ?? [];
|
|
357
|
+
const address = this.#address(at, path, 0);
|
|
281
358
|
const label = segs.join(".");
|
|
282
359
|
const steps = segs.map((seg, i) => ({ seg, where: segs.slice(0, i + 1).join("."), valid: isFieldName(seg) }));
|
|
283
360
|
return (f, c) => {
|
|
@@ -285,8 +362,8 @@ class Compiler {
|
|
|
285
362
|
// The empty address resolves to the focus, so this fast path changes no result.
|
|
286
363
|
// Stryker disable next-line ConditionalExpression,EqualityOperator: resolveAddr of [] gives the focus too
|
|
287
364
|
if (at.length > 0) {
|
|
288
|
-
const where =
|
|
289
|
-
if (!where.ok) return this.#emit(c, info, f,
|
|
365
|
+
const where = address(f, c);
|
|
366
|
+
if (!where.ok) return this.#emit(c, info, f, where);
|
|
290
367
|
key = where.value;
|
|
291
368
|
}
|
|
292
369
|
const failed = (r: Result<unknown>): Result<unknown> => this.#emit(c, info, f, r, [{ key, path: segs, ok: false }]);
|
|
@@ -327,15 +404,17 @@ class Compiler {
|
|
|
327
404
|
#each(e: ExprOf<"each">, info: Info): Node {
|
|
328
405
|
const { path } = info;
|
|
329
406
|
const at = e.at ?? [];
|
|
330
|
-
const
|
|
407
|
+
const counter = { next: 1 };
|
|
408
|
+
const targets = this.#targets(e.axis, path, counter);
|
|
331
409
|
const body = this.node(e.body, [...path, 0]);
|
|
410
|
+
const address = this.#address(at, path, counter.next);
|
|
332
411
|
return (f, c) => {
|
|
333
412
|
// An axis with an address finds its targets from the key of the address. The origin does not change.
|
|
334
413
|
let from = f;
|
|
335
414
|
// Stryker disable next-line ConditionalExpression,EqualityOperator: resolveAddr of [] gives the focus too
|
|
336
415
|
if (at.length > 0) {
|
|
337
|
-
const where =
|
|
338
|
-
if (!where.ok) return this.#emit(c, info, f,
|
|
416
|
+
const where = address(f, c);
|
|
417
|
+
if (!where.ok) return this.#emit(c, info, f, where);
|
|
339
418
|
from = { pos: { origin: f.pos.origin, focus: where.value }, env: f.env };
|
|
340
419
|
}
|
|
341
420
|
// The axis table moves the evaluation to the space of its table, where the origin of this space is not a key.
|
|
@@ -357,9 +436,124 @@ class Compiler {
|
|
|
357
436
|
};
|
|
358
437
|
}
|
|
359
438
|
|
|
439
|
+
/**
|
|
440
|
+
* This method compiles the names of a loop: `init` at the indexes from 0, and `step` after them (LOOP.NAMES). Its
|
|
441
|
+
* functions give the first values, and the values after one step. The first error stops each of them.
|
|
442
|
+
*/
|
|
443
|
+
#names(e: ExprOf<"fold"> | ExprOf<"iterate">, path: readonly number[]): {
|
|
444
|
+
readonly first: (f: Frame, c: Ctx) => Result<Map<string, Result<unknown>>>;
|
|
445
|
+
readonly next: (f: Frame, c: Ctx) => Result<Map<string, Result<unknown>>>;
|
|
446
|
+
} {
|
|
447
|
+
const inits = Object.entries(e.init).map(([name, x], i) => [name, this.node(x, [...path, i])] as const);
|
|
448
|
+
const steps = Object.entries(e.step).map(([name, x], i) => [name, this.node(x, [...path, inits.length + i])] as const);
|
|
449
|
+
return {
|
|
450
|
+
first: (f, c) => {
|
|
451
|
+
const env = new Map(f.env);
|
|
452
|
+
for (const [name, n] of inits) {
|
|
453
|
+
const r = n(f, c);
|
|
454
|
+
if (!r.ok) return r;
|
|
455
|
+
env.set(name, r);
|
|
456
|
+
}
|
|
457
|
+
return ok(env);
|
|
458
|
+
},
|
|
459
|
+
// Each value of a step reads the values before the step, so the names change only after all the values.
|
|
460
|
+
next: (f, c) => {
|
|
461
|
+
const values: (readonly [string, Result<unknown>])[] = [];
|
|
462
|
+
for (const [name, n] of steps) {
|
|
463
|
+
const r = n(f, c);
|
|
464
|
+
if (!r.ok) return r;
|
|
465
|
+
values.push([name, r]);
|
|
466
|
+
}
|
|
467
|
+
const env = new Map(f.env);
|
|
468
|
+
for (const [name, r] of values) env.set(name, r);
|
|
469
|
+
return ok(env);
|
|
470
|
+
},
|
|
471
|
+
};
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
/**
|
|
475
|
+
* This method compiles a fold (FOLD.ORDER, FOLD.ERROR). `init` evaluates at the node, then the address and the
|
|
476
|
+
* targets. A step evaluates at each target in order. `result` evaluates at the node with the last values.
|
|
477
|
+
*/
|
|
478
|
+
#fold(e: ExprOf<"fold">, info: Info): Node {
|
|
479
|
+
const { path } = info;
|
|
480
|
+
const at = e.at ?? [];
|
|
481
|
+
const names = this.#names(e, path);
|
|
482
|
+
const counter = { next: Object.keys(e.init).length + Object.keys(e.step).length };
|
|
483
|
+
const targets = this.#targets(e.axis, path, counter);
|
|
484
|
+
const address = this.#address(at, path, counter.next);
|
|
485
|
+
const result = this.node(e.result, [...path, counter.next + addrExprs(at).length]);
|
|
486
|
+
const base = baseAxis(e.axis);
|
|
487
|
+
return (f, c) => {
|
|
488
|
+
const first = names.first(f, c);
|
|
489
|
+
if (!first.ok) return this.#emit(c, info, f, first);
|
|
490
|
+
let env = first.value;
|
|
491
|
+
let from = f;
|
|
492
|
+
// Stryker disable next-line ConditionalExpression,EqualityOperator: resolveAddr of [] gives the focus too
|
|
493
|
+
if (at.length > 0) {
|
|
494
|
+
const where = address(f, c);
|
|
495
|
+
if (!where.ok) return this.#emit(c, info, f, where);
|
|
496
|
+
from = { pos: { origin: f.pos.origin, focus: where.value }, env: f.env };
|
|
497
|
+
}
|
|
498
|
+
let inner = c;
|
|
499
|
+
if (base.t === "table") {
|
|
500
|
+
const space = c.tables !== undefined && Object.hasOwn(c.tables, base.name) ? c.tables[base.name] : undefined;
|
|
501
|
+
if (space === undefined) return this.#emit(c, info, f, this.#err("no-table", `the evaluation has no table "${base.name}"`, f, path));
|
|
502
|
+
inner = { ...c, space };
|
|
503
|
+
}
|
|
504
|
+
const ts = targets(from, inner);
|
|
505
|
+
if (!ts.ok) return this.#emit(c, info, f, ts);
|
|
506
|
+
for (const { key, test } of ts.value) {
|
|
507
|
+
if (test !== undefined && !test.ok) return this.#emit(c, info, f, test);
|
|
508
|
+
const after = names.next({ pos: { origin: base.t === "table" ? key : f.pos.origin, focus: key }, env }, inner);
|
|
509
|
+
if (!after.ok) return this.#emit(c, info, f, after);
|
|
510
|
+
env = after.value;
|
|
511
|
+
}
|
|
512
|
+
return this.#emit(c, info, f, result({ pos: f.pos, env }, c));
|
|
513
|
+
};
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
/**
|
|
517
|
+
* This method compiles an iteration (ITERATE.LIMIT, ITERATE.UNTIL, ITERATE.ERROR). The test `until` evaluates before
|
|
518
|
+
* each step and after the last step. `result` evaluates with the last values.
|
|
519
|
+
*/
|
|
520
|
+
#iterate(e: ExprOf<"iterate">, info: Info): Node {
|
|
521
|
+
const { path } = info;
|
|
522
|
+
const names = this.#names(e, path);
|
|
523
|
+
const untilAt = Object.keys(e.init).length + Object.keys(e.step).length;
|
|
524
|
+
const untilPath = [...path, untilAt];
|
|
525
|
+
const until = e.until === undefined ? undefined : this.node(e.until, untilPath);
|
|
526
|
+
const result = this.node(e.result, [...path, untilAt + (until === undefined ? 0 : 1)]);
|
|
527
|
+
const { limit } = e;
|
|
528
|
+
return (f, c) => {
|
|
529
|
+
const first = names.first(f, c);
|
|
530
|
+
if (!first.ok) return this.#emit(c, info, f, first);
|
|
531
|
+
let env = first.value;
|
|
532
|
+
for (let k = 0; ; k++) {
|
|
533
|
+
const frame: Frame = { pos: f.pos, env };
|
|
534
|
+
if (until !== undefined) {
|
|
535
|
+
const t = until(frame, c);
|
|
536
|
+
if (!t.ok) return this.#emit(c, info, f, t);
|
|
537
|
+
if (t.value === true) break;
|
|
538
|
+
if (t.value !== false) return this.#emit(c, info, f, this.#err("kind-mismatch", `the test "until" of "iterate" gave a ${typeof t.value}, not a boolean`, f, untilPath));
|
|
539
|
+
}
|
|
540
|
+
if (k === limit) {
|
|
541
|
+
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));
|
|
542
|
+
break;
|
|
543
|
+
}
|
|
544
|
+
const after = names.next(frame, c);
|
|
545
|
+
if (!after.ok) return this.#emit(c, info, f, after);
|
|
546
|
+
env = after.value;
|
|
547
|
+
}
|
|
548
|
+
return this.#emit(c, info, f, result({ pos: f.pos, env }, c));
|
|
549
|
+
};
|
|
550
|
+
}
|
|
551
|
+
|
|
360
552
|
/** This method compiles the targets of an axis. For `where`, a failed test keeps the target with its error. */
|
|
361
553
|
#targets(a: Axis, path: readonly number[], counter: { next: number }): (f: Frame, c: Ctx) => Result<readonly { readonly key: string; readonly test?: Result<unknown> }[]> {
|
|
362
554
|
if (a.t === "table") return (_f, c) => ok(c.space.keys.map((key) => ({ key })));
|
|
555
|
+
const base = a.t === "reverse" ? a.axis : a;
|
|
556
|
+
if (base.t === "list") return this.#listTargets(base.list, a.t === "reverse", path, counter);
|
|
363
557
|
if (a.t !== "where") {
|
|
364
558
|
return (f, c) => {
|
|
365
559
|
const keys = axisTargets(c.space, f.pos, a);
|
|
@@ -392,6 +586,21 @@ class Compiler {
|
|
|
392
586
|
};
|
|
393
587
|
}
|
|
394
588
|
|
|
589
|
+
/**
|
|
590
|
+
* This method compiles the targets of the axis list (AXIS.LIST): the keys of the items of a list, in its order. The
|
|
591
|
+
* expression evaluates at the key of the address. An error item keeps its target with its error.
|
|
592
|
+
*/
|
|
593
|
+
#listTargets(list: Expr, reverse: boolean, path: readonly number[], counter: { next: number }): (f: Frame, c: Ctx) => Result<readonly { readonly key: string; readonly test?: Result<unknown> }[]> {
|
|
594
|
+
const node = this.node(list, [...path, counter.next++]);
|
|
595
|
+
return (f, c) => {
|
|
596
|
+
const r = node(f, c);
|
|
597
|
+
if (!r.ok) return r;
|
|
598
|
+
if (!isVexList(r.value)) return this.#err("kind-mismatch", `the axis "list" needs a list, not a ${describeType(r.value)}`, f, path);
|
|
599
|
+
const items = r.value.items.map(({ key, result }) => (result.ok ? { key } : { key, test: result }));
|
|
600
|
+
return ok(reverse ? items.toReversed() : items);
|
|
601
|
+
};
|
|
602
|
+
}
|
|
603
|
+
|
|
395
604
|
#app(op: string, args: readonly Node[], info: Info): Node {
|
|
396
605
|
const { path } = info;
|
|
397
606
|
const listOp = isListOp(op) ? op : undefined;
|
|
@@ -510,7 +719,8 @@ class Compiler {
|
|
|
510
719
|
}
|
|
511
720
|
|
|
512
721
|
#listOp(op: ListOp, list: VexList, rest: readonly unknown[], f: Frame, path: readonly number[]): Result<unknown> {
|
|
513
|
-
|
|
722
|
+
// The options come after the first argument of reduce, take and nth.
|
|
723
|
+
const optsArg = op === "reduce" || op === "take" || op === "nth" ? rest[1] : rest[0];
|
|
514
724
|
// A reduction that skips error items does not skip #DEPTH! (EVAL.DEPTH).
|
|
515
725
|
const depth = list.items.find((it) => !it.result.ok && isDepthError(it.result.error))?.result;
|
|
516
726
|
if (depth !== undefined && !depth.ok) return fail(depth.error);
|
|
@@ -527,7 +737,24 @@ class Compiler {
|
|
|
527
737
|
return bad === undefined ? ok(okValues as readonly boolean[]) : this.#err("kind-mismatch", `"${op}" needs booleans, but an item is a ${describeType(bad)}`, f, path, { op });
|
|
528
738
|
};
|
|
529
739
|
const empty = (): Result<never> => this.#err("empty", `"${op}" has no values to work with`, f, path, { op });
|
|
740
|
+
// A count or a position of take and nth is a whole number from 0.
|
|
741
|
+
const whole = (): Result<number> => {
|
|
742
|
+
const n = rest[0] as number;
|
|
743
|
+
return Number.isSafeInteger(n) && n >= 0 ? ok(n) : this.#err("kind-mismatch", `"${op}" needs a whole number from 0, not ${describeType(n)}`, f, path, { op });
|
|
744
|
+
};
|
|
745
|
+
const okItems = list.items.filter((it) => it.result.ok);
|
|
530
746
|
switch (op) {
|
|
747
|
+
case "sortBy":
|
|
748
|
+
return this.#sortBy(okItems, okValues, f, path);
|
|
749
|
+
case "take": {
|
|
750
|
+
const n = whole();
|
|
751
|
+
return n.ok ? ok(vexList(okItems.slice(0, n.value))) : n;
|
|
752
|
+
}
|
|
753
|
+
case "nth": {
|
|
754
|
+
const i = whole();
|
|
755
|
+
if (!i.ok) return i;
|
|
756
|
+
return i.value < okValues.length ? ok(okValues[i.value]) : this.#err("empty", `"nth" has no item at the position ${String(i.value)}, and the list has ${String(okValues.length)} items`, f, path, { op });
|
|
757
|
+
}
|
|
531
758
|
case "count":
|
|
532
759
|
return ok(okValues.length);
|
|
533
760
|
case "values":
|
|
@@ -568,6 +795,24 @@ class Compiler {
|
|
|
568
795
|
}
|
|
569
796
|
}
|
|
570
797
|
|
|
798
|
+
/**
|
|
799
|
+
* This method sorts the items of a list by their values, from the smallest (LIST.SORT). The sort is stable. The values
|
|
800
|
+
* are all numbers without NaN, or all texts. Texts compare by their UTF-16 code units.
|
|
801
|
+
*/
|
|
802
|
+
#sortBy(items: readonly ListItem[], values: readonly unknown[], f: Frame, path: readonly number[]): Result<VexList> {
|
|
803
|
+
const kind = typeof values[0];
|
|
804
|
+
const bad = values.findIndex((x) => typeof x !== kind || (kind !== "number" && kind !== "string") || Number.isNaN(x));
|
|
805
|
+
if (bad >= 0) return this.#err("kind-mismatch", `"sortBy" needs numbers without NaN or texts, all of one kind, but an item is ${Number.isNaN(values[bad]) ? "NaN" : `a ${describeType(values[bad])}`}`, f, path, { op: "sortBy" });
|
|
806
|
+
const order = values.map((_x, i) => i).toSorted((i, j) => {
|
|
807
|
+
const a = values[i] as number | string;
|
|
808
|
+
const b = values[j] as number | string;
|
|
809
|
+
// The sort of Node reads only a negative result, and the sort of another engine needs the whole comparison.
|
|
810
|
+
// Stryker disable next-line ConditionalExpression,EqualityOperator: see the comment above
|
|
811
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
812
|
+
});
|
|
813
|
+
return ok(vexList(order.map((i) => items[i] as ListItem)));
|
|
814
|
+
}
|
|
815
|
+
|
|
571
816
|
/**
|
|
572
817
|
* This method folds the values with a domain op, from the left. An empty list gives the identity of the op, if one
|
|
573
818
|
* domain has an identity for the op (LIST.EMPTY). The option `domain` names that domain when more domains have one.
|
|
@@ -602,11 +847,12 @@ class Compiler {
|
|
|
602
847
|
}
|
|
603
848
|
|
|
604
849
|
const FORBIDDEN_FIELDS = new Set(["__proto__", "constructor", "prototype"]);
|
|
605
|
-
|
|
850
|
+
/** This function tells if a segment of a path can name a field. A compiler uses the same rule as the interpreter. */
|
|
851
|
+
export const isFieldName = (seg: string): boolean => seg.length > 0 && !FORBIDDEN_FIELDS.has(seg);
|
|
606
852
|
|
|
607
853
|
/** This function runs the `is` test of a domain. A test that throws counts as `false`. */
|
|
608
854
|
// Stryker disable BlockStatement: an empty catch gives undefined, which also counts as false
|
|
609
|
-
function safeIs(d: AnyDomain, value: unknown): boolean {
|
|
855
|
+
export function safeIs(d: AnyDomain, value: unknown): boolean {
|
|
610
856
|
try {
|
|
611
857
|
return d.is(value);
|
|
612
858
|
} catch {
|
|
@@ -616,7 +862,8 @@ function safeIs(d: AnyDomain, value: unknown): boolean {
|
|
|
616
862
|
// Stryker restore BlockStatement
|
|
617
863
|
|
|
618
864
|
|
|
619
|
-
function
|
|
865
|
+
/** This function tells if an argument has the kind of a parameter of an op of the domain `domain`. */
|
|
866
|
+
export function matchesKind(kind: ParamKind, value: unknown, domain: AnyDomain): boolean {
|
|
620
867
|
switch (kind) {
|
|
621
868
|
case "domain":
|
|
622
869
|
return safeIs(domain, value);
|
|
@@ -654,12 +901,20 @@ export function labelOf(e: Expr): string {
|
|
|
654
901
|
return e.op;
|
|
655
902
|
case "let":
|
|
656
903
|
return `let ${Object.keys(e.bind).join(", ")}`;
|
|
904
|
+
// A function makes no event of the trace, so its label only completes the switch.
|
|
905
|
+
// Stryker disable next-line all: see the comment above
|
|
906
|
+
case "fn": return `fn (${e.params.join(", ")})`;
|
|
907
|
+
case "call":
|
|
908
|
+
return `call ${e.fn}`;
|
|
657
909
|
case "var":
|
|
658
910
|
return e.name;
|
|
659
911
|
case "rec":
|
|
660
912
|
return `{ ${Object.keys(e.fields).join(", ")} }`;
|
|
661
913
|
case "each":
|
|
662
|
-
|
|
914
|
+
case "fold":
|
|
915
|
+
return e.at === undefined ? `${e.tag} ${e.axis.t}` : `${e.tag} ${e.axis.t} from ${e.at.map(moveText).join(".")}`;
|
|
916
|
+
case "iterate":
|
|
917
|
+
return `iterate ${String(e.limit)}`;
|
|
663
918
|
case "ext":
|
|
664
919
|
return e.kind;
|
|
665
920
|
}
|
|
@@ -669,9 +924,9 @@ export function labelOf(e: Expr): string {
|
|
|
669
924
|
function moveText(m: Move): string {
|
|
670
925
|
switch (m.t) {
|
|
671
926
|
case "key":
|
|
672
|
-
return `key(${m.key})`;
|
|
927
|
+
return `key(${typeof m.key === "string" ? m.key : labelOf(m.key)})`;
|
|
673
928
|
case "index":
|
|
674
|
-
return `index(${m.i})`;
|
|
929
|
+
return `index(${typeof m.i === "number" ? String(m.i) : labelOf(m.i)})`;
|
|
675
930
|
case "offset":
|
|
676
931
|
return `offset(${m.d.join(", ")})`;
|
|
677
932
|
case "other":
|