@mark1russell7/vex 0.17.2 → 0.19.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 +6 -0
- package/build/index.d.ts +529 -125
- package/build/index.d.ts.map +1 -1
- package/build/index.js +2573 -374
- package/build/index.js.map +1 -1
- package/package.json +5 -4
- package/src/builder.ts +75 -16
- package/src/constructs.ts +31 -0
- package/src/deps.ts +7 -1
- package/src/document.ts +18 -4
- package/src/domain.ts +128 -5
- package/src/error-text.ts +114 -0
- package/src/evaluate.ts +272 -87
- package/src/fix.ts +46 -0
- package/src/index.ts +6 -0
- package/src/ir.ts +64 -6
- package/src/json.ts +10 -1
- package/src/kernel.ts +126 -10
- package/src/limit-error.ts +14 -0
- package/src/list.ts +48 -2
- package/src/monotone.ts +259 -0
- package/src/plan.ts +11 -5
- package/src/sheet.ts +30 -19
- package/src/size.ts +1104 -0
- package/src/steps.ts +83 -0
- package/src/trace.ts +2 -0
- package/src/write.ts +18 -7
package/src/fix.ts
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* These are the rules of a fixed-point column that the closure compiler and the kernel share (FIX.ROUNDS, FIX.JOIN,
|
|
3
|
+
* FIX.LIMIT). They are the limit of the rounds, the kinds of the values of a row and the join of a row. The package
|
|
4
|
+
* index exports the rules that the compiler needs too (COMPILE.FIX).
|
|
5
|
+
*/
|
|
6
|
+
import { errorText, type ErrorText } from "./error-text.ts";
|
|
7
|
+
import { MAX_ITERATIONS, type FixJoin } from "./ir.ts";
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* This function gives the largest number of rounds of a column of `rows` rows. A boolean column changes at least one row
|
|
11
|
+
* in each round before the last, and a row changes one time. A path has fewer rows than the column, so a number
|
|
12
|
+
* column stops in this bound when its steps follow paths (FIX.LIMIT).
|
|
13
|
+
*/
|
|
14
|
+
export const fixRounds = (rows: number): number => Math.min(rows + 1, MAX_ITERATIONS);
|
|
15
|
+
|
|
16
|
+
/** This function gives the kind of the values of a join. */
|
|
17
|
+
export const joinKind = (join: FixJoin): "boolean" | "number" => (join === "or" || join === "and" ? "boolean" : "number");
|
|
18
|
+
|
|
19
|
+
/** This function gives the reason that a value cannot be a value of a row, or `undefined` for a good value (FIX.KIND). */
|
|
20
|
+
export function fixValueError(name: string, join: FixJoin, value: unknown): ErrorText | undefined {
|
|
21
|
+
const kind = joinKind(join);
|
|
22
|
+
if (typeof value !== kind) return errorText.fixKind(name, join, kind, value);
|
|
23
|
+
return kind === "boolean" || Number.isFinite(value) ? undefined : errorText.fixNumber(name, value);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* This function gives the error that stands for the failed rows of a round, or `undefined` when `#ARGS` must collect them
|
|
28
|
+
* (FIX.ERROR). `#DEPTH!` wins. `#CYCLE!` comes next, so a cell on a cycle reports the cycle (SHEET.CYCLE).
|
|
29
|
+
*/
|
|
30
|
+
export function worstRow<E extends { readonly code: string }>(errors: readonly E[]): E | undefined {
|
|
31
|
+
return errors.find((x) => x.code === "#DEPTH!") ?? errors.find((x) => x.code === "#CYCLE!") ?? (errors.length === 1 ? errors[0] : undefined);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** This function joins the next value of a row to its old value (FIX.JOIN). The values have the kind of the join. */
|
|
35
|
+
export function joinValues(join: FixJoin, old: unknown, next: unknown): unknown {
|
|
36
|
+
switch (join) {
|
|
37
|
+
case "or":
|
|
38
|
+
return old === true || next === true;
|
|
39
|
+
case "and":
|
|
40
|
+
return old === true && next === true;
|
|
41
|
+
case "max":
|
|
42
|
+
return Math.max(old as number, next as number);
|
|
43
|
+
case "min":
|
|
44
|
+
return Math.min(old as number, next as number);
|
|
45
|
+
}
|
|
46
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -4,10 +4,12 @@
|
|
|
4
4
|
*/
|
|
5
5
|
export * from "./result.ts";
|
|
6
6
|
export * from "./errors.ts";
|
|
7
|
+
export * from "./error-text.ts";
|
|
7
8
|
export * from "./ir.ts";
|
|
8
9
|
export * from "./space.ts";
|
|
9
10
|
export * from "./domain.ts";
|
|
10
11
|
export * from "./list.ts";
|
|
12
|
+
export { asList } from "./array-list.ts";
|
|
11
13
|
export * from "./trace.ts";
|
|
12
14
|
export * from "./evaluate.ts";
|
|
13
15
|
export * from "./deps.ts";
|
|
@@ -18,3 +20,7 @@ export * from "./plan.ts";
|
|
|
18
20
|
export * from "./traversal.ts";
|
|
19
21
|
export * from "./sheet.ts";
|
|
20
22
|
export * from "./builder.ts";
|
|
23
|
+
export { monotoneError, type MonotoneOptions } from "./monotone.ts";
|
|
24
|
+
export { fixRounds, fixValueError, joinKind, worstRow } from "./fix.ts";
|
|
25
|
+
export * from "./size.ts";
|
|
26
|
+
export * from "./steps.ts";
|
package/src/ir.ts
CHANGED
|
@@ -52,7 +52,9 @@ export type Expr =
|
|
|
52
52
|
| { readonly tag: "rec"; readonly fields: Readonly<Record<string, Expr>> }
|
|
53
53
|
| { readonly tag: "each"; readonly axis: Axis; readonly body: Expr; readonly at?: Addr; readonly as?: ItemNames }
|
|
54
54
|
| { readonly tag: "fold"; readonly axis: Axis; readonly init: Names; readonly step: Names; readonly result: Expr; readonly at?: Addr; readonly as?: ItemNames }
|
|
55
|
-
| { readonly tag: "iterate"; readonly limit: number; readonly init: Names; readonly step: Names; readonly until?: Expr; readonly result: Expr }
|
|
55
|
+
| { readonly tag: "iterate"; readonly limit: number | DataLimit; readonly init: Names; readonly step: Names; readonly until?: Expr; readonly result: Expr }
|
|
56
|
+
| { readonly tag: "fix"; readonly name: string; readonly join: FixJoin; readonly init: Expr; readonly step: Expr }
|
|
57
|
+
| { readonly tag: "last"; readonly name: string }
|
|
56
58
|
| { readonly tag: "fn"; readonly params: readonly string[]; readonly body: Expr }
|
|
57
59
|
| { readonly tag: "call"; readonly fn: string; readonly args: readonly Expr[] }
|
|
58
60
|
| { readonly tag: "ext"; readonly kind: string; readonly data: unknown };
|
|
@@ -66,9 +68,20 @@ export type Names = Readonly<Record<string, Expr>>;
|
|
|
66
68
|
*/
|
|
67
69
|
export type ItemNames = readonly [item: string] | readonly [item: string, index: string];
|
|
68
70
|
|
|
71
|
+
/** The joins of `fix`. The join `or` or `max` moves a row up, and `and` or `min` moves a row down (FIX.JOIN). */
|
|
72
|
+
export type FixJoin = "or" | "and" | "max" | "min";
|
|
73
|
+
|
|
69
74
|
/** The largest number of steps of `iterate` (ITERATE.LIMIT). */
|
|
70
75
|
export const MAX_ITERATIONS = 100_000;
|
|
71
76
|
|
|
77
|
+
/**
|
|
78
|
+
* The limit of `iterate` from the size of the data (ITERATE.LIMIT.DATA): the number of targets of an axis. This is the
|
|
79
|
+
* number of steps that a `fold` over the axis makes. The axis `list` gives the count of a list. This limit needs step B.
|
|
80
|
+
*/
|
|
81
|
+
export interface DataLimit {
|
|
82
|
+
readonly axis: Axis;
|
|
83
|
+
}
|
|
84
|
+
|
|
72
85
|
/** The tag of an expression kind. */
|
|
73
86
|
export type ExprTag = Expr["tag"];
|
|
74
87
|
|
|
@@ -127,10 +140,38 @@ export function fold(axis: Axis, init: Names, step: Names, result: Expr, at?: Ad
|
|
|
127
140
|
* This function makes an iteration: up to `limit` steps. `init` gives the names and their first values, and `step`
|
|
128
141
|
* gives the next values. A true `until` stops it, and `result` gives the value (ITERATE.LIMIT, ITERATE.UNTIL).
|
|
129
142
|
*/
|
|
130
|
-
export function iterate(limit: number, init: Names, step: Names, result: Expr, until?: Expr): ExprOf<"iterate"> {
|
|
143
|
+
export function iterate(limit: number | DataLimit, init: Names, step: Names, result: Expr, until?: Expr): ExprOf<"iterate"> {
|
|
131
144
|
return until === undefined ? { tag: "iterate", limit, init, step, result } : { tag: "iterate", limit, init, step, until, result };
|
|
132
145
|
}
|
|
133
146
|
|
|
147
|
+
/**
|
|
148
|
+
* This function makes a fixed-point column (FIX.ROUNDS). `init` gives the first value of each row. `step` gives the next
|
|
149
|
+
* value of each row, and it reads the last round with `last`. `join` joins each next value to the old value of its row.
|
|
150
|
+
*/
|
|
151
|
+
export function fix(name: string, join: FixJoin, init: Expr, step: Expr): ExprOf<"fix"> {
|
|
152
|
+
return { tag: "fix", name, join, init, step };
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** This function makes a read of the value of the focus in the last round of the `fix` with the name `name` (FIX.LAST). */
|
|
156
|
+
export function last(name: string): ExprOf<"last"> {
|
|
157
|
+
return { tag: "last", name };
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** This function makes the limit of `iterate` from the size of the data: the number of targets of an axis (ITERATE.LIMIT.DATA). */
|
|
161
|
+
export const dataLimit = (axis: Axis): DataLimit => ({ axis });
|
|
162
|
+
|
|
163
|
+
/** This function gives the axis of the data limit of an iteration, or `undefined` for a limit that is a number. */
|
|
164
|
+
export const limitAxis = (e: ExprOf<"iterate">): Axis | undefined => (typeof e.limit === "number" ? undefined : e.limit.axis);
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* This function gives the parts of an iteration with a data limit, for a walk that tells the axes apart. The parts are
|
|
168
|
+
* an `each` over the axis, and the iteration without its axis. An iteration with a number has `undefined`.
|
|
169
|
+
*/
|
|
170
|
+
export function splitLimit(e: ExprOf<"iterate">): readonly [ExprOf<"each">, ExprOf<"iterate">] | undefined {
|
|
171
|
+
const axis = limitAxis(e);
|
|
172
|
+
return axis === undefined ? undefined : [each(axis, lit(0)), { ...e, limit: 0 }];
|
|
173
|
+
}
|
|
174
|
+
|
|
134
175
|
/**
|
|
135
176
|
* This function makes a function (FN.BIND): the names of its parameters and its body. A function is only the value of
|
|
136
177
|
* a binding of `let`. The body sees the names of the place of that `let`, so a function cannot call itself.
|
|
@@ -276,7 +317,10 @@ export function isExpr(u: unknown): u is Expr {
|
|
|
276
317
|
}
|
|
277
318
|
|
|
278
319
|
/** The tags of the expressions of this version of Vex. */
|
|
279
|
-
const TAGS: ReadonlySet<unknown> = new Set(["lit", "ref", "app", "let", "var", "rec", "each", "fold", "iterate", "fn", "call", "ext"]);
|
|
320
|
+
const TAGS: ReadonlySet<unknown> = new Set(["lit", "ref", "app", "let", "var", "rec", "each", "fold", "iterate", "fix", "last", "fn", "call", "ext"]);
|
|
321
|
+
|
|
322
|
+
/** The joins of `fix`. */
|
|
323
|
+
const JOINS: ReadonlySet<unknown> = new Set<FixJoin>(["or", "and", "max", "min"]);
|
|
280
324
|
|
|
281
325
|
/**
|
|
282
326
|
* This function gives the reason that a value is not a valid expression, or `undefined` for a valid expression
|
|
@@ -406,10 +450,19 @@ function badPart(todo: { readonly axis: boolean; readonly u: unknown }[], whole:
|
|
|
406
450
|
case "iterate": {
|
|
407
451
|
const limit = u["limit"];
|
|
408
452
|
const names = loopParts(u);
|
|
409
|
-
if (
|
|
453
|
+
if (names === undefined) return item;
|
|
454
|
+
if (isObject(limit)) push(true, [limit["axis"]]);
|
|
455
|
+
else if (typeof limit !== "number" || !Number.isInteger(limit) || limit < 0 || limit > MAX_ITERATIONS) return item;
|
|
410
456
|
push(false, [...names, ...(u["until"] === undefined ? [] : [u["until"]])]);
|
|
411
457
|
break;
|
|
412
458
|
}
|
|
459
|
+
case "fix":
|
|
460
|
+
if (typeof u["name"] !== "string" || !JOINS.has(u["join"])) return item;
|
|
461
|
+
push(false, [u["init"], u["step"]]);
|
|
462
|
+
break;
|
|
463
|
+
case "last":
|
|
464
|
+
if (typeof u["name"] !== "string") return item;
|
|
465
|
+
break;
|
|
413
466
|
case "ext":
|
|
414
467
|
if (typeof u["kind"] !== "string" || !("data" in u)) return item;
|
|
415
468
|
break;
|
|
@@ -439,12 +492,17 @@ export function children(e: Expr): readonly Expr[] {
|
|
|
439
492
|
return [e.body, ...axisExprs(e.axis), ...addrExprs(e.at)];
|
|
440
493
|
case "fold":
|
|
441
494
|
return [...Object.values(e.init), ...Object.values(e.step), ...axisExprs(e.axis), ...addrExprs(e.at), e.result];
|
|
442
|
-
case "iterate":
|
|
443
|
-
|
|
495
|
+
case "iterate": {
|
|
496
|
+
const axis = limitAxis(e);
|
|
497
|
+
return [...Object.values(e.init), ...Object.values(e.step), ...(axis === undefined ? [] : axisExprs(axis)), ...(e.until === undefined ? [] : [e.until]), e.result];
|
|
498
|
+
}
|
|
499
|
+
case "fix":
|
|
500
|
+
return [e.init, e.step];
|
|
444
501
|
case "ref":
|
|
445
502
|
return addrExprs(e.at);
|
|
446
503
|
case "lit":
|
|
447
504
|
case "var":
|
|
505
|
+
case "last":
|
|
448
506
|
case "ext":
|
|
449
507
|
return [];
|
|
450
508
|
}
|
package/src/json.ts
CHANGED
|
@@ -97,8 +97,17 @@ function mapValues(u: unknown, f: (value: unknown) => Result<unknown>): Result<u
|
|
|
97
97
|
out["axis"] = a.value;
|
|
98
98
|
return each("init") ?? each("step") ?? child("result") ?? address() ?? ok(out);
|
|
99
99
|
}
|
|
100
|
-
case "iterate":
|
|
100
|
+
case "iterate": {
|
|
101
|
+
const limit = u["limit"];
|
|
102
|
+
if (isRecord(limit)) {
|
|
103
|
+
const a = axis(limit["axis"]);
|
|
104
|
+
if (!a.ok) return a;
|
|
105
|
+
out["limit"] = { ...limit, axis: a.value };
|
|
106
|
+
}
|
|
101
107
|
return each("init") ?? each("step") ?? (u["until"] === undefined ? undefined : child("until")) ?? child("result") ?? ok(out);
|
|
108
|
+
}
|
|
109
|
+
case "fix":
|
|
110
|
+
return child("init") ?? child("step") ?? ok(out);
|
|
102
111
|
case "fn":
|
|
103
112
|
return child("body") ?? ok(out);
|
|
104
113
|
case "call":
|
package/src/kernel.ts
CHANGED
|
@@ -38,8 +38,11 @@ import { asList, fillList, isFillCount, isIndexValue, listOfArray } from "./arra
|
|
|
38
38
|
import { decodeValue } from "./codec.ts";
|
|
39
39
|
import type { AnyDomain } from "./domain.ts";
|
|
40
40
|
import { vexError, type ErrorCode, type ErrorDetails, type ErrorKind, type VexError } from "./errors.ts";
|
|
41
|
+
import { limitError, overLimitMessage, worstError } from "./limit-error.ts";
|
|
41
42
|
import type { CompileOptions } from "./evaluate.ts";
|
|
42
|
-
import {
|
|
43
|
+
import { errorText } from "./error-text.ts";
|
|
44
|
+
import { fixRounds, fixValueError, joinValues, worstRow } from "./fix.ts";
|
|
45
|
+
import { MAX_ITERATIONS, type Axis, type FixJoin, type FixedMove } from "./ir.ts";
|
|
43
46
|
import { isVexList, LIST_OPS, vexList, type ListItem } from "./list.ts";
|
|
44
47
|
import { fail as vexFail, ok as vexOk, type Result } from "./result.ts";
|
|
45
48
|
import { isVexError } from "./same.ts";
|
|
@@ -48,7 +51,7 @@ import { applyMove, axisTargets, type Space } from "./space.ts";
|
|
|
48
51
|
// ---------------------------------------------------------------- the contracts
|
|
49
52
|
|
|
50
53
|
/** The kinds of the terms of Vex. A part in the position of a term has one of these kinds (DOC.TERM). */
|
|
51
|
-
export const TERM_KINDS: readonly (readonly string[])[] = [["lit"], ["ref"], ["record"], ["let"], ["call"], ["each"], ["fold"], ["iterate"], ["ops"], ["ext"]];
|
|
54
|
+
export const TERM_KINDS: readonly (readonly string[])[] = [["lit"], ["ref"], ["record"], ["let"], ["call"], ["each"], ["fold"], ["iterate"], ["fix"], ["last"], ["ops"], ["ext"]];
|
|
52
55
|
|
|
53
56
|
/** A term: an envelope of a term kind, or a bare value, which is a literal. */
|
|
54
57
|
const TERM: PartShape = { shape: "term", of: "lit", kinds: TERM_KINDS };
|
|
@@ -58,6 +61,8 @@ const AXIS: PartShape = { shape: "term", kinds: [["axes"]] };
|
|
|
58
61
|
/** The address of `each` and `fold`: a reference that gives a key of the space, not a value (DOC.ADDRESS). */
|
|
59
62
|
const ADDRESS: PartShape = { shape: "term", kinds: [["ref"]], address: true };
|
|
60
63
|
const NO_VALUE: PartShape = { shape: "one", values: [null] };
|
|
64
|
+
/** The limit of `iterate`: a bare whole number, or the size of an axis (ITERATE.LIMIT.DATA). */
|
|
65
|
+
const LIMIT: PartShape = { shape: "term", of: "limit", kinds: [["limit"], ["size"]] };
|
|
61
66
|
|
|
62
67
|
/** This function gives the shape of a record with these fields and no other fields (DOC.CONSTRUCT). */
|
|
63
68
|
const closed = (fields: Readonly<Record<string, PartShape>>, required: readonly string[]): PartShape => ({ shape: "record", fields, required, closed: true });
|
|
@@ -119,10 +124,30 @@ function worldOfVex(): World {
|
|
|
119
124
|
},
|
|
120
125
|
iterate: {
|
|
121
126
|
verbs: { eval: "vex.iterate" },
|
|
122
|
-
parts: closed({ limit:
|
|
127
|
+
parts: closed({ limit: LIMIT, init: NAMES, step: NAMES, until: TERM, result: TERM }, ["limit", "init", "step", "result"]),
|
|
123
128
|
scope: LOOP_SCOPE,
|
|
124
129
|
summary: "Up to limit steps, until a test is true, and a result.",
|
|
125
130
|
},
|
|
131
|
+
fix: {
|
|
132
|
+
verbs: { eval: "vex.fix" },
|
|
133
|
+
parts: closed({ name: { shape: "text" }, join: { shape: "one", values: ["or", "and", "max", "min"] }, init: TERM, step: TERM }, ["name", "join", "init", "step"]),
|
|
134
|
+
summary: "A column: a step at each row in rounds, until no row changes (step B).",
|
|
135
|
+
},
|
|
136
|
+
last: {
|
|
137
|
+
verbs: { eval: "vex.last" },
|
|
138
|
+
parts: { shape: "text" },
|
|
139
|
+
summary: "The value of the focus in the last round of a fix (step B).",
|
|
140
|
+
},
|
|
141
|
+
limit: {
|
|
142
|
+
verbs: { eval: "vex.limit" },
|
|
143
|
+
parts: { shape: "number", whole: true, min: 0, max: MAX_ITERATIONS },
|
|
144
|
+
summary: "The limit of iterate as a whole number: the bare number of step A.",
|
|
145
|
+
},
|
|
146
|
+
size: {
|
|
147
|
+
verbs: { eval: "vex.size" },
|
|
148
|
+
parts: closed({ axis: AXIS }, ["axis"]),
|
|
149
|
+
summary: "The limit of iterate from the data: the number of targets of an axis (step B).",
|
|
150
|
+
},
|
|
126
151
|
ops: { kinds: {}, fallback: { verbs: { eval: "formula.op" }, parts: TERMS, summary: "An op, applied to the values of its arguments." } },
|
|
127
152
|
ext: { kinds: {}, fallback: { verbs: { eval: "formula.ext" }, summary: "An extension: its handler gives the value of its data." } },
|
|
128
153
|
axes: {
|
|
@@ -223,14 +248,17 @@ class Place implements HostThing {
|
|
|
223
248
|
readonly origin: string;
|
|
224
249
|
readonly focus: string;
|
|
225
250
|
readonly failure: EvalError | undefined;
|
|
251
|
+
/** The columns of the `fix` nodes around this position, by name (FIX.LAST). A column is no name of the program. */
|
|
252
|
+
readonly columns: ReadonlyMap<string, ReadonlyMap<string, unknown>> | undefined;
|
|
226
253
|
|
|
227
|
-
constructor(space: Space, tables: Readonly<Record<string, Space>>, origin: string, focus: string, failure?: EvalError) {
|
|
254
|
+
constructor(space: Space, tables: Readonly<Record<string, Space>>, origin: string, focus: string, failure?: EvalError, columns?: ReadonlyMap<string, ReadonlyMap<string, unknown>>) {
|
|
228
255
|
(this as { [THING]: true })[THING] = true;
|
|
229
256
|
this.space = space;
|
|
230
257
|
this.tables = tables;
|
|
231
258
|
this.origin = origin;
|
|
232
259
|
this.focus = focus;
|
|
233
260
|
this.failure = failure;
|
|
261
|
+
this.columns = columns;
|
|
234
262
|
}
|
|
235
263
|
|
|
236
264
|
/** The text of the position for a trace. */
|
|
@@ -240,12 +268,17 @@ class Place implements HostThing {
|
|
|
240
268
|
|
|
241
269
|
/** This method gives the position of a key of the same space, with the same origin. */
|
|
242
270
|
to(focus: string): Place {
|
|
243
|
-
return new Place(this.space, this.tables, this.origin, focus);
|
|
271
|
+
return new Place(this.space, this.tables, this.origin, focus, undefined, this.columns);
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/** This method gives this position with a new column of a `fix`. */
|
|
275
|
+
withColumn(name: string, column: ReadonlyMap<string, unknown>): Place {
|
|
276
|
+
return new Place(this.space, this.tables, this.origin, this.focus, undefined, new Map(this.columns).set(name, column));
|
|
244
277
|
}
|
|
245
278
|
|
|
246
279
|
/** This method gives the position with a failure, for a move that failed. */
|
|
247
280
|
failed(failure: EvalError): Place {
|
|
248
|
-
return new Place(this.space, this.tables, this.origin, this.focus, failure);
|
|
281
|
+
return new Place(this.space, this.tables, this.origin, this.focus, failure, this.columns);
|
|
249
282
|
}
|
|
250
283
|
|
|
251
284
|
/** This method reads one field of the record at the focus. */
|
|
@@ -495,7 +528,32 @@ function withItem(names: Readonly<Record<string, unknown>>, as: readonly string[
|
|
|
495
528
|
/** This function gives the names `as` of a loop, or `undefined` (AXIS.LIST.SCOPE). */
|
|
496
529
|
const itemNamesOf = (value: unknown): readonly string[] | undefined => (value as { readonly as?: readonly string[] }).as;
|
|
497
530
|
|
|
498
|
-
/**
|
|
531
|
+
/**
|
|
532
|
+
* This function evaluates a part at each row of a column. Each row runs, also after an error (FIX.ERROR).
|
|
533
|
+
*/
|
|
534
|
+
function rowsOf(part: Part, at: Place, context: Context, name: string, join: FixJoin): Outcome<ReadonlyMap<string, unknown>> {
|
|
535
|
+
const out = new Map<string, unknown>();
|
|
536
|
+
const errors: EvalError[] = [];
|
|
537
|
+
for (const key of at.space.keys) {
|
|
538
|
+
const r = part.evaluate({ ...context, self: at.to(key) });
|
|
539
|
+
const wrong = r.ok ? fixValueError(name, join, r.value) : undefined;
|
|
540
|
+
if (!r.ok) errors.push(r.error);
|
|
541
|
+
else if (wrong !== undefined) errors.push(kernelError(wrong.kind, wrong.message));
|
|
542
|
+
else out.set(key, r.value);
|
|
543
|
+
}
|
|
544
|
+
if (errors.length === 0) return ok(out);
|
|
545
|
+
return { ok: false, error: worstRow(errors) ?? kernelError("args", `${String(errors.length)} rows failed`, { causes: errors.map(toVexError) }) };
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
/** This function gives the value of the row of the focus. The focus of an item of the axis `list` can be no row (FIX.LAST). */
|
|
549
|
+
function rowAt(name: string, column: ReadonlyMap<string, unknown> | undefined, at: Place): Outcome {
|
|
550
|
+
const value = column?.get(at.focus);
|
|
551
|
+
if (value !== undefined) return ok(value);
|
|
552
|
+
const { kind, message } = errorText.lastKey(name, at.focus);
|
|
553
|
+
return failed(kind, message);
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
/** The evaluators of the loops: each, fold, iterate and fix (LOOP.NAMES, FOLD.ORDER, ITERATE.LIMIT, FIX.ROUNDS). */
|
|
499
557
|
const LOOPS: Readonly<Record<string, EvalFn>> = {
|
|
500
558
|
"vex.each": ({ value, context }) => {
|
|
501
559
|
const found = targetsOf(value, context);
|
|
@@ -530,12 +588,27 @@ const LOOPS: Readonly<Record<string, EvalFn>> = {
|
|
|
530
588
|
return partAt(value, "result").evaluate({ ...context, names });
|
|
531
589
|
},
|
|
532
590
|
|
|
591
|
+
"vex.limit": ({ value }) => ok(value),
|
|
592
|
+
|
|
593
|
+
// ITERATE.LIMIT.ERROR: each failure of the size of an axis is one error. Only an error of the run stays as it is.
|
|
594
|
+
"vex.size": ({ value, context }) => {
|
|
595
|
+
const found = targetsOf(value, context);
|
|
596
|
+
if (!found.ok) return { ok: false, error: toKernelError(limitError(toVexError(found.error))) };
|
|
597
|
+
const { targets } = found.value;
|
|
598
|
+
const cause = worstError(targets.flatMap((t) => t.error ?? []));
|
|
599
|
+
if (cause !== undefined) return { ok: false, error: toKernelError(limitError(cause)) };
|
|
600
|
+
return targets.length > MAX_ITERATIONS ? failed("limit", overLimitMessage(targets.length)) : ok(targets.length);
|
|
601
|
+
},
|
|
602
|
+
|
|
533
603
|
"vex.iterate": ({ value, context }) => {
|
|
534
|
-
const { init, step, until } = partsOf(value);
|
|
535
|
-
const limit = (value as { readonly limit: number }).limit;
|
|
604
|
+
const { init, limit: bound, step, until } = partsOf(value);
|
|
536
605
|
const first = bindAll(init, context, context.names);
|
|
537
606
|
if (!first.ok) return first;
|
|
538
607
|
let names = first.value;
|
|
608
|
+
// The limit evaluates at the node, after the first values and before the steps (ITERATE.LIMIT.DATA).
|
|
609
|
+
const counted = (bound as Part).evaluate(context);
|
|
610
|
+
if (!counted.ok) return counted;
|
|
611
|
+
const limit = counted.value as number;
|
|
539
612
|
for (let k = 0; ; k++) {
|
|
540
613
|
const here: Context = { ...context, names };
|
|
541
614
|
if (until !== undefined) {
|
|
@@ -554,6 +627,39 @@ const LOOPS: Readonly<Record<string, EvalFn>> = {
|
|
|
554
627
|
}
|
|
555
628
|
return partAt(value, "result").evaluate({ ...context, names });
|
|
556
629
|
},
|
|
630
|
+
|
|
631
|
+
"vex.fix": ({ value, context }) => {
|
|
632
|
+
const self = selfOf(context);
|
|
633
|
+
if (!(self instanceof Place)) return { ok: false, error: self };
|
|
634
|
+
const { name, join } = value as { readonly name: string; readonly join: FixJoin };
|
|
635
|
+
const first = rowsOf(partAt(value, "init"), self, context, name, join);
|
|
636
|
+
if (!first.ok) return first;
|
|
637
|
+
let column = first.value;
|
|
638
|
+
const { keys } = self.space;
|
|
639
|
+
const limit = fixRounds(keys.length);
|
|
640
|
+
for (let round = 1; round <= limit; round++) {
|
|
641
|
+
const stepped = rowsOf(partAt(value, "step"), self.withColumn(name, column), context, name, join);
|
|
642
|
+
if (!stepped.ok) return stepped;
|
|
643
|
+
const next = new Map<string, unknown>();
|
|
644
|
+
let changed = false;
|
|
645
|
+
for (const key of keys) {
|
|
646
|
+
const joined = joinValues(join, column.get(key), stepped.value.get(key));
|
|
647
|
+
changed ||= joined !== column.get(key);
|
|
648
|
+
next.set(key, joined);
|
|
649
|
+
}
|
|
650
|
+
if (!changed) return rowAt(name, column, self);
|
|
651
|
+
column = next;
|
|
652
|
+
}
|
|
653
|
+
const { kind, message } = errorText.fixLimit(name, limit);
|
|
654
|
+
return failed(kind, message);
|
|
655
|
+
},
|
|
656
|
+
|
|
657
|
+
"vex.last": ({ value, context }) => {
|
|
658
|
+
const self = selfOf(context);
|
|
659
|
+
if (!(self instanceof Place)) return { ok: false, error: self };
|
|
660
|
+
const name = value as string;
|
|
661
|
+
return rowAt(name, self.columns?.get(name), self);
|
|
662
|
+
},
|
|
557
663
|
};
|
|
558
664
|
|
|
559
665
|
// ---------------------------------------------------------------- functions
|
|
@@ -726,7 +832,7 @@ function group(items: readonly ListItem[], keys: unknown, strict: boolean): unkn
|
|
|
726
832
|
|
|
727
833
|
/** This function applies a list op (LIST.*). The error items are skipped, except with `{ strict: true }`, and except `#DEPTH!`. */
|
|
728
834
|
function listOp(op: string, items: readonly ListItem[], rest: readonly unknown[], domains: readonly AnyDomain[]): unknown {
|
|
729
|
-
const o = WITH_ARGUMENT.has(op) ? rest[1] : rest[0];
|
|
835
|
+
const o = op === "setNth" ? rest[2] : WITH_ARGUMENT.has(op) ? rest[1] : rest[0];
|
|
730
836
|
const strict = (o as { strict?: unknown } | null | undefined)?.strict === true;
|
|
731
837
|
if (op === "group") return group(items, rest[0], strict);
|
|
732
838
|
const good = goodOf(items, strict);
|
|
@@ -760,6 +866,16 @@ function listOp(op: string, items: readonly ListItem[], rest: readonly unknown[]
|
|
|
760
866
|
if (op === "drop") return vexList(good.slice(n));
|
|
761
867
|
return n < vs.length ? vs[n] : stop("empty", `"nth" has no item at the position ${String(n)}`);
|
|
762
868
|
}
|
|
869
|
+
case "setNth": {
|
|
870
|
+
const n = rest[0] as number;
|
|
871
|
+
if (!Number.isSafeInteger(n) || n < 0) return stop("kind-mismatch", '"setNth" needs a whole number from 0');
|
|
872
|
+
const old = good[n];
|
|
873
|
+
if (old === undefined) return stop("empty", `"setNth" has no item at the position ${String(n)}`);
|
|
874
|
+
if (rest[1] === undefined) return stop("bad-expression", '"setNth" needs argument 3');
|
|
875
|
+
const next = [...good];
|
|
876
|
+
next[n] = { key: old.key, result: vexOk(rest[1]) };
|
|
877
|
+
return vexList(next);
|
|
878
|
+
}
|
|
763
879
|
case "append":
|
|
764
880
|
return vexList([...good, ...otherOf(op, rest[0], strict)]);
|
|
765
881
|
case "without": {
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { isDepthError, vexError, type ErrorDetails, type VexError } from "./errors.ts";
|
|
2
|
+
|
|
3
|
+
/** This function gives the error that decides for a list of errors: `#DEPTH!`, or else the first (EVAL.DEPTH). */
|
|
4
|
+
export const worstError = (errors: readonly VexError[]): VexError | undefined => errors.find(isDepthError) ?? errors[0];
|
|
5
|
+
|
|
6
|
+
/** This function gives the message of a data limit above the cap (ITERATE.LIMIT.ERROR). */
|
|
7
|
+
export const overLimitMessage = (count: number): string => `the data limit of "iterate" is ${String(count)}, above the cap of 100000`;
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* This function gives the error of a data limit that is not valid, with its cause (ITERATE.LIMIT.ERROR). An error of the
|
|
11
|
+
* run stays as it is: the engine failed or a cycle of cells stopped, not the limit.
|
|
12
|
+
*/
|
|
13
|
+
export const limitError = (cause: VexError, details: Omit<ErrorDetails, "causes"> = {}): VexError =>
|
|
14
|
+
isDepthError(cause) || cause.kind === "cycle" ? cause : vexError("limit", 'the data limit of "iterate" is not valid', { ...details, causes: [cause] });
|
package/src/list.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { CHECKED } from "./checked.ts";
|
|
2
|
+
import type { SizeRule } from "./domain.ts";
|
|
2
3
|
import type { Result } from "./result.ts";
|
|
3
4
|
|
|
4
5
|
/** One item of a list: the key of the target and the result of the body there. */
|
|
@@ -53,14 +54,59 @@ export const isVexList = (u: unknown): u is VexList => {
|
|
|
53
54
|
* The name of a core list op. `sortBy`, `take`, `drop`, `append`, `flat` and `without` give a list (LIST.BUILD), and
|
|
54
55
|
* the other ops give a value. `get` gives the value at a key (LIST.GET), and `indexOf` gives the position of a value
|
|
55
56
|
* (LIST.INDEXOF). `distinct` and `group` give a list, and `join` gives a text (LIST.DISTINCT, LIST.GROUP, LIST.JOIN).
|
|
57
|
+
* `setNth` gives a list with a new value at one position (LIST.SETNTH).
|
|
56
58
|
*/
|
|
57
|
-
export type ListOp = "count" | "sum" | "min" | "max" | "mean" | "any" | "all" | "none" | "values" | "keys" | "reduce" | "first" | "errors" | "sortBy" | "take" | "nth" | "drop" | "append" | "flat" | "without" | "get" | "indexOf" | "distinct" | "group" | "join";
|
|
59
|
+
export type ListOp = "count" | "sum" | "min" | "max" | "mean" | "any" | "all" | "none" | "values" | "keys" | "reduce" | "first" | "errors" | "sortBy" | "take" | "nth" | "setNth" | "drop" | "append" | "flat" | "without" | "get" | "indexOf" | "distinct" | "group" | "join";
|
|
58
60
|
|
|
59
61
|
/**
|
|
60
62
|
* The names of the core list ops. They apply when the first argument is a list. They apply to an array too, when no
|
|
61
63
|
* domain and no function of the host has the op for it (LIST.ARRAY).
|
|
62
64
|
*/
|
|
63
|
-
export const LIST_OPS: ReadonlySet<string> = new Set<ListOp>(["count", "sum", "min", "max", "mean", "any", "all", "none", "values", "keys", "reduce", "first", "errors", "sortBy", "take", "nth", "drop", "append", "flat", "without", "get", "indexOf", "distinct", "group", "join"]);
|
|
65
|
+
export const LIST_OPS: ReadonlySet<string> = new Set<ListOp>(["count", "sum", "min", "max", "mean", "any", "all", "none", "values", "keys", "reduce", "first", "errors", "sortBy", "take", "nth", "setNth", "drop", "append", "flat", "without", "get", "indexOf", "distinct", "group", "join"]);
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* The size rules of the core list ops and of `fill` (LOOP.SIZE.OPS). Each op that gives a list has a rule here. An
|
|
69
|
+
* error item has no size, so `errors` has no bound: the messages of the errors can hold texts.
|
|
70
|
+
*/
|
|
71
|
+
export const LIST_SIZES: Readonly<Record<ListOp | "fill", SizeRule>> = Object.freeze<Record<ListOp | "fill", SizeRule>>({
|
|
72
|
+
count: "scalar",
|
|
73
|
+
sum: "scalar",
|
|
74
|
+
min: "scalar",
|
|
75
|
+
max: "scalar",
|
|
76
|
+
mean: "scalar",
|
|
77
|
+
any: "scalar",
|
|
78
|
+
all: "scalar",
|
|
79
|
+
none: "scalar",
|
|
80
|
+
indexOf: "scalar",
|
|
81
|
+
values: { size: [1], count: [1], inner: [1], item: [1], part: [1], keys: "position" },
|
|
82
|
+
keys: { size: [1], count: [1], keys: "position" },
|
|
83
|
+
errors: { size: ["unbounded"] },
|
|
84
|
+
reduce: "reduce",
|
|
85
|
+
first: { size: [[1, "item"]], count: [[1, "item"]], inner: [[1, "item"]], item: [[1, "part"]] },
|
|
86
|
+
nth: { size: [[1, "item"], 0], count: [[1, "item"], 0], inner: [[1, "item"], 0], item: [[1, "part"], 0] },
|
|
87
|
+
get: { size: [[1, "item"], 0], count: [[1, "item"], 0], inner: [[1, "item"], 0], item: [[1, "part"], 0] },
|
|
88
|
+
// LOOP.SIZE.SETNTH: the bound counts the list and the value one time each. A bound cannot subtract the old item.
|
|
89
|
+
setNth: { size: [1, 0, 1], count: [1, 0, 0], inner: [1, 0, [1, "count"]], item: [1, 0, [1, "size"]], part: [1, 0, [1, "item"]] },
|
|
90
|
+
sortBy: { size: [1, 0], count: [1, 0], inner: [1, 0], item: [1, 0], part: [1, 0] },
|
|
91
|
+
// LOOP.SIZE.PART: the second reading counts the items that a literal limit keeps.
|
|
92
|
+
take: {
|
|
93
|
+
size: [1, 0],
|
|
94
|
+
count: [1, 0],
|
|
95
|
+
inner: [1, 0],
|
|
96
|
+
item: [1, 0],
|
|
97
|
+
part: [1, 0],
|
|
98
|
+
limit: 1,
|
|
99
|
+
byParts: { size: [["limit", "item"], 0], count: [1, 0], inner: [["limit", "item"], 0], item: [1, 0], part: [1, 0] },
|
|
100
|
+
},
|
|
101
|
+
drop: { size: [1, 0], count: [1, 0], inner: [1, 0], item: [1, 0], part: [1, 0] },
|
|
102
|
+
without: { size: [1, 0], count: [1, 0], inner: [1, 0], item: [1, 0], part: [1, 0] },
|
|
103
|
+
append: { size: [1, 1], count: [1, 1], inner: [1, 1], item: [1, 1], part: [1, 1] },
|
|
104
|
+
flat: { size: [1], count: [[1, "inner"]], item: [[1, "part"]] },
|
|
105
|
+
distinct: { size: [1], count: [1], inner: [1], item: [1], part: [1] },
|
|
106
|
+
group: { size: [1, "scaled"], count: [0, 1], inner: [[1, "count"], 0] },
|
|
107
|
+
join: { size: [1, "each"] },
|
|
108
|
+
fill: { size: [0, "copies"], count: ["number", 0], inner: [0, ["copies", "count"]], item: [0, [1, "size"]], part: [0, [1, "item"]], keys: "position" },
|
|
109
|
+
});
|
|
64
110
|
|
|
65
111
|
/** This function tells if a name is the name of a core list op. */
|
|
66
112
|
export const isListOp = (op: string): op is ListOp => LIST_OPS.has(op);
|