@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.
@@ -0,0 +1,259 @@
1
+ /**
2
+ * The check of the steps of `fix` (FIX.MONOTONE). The check proves from the kinds of the ops that the step of each `fix`
3
+ * does not fall when the last round rises. The rounds then reach the least fixed point above `init`, and the dual
4
+ * for `and` and `min`. A program without a proof does not run (fail closed).
5
+ *
6
+ * The proof follows the reads of `last` through the program. Each part has a direction: it does not depend on the last
7
+ * round, it follows the last round, or it moves against the last round. An op states the direction of each argument
8
+ * as data (FIX.OPS). A part that the rules do not cover and that reads `last` ends the check with a reason.
9
+ */
10
+ import type { AnyDomain, Monotone, OpSpec, ReturnKind } from "./domain.ts";
11
+ import { joinKind } from "./fix.ts";
12
+ import { addrExprs, axisExprs, children, type Axis, type Expr, type ExprOf } from "./ir.ts";
13
+
14
+ /** The options of the check: the domains and the functions of the host, as the options of a compilation give them. */
15
+ export interface MonotoneOptions {
16
+ readonly domains?: readonly AnyDomain[];
17
+ readonly fns?: Readonly<Record<string, unknown>>;
18
+ }
19
+
20
+ /** The direction of a part: 1 follows the last round, -1 moves against it, and 0 does not read it. */
21
+ type Direction = -1 | 0 | 1;
22
+
23
+ /** What the check knows of a part: its direction, and the kind of its value if the check knows it. */
24
+ interface Flow {
25
+ readonly dir: Direction;
26
+ readonly tag: "boolean" | "number" | "list" | undefined;
27
+ }
28
+
29
+ /** A rule of an op: the direction of each argument, and the kind of the result. */
30
+ interface Rule {
31
+ readonly args: readonly Monotone[];
32
+ readonly returns: ReturnKind | undefined;
33
+ }
34
+
35
+ /** The names of a program and the flow of each. A name that the map does not have does not read the last round. */
36
+ type Names = ReadonlyMap<string, Flow>;
37
+
38
+ /** The end of a proof. The methods of `Proof` throw it, and `monotoneError` gives its reason. */
39
+ class Refusal {
40
+ readonly reason: string;
41
+
42
+ constructor(reason: string) {
43
+ this.reason = reason;
44
+ }
45
+ }
46
+
47
+ const STEADY: Flow = { dir: 0, tag: undefined };
48
+
49
+ /**
50
+ * The rules of the list ops. The items of a list come from an axis that does not read the last round. Thus the set of
51
+ * the items stays the same in each round. Each of these ops ignores the order of the items. `sum` has no rule. The
52
+ * rounding of a sum of floats depends on the order of the items (FIX.ORDER).
53
+ */
54
+ const LIST_RULES: Readonly<Record<string, Rule>> = {
55
+ any: { args: ["up"], returns: "boolean" },
56
+ all: { args: ["up"], returns: "boolean" },
57
+ none: { args: ["down"], returns: "boolean" },
58
+ min: { args: ["up"], returns: "number" },
59
+ max: { args: ["up"], returns: "number" },
60
+ };
61
+
62
+ /** This function gives the flow of a literal. The kind of a number or a boolean is known. */
63
+ function steadyValue(value: unknown): Flow {
64
+ if (typeof value === "number") return { dir: 0, tag: "number" };
65
+ return typeof value === "boolean" ? { dir: 0, tag: "boolean" } : STEADY;
66
+ }
67
+
68
+ /** This function gives the axis inside the `where` axes of an axis. */
69
+ const baseOf = (a: Axis): Axis => (a.t === "where" ? baseOf(a.axis) : a);
70
+
71
+ /** This function gives the names without the names that a part of the program hides. */
72
+ function without(names: Names, hidden: readonly string[]): Names {
73
+ const out = new Map(names);
74
+ for (const name of hidden) out.delete(name);
75
+ return out;
76
+ }
77
+
78
+ /** The proof of the step of one `fix`. */
79
+ class Proof {
80
+ readonly #fix: ExprOf<"fix">;
81
+ readonly #domains: readonly AnyDomain[];
82
+ readonly #fns: Readonly<Record<string, unknown>>;
83
+ /** This field is `true` inside a `fix` of the same name: a read there reads that `fix`. */
84
+ #hidden = false;
85
+
86
+ constructor(fix: ExprOf<"fix">, opts: MonotoneOptions) {
87
+ this.#fix = fix;
88
+ this.#domains = opts.domains ?? [];
89
+ this.#fns = opts.fns ?? {};
90
+ }
91
+
92
+ /** This method proves the step. It throws a refusal, or it returns. */
93
+ prove(): void {
94
+ if (this.#flow(this.#fix.step, new Map()).dir < 0) this.#refuse("it moves against the last round");
95
+ }
96
+
97
+ #refuse(why: string): never {
98
+ throw new Refusal(`the step of the "fix" "${this.#fix.name}" does not move one way: ${why}`);
99
+ }
100
+
101
+ #flow(e: Expr, names: Names): Flow {
102
+ switch (e.tag) {
103
+ case "lit":
104
+ return steadyValue(e.value);
105
+ case "var":
106
+ return names.get(e.name) ?? STEADY;
107
+ case "last":
108
+ return e.name === this.#fix.name && !this.#hidden ? { dir: 1, tag: joinKind(this.#fix.join) } : STEADY;
109
+ case "let": {
110
+ const bound = new Map(names);
111
+ for (const [name, x] of Object.entries(e.bind)) bound.set(name, this.#flow(x, names));
112
+ return this.#flow(e.body, bound);
113
+ }
114
+ case "fn":
115
+ return this.#flow(e.body, without(names, e.params));
116
+ case "call":
117
+ if ((names.get(e.fn)?.dir ?? 0) !== 0) this.#refuse(`the function "${e.fn}" reads the last round`);
118
+ return this.#steady(e.args, names, `an argument of the function "${e.fn}"`);
119
+ case "each":
120
+ return this.#each(e, names);
121
+ case "app":
122
+ return this.#app(e, names);
123
+ case "fix":
124
+ return this.#inner(e, names);
125
+ // The fields of a record, the moves of a reference and the parts of a fold and of an iterate have no rule.
126
+ case "rec":
127
+ case "ref":
128
+ case "fold":
129
+ case "iterate":
130
+ case "ext":
131
+ return this.#steady(children(e), names, `a node "${e.tag}"`);
132
+ }
133
+ }
134
+
135
+ /** This method refuses a part that reads the last round. Only an op or a loop with a rule can take such a part. */
136
+ #steady(parts: readonly Expr[], names: Names, what: string): Flow {
137
+ for (const x of parts) if (this.#flow(x, names).dir !== 0) this.#refuse(`${what} reads the last round`);
138
+ return STEADY;
139
+ }
140
+
141
+ /**
142
+ * This method reads a `fix` inside the step. Its rounds end in each round of the outer `fix`. Thus a column of the
143
+ * outer `fix` as an input of the inner `fix` has no proof.
144
+ */
145
+ #inner(e: ExprOf<"fix">, names: Names): Flow {
146
+ this.#steady([e.init], names, `the start of the "fix" "${e.name}"`);
147
+ const outer = this.#hidden;
148
+ this.#hidden ||= e.name === this.#fix.name;
149
+ this.#steady([e.step], names, `the step of the "fix" "${e.name}"`);
150
+ this.#hidden = outer;
151
+ return { dir: 0, tag: joinKind(e.join) };
152
+ }
153
+
154
+ /** This method reads an `each`. The targets must not read the last round, so each round has the same items. */
155
+ #each(e: ExprOf<"each">, names: Names): Flow {
156
+ this.#steady([...axisExprs(e.axis), ...addrExprs(e.at)], names, "an axis");
157
+ const body = this.#flow(e.body, without(names, e.as ?? []));
158
+ if (body.dir !== 0 && baseOf(e.axis).t === "table") this.#refuse("the axis table leaves the rows of the column");
159
+ return { dir: body.dir, tag: "list" };
160
+ }
161
+
162
+ #app(e: ExprOf<"app">, names: Names): Flow {
163
+ const flows = e.args.map((x) => this.#flow(x, names));
164
+ const [head] = flows;
165
+ switch (e.op) {
166
+ case "if":
167
+ if ((head?.dir ?? 0) !== 0) this.#refuse('the test of "if" reads the last round');
168
+ return this.#joined(flows.slice(1), e.op);
169
+ case "and":
170
+ case "or":
171
+ case "ifError":
172
+ return this.#joined(flows, e.op);
173
+ }
174
+ if (flows.every((x) => x.dir === 0)) return STEADY;
175
+ const rule = this.#rule(e.op, head?.tag);
176
+ const moves = flows.map((x, i): number => {
177
+ const move = rule.args[i];
178
+ if (x.dir !== 0 && move === undefined) this.#refuse(`the argument ${String(i + 1)} of the op "${e.op}" reads the last round`);
179
+ return move === "down" ? -x.dir : x.dir;
180
+ });
181
+ const { returns } = rule;
182
+ return { dir: this.#one(moves, e.op), tag: returns === "number" || returns === "boolean" ? returns : undefined };
183
+ }
184
+
185
+ /** This method gives the flow of the branches of a form. Each branch can be the result. */
186
+ #joined(flows: readonly Flow[], op: string): Flow {
187
+ const [head] = flows;
188
+ const dir = this.#one(
189
+ flows.map((x) => x.dir),
190
+ op,
191
+ );
192
+ return { dir, tag: flows.every((x) => x.tag === head?.tag) ? head?.tag : undefined };
193
+ }
194
+
195
+ /** This method gives the one direction of the moves of a node. Two directions have no proof. */
196
+ #one(moves: readonly number[], op: string): Direction {
197
+ const up = moves.some((m) => m > 0);
198
+ if (up && moves.some((m) => m < 0)) this.#refuse(`the op "${op}" reads the last round in both directions`);
199
+ return up ? 1 : moves.some((m) => m < 0) ? -1 : 0;
200
+ }
201
+
202
+ /**
203
+ * This method gives the rule of an op for a receiver of a known kind, in the order of the interpreter. A list op on a
204
+ * list comes first, then the domains in order, then a function of the host. A receiver of another kind has no rule.
205
+ */
206
+ #rule(op: string, tag: Flow["tag"]): Rule {
207
+ if (tag === undefined) this.#refuse(`the kind of the first argument of the op "${op}" does not decide the op. Put an argument of a known kind first`);
208
+ if (tag === "list") return Object.hasOwn(LIST_RULES, op) ? (LIST_RULES[op] as Rule) : this.#noRule(op);
209
+ const found: Rule[] = [];
210
+ for (const d of this.#domains) {
211
+ if (d.primitive !== undefined && d.primitive !== tag) continue;
212
+ const spec = Object.hasOwn(d.ops, op) ? (d.ops[op] as OpSpec<unknown>) : undefined;
213
+ if (spec?.fn === undefined) continue;
214
+ found.push(this.#declared(spec, op));
215
+ if (d.primitive === tag) return this.#same(found, op);
216
+ }
217
+ if (Object.hasOwn(this.#fns, op)) found.push(this.#declared(this.#fns[op] as Pick<OpSpec<unknown>, "monotone" | "returns">, op));
218
+ return found.length > 0 ? this.#same(found, op) : this.#noRule(op);
219
+ }
220
+
221
+ #declared(spec: Pick<OpSpec<unknown>, "monotone" | "returns">, op: string): Rule {
222
+ return spec.monotone === undefined ? this.#noRule(op) : { args: spec.monotone, returns: spec.returns };
223
+ }
224
+
225
+ /** This method gives the rule of the ops that can apply. They must have the same rule, because the data decides among them. */
226
+ #same(rules: readonly Rule[], op: string): Rule {
227
+ const first = rules[0] as Rule;
228
+ if (rules.some((r) => r.args.join() !== first.args.join())) this.#refuse(`the op "${op}" has two rules, and the data decides among them`);
229
+ return first;
230
+ }
231
+
232
+ #noRule(op: string): never {
233
+ this.#refuse(`the op "${op}" has no rule of direction`);
234
+ }
235
+ }
236
+
237
+ /** This function walks a program. `open` has the names of the `fix` nodes around a node (FIX.LAST). */
238
+ function walk(e: Expr, open: ReadonlySet<string>, opts: MonotoneOptions): void {
239
+ if (e.tag === "last" && !open.has(e.name)) throw new Refusal(`the read "last" of "${e.name}" has no "fix" of that name around it`);
240
+ if (e.tag !== "fix") {
241
+ for (const x of children(e)) walk(x, open, opts);
242
+ return;
243
+ }
244
+ walk(e.init, open, opts);
245
+ walk(e.step, new Set([...open, e.name]), opts);
246
+ new Proof(e, opts).prove();
247
+ }
248
+
249
+ /** This function gives the reason that a program breaks a rule of `fix`, or `undefined` for a program that keeps them (FIX.LAST, FIX.MONOTONE). */
250
+ export function monotoneError(e: Expr, opts: MonotoneOptions): string | undefined {
251
+ try {
252
+ walk(e, new Set(), opts);
253
+ return undefined;
254
+ } catch (thrown) {
255
+ // Stryker disable next-line ConditionalExpression: only a Refusal comes here, and a mutant that always takes it reads its field
256
+ if (thrown instanceof Refusal) return thrown.reason;
257
+ throw thrown;
258
+ }
259
+ }
package/src/plan.ts CHANGED
@@ -6,11 +6,14 @@
6
6
  import { agree as kernelAgree, context, prepare, reference as kernelReference, type Agreement, type Context, type Failed, type Result as Outcome } from "@mark1russell7/coeval";
