@toiroakr/chisel 0.1.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +354 -21
- package/dist/absence.d.ts +28 -0
- package/dist/absence.js +266 -0
- package/dist/absence.js.map +1 -0
- package/dist/behavior.d.ts +26 -19
- package/dist/behavior.js +193 -203
- package/dist/behavior.js.map +1 -1
- package/dist/beside.d.ts +5 -0
- package/dist/beside.js +10 -0
- package/dist/beside.js.map +1 -1
- package/dist/border.d.ts +7 -8
- package/dist/border.js +88 -36
- package/dist/border.js.map +1 -1
- package/dist/bounds.d.ts +1 -0
- package/dist/bounds.js +27 -0
- package/dist/bounds.js.map +1 -0
- package/dist/changes.d.ts +23 -0
- package/dist/changes.js +355 -0
- package/dist/changes.js.map +1 -0
- package/dist/checks.d.ts +1 -0
- package/dist/checks.js +295 -0
- package/dist/checks.js.map +1 -0
- package/dist/cli.d.ts +4 -0
- package/dist/cli.js +351 -14
- package/dist/cli.js.map +1 -1
- package/dist/codec.js +16 -7
- package/dist/codec.js.map +1 -1
- package/dist/codegen.js +6 -8
- package/dist/codegen.js.map +1 -1
- package/dist/composition.d.ts +3 -3
- package/dist/composition.js +9 -8
- package/dist/composition.js.map +1 -1
- package/dist/conformance.d.ts +24 -0
- package/dist/conformance.js +44 -0
- package/dist/conformance.js.map +1 -0
- package/dist/data.d.ts +3 -2
- package/dist/data.js +7 -3
- package/dist/data.js.map +1 -1
- package/dist/decimal-js.d.ts +2 -0
- package/dist/decimal-js.js +5 -0
- package/dist/decimal-js.js.map +1 -0
- package/dist/decimal.d.ts +2 -0
- package/dist/decimal.js +3 -0
- package/dist/decimal.js.map +1 -0
- package/dist/dependency.d.ts +9 -6
- package/dist/dependency.js +23 -17
- package/dist/dependency.js.map +1 -1
- package/dist/domain.d.ts +6 -2
- package/dist/domain.js +65 -25
- package/dist/domain.js.map +1 -1
- package/dist/ensures.js +3 -3
- package/dist/ensures.js.map +1 -1
- package/dist/equal.d.ts +1 -0
- package/dist/equal.js +135 -0
- package/dist/equal.js.map +1 -0
- package/dist/errors.d.ts +18 -0
- package/dist/errors.js +25 -0
- package/dist/errors.js.map +1 -0
- package/dist/exact.d.ts +13 -1
- package/dist/exact.js +52 -3
- package/dist/exact.js.map +1 -1
- package/dist/feasibility.d.ts +5 -3
- package/dist/feasibility.js +309 -53
- package/dist/feasibility.js.map +1 -1
- package/dist/guard-borders.d.ts +14 -5
- package/dist/guard-borders.js +229 -190
- package/dist/guard-borders.js.map +1 -1
- package/dist/guard-scope.d.ts +65 -0
- package/dist/guard-scope.js +384 -0
- package/dist/guard-scope.js.map +1 -0
- package/dist/hooks.d.ts +22 -0
- package/dist/hooks.js +2 -0
- package/dist/hooks.js.map +1 -0
- package/dist/index.d.ts +30 -8
- package/dist/index.js +18 -5
- package/dist/index.js.map +1 -1
- package/dist/interleave.d.ts +31 -0
- package/dist/interleave.js +202 -0
- package/dist/interleave.js.map +1 -0
- package/dist/interval.d.ts +8 -0
- package/dist/interval.js +213 -23
- package/dist/interval.js.map +1 -1
- package/dist/isolated.d.ts +7 -1
- package/dist/isolated.js +53 -5
- package/dist/isolated.js.map +1 -1
- package/dist/kinds/decimal.d.ts +1 -0
- package/dist/kinds/decimal.js +16 -0
- package/dist/kinds/decimal.js.map +1 -0
- package/dist/kinds/rational.d.ts +1 -0
- package/dist/kinds/rational.js +13 -0
- package/dist/kinds/rational.js.map +1 -0
- package/dist/kinds/temporal.d.ts +1 -0
- package/dist/kinds/temporal.js +15 -0
- package/dist/kinds/temporal.js.map +1 -0
- package/dist/lean/behavior.d.ts +29 -0
- package/dist/lean/behavior.js +76 -0
- package/dist/lean/behavior.js.map +1 -0
- package/dist/lean/given.d.ts +10 -0
- package/dist/lean/given.js +15 -0
- package/dist/lean/given.js.map +1 -0
- package/dist/lean/index.d.ts +11 -0
- package/dist/lean/index.js +8 -0
- package/dist/lean/index.js.map +1 -0
- package/dist/lean/model.d.ts +20 -0
- package/dist/lean/model.js +133 -0
- package/dist/lean/model.js.map +1 -0
- package/dist/lean/protocol.d.ts +14 -0
- package/dist/lean/protocol.js +34 -0
- package/dist/lean/protocol.js.map +1 -0
- package/dist/lean/rule.d.ts +54 -0
- package/dist/lean/rule.js +149 -0
- package/dist/lean/rule.js.map +1 -0
- package/dist/lean/schema.d.ts +46 -0
- package/dist/lean/schema.js +155 -0
- package/dist/lean/schema.js.map +1 -0
- package/dist/machine-check.d.ts +73 -0
- package/dist/machine-check.js +215 -0
- package/dist/machine-check.js.map +1 -0
- package/dist/machine.d.ts +122 -0
- package/dist/machine.js +271 -0
- package/dist/machine.js.map +1 -0
- package/dist/model.d.ts +110 -11
- package/dist/model.js +724 -80
- package/dist/model.js.map +1 -1
- package/dist/off-grid.d.ts +4 -0
- package/dist/off-grid.js +92 -0
- package/dist/off-grid.js.map +1 -0
- package/dist/outcomes.d.ts +15 -0
- package/dist/outcomes.js +120 -0
- package/dist/outcomes.js.map +1 -0
- package/dist/pairs.js +14 -5
- package/dist/pairs.js.map +1 -1
- package/dist/partition.d.ts +1 -0
- package/dist/partition.js +101 -19
- package/dist/partition.js.map +1 -1
- package/dist/placeholders.d.ts +3 -0
- package/dist/placeholders.js +44 -0
- package/dist/placeholders.js.map +1 -0
- package/dist/proof.d.ts +6 -0
- package/dist/proof.js +282 -56
- package/dist/proof.js.map +1 -1
- package/dist/protocol.d.ts +22 -0
- package/dist/protocol.js +12 -0
- package/dist/protocol.js.map +1 -0
- package/dist/relations.d.ts +30 -0
- package/dist/relations.js +235 -0
- package/dist/relations.js.map +1 -0
- package/dist/replay.d.ts +45 -0
- package/dist/replay.js +157 -0
- package/dist/replay.js.map +1 -0
- package/dist/rewrites.d.ts +41 -0
- package/dist/rewrites.js +180 -0
- package/dist/rewrites.js.map +1 -0
- package/dist/rule.d.ts +74 -11
- package/dist/rule.js +429 -22
- package/dist/rule.js.map +1 -1
- package/dist/runtime.d.ts +12 -0
- package/dist/runtime.js +8 -0
- package/dist/runtime.js.map +1 -0
- package/dist/schema.d.ts +44 -28
- package/dist/schema.js +50 -113
- package/dist/schema.js.map +1 -1
- package/dist/specification.d.ts +23 -3
- package/dist/specification.js +1001 -96
- package/dist/specification.js.map +1 -1
- package/dist/stops.d.ts +20 -0
- package/dist/stops.js +221 -0
- package/dist/stops.js.map +1 -0
- package/dist/temporal-global.d.ts +4 -0
- package/dist/temporal-global.js +11 -0
- package/dist/temporal-global.js.map +1 -0
- package/dist/temporal.d.ts +22 -0
- package/dist/temporal.js +113 -0
- package/dist/temporal.js.map +1 -0
- package/dist/tla-validate.d.ts +31 -0
- package/dist/tla-validate.js +151 -0
- package/dist/tla-validate.js.map +1 -0
- package/dist/tla.d.ts +61 -0
- package/dist/tla.js +722 -0
- package/dist/tla.js.map +1 -0
- package/dist/verification.d.ts +9 -0
- package/dist/verification.js +7 -0
- package/dist/verification.js.map +1 -0
- package/dist/ways.d.ts +11 -5
- package/dist/ways.js +51 -45
- package/dist/ways.js.map +1 -1
- package/dist/world.d.ts +98 -0
- package/dist/world.js +463 -0
- package/dist/world.js.map +1 -0
- package/package.json +49 -10
- package/schema/report.schema.json +169 -1
package/dist/model.js
CHANGED
|
@@ -1,23 +1,59 @@
|
|
|
1
|
-
import { snapshotValue } from "./data.js";
|
|
2
|
-
import { Rational, isRational, fractionOf, decimalOf, EvaluationLimit } from "./exact.js";
|
|
3
|
-
import { DEPS, depsTerm, holds, isDecimal, isTerm, positionData, readOperand, selfTerm, termData, rootTerm, positionTerm, withLocal } from "./rule.js";
|
|
4
|
-
import {
|
|
1
|
+
import { isPromiseLike, snapshotValue } from "./data.js";
|
|
2
|
+
import { Rational, isRational, fractionOf, decimalOf, EvaluationLimit, OutOfRoom, roundedAt } from "./exact.js";
|
|
3
|
+
import { DEPS, depsTerm, describeTerm, holds, rebaseRule, rebaseTerm, pathsRead as pathsReadOfRule, isDecimal, isTerm, linearCombination, positionData, readOperand, selfTerm, substitutedOperand, substitutedRule, termData, rootTerm, positionTerm, withLocal } from "./rule.js";
|
|
4
|
+
import { array, isVariantsSchema } from "./schema.js";
|
|
5
|
+
import { NO_FACTS, outcomesOf } from "./outcomes.js";
|
|
6
|
+
import { countBetween, moveTemporal } from "./temporal.js";
|
|
5
7
|
const EXPRESSION = Symbol.for("chisel.expression");
|
|
6
8
|
function expression(node) {
|
|
7
9
|
return Object.freeze({ [EXPRESSION]: Object.freeze(node) });
|
|
8
10
|
}
|
|
9
11
|
const LOCAL = "#local:";
|
|
10
12
|
let nextLocal = 0;
|
|
11
|
-
|
|
13
|
+
// A local's name says what it holds, for reports (localLabel): a dependency's
|
|
14
|
+
// answer `#local:call:<dependency>:<n>`, an element `#local:<n>@<collection>[]`,
|
|
15
|
+
// an accumulator `#local:<n>@accumulator`, any other `#local:<n>`.
|
|
16
|
+
function localName(value, role) {
|
|
17
|
+
const node = nodeOf(value);
|
|
18
|
+
if (node?.kind === "call")
|
|
19
|
+
return `${LOCAL}call:${dependencyName(node.dependency)}:${nextLocal++}`;
|
|
20
|
+
if (role === "accumulator")
|
|
21
|
+
return `${LOCAL}${nextLocal++}@accumulator`;
|
|
22
|
+
if (role === "element") {
|
|
23
|
+
const position = isTerm(value) ? positionData(value) : undefined;
|
|
24
|
+
const over = position?.measure === "value" && position.path.length > 0 && !position.path[0].startsWith("#") ? `$.${position.path.join(".")}[]` : "element";
|
|
25
|
+
return `${LOCAL}${nextLocal++}@${over}`;
|
|
26
|
+
}
|
|
27
|
+
const described = node?.kind === "choose" ? "choose" : node === undefined ? undefined : describeOperand(value);
|
|
28
|
+
return described === undefined || described === "…" ? `${LOCAL}${nextLocal++}` : `${LOCAL}${nextLocal++}@${described}`;
|
|
29
|
+
}
|
|
30
|
+
function describeOperand(value) {
|
|
31
|
+
if (isTerm(value)) {
|
|
32
|
+
const position = positionData(value);
|
|
33
|
+
if (position === undefined)
|
|
34
|
+
return "…";
|
|
35
|
+
if (position.path[0] === DEPS)
|
|
36
|
+
return ["deps", ...position.path.slice(1)].join(".");
|
|
37
|
+
return position.path.some(key => key.startsWith("#")) ? "…" : describeTerm(value);
|
|
38
|
+
}
|
|
39
|
+
const node = nodeOf(value);
|
|
40
|
+
if (node?.kind === "call")
|
|
41
|
+
return `${dependencyName(node.dependency)}()`;
|
|
42
|
+
if (node?.kind === "operation" || node?.kind === "temporal")
|
|
43
|
+
return `${node.operator}(${describeOperand(node.left)}, ${describeOperand(node.right)})`;
|
|
44
|
+
if (node !== undefined)
|
|
45
|
+
return "…";
|
|
46
|
+
return typeof value === "string" ? JSON.stringify(value) : atom(value) ? String(value) : "…";
|
|
47
|
+
}
|
|
12
48
|
export function bind(schema, value, build) {
|
|
13
|
-
const name = localName();
|
|
49
|
+
const name = localName(value);
|
|
14
50
|
return expression({ kind: "bind", name, schema: schema, value, body: build(rootTerm(name)) });
|
|
15
51
|
}
|
|
16
52
|
export function matchValue(schema, value, cases) {
|
|
17
53
|
const tags = schema.variantTags;
|
|
18
54
|
if (tags.length === 0 || Object.keys(cases).length !== tags.length || tags.some(tag => !Object.hasOwn(cases, tag) || typeof cases[tag] !== "function"))
|
|
19
55
|
throw new Error("matchValue requires exactly one body for every variant");
|
|
20
|
-
const name = localName();
|
|
56
|
+
const name = localName(value);
|
|
21
57
|
const handlers = cases;
|
|
22
58
|
const bodies = tags.map(tag => handlers[tag](rootTerm(name)));
|
|
23
59
|
let body = bodies.at(-1);
|
|
@@ -25,21 +61,56 @@ export function matchValue(schema, value, cases) {
|
|
|
25
61
|
body = expression({ kind: "choose", condition: { kind: "compare", left: positionTerm([name, schema.discriminant], "value"), operator: "==", right: tags[index] }, yes: bodies[index], no: body });
|
|
26
62
|
return expression({ kind: "bind", name, schema, value, body });
|
|
27
63
|
}
|
|
64
|
+
const STEPS = new WeakMap();
|
|
65
|
+
// A step's arguments are named by a tuple: `[Element]` for a map's, and
|
|
66
|
+
// `[Accumulator, Element]` for a fold's, the accumulator first.
|
|
67
|
+
export function step(build) {
|
|
68
|
+
if (typeof build !== "function")
|
|
69
|
+
throw new Error("step takes the step's body as a function of its arguments");
|
|
70
|
+
const value = Object.freeze({ description: "a step handed over as a value" });
|
|
71
|
+
STEPS.set(value, build);
|
|
72
|
+
return value;
|
|
73
|
+
}
|
|
74
|
+
// The step values a choose tree holds, with each leaf made into what `leaf`
|
|
75
|
+
// builds of its body.
|
|
76
|
+
function steppedBy(tree, leaf) {
|
|
77
|
+
const build = typeof tree === "object" && tree !== null ? STEPS.get(tree) : undefined;
|
|
78
|
+
if (build !== undefined)
|
|
79
|
+
return leaf(build);
|
|
80
|
+
const node = nodeOf(tree);
|
|
81
|
+
if (node?.kind === "choose")
|
|
82
|
+
return expression({ kind: "choose", condition: node.condition, yes: steppedBy(node.yes, leaf), no: steppedBy(node.no, leaf) });
|
|
83
|
+
throw new Error("A walk takes a step written in place, one made with step(), or a choice among such steps");
|
|
84
|
+
}
|
|
28
85
|
export function map(element, output, values, build) {
|
|
29
|
-
|
|
86
|
+
if (typeof build !== "function") {
|
|
87
|
+
return bind(array(element), values, list => steppedBy(build, body => map(element, output, list, body)));
|
|
88
|
+
}
|
|
89
|
+
const name = localName(values, "element");
|
|
30
90
|
return expression({ kind: "map", name, element: element, output: output, values, body: build(rootTerm(name)) });
|
|
31
91
|
}
|
|
32
92
|
export function fold(element, output, values, initial, build) {
|
|
33
|
-
|
|
93
|
+
if (typeof build !== "function") {
|
|
94
|
+
return bind(array(element), values, list => bind(output, initial, seed => steppedBy(build, body => fold(element, output, list, seed, body))));
|
|
95
|
+
}
|
|
96
|
+
const name = localName(values, "element"), accumulator = localName(undefined, "accumulator");
|
|
34
97
|
return expression({ kind: "fold", name, accumulator, element: element, output: output, values, initial, body: build(rootTerm(accumulator), rootTerm(name)) });
|
|
35
98
|
}
|
|
36
|
-
export function
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
return
|
|
99
|
+
export function isAnswer(local) {
|
|
100
|
+
return local.startsWith(`${LOCAL}call:`);
|
|
101
|
+
}
|
|
102
|
+
// Each dependency's answer a bind holds outside a map or a fold, by its local's
|
|
103
|
+
// name, with the schema it is bound under and the call it holds the answer of.
|
|
104
|
+
export function bindingsOf(template) {
|
|
105
|
+
return answersOf(template).map(({ name, schema }) => [name, schema]);
|
|
106
|
+
}
|
|
107
|
+
export function answersOf(template) {
|
|
108
|
+
const node = nodeOf(template);
|
|
109
|
+
const call = node?.kind === "bind" ? nodeOf(node.value) : undefined;
|
|
110
|
+
const own = node?.kind === "bind" && call?.kind === "call" && isAnswer(node.name)
|
|
111
|
+
? [{ name: node.name, schema: node.schema, dependency: dependencyName(call.dependency), input: call.input }]
|
|
112
|
+
: [];
|
|
113
|
+
return [...own, ...childrenOf(template).flatMap(answersOf)];
|
|
43
114
|
}
|
|
44
115
|
export function localRoots(value) {
|
|
45
116
|
if (isTerm(value)) {
|
|
@@ -65,14 +136,56 @@ export function dependencyName(dependency) {
|
|
|
65
136
|
return position.path[1];
|
|
66
137
|
}
|
|
67
138
|
export function concat(left, right) {
|
|
139
|
+
evaluators.concat = concatOf;
|
|
68
140
|
return expression({ kind: "operation", operator: "concat", left, right });
|
|
69
141
|
}
|
|
70
142
|
export function arithmetic(operator, left, right) {
|
|
143
|
+
for (const name of ["add", "subtract", "multiply", "divide"])
|
|
144
|
+
evaluators[name] = arithmeticOf;
|
|
71
145
|
return expression({ kind: "operation", operator, left, right });
|
|
72
146
|
}
|
|
147
|
+
function temporalOf(node, left, right) {
|
|
148
|
+
return node.operator === "between" ? countBetween(left, right, node.unit) : moveTemporal(node.operator, left, right, node.unit, node.overflow);
|
|
149
|
+
}
|
|
150
|
+
function temporal(operator, left, right, unit, options = {}) {
|
|
151
|
+
const overflow = options.overflow ?? "constrain";
|
|
152
|
+
// Refused here, as Temporal would refuse it on every run: the proof reads no overflow.
|
|
153
|
+
if (overflow !== "constrain" && overflow !== "reject")
|
|
154
|
+
throw new Error(`${operator} takes an overflow of "constrain" or "reject", not ${String(overflow)}`);
|
|
155
|
+
evaluators.temporal = temporalOf;
|
|
156
|
+
return expression({ kind: "temporal", operator, left, right, unit, overflow });
|
|
157
|
+
}
|
|
158
|
+
export function plus(value, amount, unit, options) {
|
|
159
|
+
return temporal("plus", value, amount, unit, options);
|
|
160
|
+
}
|
|
161
|
+
export function minus(value, amount, unit, options) {
|
|
162
|
+
return temporal("minus", value, amount, unit, options);
|
|
163
|
+
}
|
|
164
|
+
export function between(start, end, unit) {
|
|
165
|
+
return temporal("between", start, end, unit);
|
|
166
|
+
}
|
|
73
167
|
export function quotient(left, right) {
|
|
168
|
+
evaluators.quotient = quotientOf;
|
|
74
169
|
return expression({ kind: "operation", operator: "quotient", left, right });
|
|
75
170
|
}
|
|
171
|
+
const ROUNDINGS = ["half-up", "half-down", "half-even", "up", "down", "ceiling", "floor"];
|
|
172
|
+
// A decimal of `scale` digits after the point, rounded as `mode` says
|
|
173
|
+
// (ADR-0128): a decimal, a rational, an integer or an int64 rounded exactly, at
|
|
174
|
+
// any scale, so it always has an answer.
|
|
175
|
+
export function round(value, scale, mode) {
|
|
176
|
+
if (!Number.isSafeInteger(scale) || scale < 0)
|
|
177
|
+
throw new Error(`round takes a whole number of digits, not ${scale}`);
|
|
178
|
+
if (!ROUNDINGS.includes(mode))
|
|
179
|
+
throw new Error(`round takes a rounding mode of ${ROUNDINGS.join(", ")}, not ${String(mode)}`);
|
|
180
|
+
evaluators.round = roundOf;
|
|
181
|
+
return expression({ kind: "operation", operator: "round", left: value, right: scale, mode });
|
|
182
|
+
}
|
|
183
|
+
// The quotient of two numbers as a decimal of `scale` digits, rounded as
|
|
184
|
+
// `mode` says, as Souther's Decimal.divide is: it has an answer wherever the
|
|
185
|
+
// divisor is not nought.
|
|
186
|
+
export function divide(left, right, scale, mode) {
|
|
187
|
+
return round(quotient(left, right), scale, mode);
|
|
188
|
+
}
|
|
76
189
|
export function nodeOf(value) {
|
|
77
190
|
return typeof value === "object" && value !== null && !isTerm(value)
|
|
78
191
|
? value[EXPRESSION] : undefined;
|
|
@@ -91,14 +204,14 @@ export function childrenOf(value) {
|
|
|
91
204
|
return [node.yes, node.no];
|
|
92
205
|
if (node?.kind === "construct")
|
|
93
206
|
return [node.value];
|
|
94
|
-
if (node?.kind === "operation")
|
|
207
|
+
if (node?.kind === "operation" || node?.kind === "temporal")
|
|
95
208
|
return [node.left, node.right];
|
|
96
209
|
if (isTerm(value) || atom(value))
|
|
97
210
|
return [];
|
|
98
211
|
return Object.values(value);
|
|
99
212
|
}
|
|
100
213
|
export function modelDependencyIssue(template, definition, tags) {
|
|
101
|
-
const inputOwnsRoot = Object.keys(definition.
|
|
214
|
+
const inputOwnsRoot = Object.keys(definition.dependencies).length === 0 && tags.every(tag => definition.input.discriminant === DEPS || Object.hasOwn(definition.input.variants[tag].shape, DEPS));
|
|
102
215
|
const declared = new Set();
|
|
103
216
|
if (tags.some(tag => definition.input.discriminant.startsWith(LOCAL) || Object.keys(definition.input.variants[tag].shape).some(key => key.startsWith(LOCAL))))
|
|
104
217
|
return "Model input uses a reserved local name";
|
|
@@ -112,14 +225,14 @@ export function modelDependencyIssue(template, definition, tags) {
|
|
|
112
225
|
if (path[0] !== DEPS)
|
|
113
226
|
continue;
|
|
114
227
|
const name = path[1];
|
|
115
|
-
if (name === undefined || !Object.hasOwn(definition.
|
|
228
|
+
if (name === undefined || !Object.hasOwn(definition.dependencies, name) || definition.dependencies[name]?.takes !== "nothing")
|
|
116
229
|
return `Model requires a declared value dependency ${name ?? "<root>"}`;
|
|
117
230
|
}
|
|
118
231
|
}
|
|
119
232
|
const node = nodeOf(value);
|
|
120
233
|
if (node?.kind === "call") {
|
|
121
234
|
const name = dependencyName(node.dependency);
|
|
122
|
-
if (!Object.hasOwn(definition.
|
|
235
|
+
if (!Object.hasOwn(definition.dependencies, name) || definition.dependencies[name]?.takes !== "input")
|
|
123
236
|
return "call requires a declared function dependency";
|
|
124
237
|
}
|
|
125
238
|
if (node?.kind === "bind" || node?.kind === "map" || node?.kind === "fold") {
|
|
@@ -127,6 +240,9 @@ export function modelDependencyIssue(template, definition, tags) {
|
|
|
127
240
|
if (names.some(name => declared.has(name)))
|
|
128
241
|
return "Model binding cannot be reused; declare a separate binding for each evaluation";
|
|
129
242
|
names.forEach(name => declared.add(name));
|
|
243
|
+
const refused = node.kind === "bind" ? answerRefusedBy(node.value, node.schema, definition) : undefined;
|
|
244
|
+
if (refused)
|
|
245
|
+
return refused;
|
|
130
246
|
const before = node.kind === "bind" ? [node.value] : node.kind === "map" ? [node.values] : [node.values, node.initial];
|
|
131
247
|
for (const child of before) {
|
|
132
248
|
const issue = inspect(child, locals);
|
|
@@ -149,6 +265,19 @@ export function modelDependencyIssue(template, definition, tags) {
|
|
|
149
265
|
}
|
|
150
266
|
return inspect(template);
|
|
151
267
|
}
|
|
268
|
+
// A call whose answer is a sum bound under a sum sharing none of its cases: every answer fails to bind.
|
|
269
|
+
function answerRefusedBy(value, bound, definition) {
|
|
270
|
+
const call = nodeOf(value);
|
|
271
|
+
if (call?.kind !== "call")
|
|
272
|
+
return undefined;
|
|
273
|
+
const name = dependencyName(call.dependency);
|
|
274
|
+
const output = Object.hasOwn(definition.dependencies, name) ? definition.dependencies[name].output : undefined;
|
|
275
|
+
if (output === undefined || !isVariantsSchema(output) || !isVariantsSchema(bound) || output.discriminant !== bound.discriminant)
|
|
276
|
+
return undefined;
|
|
277
|
+
const declared = output.variantTags;
|
|
278
|
+
return declared.some(tag => bound.variantTags.includes(tag)) ? undefined
|
|
279
|
+
: `Model binds the answer of ${name} under a schema taking none of the cases it declares (${declared.join(", ")}), so every run fails`;
|
|
280
|
+
}
|
|
152
281
|
function atom(value) {
|
|
153
282
|
return value === null || typeof value !== "object" || isDecimal(value) ||
|
|
154
283
|
Object.getPrototypeOf(value) !== Object.prototype && !Array.isArray(value);
|
|
@@ -164,20 +293,22 @@ export function choicesOf(template) {
|
|
|
164
293
|
visit(template);
|
|
165
294
|
return nodes;
|
|
166
295
|
}
|
|
167
|
-
function checkedTemplate(value, ancestors = new Set(), remaining = { value: 10000 }) {
|
|
296
|
+
export function checkedTemplate(value, ancestors = new Set(), remaining = { value: 10000 }) {
|
|
168
297
|
if (--remaining.value < 0)
|
|
169
298
|
throw new Error("Model declaration exceeds 10000 nodes");
|
|
170
299
|
if (typeof value === "function" || typeof value === "symbol")
|
|
171
300
|
throw new Error("Model expressions cannot contain callbacks or symbols");
|
|
301
|
+
if (typeof value === "object" && value !== null && STEPS.has(value))
|
|
302
|
+
throw new Error("A step made with step() is handed to map or fold, not left in a model");
|
|
172
303
|
if (isTerm(value))
|
|
173
304
|
return value;
|
|
174
305
|
if (atom(value)) {
|
|
175
306
|
if (isDecimal(value))
|
|
176
307
|
return snapshotValue(value);
|
|
177
|
-
if (
|
|
178
|
-
if (
|
|
179
|
-
throw new Error("Model
|
|
180
|
-
return value
|
|
308
|
+
if (value instanceof Date) {
|
|
309
|
+
if (Number.isNaN(value.getTime()))
|
|
310
|
+
throw new Error("Model constants cannot be an invalid Date");
|
|
311
|
+
return snapshotValue(value);
|
|
181
312
|
}
|
|
182
313
|
if (value && typeof value === "object" && !isDecimal(value) && !isRational(value) && !String(value.constructor?.name).startsWith("Plain") && value.constructor?.name !== "Instant")
|
|
183
314
|
throw new Error("Unsupported model constant");
|
|
@@ -200,45 +331,117 @@ function checkedTemplate(value, ancestors = new Set(), remaining = { value: 1000
|
|
|
200
331
|
return expression({ ...node, yes: check(node.yes), no: check(node.no) });
|
|
201
332
|
if (node?.kind === "construct")
|
|
202
333
|
return expression({ ...node, value: check(node.value) });
|
|
203
|
-
if (node?.kind === "operation")
|
|
334
|
+
if (node?.kind === "operation" || node?.kind === "temporal")
|
|
204
335
|
return expression({ ...node, left: check(node.left), right: check(node.right) });
|
|
205
336
|
return Object.freeze(Array.isArray(value) ? value.map(check) : Object.fromEntries(Object.entries(value).map(([key, child]) => [key, check(child)])));
|
|
206
337
|
}
|
|
207
338
|
export function model(id, build) {
|
|
208
339
|
const template = checkedTemplate(build(selfTerm(), depsTerm()));
|
|
209
340
|
return Object.freeze({
|
|
210
|
-
kind: "rules", id, expression: template,
|
|
211
|
-
guards:
|
|
341
|
+
kind: "rules", id, expression: template, runs: template,
|
|
342
|
+
guards: guardsOf(template),
|
|
212
343
|
otherwise: () => { throw new Error("Expression models are interpreted"); },
|
|
213
344
|
});
|
|
214
345
|
}
|
|
346
|
+
let walkRewrite;
|
|
347
|
+
let walkObserver;
|
|
348
|
+
export function withWalk(rewrite, observer, run) {
|
|
349
|
+
const [rewriteBefore, observerBefore] = [walkRewrite, walkObserver];
|
|
350
|
+
walkRewrite = rewrite;
|
|
351
|
+
walkObserver = observer;
|
|
352
|
+
try {
|
|
353
|
+
return run();
|
|
354
|
+
}
|
|
355
|
+
finally {
|
|
356
|
+
walkRewrite = rewriteBefore;
|
|
357
|
+
walkObserver = observerBefore;
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
let stopObserver;
|
|
361
|
+
export function withStops(observer, run) {
|
|
362
|
+
const before = stopObserver;
|
|
363
|
+
stopObserver = observer;
|
|
364
|
+
try {
|
|
365
|
+
return run();
|
|
366
|
+
}
|
|
367
|
+
finally {
|
|
368
|
+
stopObserver = before;
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
function stopping(step, compute) {
|
|
372
|
+
if (stopObserver === undefined)
|
|
373
|
+
return compute();
|
|
374
|
+
try {
|
|
375
|
+
return compute();
|
|
376
|
+
}
|
|
377
|
+
catch (error) {
|
|
378
|
+
stopObserver(step, error);
|
|
379
|
+
throw error;
|
|
380
|
+
}
|
|
381
|
+
}
|
|
215
382
|
export function interpret(template, scope, options = {}) {
|
|
216
383
|
let remaining = options.steps ?? 100000;
|
|
217
384
|
const choices = choicesOf(template);
|
|
385
|
+
let distinguishing = options.distinguish;
|
|
218
386
|
function parsed(schema, value) {
|
|
219
387
|
const result = schema.parse(value);
|
|
220
388
|
if (!result.success)
|
|
221
389
|
throw new Error(`Invalid local construction: ${result.issues.map(issue => `${issue.path}: ${issue.message}`).join("; ")}`);
|
|
222
390
|
return snapshotValue(result.value);
|
|
223
391
|
}
|
|
224
|
-
|
|
392
|
+
const inPart = new Set();
|
|
393
|
+
function* read(value, current = scope) {
|
|
225
394
|
if (--remaining < 0)
|
|
226
395
|
throw new EvaluationLimit("Model evaluation step budget exceeded");
|
|
227
396
|
if (isTerm(value))
|
|
228
397
|
return readOperand(value, current);
|
|
229
398
|
const node = nodeOf(value);
|
|
399
|
+
if (node !== undefined && options.parts?.has(node) && !inPart.has(node)) {
|
|
400
|
+
const around = distinguishing;
|
|
401
|
+
const steps = [];
|
|
402
|
+
distinguishing = (distinction, outcome) => steps.push({ distinction, outcome });
|
|
403
|
+
inPart.add(node);
|
|
404
|
+
try {
|
|
405
|
+
return yield* read(value, current);
|
|
406
|
+
}
|
|
407
|
+
finally {
|
|
408
|
+
inPart.delete(node);
|
|
409
|
+
distinguishing = around;
|
|
410
|
+
options.iterate?.(node, steps);
|
|
411
|
+
}
|
|
412
|
+
}
|
|
230
413
|
if (node?.kind === "bind")
|
|
231
|
-
return read(node.body, withLocal(current, node.name, parsed(node.schema, read(node.value, current))));
|
|
414
|
+
return yield* read(node.body, withLocal(current, node.name, parsed(node.schema, yield* read(node.value, current))));
|
|
232
415
|
if (node?.kind === "map" || node?.kind === "fold") {
|
|
233
|
-
const values = read(node.values, current);
|
|
416
|
+
const values = yield* read(node.values, current);
|
|
234
417
|
if (!Array.isArray(values))
|
|
235
418
|
throw new Error("Iteration expects an array");
|
|
236
|
-
let accumulator = node.kind === "fold" ? parsed(node.output, read(node.initial, current)) : undefined;
|
|
419
|
+
let accumulator = node.kind === "fold" ? parsed(node.output, yield* read(node.initial, current)) : undefined;
|
|
420
|
+
const seed = accumulator;
|
|
421
|
+
const walk = node.kind === "fold" && walkRewrite?.node === node ? walkRewrite.walk : undefined;
|
|
422
|
+
if (node.kind === "fold")
|
|
423
|
+
walkObserver?.(node, values.length);
|
|
237
424
|
const result = [];
|
|
238
|
-
for (const value of values) {
|
|
425
|
+
for (const [index, value] of values.entries()) {
|
|
426
|
+
if (walk === "after one step" && index > 0)
|
|
427
|
+
break;
|
|
428
|
+
if (walk === "from the seed")
|
|
429
|
+
accumulator = seed;
|
|
239
430
|
const elementScope = withLocal(current, node.name, parsed(node.element, value));
|
|
240
431
|
const iterationScope = node.kind === "fold" ? withLocal(elementScope, node.accumulator, accumulator) : elementScope;
|
|
241
|
-
const
|
|
432
|
+
const around = distinguishing;
|
|
433
|
+
const steps = [];
|
|
434
|
+
distinguishing = (distinction, outcome) => steps.push({ distinction, outcome });
|
|
435
|
+
let answer;
|
|
436
|
+
try {
|
|
437
|
+
answer = yield* read(node.body, iterationScope);
|
|
438
|
+
}
|
|
439
|
+
finally {
|
|
440
|
+
// An element whose body fails took the way it failed on.
|
|
441
|
+
distinguishing = around;
|
|
442
|
+
options.iterate?.(node, steps);
|
|
443
|
+
}
|
|
444
|
+
const next = parsed(node.output, answer);
|
|
242
445
|
if (node.kind === "fold")
|
|
243
446
|
accumulator = next;
|
|
244
447
|
else
|
|
@@ -249,66 +452,203 @@ export function interpret(template, scope, options = {}) {
|
|
|
249
452
|
if (node?.kind === "call") {
|
|
250
453
|
if (!options.invoke)
|
|
251
454
|
throw new Error("Dependency calls require an execution environment");
|
|
252
|
-
|
|
455
|
+
const answer = options.invoke(dependencyName(node.dependency), yield* read(node.input, current));
|
|
456
|
+
return isPromiseLike(answer) ? yield answer : answer;
|
|
253
457
|
}
|
|
254
458
|
if (node?.kind === "choose") {
|
|
255
|
-
const outcome = holds(node.condition, current, options.observe,
|
|
459
|
+
const outcome = holds(node.condition, current, options.observe, distinguishing);
|
|
256
460
|
options.arm?.(choices.indexOf(node), outcome);
|
|
257
|
-
return read(outcome ? node.yes : node.no, current);
|
|
461
|
+
return yield* read(outcome ? node.yes : node.no, current);
|
|
258
462
|
}
|
|
259
463
|
if (node?.kind === "construct") {
|
|
260
|
-
const
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
464
|
+
const value = yield* read(node.value, current);
|
|
465
|
+
return stopping(node, () => {
|
|
466
|
+
const parsed = node.schema.parse(value);
|
|
467
|
+
if (!parsed.success)
|
|
468
|
+
throw new Error(`Invalid construction: ${parsed.issues.map(issue => `${issue.path}: ${issue.message}`).join("; ")}`);
|
|
469
|
+
return parsed.value;
|
|
470
|
+
});
|
|
471
|
+
}
|
|
472
|
+
if (node?.kind === "temporal") {
|
|
473
|
+
const left = yield* read(node.left, current), right = yield* read(node.right, current);
|
|
474
|
+
return stopping(node, () => evaluate("temporal", node, left, right));
|
|
264
475
|
}
|
|
265
476
|
if (node?.kind === "operation") {
|
|
266
|
-
const left = read(node.left, current), right = read(node.right, current);
|
|
267
|
-
|
|
268
|
-
if (typeof left !== "string" || typeof right !== "string")
|
|
269
|
-
throw new Error("concat expects strings");
|
|
270
|
-
return (left + right).normalize("NFC");
|
|
271
|
-
}
|
|
272
|
-
if (node.operator === "quotient")
|
|
273
|
-
return fractionOf(left).dividedBy(fractionOf(right));
|
|
274
|
-
if (isDecimal(left) && isDecimal(right)) {
|
|
275
|
-
const a = fractionOf(left), b = fractionOf(right);
|
|
276
|
-
return decimalOf(node.operator === "add" ? a.plus(b) : node.operator === "subtract" ? a.minus(b) : node.operator === "multiply" ? a.times(b) : a.dividedBy(b));
|
|
277
|
-
}
|
|
278
|
-
if (isRational(left) && isRational(right))
|
|
279
|
-
return node.operator === "add" ? left.plus(right) : node.operator === "subtract" ? left.minus(right) : node.operator === "multiply" ? left.times(right) : left.dividedBy(right);
|
|
280
|
-
if (typeof left === "bigint" && typeof right === "bigint") {
|
|
281
|
-
if (node.operator === "divide" && (right === 0n || left % right !== 0n))
|
|
282
|
-
throw new Error("Integer division must be exact and nonzero");
|
|
283
|
-
return node.operator === "add" ? left + right : node.operator === "subtract" ? left - right : node.operator === "multiply" ? left * right : left / right;
|
|
284
|
-
}
|
|
285
|
-
if (typeof left !== "number" || typeof right !== "number")
|
|
286
|
-
throw new Error("Arithmetic expects matching numeric types");
|
|
287
|
-
if (node.operator === "divide" && right === 0)
|
|
288
|
-
throw new Error("Division by zero");
|
|
289
|
-
const result = node.operator === "add" ? left + right : node.operator === "subtract" ? left - right : node.operator === "multiply" ? left * right : left / right;
|
|
290
|
-
if (!Number.isFinite(result) || Number.isInteger(result) && !Number.isSafeInteger(result))
|
|
291
|
-
throw new Error("Arithmetic result is outside the exact number range");
|
|
292
|
-
return result;
|
|
477
|
+
const left = yield* read(node.left, current), right = yield* read(node.right, current);
|
|
478
|
+
return stopping(node, () => operate(node, left, right));
|
|
293
479
|
}
|
|
294
480
|
if (atom(value))
|
|
295
481
|
return value;
|
|
296
|
-
|
|
482
|
+
if (Array.isArray(value)) {
|
|
483
|
+
const elements = [];
|
|
484
|
+
for (const child of value)
|
|
485
|
+
elements.push(yield* read(child, current));
|
|
486
|
+
return elements;
|
|
487
|
+
}
|
|
488
|
+
const entries = [];
|
|
489
|
+
for (const [key, child] of Object.entries(value))
|
|
490
|
+
entries.push([key, yield* read(child, current)]);
|
|
491
|
+
return Object.fromEntries(entries);
|
|
492
|
+
}
|
|
493
|
+
const evaluation = read(template);
|
|
494
|
+
const first = evaluation.next();
|
|
495
|
+
if (first.done)
|
|
496
|
+
return first.value;
|
|
497
|
+
if (options.onPending !== undefined) {
|
|
498
|
+
evaluation.return(undefined);
|
|
499
|
+
return options.onPending(first.value);
|
|
500
|
+
}
|
|
501
|
+
return resume(evaluation, first.value);
|
|
502
|
+
}
|
|
503
|
+
// Each builder registers how its node is worked out, so a model that never builds
|
|
504
|
+
// one leaves the arithmetic it needs out of the bundle.
|
|
505
|
+
// Kept on the global object under a registered symbol, as the terms are, since the
|
|
506
|
+
// CLI loads a specification in a module graph of its own.
|
|
507
|
+
const EVALUATORS = Symbol.for("chisel.evaluators");
|
|
508
|
+
const evaluators = (globalThis[EVALUATORS] ??= {});
|
|
509
|
+
function evaluate(operator, node, left, right) {
|
|
510
|
+
const found = evaluators[operator];
|
|
511
|
+
if (found === undefined)
|
|
512
|
+
throw new Error(`No way to work out ${operator}`);
|
|
513
|
+
return found(node, left, right);
|
|
514
|
+
}
|
|
515
|
+
// What the analyses install, since a declaration made with the package root calls none of the builders above that register these.
|
|
516
|
+
export function installEvaluators() {
|
|
517
|
+
evaluators.concat = concatOf;
|
|
518
|
+
for (const name of ["add", "subtract", "multiply", "divide"])
|
|
519
|
+
evaluators[name] = arithmeticOf;
|
|
520
|
+
evaluators.temporal = temporalOf;
|
|
521
|
+
evaluators.quotient = quotientOf;
|
|
522
|
+
evaluators.round = roundOf;
|
|
523
|
+
}
|
|
524
|
+
function operate(node, left, right) {
|
|
525
|
+
try {
|
|
526
|
+
return evaluate(node.operator, node, left, right);
|
|
527
|
+
}
|
|
528
|
+
catch (error) {
|
|
529
|
+
// A whole number larger than the platform builds is a run short of room.
|
|
530
|
+
if (error instanceof RangeError)
|
|
531
|
+
throw new OutOfRoom(`No room to work out ${node.operator}: ${error.message}`);
|
|
532
|
+
throw error;
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
function roundOf(node, left, right) {
|
|
536
|
+
if (typeof left === "number" && !Number.isSafeInteger(left))
|
|
537
|
+
throw new Error("round takes an exact number");
|
|
538
|
+
return decimalOf(roundedAt(fractionOf(left), right, node.mode ?? "half-even"));
|
|
539
|
+
}
|
|
540
|
+
function concatOf(_node, left, right) {
|
|
541
|
+
if (typeof left !== "string" || typeof right !== "string")
|
|
542
|
+
throw new Error("concat expects strings");
|
|
543
|
+
return (left + right).normalize("NFC");
|
|
544
|
+
}
|
|
545
|
+
function quotientOf(_node, left, right) {
|
|
546
|
+
return fractionOf(left).dividedBy(fractionOf(right));
|
|
547
|
+
}
|
|
548
|
+
function arithmeticOf(node, left, right) {
|
|
549
|
+
if (isDecimal(left) && isDecimal(right)) {
|
|
550
|
+
const a = fractionOf(left), b = fractionOf(right);
|
|
551
|
+
return decimalOf(node.operator === "add" ? a.plus(b) : node.operator === "subtract" ? a.minus(b) : node.operator === "multiply" ? a.times(b) : a.dividedBy(b));
|
|
552
|
+
}
|
|
553
|
+
if (isRational(left) && isRational(right))
|
|
554
|
+
return node.operator === "add" ? left.plus(right) : node.operator === "subtract" ? left.minus(right) : node.operator === "multiply" ? left.times(right) : left.dividedBy(right);
|
|
555
|
+
if (typeof left === "bigint" && typeof right === "bigint") {
|
|
556
|
+
if (node.operator === "divide" && (right === 0n || left % right !== 0n))
|
|
557
|
+
throw new Error("Integer division must be exact and nonzero");
|
|
558
|
+
return node.operator === "add" ? left + right : node.operator === "subtract" ? left - right : node.operator === "multiply" ? left * right : left / right;
|
|
559
|
+
}
|
|
560
|
+
if (typeof left !== "number" || typeof right !== "number")
|
|
561
|
+
throw new Error("Arithmetic expects matching numeric types");
|
|
562
|
+
if (node.operator === "divide" && right === 0)
|
|
563
|
+
throw new Error("Division by zero");
|
|
564
|
+
const result = node.operator === "add" ? left + right : node.operator === "subtract" ? left - right : node.operator === "multiply" ? left * right : left / right;
|
|
565
|
+
if (!Number.isFinite(result) || Number.isInteger(result) && !Number.isSafeInteger(result))
|
|
566
|
+
throw new Error("Arithmetic result is outside the exact number range");
|
|
567
|
+
return result;
|
|
568
|
+
}
|
|
569
|
+
async function resume(evaluation, pending) {
|
|
570
|
+
for (;;) {
|
|
571
|
+
let settled;
|
|
572
|
+
try {
|
|
573
|
+
settled = { value: await pending };
|
|
574
|
+
}
|
|
575
|
+
catch (error) {
|
|
576
|
+
settled = { error };
|
|
577
|
+
}
|
|
578
|
+
const step = "error" in settled ? evaluation.throw(settled.error) : evaluation.next(settled.value);
|
|
579
|
+
if (step.done)
|
|
580
|
+
return step.value;
|
|
581
|
+
pending = step.value;
|
|
297
582
|
}
|
|
298
|
-
return read(template);
|
|
299
583
|
}
|
|
300
|
-
|
|
584
|
+
// The parts of a model whose values meet only in its answer: each field of the answer (and each
|
|
585
|
+
// element of a list in it), through plain objects and lists and the bodies of binds of a value
|
|
586
|
+
// that chooses nothing, that holds a choice. No part reads what another computes, so the way a run
|
|
587
|
+
// takes through one never turns on the way it takes through another, and each part's ways are
|
|
588
|
+
// listed on their own rather than combined with every way of every other part. Undefined where
|
|
589
|
+
// fewer than two parts hold a choice, which leaves the model one part, as it always was.
|
|
590
|
+
const partLabels = new WeakMap();
|
|
591
|
+
const partTemplates = new WeakMap();
|
|
592
|
+
const partsCache = new WeakMap();
|
|
593
|
+
export function independentParts(template) {
|
|
594
|
+
if (template === null || typeof template !== "object")
|
|
595
|
+
return undefined;
|
|
596
|
+
const cached = partsCache.get(template);
|
|
597
|
+
if (cached !== undefined)
|
|
598
|
+
return cached ?? undefined;
|
|
599
|
+
const parts = [];
|
|
600
|
+
const collect = (value, at) => {
|
|
601
|
+
const node = nodeOf(value);
|
|
602
|
+
if (node === undefined) {
|
|
603
|
+
if (isTerm(value) || value === null || typeof value !== "object")
|
|
604
|
+
return;
|
|
605
|
+
if (Array.isArray(value))
|
|
606
|
+
value.forEach((child, index) => collect(child, `${at}[${index}]`));
|
|
607
|
+
else
|
|
608
|
+
for (const [key, child] of Object.entries(value))
|
|
609
|
+
collect(child, at === "" ? key : `${at}.${key}`);
|
|
610
|
+
return;
|
|
611
|
+
}
|
|
612
|
+
if (choicesOf(value).length === 0)
|
|
613
|
+
return;
|
|
614
|
+
if (node.kind === "bind" && choicesOf(node.value).length === 0) {
|
|
615
|
+
collect(node.body, at);
|
|
616
|
+
return;
|
|
617
|
+
}
|
|
618
|
+
if (!parts.includes(node)) {
|
|
619
|
+
parts.push(node);
|
|
620
|
+
partTemplates.set(node, value);
|
|
621
|
+
if (!partLabels.has(node))
|
|
622
|
+
partLabels.set(node, at === "" ? "答え" : at);
|
|
623
|
+
}
|
|
624
|
+
};
|
|
625
|
+
collect(template, "");
|
|
626
|
+
const found = parts.length >= 2 ? parts : undefined;
|
|
627
|
+
partsCache.set(template, found ?? null);
|
|
628
|
+
return found;
|
|
629
|
+
}
|
|
630
|
+
export function partTemplate(node) {
|
|
631
|
+
return partTemplates.get(node);
|
|
632
|
+
}
|
|
633
|
+
export function partLabel(node) {
|
|
634
|
+
return node !== null && typeof node === "object" ? partLabels.get(node) : undefined;
|
|
635
|
+
}
|
|
636
|
+
export function isIteration(node) {
|
|
637
|
+
const kind = node?.kind;
|
|
638
|
+
return kind === "map" || kind === "fold";
|
|
639
|
+
}
|
|
640
|
+
export function* modelPaths(template, facts = NO_FACTS) {
|
|
301
641
|
const node = nodeOf(template);
|
|
302
642
|
if (node?.kind === "choose") {
|
|
303
|
-
for (const outcome of outcomesOf(node.condition))
|
|
304
|
-
for (const branch of modelPaths(outcome.result ? node.yes : node.no)) {
|
|
305
|
-
yield { value: branch.value, steps: [...outcome.steps, ...branch.steps], choices: [{ condition: node.condition, outcome: outcome.result }, ...branch.choices] };
|
|
643
|
+
for (const outcome of outcomesOf(node.condition, facts))
|
|
644
|
+
for (const branch of modelPaths(outcome.result ? node.yes : node.no, outcome.facts)) {
|
|
645
|
+
yield { value: branch.value, steps: [...outcome.steps, ...branch.steps], choices: [{ condition: node.condition, outcome: outcome.result }, ...branch.choices], facts: branch.facts };
|
|
306
646
|
}
|
|
307
647
|
return;
|
|
308
648
|
}
|
|
309
649
|
const children = node?.kind === "map" ? [node.values] : node?.kind === "fold" ? [node.values, node.initial] : childrenOf(template);
|
|
310
650
|
if (children.length === 0) {
|
|
311
|
-
yield { value: template, steps: [], choices: [] };
|
|
651
|
+
yield { value: template, steps: [], choices: [], facts };
|
|
312
652
|
return;
|
|
313
653
|
}
|
|
314
654
|
function* product(index, before) {
|
|
@@ -316,12 +656,12 @@ export function* modelPaths(template) {
|
|
|
316
656
|
yield before;
|
|
317
657
|
return;
|
|
318
658
|
}
|
|
319
|
-
for (const child of modelPaths(children[index]))
|
|
320
|
-
yield* product(index + 1, { value: undefined, values: [...before.values, child.value], steps: [...before.steps, ...child.steps], choices: [...before.choices, ...child.choices] });
|
|
659
|
+
for (const child of modelPaths(children[index], before.facts))
|
|
660
|
+
yield* product(index + 1, { value: undefined, values: [...before.values, child.value], steps: [...before.steps, ...child.steps], choices: [...before.choices, ...child.choices], facts: child.facts });
|
|
321
661
|
}
|
|
322
|
-
for (const path of product(0, { value: undefined, values: [], steps: [], choices: [] })) {
|
|
662
|
+
for (const path of product(0, { value: undefined, values: [], steps: [], choices: [], facts })) {
|
|
323
663
|
const value = replaceChildren(template, path.values);
|
|
324
|
-
yield { value, steps: path.steps, choices: path.choices };
|
|
664
|
+
yield { value, steps: path.steps, choices: path.choices, facts: path.facts };
|
|
325
665
|
}
|
|
326
666
|
}
|
|
327
667
|
export function replaceChildren(template, values) {
|
|
@@ -336,8 +676,312 @@ export function replaceChildren(template, values) {
|
|
|
336
676
|
return expression({ ...node, input: values[0] });
|
|
337
677
|
if (node?.kind === "construct")
|
|
338
678
|
return expression({ ...node, value: values[0] });
|
|
339
|
-
if (node?.kind === "operation")
|
|
679
|
+
if (node?.kind === "operation" || node?.kind === "temporal")
|
|
340
680
|
return expression({ ...node, left: values[0], right: values[1] });
|
|
341
681
|
return Array.isArray(template) ? values : Object.fromEntries(Object.keys(template).map((key, index) => [key, values[index]]));
|
|
342
682
|
}
|
|
683
|
+
// What a model binds, read where the binding is read, so its choices are
|
|
684
|
+
// conditions on the input and measured like any guard:
|
|
685
|
+
// - a field of the input is the field itself; bound under another schema than
|
|
686
|
+
// the field's, the binding is kept to parse the field with it;
|
|
687
|
+
// - a sum or difference of input numbers, a multiple of one by a whole number,
|
|
688
|
+
// a constant, or an object of such values is read as that expression, unless
|
|
689
|
+
// it is computed and the schema it is bound under has invariants of its own.
|
|
690
|
+
// A binding of anything else (a quotient, a concatenation, a temporal value,
|
|
691
|
+
// an iteration's answer) is left as it is and read as a value of its own.
|
|
692
|
+
export function inlineInputBindings(template, schemaAt) {
|
|
693
|
+
let inlined = false;
|
|
694
|
+
// Integers and decimals are added exactly at run time as in an expression;
|
|
695
|
+
// a number is added in floating point, so a sum of numbers is not read.
|
|
696
|
+
const kindAt = (path) => schemaAt(path)?.kind;
|
|
697
|
+
const aliasOf = (value) => {
|
|
698
|
+
if (isTerm(value)) {
|
|
699
|
+
const data = termData(value);
|
|
700
|
+
if (data.kind === "position") {
|
|
701
|
+
return data.measure === "value" ? rest => ({ with: rest.length === 0 ? value : positionTerm([...data.path, ...rest], "value") }) : undefined;
|
|
702
|
+
}
|
|
703
|
+
return rest => (rest.length === 0 ? { with: value } : undefined);
|
|
704
|
+
}
|
|
705
|
+
const node = nodeOf(value);
|
|
706
|
+
if (node === undefined) {
|
|
707
|
+
if (atom(value))
|
|
708
|
+
return rest => (rest.length === 0 ? { with: value } : undefined);
|
|
709
|
+
return rest => {
|
|
710
|
+
const [key, ...more] = rest;
|
|
711
|
+
if (key === undefined || !Object.hasOwn(value, key))
|
|
712
|
+
return undefined;
|
|
713
|
+
return aliasOf(value[key])?.(more);
|
|
714
|
+
};
|
|
715
|
+
}
|
|
716
|
+
if (node.kind === "construct")
|
|
717
|
+
return aliasOf(node.value);
|
|
718
|
+
if (node.kind !== "operation" || !["add", "subtract", "multiply", "quotient"].includes(node.operator))
|
|
719
|
+
return undefined;
|
|
720
|
+
const kindOf = (side) => {
|
|
721
|
+
if (typeof side === "number")
|
|
722
|
+
return Number.isSafeInteger(side) ? "either" : undefined;
|
|
723
|
+
if (isDecimal(side))
|
|
724
|
+
return "decimal";
|
|
725
|
+
if (!isTerm(side))
|
|
726
|
+
return undefined;
|
|
727
|
+
const data = termData(side);
|
|
728
|
+
const kinds = new Set((data.kind === "position" ? [data.path] : data.parts.map(part => part.path)).map(path => (path[0].startsWith(LOCAL) ? undefined : kindAt(path))));
|
|
729
|
+
if (data.kind === "linear")
|
|
730
|
+
kinds.add(isDecimal(data.constant) ? "decimal" : "integer");
|
|
731
|
+
return kinds.size === 1 && (kinds.has("integer") || kinds.has("decimal")) ? [...kinds][0] : undefined;
|
|
732
|
+
};
|
|
733
|
+
const left = aliasOf(node.left)?.([]), right = aliasOf(node.right)?.([]);
|
|
734
|
+
if (left === undefined || right === undefined || left.over !== undefined || right.over !== undefined)
|
|
735
|
+
return undefined;
|
|
736
|
+
const [leftKind, rightKind] = [kindOf(left.with), kindOf(right.with)];
|
|
737
|
+
if (leftKind === undefined || rightKind === undefined)
|
|
738
|
+
return undefined;
|
|
739
|
+
// A decimal and a plain number are no sum the model computes as written.
|
|
740
|
+
if (leftKind !== rightKind && leftKind !== "either" && rightKind !== "either")
|
|
741
|
+
return undefined;
|
|
742
|
+
if (node.operator !== "multiply" && (leftKind === "decimal" || rightKind === "decimal") && (leftKind === "either" || rightKind === "either"))
|
|
743
|
+
return undefined;
|
|
744
|
+
if (node.operator === "quotient") {
|
|
745
|
+
// A quotient by a whole number stands in a comparison multiplied out.
|
|
746
|
+
const divisor = right.with;
|
|
747
|
+
return typeof divisor === "number" && Number.isSafeInteger(divisor) && divisor !== 0
|
|
748
|
+
? rest => (rest.length === 0 ? { with: left.with, over: divisor } : undefined)
|
|
749
|
+
: undefined;
|
|
750
|
+
}
|
|
751
|
+
const combined = node.operator === "multiply"
|
|
752
|
+
? (Number.isSafeInteger(right.with) ? linearCombination([{ operand: left.with, coefficient: right.with }])
|
|
753
|
+
: Number.isSafeInteger(left.with) ? linearCombination([{ operand: right.with, coefficient: left.with }]) : undefined)
|
|
754
|
+
: linearCombination([{ operand: left.with, coefficient: 1 }, { operand: right.with, coefficient: node.operator === "add" ? 1 : -1 }]);
|
|
755
|
+
if (combined === undefined)
|
|
756
|
+
return undefined;
|
|
757
|
+
const decimal = leftKind === "decimal" || rightKind === "decimal";
|
|
758
|
+
const exact = decimal && typeof combined === "number" ? decimalOf(fractionOf(combined)) : combined;
|
|
759
|
+
return rest => (rest.length === 0 ? { with: exact } : undefined);
|
|
760
|
+
};
|
|
761
|
+
// A local is bound once, so a condition or a node written in two places is
|
|
762
|
+
// rewritten alike in both, and stands for one rewritten object.
|
|
763
|
+
const rewrittenRules = new Map();
|
|
764
|
+
const rewrittenNodes = new Map();
|
|
765
|
+
const visit = (value, aliases) => {
|
|
766
|
+
const node = nodeOf(value);
|
|
767
|
+
if (node === undefined)
|
|
768
|
+
return rewrite(value, aliases);
|
|
769
|
+
if (!rewrittenNodes.has(node))
|
|
770
|
+
rewrittenNodes.set(node, rewrite(value, aliases));
|
|
771
|
+
return rewrittenNodes.get(node);
|
|
772
|
+
};
|
|
773
|
+
const rewrite = (value, aliases) => {
|
|
774
|
+
const replace = (path) => (path.length > 0 ? aliases.get(path[0])?.(path.slice(1)) : undefined);
|
|
775
|
+
if (isTerm(value)) {
|
|
776
|
+
if (aliases.size === 0)
|
|
777
|
+
return value;
|
|
778
|
+
const found = substitutedOperand(value, replace);
|
|
779
|
+
return found === undefined || found.over !== undefined ? value : found.with;
|
|
780
|
+
}
|
|
781
|
+
const node = nodeOf(value);
|
|
782
|
+
if (node === undefined) {
|
|
783
|
+
if (atom(value))
|
|
784
|
+
return value;
|
|
785
|
+
return Array.isArray(value) ? value.map(item => visit(item, aliases))
|
|
786
|
+
: Object.fromEntries(Object.entries(value).map(([key, child]) => [key, visit(child, aliases)]));
|
|
787
|
+
}
|
|
788
|
+
switch (node.kind) {
|
|
789
|
+
case "bind": {
|
|
790
|
+
const bound = visit(node.value, aliases);
|
|
791
|
+
const position = isTerm(bound) ? positionData(bound) : undefined;
|
|
792
|
+
if (position !== undefined && position.measure === "value" && position.path.length > 0 && !position.path[0].startsWith(LOCAL)) {
|
|
793
|
+
inlined = true;
|
|
794
|
+
// The binding is kept, so the field is still parsed with its schema
|
|
795
|
+
// and a read the field cannot stand in for still reads the local.
|
|
796
|
+
const body = visit(node.body, new Map([...aliases, [node.name, rest => ({ with: positionTerm([...position.path, ...rest], "value") })]]));
|
|
797
|
+
return expression({ ...node, value: bound, body });
|
|
798
|
+
}
|
|
799
|
+
// A computed value bound under a schema with invariants may be one the
|
|
800
|
+
// schema refuses at run time, which the expression it would stand for
|
|
801
|
+
// does not say, so it stays a local of its own.
|
|
802
|
+
const refusable = nodeOf(bound) !== undefined && node.schema.invariants.length > 0;
|
|
803
|
+
const alias = isAnswer(node.name) || refusable ? undefined : aliasOf(bound);
|
|
804
|
+
if (alias !== undefined)
|
|
805
|
+
inlined = true;
|
|
806
|
+
return expression({ ...node, value: bound, body: visit(node.body, alias === undefined ? aliases : new Map([...aliases, [node.name, alias]])) });
|
|
807
|
+
}
|
|
808
|
+
case "choose": {
|
|
809
|
+
if (!rewrittenRules.has(node.condition))
|
|
810
|
+
rewrittenRules.set(node.condition, aliases.size === 0 ? node.condition : substitutedRule(node.condition, replace) ?? node.condition);
|
|
811
|
+
const condition = rewrittenRules.get(node.condition);
|
|
812
|
+
return expression({ ...node, condition, yes: visit(node.yes, aliases), no: visit(node.no, aliases) });
|
|
813
|
+
}
|
|
814
|
+
case "map":
|
|
815
|
+
return expression({ ...node, values: visit(node.values, aliases), body: visit(node.body, aliases) });
|
|
816
|
+
case "fold":
|
|
817
|
+
return expression({ ...node, values: visit(node.values, aliases), initial: visit(node.initial, aliases), body: visit(node.body, aliases) });
|
|
818
|
+
case "call":
|
|
819
|
+
return expression({ ...node, input: visit(node.input, aliases) });
|
|
820
|
+
case "construct":
|
|
821
|
+
return expression({ ...node, value: visit(node.value, aliases) });
|
|
822
|
+
case "operation":
|
|
823
|
+
case "temporal":
|
|
824
|
+
return expression({ ...node, left: visit(node.left, aliases), right: visit(node.right, aliases) });
|
|
825
|
+
}
|
|
826
|
+
};
|
|
827
|
+
const result = visit(template, new Map());
|
|
828
|
+
return inlined ? result : template;
|
|
829
|
+
}
|
|
830
|
+
export function guardsOf(template) {
|
|
831
|
+
return choicesOf(template).map(node => ({ kind: "guard", condition: node.condition, orElse: () => { throw new Error("Expression guards are interpreted"); } }));
|
|
832
|
+
}
|
|
833
|
+
// The calls a model makes, by dependency, with the argument each is written with.
|
|
834
|
+
export function callsIn(template) {
|
|
835
|
+
const node = nodeOf(template);
|
|
836
|
+
const own = node?.kind === "call" ? [{ dependency: dependencyName(node.dependency), input: node.input }] : [];
|
|
837
|
+
return [...own, ...childrenOf(template).flatMap(callsIn)];
|
|
838
|
+
}
|
|
839
|
+
// The input with an argument written so it reads `value`: each field of the
|
|
840
|
+
// input the argument reads takes the part of `value` it stands at, and a
|
|
841
|
+
// constant must already be `value`. Undefined where the argument is computed
|
|
842
|
+
// or reads anything but the input.
|
|
843
|
+
export function writtenArgument(input, argument, value) {
|
|
844
|
+
if (isTerm(argument)) {
|
|
845
|
+
const position = positionData(argument);
|
|
846
|
+
if (position === undefined || position.measure !== "value")
|
|
847
|
+
return undefined;
|
|
848
|
+
const [first] = position.path;
|
|
849
|
+
if (first !== undefined && (first === DEPS || first.startsWith(LOCAL)))
|
|
850
|
+
return undefined;
|
|
851
|
+
return writePath(input, position.path, value);
|
|
852
|
+
}
|
|
853
|
+
if (nodeOf(argument) !== undefined)
|
|
854
|
+
return undefined;
|
|
855
|
+
if (atom(argument))
|
|
856
|
+
return deepEqualValue(argument, value) ? input : undefined;
|
|
857
|
+
if (typeof value !== "object" || value === null || Array.isArray(argument) !== Array.isArray(value))
|
|
858
|
+
return undefined;
|
|
859
|
+
const keys = Object.keys(argument);
|
|
860
|
+
if (keys.length !== Object.keys(value).length)
|
|
861
|
+
return undefined;
|
|
862
|
+
let written = input;
|
|
863
|
+
for (const key of keys) {
|
|
864
|
+
if (!Object.hasOwn(value, key))
|
|
865
|
+
return undefined;
|
|
866
|
+
written = writtenArgument(written, argument[key], value[key]);
|
|
867
|
+
if (written === undefined)
|
|
868
|
+
return undefined;
|
|
869
|
+
}
|
|
870
|
+
return written;
|
|
871
|
+
}
|
|
872
|
+
function writePath(value, path, leaf) {
|
|
873
|
+
const [key, ...rest] = path;
|
|
874
|
+
if (key === undefined)
|
|
875
|
+
return leaf;
|
|
876
|
+
const record = (typeof value === "object" && value !== null ? value : {});
|
|
877
|
+
return { ...record, [key]: writePath(record[key], rest, leaf) };
|
|
878
|
+
}
|
|
879
|
+
function deepEqualValue(left, right) {
|
|
880
|
+
return left === right || (isDecimal(left) && isDecimal(right) && left.equals(right));
|
|
881
|
+
}
|
|
882
|
+
export function* iterationEntries(template, steps = [], facts = NO_FACTS) {
|
|
883
|
+
const node = nodeOf(template);
|
|
884
|
+
if (node?.kind === "choose") {
|
|
885
|
+
// A choice whose branches hold no iteration is not expanded: its outcomes may be far more than any iteration needs.
|
|
886
|
+
if (iterationsOf(node.yes).length === 0 && iterationsOf(node.no).length === 0)
|
|
887
|
+
return;
|
|
888
|
+
for (const outcome of outcomesOf(node.condition, facts))
|
|
889
|
+
yield* iterationEntries(outcome.result ? node.yes : node.no, [...steps, ...outcome.steps], outcome.facts);
|
|
890
|
+
return;
|
|
891
|
+
}
|
|
892
|
+
if (node?.kind === "map" || node?.kind === "fold")
|
|
893
|
+
yield { node, steps };
|
|
894
|
+
for (const child of childrenOf(template))
|
|
895
|
+
yield* iterationEntries(child, steps, facts);
|
|
896
|
+
}
|
|
897
|
+
// Every map and fold in a model, each with the body one element is read in.
|
|
898
|
+
export function iterationsOf(template) {
|
|
899
|
+
const node = nodeOf(template);
|
|
900
|
+
const own = node?.kind === "map" || node?.kind === "fold" ? [node] : [];
|
|
901
|
+
return [...own, ...childrenOf(template).flatMap(iterationsOf)];
|
|
902
|
+
}
|
|
903
|
+
// The values a model reads that no input field holds, each under the schema it
|
|
904
|
+
// takes, besides a dependency's answer: what a bind holds that is read as a
|
|
905
|
+
// value of its own, an element of a map or a fold, and a fold's accumulator.
|
|
906
|
+
// `opaque` where the input settles the value in a way no position shows, so a
|
|
907
|
+
// way reading it is told only by a row taking it: a computed value, an
|
|
908
|
+
// accumulator, and an element of anything but an array the input holds.
|
|
909
|
+
export function localsOf(template, opaque = new Set()) {
|
|
910
|
+
const node = nodeOf(template);
|
|
911
|
+
const rootedIn = (value, seen) => {
|
|
912
|
+
const position = isTerm(value) ? positionData(value) : undefined;
|
|
913
|
+
const first = position?.path[0];
|
|
914
|
+
return position !== undefined && position.measure === "value" && first !== undefined && first !== DEPS && !isAnswer(first) && !seen.has(first);
|
|
915
|
+
};
|
|
916
|
+
if (node?.kind === "bind" && !isAnswer(node.name)) {
|
|
917
|
+
const inner = new Set([...opaque, node.name]);
|
|
918
|
+
return [{ name: node.name, schema: node.schema, opaque: true }, ...childrenOf(template).flatMap(child => localsOf(child, inner))];
|
|
919
|
+
}
|
|
920
|
+
if (node?.kind === "map" || node?.kind === "fold") {
|
|
921
|
+
const elementOpaque = !rootedIn(node.values, opaque);
|
|
922
|
+
const own = [{ name: node.name, schema: node.element, opaque: elementOpaque }, ...(node.kind === "fold" ? [{ name: node.accumulator, schema: node.output, opaque: true }] : [])];
|
|
923
|
+
const inner = new Set([...opaque, ...own.filter(local => local.opaque).map(local => local.name)]);
|
|
924
|
+
return [...own, ...childrenOf(template).flatMap(child => localsOf(child, inner))];
|
|
925
|
+
}
|
|
926
|
+
return childrenOf(template).flatMap(child => localsOf(child, opaque));
|
|
927
|
+
}
|
|
928
|
+
// The top-level input fields a run of the model may turn on: every field it
|
|
929
|
+
// reads, since a value computed before a choice may throw on one, less what a
|
|
930
|
+
// dependency is asked where `matters` says neither its answer nor its refusal
|
|
931
|
+
// of the argument differs with it. Undefined where the model reads the whole
|
|
932
|
+
// input.
|
|
933
|
+
export function fieldsTurnedOn(template, matters = () => true) {
|
|
934
|
+
const fields = new Set();
|
|
935
|
+
let whole = false;
|
|
936
|
+
const add = (path) => {
|
|
937
|
+
if (path.length === 0)
|
|
938
|
+
whole = true;
|
|
939
|
+
else if (!path[0].startsWith(LOCAL) && path[0] !== DEPS)
|
|
940
|
+
fields.add(path[0]);
|
|
941
|
+
};
|
|
942
|
+
const visit = (value) => {
|
|
943
|
+
if (isTerm(value)) {
|
|
944
|
+
const data = termData(value);
|
|
945
|
+
(data.kind === "position" ? [data.path] : data.parts.map(part => part.path)).forEach(add);
|
|
946
|
+
return;
|
|
947
|
+
}
|
|
948
|
+
const node = nodeOf(value);
|
|
949
|
+
if (node?.kind === "choose")
|
|
950
|
+
pathsReadOfRule(node.condition).forEach(add);
|
|
951
|
+
if (node?.kind === "call" && !matters(dependencyName(node.dependency), node.input))
|
|
952
|
+
return;
|
|
953
|
+
childrenOf(value).forEach(visit);
|
|
954
|
+
};
|
|
955
|
+
visit(template);
|
|
956
|
+
return whole ? undefined : fields;
|
|
957
|
+
}
|
|
958
|
+
export function translationOf(written, rewritten) {
|
|
959
|
+
const rules = new Map();
|
|
960
|
+
const nodes = new Map();
|
|
961
|
+
const pairRules = (a, b) => {
|
|
962
|
+
if (a === b)
|
|
963
|
+
return;
|
|
964
|
+
rules.set(a, b);
|
|
965
|
+
if ((a.kind === "and" || a.kind === "or") && (b.kind === "and" || b.kind === "or"))
|
|
966
|
+
a.rules.forEach((part, index) => b.rules[index] && pairRules(part, b.rules[index]));
|
|
967
|
+
if (a.kind === "not" && b.kind === "not")
|
|
968
|
+
pairRules(a.rule, b.rule);
|
|
969
|
+
if ((a.kind === "all" || a.kind === "any") && (b.kind === "all" || b.kind === "any"))
|
|
970
|
+
pairRules(a.each, b.each);
|
|
971
|
+
};
|
|
972
|
+
const walk = (a, b) => {
|
|
973
|
+
if (a === b)
|
|
974
|
+
return;
|
|
975
|
+
const left = nodeOf(a), right = nodeOf(b);
|
|
976
|
+
if (left !== undefined && right !== undefined) {
|
|
977
|
+
nodes.set(left, right);
|
|
978
|
+
if (left.kind === "choose" && right.kind === "choose")
|
|
979
|
+
pairRules(left.condition, right.condition);
|
|
980
|
+
}
|
|
981
|
+
const [first, second] = [childrenOf(a), childrenOf(b)];
|
|
982
|
+
first.forEach((child, index) => walk(child, second[index]));
|
|
983
|
+
};
|
|
984
|
+
walk(written, rewritten);
|
|
985
|
+
return { rules, nodes };
|
|
986
|
+
}
|
|
343
987
|
//# sourceMappingURL=model.js.map
|