7
7
  import { fromDocument, isDocument, type Envelope } from "./document.ts";
8
8
  import { vexError, type VexError } from "./errors.ts";
9
- import { MAX_NESTING, nestingOf, type CompileOptions, type RunOptions } from "./evaluate.ts";
9
+ import { nestingError, type CompileOptions, type RunOptions } from "./evaluate.ts";
10
10
  import { shapeError, type Expr } from "./ir.ts";
11
11
  import { toKernelError, toVexResult, vexDefinitions, vexMachine, vexSelf } from "./kernel.ts";
12
12
  import type { Result } from "./result.ts";
13
13
  import { sameVex } from "./same.ts";
14
+ import { monotoneError } from "./monotone.ts";
15
+ import { sizeError } from "./size.ts";
16
+ import { stepError } from "./steps.ts";
14
17
  import { writeDocument } from "./write.ts";
15
18
 
16
19
  /** The options of a run of a plan of the kernel: the options of a run without a trace. */
@@ -56,12 +59,15 @@ export function kernelPlan(source: Expr | Envelope, opts: CompileOptions = {}):
56
59
  let bad: VexError | undefined;
57
60
  if (isDocument(source)) {
58
61
  const read = fromDocument(source, domains);
59
- if (read.ok) doc = source;
60
- else bad = read.error;
62
+ // EVAL.NESTING, LOOP.SIZE, STEP.MAX: the plan refuses the same programs as `compile`. The nesting comes first, because the
63
+ // other checks recurse, and a document can be deeper than the limit of an expression.
64
+ const size = read.ok ? (nestingError(read.value) ?? sizeError(read.value, opts) ?? stepError(read.value, opts) ?? monotoneError(read.value, opts)) : undefined;
65
+ if (read.ok && size === undefined) doc = source;
66
+ else bad = read.ok ? vexError("bad-expression", size ?? "") : read.error;
61
67
  } else {
62
68
  const shape = shapeError(source);
63
- const nesting = shape === undefined ? nestingOf(source) : 0;
64
- const reason = shape ?? (nesting > MAX_NESTING ? `the expression is nested ${String(nesting)} levels deep, and the limit is ${String(MAX_NESTING)}` : undefined);
69
+ const deep = shape ?? nestingError(source);
70
+ const reason = deep ?? sizeError(source, opts) ?? stepError(source, opts) ?? monotoneError(source, opts);
65
71
  // Stryker disable next-line StringLiteral: the writer tests only the mode "json" and the order "reads"
66
72
  if (reason === undefined) doc = writeDocument(source, { domains, literals: "host", order: "document" });
67
73
  else bad = vexError("bad-expression", reason);
package/src/sheet.ts CHANGED
@@ -11,7 +11,7 @@
11
11
  */
12
12
  import { vexError } from "./errors.ts";
13
13
  import { evaluate, explain, nestingOf, type CompileOptions, type EvalOptions, type ExtHandler, type Program } from "./evaluate.ts";
14
- import { addrExprs, children, ext, isMove, listOf, moveExpr, shapeError, type Axis, type Expr, type FixedMove, type Move } from "./ir.ts";
14
+ import { addrExprs, app, axes, children, each, ext, isFixedAddr, isMove, listOf, lit, moveExpr, shapeError, splitLimit, type Addr, type Axis, type Expr, type FixedMove, type Move } from "./ir.ts";
15
15
  import { fail, type Result } from "./result.ts";
16
16
  import { resolveAddr, type Space } from "./space.ts";
17
17
  import type { Trace } from "./trace.ts";
@@ -21,17 +21,25 @@ export const CELL_KIND = "vex.cell";
21
21
 
22
22
  /**
23
23
  * The data of a cell reference: the column, and the address from the focus. The data of an extension is not an
24
- * expression, so the address has only fixed moves.
24
+ * expression, so the address has only fixed moves. `cell` takes computed moves in another form.
25
25
  */
26
26
  export interface CellRef {
27
27
  readonly column: string;
28
28
  readonly at: readonly FixedMove[];
29
29
  }
30
30
 
31
- /** This function makes a cell reference: the column `column` at the address `at` from the focus. */
32
- export const cell = (column: string, at: readonly FixedMove[] = []): Expr => ext(CELL_KIND, { column, at } satisfies CellRef);
31
+ /** This function makes the extension node of a cell reference. */
32
+ const cellRef = (column: string, at: readonly FixedMove[]): Expr => ext(CELL_KIND, { column, at } satisfies CellRef);
33
33
 
34
- const isCellRef = (u: unknown): u is CellRef =>
34
+ /**
35
+ * This function makes a read of the column `column` at the address `at` from the focus. An address of fixed moves gives
36
+ * a cell reference. A computed move is an expression, not data (SHEET.CELL.COMPUTED). Thus it goes in the address of the
37
+ * axis `window(0, 0)`, and the read is the one item of that axis. Each tier and the JSON form have this form.
38
+ */
39
+ export const cell = (column: string, at: Addr = []): Expr => (isFixedAddr(at) ? cellRef(column, at) : app("first", each(axes.window(0, 0), cellRef(column, []), at), lit({ strict: true })));
40
+
41
+ /** This function tells if the data of an extension is a cell reference: a column, and an address of fixed moves. */
42
+ export const isCellRef = (u: unknown): u is CellRef =>
35
43
  typeof u === "object" &&
36
44
  u !== null &&
37
45
  typeof (u as { column?: unknown }).column === "string" &&
@@ -116,7 +124,7 @@ function setDone(t: Table, column: string, key: string, result: Result<unknown>)
116
124
  }
117
125
 
118
126
  /** A direction of the reads of a column from itself: to an earlier key, to a later key, or down a tree to the children. */
119
- type Direction = "before" | "after" | "down";
127
+ export type Direction = "before" | "after" | "down";
120
128
 
121
129
  /** This function adds the direction of one move or one axis of a read of a column from itself. */
122
130
  function addDirection(d: Set<Direction>, m: Move | Axis): void {
@@ -153,15 +161,18 @@ function partsOf(axis: Axis): { readonly base: Axis; readonly tests: readonly Ex
153
161
  * the formulas of its cells. It also gives the directions of their reads of the column itself. A read in the body or
154
162
  * in a test of an axis also has the direction of that axis. It walks each expression with a stack, not with recursion.
155
163
  */
156
- function readsOf(t: Table, self: string): { readonly columns: ReadonlySet<string>; readonly directions: ReadonlySet<Direction> } {
157
- const columns = new Set<string>();
164
+ export function readsOf(columns: ReadonlyMap<string, Expr>, cells: CellFormulas, self: string): { readonly columns: ReadonlySet<string>; readonly directions: ReadonlySet<Direction> } {
165
+ const read = new Set<string>();
158
166
  const directions = new Set<Direction>();
159
- const formula = t.columns.get(self);
167
+ const formula = columns.get(self);
160
168
  // An expression that is not valid reads no column. Its evaluation gives the error (EVAL.SHAPE).
161
- const todo: [Expr, Axis | undefined][] = [...(formula === undefined ? [] : [formula]), ...(t.cells.get(self)?.values() ?? [])].filter((e) => shapeError(e) === undefined).map((e) => [e, undefined]);
169
+ const todo: [Expr, Axis | undefined][] = [...(formula === undefined ? [] : [formula]), ...(cells.get(self)?.values() ?? [])].filter((e) => shapeError(e) === undefined).map((e) => [e, undefined]);
162
170
  for (let item = todo.pop(); item !== undefined; item = todo.pop()) {
163
171
  const [e, axis] = item;
164
- if (e.tag === "each" || e.tag === "fold") {
172
+ // A test of the axis of a data limit reads at each target, as the test of an `each` does.
173
+ const split = e.tag === "iterate" ? splitLimit(e) : undefined;
174
+ if (split !== undefined) for (const x of split) todo.push([x, axis]);
175
+ else if (e.tag === "each" || e.tag === "fold") {
165
176
  const { base, tests } = partsOf(e.axis);
166
177
  for (const x of [...(e.tag === "each" ? [e.body] : Object.values(e.step)), ...tests]) todo.push([x, base]);
167
178
  // The values of init, the result of a fold, the list of the axis list and the expressions of the address evaluate
@@ -173,22 +184,22 @@ function readsOf(t: Table, self: string): { readonly columns: ReadonlySet<string
173
184
  // The data of an extension of another kind can look like a cell reference. It only changes the order of a fill.
174
185
  // Stryker disable next-line ConditionalExpression,LogicalOperator: see the comment above
175
186
  } else if (e.kind === CELL_KIND && isCellRef(e.data)) {
176
- columns.add(e.data.column);
187
+ read.add(e.data.column);
177
188
  // The directions of the reads of another column only change the order of a fill, because that column comes first.
178
189
  // Stryker disable next-line ConditionalExpression: see the comment above
179
190
  if (e.data.column === self) for (const m of [...(axis === undefined ? [] : [axis]), ...e.data.at]) addDirection(directions, m);
180
191
  }
181
192
  }
182
- return { columns, directions };
193
+ return { columns: read, directions };
183
194
  }
184
195
 
185
196
  /**
186
- * This function gives the columns of a table in an order where each column comes after the columns that it reads.
197
+ * This function gives the columns of a sheet in an order where each column comes after the columns that it reads.
187
198
  * The columns of a cycle keep their order. The columns with formulas of cells only come last.
188
199
  */
189
- function columnOrder(t: Table): readonly string[] {
190
- const names = new Set([...t.columns.keys(), ...t.cells.keys()]);
191
- let left = [...names].map((c) => ({ c, needs: [...readsOf(t, c).columns].filter((x) => x !== c && names.has(x)) }));
200
+ export function columnOrder(columns: ReadonlyMap<string, Expr>, cells: CellFormulas): readonly string[] {
201
+ const names = new Set([...columns.keys(), ...cells.keys()]);
202
+ let left = [...names].map((c) => ({ c, needs: [...readsOf(columns, cells, c).columns].filter((x) => x !== c && names.has(x)) }));
192
203
  const order: string[] = [];
193
204
  const placed = new Set<string>();
194
205
  // Each pass places each column whose reads are placed. A pass that places no column leaves a cycle, so it places
@@ -560,8 +571,8 @@ export class SheetRun {
560
571
  // A read inside a formula has a cell at the top. A fill there has no effect.
561
572
  if (t === undefined || this.#top.index >= 0) return;
562
573
  const host = this.#top;
563
- for (const column of columnOrder(t)) {
564
- for (const key of keyOrder(t.space, readsOf(t, column).directions)) {
574
+ for (const column of columnOrder(t.columns, t.cells)) {
575
+ for (const key of keyOrder(t.space, readsOf(t.columns, t.cells, column).directions)) {
565
576
  const program = this.#programOf(t, column, key);
566
577
  if (program === undefined || doneOf(t, column, key) !== undefined) continue;
567
578
  this.#top = this.#filling;