@toiroakr/chisel 0.1.0 → 0.2.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 +249 -20
- package/dist/absence.d.ts +27 -0
- package/dist/absence.js +228 -0
- package/dist/absence.js.map +1 -0
- package/dist/behavior.d.ts +21 -9
- package/dist/behavior.js +219 -52
- package/dist/behavior.js.map +1 -1
- package/dist/border.d.ts +4 -7
- package/dist/border.js +43 -35
- package/dist/border.js.map +1 -1
- package/dist/bounds.d.ts +1 -0
- package/dist/bounds.js +26 -0
- package/dist/bounds.js.map +1 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +272 -4
- package/dist/cli.js.map +1 -1
- package/dist/codec.js +7 -4
- package/dist/codec.js.map +1 -1
- package/dist/codegen.js +4 -8
- package/dist/codegen.js.map +1 -1
- package/dist/composition.d.ts +3 -3
- package/dist/composition.js +4 -4
- package/dist/composition.js.map +1 -1
- package/dist/data.d.ts +1 -0
- package/dist/data.js +2 -0
- package/dist/data.js.map +1 -1
- 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 +5 -1
- package/dist/domain.js +6 -6
- package/dist/domain.js.map +1 -1
- package/dist/ensures.js +2 -2
- 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/feasibility.d.ts +5 -3
- package/dist/feasibility.js +106 -37
- package/dist/feasibility.js.map +1 -1
- package/dist/guard-borders.d.ts +12 -5
- package/dist/guard-borders.js +122 -171
- package/dist/guard-borders.js.map +1 -1
- package/dist/guard-scope.d.ts +61 -0
- package/dist/guard-scope.js +364 -0
- package/dist/guard-scope.js.map +1 -0
- package/dist/index.d.ts +17 -6
- package/dist/index.js +8 -3
- 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 +7 -0
- package/dist/interval.js +171 -21
- package/dist/interval.js.map +1 -1
- package/dist/isolated.js.map +1 -1
- 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 +97 -0
- package/dist/machine.js +200 -0
- package/dist/machine.js.map +1 -0
- package/dist/model.d.ts +74 -9
- package/dist/model.js +469 -34
- package/dist/model.js.map +1 -1
- package/dist/outcomes.d.ts +7 -0
- package/dist/outcomes.js +38 -0
- package/dist/outcomes.js.map +1 -0
- package/dist/pairs.js +12 -4
- package/dist/pairs.js.map +1 -1
- package/dist/partition.d.ts +1 -0
- package/dist/partition.js +90 -11
- package/dist/partition.js.map +1 -1
- package/dist/proof.d.ts +6 -0
- package/dist/proof.js +96 -22
- package/dist/proof.js.map +1 -1
- package/dist/replay.d.ts +45 -0
- package/dist/replay.js +157 -0
- package/dist/replay.js.map +1 -0
- package/dist/rule.d.ts +47 -7
- package/dist/rule.js +284 -17
- 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.js +16 -12
- package/dist/schema.js.map +1 -1
- package/dist/specification.d.ts +12 -2
- package/dist/specification.js +622 -82
- package/dist/specification.js.map +1 -1
- 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.d.ts +54 -0
- package/dist/tla.js +579 -0
- package/dist/tla.js.map +1 -0
- package/dist/verification.d.ts +7 -0
- package/dist/verification.js +5 -0
- package/dist/verification.js.map +1 -0
- package/dist/ways.d.ts +8 -5
- package/dist/ways.js +30 -39
- package/dist/ways.js.map +1 -1
- package/dist/world.d.ts +98 -0
- package/dist/world.js +467 -0
- package/dist/world.js.map +1 -0
- package/package.json +32 -9
package/dist/model.js
CHANGED
|
@@ -1,23 +1,59 @@
|
|
|
1
|
-
import { snapshotValue } from "./data.js";
|
|
1
|
+
import { isPromiseLike, snapshotValue } from "./data.js";
|
|
2
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 {
|
|
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 { isVariantsSchema } from "./schema.js";
|
|
5
|
+
import { 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);
|
|
@@ -26,20 +62,28 @@ export function matchValue(schema, value, cases) {
|
|
|
26
62
|
return expression({ kind: "bind", name, schema, value, body });
|
|
27
63
|
}
|
|
28
64
|
export function map(element, output, values, build) {
|
|
29
|
-
const name = localName();
|
|
65
|
+
const name = localName(values, "element");
|
|
30
66
|
return expression({ kind: "map", name, element: element, output: output, values, body: build(rootTerm(name)) });
|
|
31
67
|
}
|
|
32
68
|
export function fold(element, output, values, initial, build) {
|
|
33
|
-
const name = localName(), accumulator = localName();
|
|
69
|
+
const name = localName(values, "element"), accumulator = localName(undefined, "accumulator");
|
|
34
70
|
return expression({ kind: "fold", name, accumulator, element: element, output: output, values, initial, body: build(rootTerm(accumulator), rootTerm(name)) });
|
|
35
71
|
}
|
|
36
|
-
export function
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
return
|
|
72
|
+
export function isAnswer(local) {
|
|
73
|
+
return local.startsWith(`${LOCAL}call:`);
|
|
74
|
+
}
|
|
75
|
+
// Each dependency's answer a bind holds outside a map or a fold, by its local's
|
|
76
|
+
// name, with the schema it is bound under and the call it holds the answer of.
|
|
77
|
+
export function bindingsOf(template) {
|
|
78
|
+
return answersOf(template).map(({ name, schema }) => [name, schema]);
|
|
79
|
+
}
|
|
80
|
+
export function answersOf(template) {
|
|
81
|
+
const node = nodeOf(template);
|
|
82
|
+
const call = node?.kind === "bind" ? nodeOf(node.value) : undefined;
|
|
83
|
+
const own = node?.kind === "bind" && call?.kind === "call" && isAnswer(node.name)
|
|
84
|
+
? [{ name: node.name, schema: node.schema, dependency: dependencyName(call.dependency), input: call.input }]
|
|
85
|
+
: [];
|
|
86
|
+
return [...own, ...childrenOf(template).flatMap(answersOf)];
|
|
43
87
|
}
|
|
44
88
|
export function localRoots(value) {
|
|
45
89
|
if (isTerm(value)) {
|
|
@@ -70,6 +114,22 @@ export function concat(left, right) {
|
|
|
70
114
|
export function arithmetic(operator, left, right) {
|
|
71
115
|
return expression({ kind: "operation", operator, left, right });
|
|
72
116
|
}
|
|
117
|
+
function temporal(operator, left, right, unit, options = {}) {
|
|
118
|
+
const overflow = options.overflow ?? "constrain";
|
|
119
|
+
// Refused here, as Temporal would refuse it on every run: the proof reads no overflow.
|
|
120
|
+
if (overflow !== "constrain" && overflow !== "reject")
|
|
121
|
+
throw new Error(`${operator} takes an overflow of "constrain" or "reject", not ${String(overflow)}`);
|
|
122
|
+
return expression({ kind: "temporal", operator, left, right, unit, overflow });
|
|
123
|
+
}
|
|
124
|
+
export function plus(value, amount, unit, options) {
|
|
125
|
+
return temporal("plus", value, amount, unit, options);
|
|
126
|
+
}
|
|
127
|
+
export function minus(value, amount, unit, options) {
|
|
128
|
+
return temporal("minus", value, amount, unit, options);
|
|
129
|
+
}
|
|
130
|
+
export function between(start, end, unit) {
|
|
131
|
+
return temporal("between", start, end, unit);
|
|
132
|
+
}
|
|
73
133
|
export function quotient(left, right) {
|
|
74
134
|
return expression({ kind: "operation", operator: "quotient", left, right });
|
|
75
135
|
}
|
|
@@ -91,14 +151,14 @@ export function childrenOf(value) {
|
|
|
91
151
|
return [node.yes, node.no];
|
|
92
152
|
if (node?.kind === "construct")
|
|
93
153
|
return [node.value];
|
|
94
|
-
if (node?.kind === "operation")
|
|
154
|
+
if (node?.kind === "operation" || node?.kind === "temporal")
|
|
95
155
|
return [node.left, node.right];
|
|
96
156
|
if (isTerm(value) || atom(value))
|
|
97
157
|
return [];
|
|
98
158
|
return Object.values(value);
|
|
99
159
|
}
|
|
100
160
|
export function modelDependencyIssue(template, definition, tags) {
|
|
101
|
-
const inputOwnsRoot = Object.keys(definition.
|
|
161
|
+
const inputOwnsRoot = Object.keys(definition.dependencies).length === 0 && tags.every(tag => definition.input.discriminant === DEPS || Object.hasOwn(definition.input.variants[tag].shape, DEPS));
|
|
102
162
|
const declared = new Set();
|
|
103
163
|
if (tags.some(tag => definition.input.discriminant.startsWith(LOCAL) || Object.keys(definition.input.variants[tag].shape).some(key => key.startsWith(LOCAL))))
|
|
104
164
|
return "Model input uses a reserved local name";
|
|
@@ -112,14 +172,14 @@ export function modelDependencyIssue(template, definition, tags) {
|
|
|
112
172
|
if (path[0] !== DEPS)
|
|
113
173
|
continue;
|
|
114
174
|
const name = path[1];
|
|
115
|
-
if (name === undefined || !Object.hasOwn(definition.
|
|
175
|
+
if (name === undefined || !Object.hasOwn(definition.dependencies, name) || definition.dependencies[name]?.takes !== "nothing")
|
|
116
176
|
return `Model requires a declared value dependency ${name ?? "<root>"}`;
|
|
117
177
|
}
|
|
118
178
|
}
|
|
119
179
|
const node = nodeOf(value);
|
|
120
180
|
if (node?.kind === "call") {
|
|
121
181
|
const name = dependencyName(node.dependency);
|
|
122
|
-
if (!Object.hasOwn(definition.
|
|
182
|
+
if (!Object.hasOwn(definition.dependencies, name) || definition.dependencies[name]?.takes !== "input")
|
|
123
183
|
return "call requires a declared function dependency";
|
|
124
184
|
}
|
|
125
185
|
if (node?.kind === "bind" || node?.kind === "map" || node?.kind === "fold") {
|
|
@@ -127,6 +187,9 @@ export function modelDependencyIssue(template, definition, tags) {
|
|
|
127
187
|
if (names.some(name => declared.has(name)))
|
|
128
188
|
return "Model binding cannot be reused; declare a separate binding for each evaluation";
|
|
129
189
|
names.forEach(name => declared.add(name));
|
|
190
|
+
const refused = node.kind === "bind" ? answerRefusedBy(node.value, node.schema, definition) : undefined;
|
|
191
|
+
if (refused)
|
|
192
|
+
return refused;
|
|
130
193
|
const before = node.kind === "bind" ? [node.value] : node.kind === "map" ? [node.values] : [node.values, node.initial];
|
|
131
194
|
for (const child of before) {
|
|
132
195
|
const issue = inspect(child, locals);
|
|
@@ -149,6 +212,19 @@ export function modelDependencyIssue(template, definition, tags) {
|
|
|
149
212
|
}
|
|
150
213
|
return inspect(template);
|
|
151
214
|
}
|
|
215
|
+
// A call whose answer is a sum bound under a sum sharing none of its cases: every answer fails to bind.
|
|
216
|
+
function answerRefusedBy(value, bound, definition) {
|
|
217
|
+
const call = nodeOf(value);
|
|
218
|
+
if (call?.kind !== "call")
|
|
219
|
+
return undefined;
|
|
220
|
+
const name = dependencyName(call.dependency);
|
|
221
|
+
const output = Object.hasOwn(definition.dependencies, name) ? definition.dependencies[name].output : undefined;
|
|
222
|
+
if (output === undefined || !isVariantsSchema(output) || !isVariantsSchema(bound) || output.discriminant !== bound.discriminant)
|
|
223
|
+
return undefined;
|
|
224
|
+
const declared = output.variantTags;
|
|
225
|
+
return declared.some(tag => bound.variantTags.includes(tag)) ? undefined
|
|
226
|
+
: `Model binds the answer of ${name} under a schema taking none of the cases it declares (${declared.join(", ")}), so every run fails`;
|
|
227
|
+
}
|
|
152
228
|
function atom(value) {
|
|
153
229
|
return value === null || typeof value !== "object" || isDecimal(value) ||
|
|
154
230
|
Object.getPrototypeOf(value) !== Object.prototype && !Array.isArray(value);
|
|
@@ -200,7 +276,7 @@ function checkedTemplate(value, ancestors = new Set(), remaining = { value: 1000
|
|
|
200
276
|
return expression({ ...node, yes: check(node.yes), no: check(node.no) });
|
|
201
277
|
if (node?.kind === "construct")
|
|
202
278
|
return expression({ ...node, value: check(node.value) });
|
|
203
|
-
if (node?.kind === "operation")
|
|
279
|
+
if (node?.kind === "operation" || node?.kind === "temporal")
|
|
204
280
|
return expression({ ...node, left: check(node.left), right: check(node.right) });
|
|
205
281
|
return Object.freeze(Array.isArray(value) ? value.map(check) : Object.fromEntries(Object.entries(value).map(([key, child]) => [key, check(child)])));
|
|
206
282
|
}
|
|
@@ -208,37 +284,55 @@ export function model(id, build) {
|
|
|
208
284
|
const template = checkedTemplate(build(selfTerm(), depsTerm()));
|
|
209
285
|
return Object.freeze({
|
|
210
286
|
kind: "rules", id, expression: template,
|
|
211
|
-
guards:
|
|
287
|
+
guards: guardsOf(template),
|
|
212
288
|
otherwise: () => { throw new Error("Expression models are interpreted"); },
|
|
213
289
|
});
|
|
214
290
|
}
|
|
291
|
+
// Evaluates an expression model. A dependency call that answers a promise is
|
|
292
|
+
// awaited, and the evaluation then answers a promise too; one that answers a
|
|
293
|
+
// value continues at once, so a model whose dependencies answer values (or
|
|
294
|
+
// that calls none) is evaluated synchronously, as the analyses that trace it
|
|
295
|
+
// need. `read` is a generator that yields only a pending call.
|
|
215
296
|
export function interpret(template, scope, options = {}) {
|
|
216
297
|
let remaining = options.steps ?? 100000;
|
|
217
298
|
const choices = choicesOf(template);
|
|
299
|
+
let distinguishing = options.distinguish;
|
|
218
300
|
function parsed(schema, value) {
|
|
219
301
|
const result = schema.parse(value);
|
|
220
302
|
if (!result.success)
|
|
221
303
|
throw new Error(`Invalid local construction: ${result.issues.map(issue => `${issue.path}: ${issue.message}`).join("; ")}`);
|
|
222
304
|
return snapshotValue(result.value);
|
|
223
305
|
}
|
|
224
|
-
function read(value, current = scope) {
|
|
306
|
+
function* read(value, current = scope) {
|
|
225
307
|
if (--remaining < 0)
|
|
226
308
|
throw new EvaluationLimit("Model evaluation step budget exceeded");
|
|
227
309
|
if (isTerm(value))
|
|
228
310
|
return readOperand(value, current);
|
|
229
311
|
const node = nodeOf(value);
|
|
230
312
|
if (node?.kind === "bind")
|
|
231
|
-
return read(node.body, withLocal(current, node.name, parsed(node.schema, read(node.value, current))));
|
|
313
|
+
return yield* read(node.body, withLocal(current, node.name, parsed(node.schema, yield* read(node.value, current))));
|
|
232
314
|
if (node?.kind === "map" || node?.kind === "fold") {
|
|
233
|
-
const values = read(node.values, current);
|
|
315
|
+
const values = yield* read(node.values, current);
|
|
234
316
|
if (!Array.isArray(values))
|
|
235
317
|
throw new Error("Iteration expects an array");
|
|
236
|
-
let accumulator = node.kind === "fold" ? parsed(node.output, read(node.initial, current)) : undefined;
|
|
318
|
+
let accumulator = node.kind === "fold" ? parsed(node.output, yield* read(node.initial, current)) : undefined;
|
|
237
319
|
const result = [];
|
|
238
320
|
for (const value of values) {
|
|
239
321
|
const elementScope = withLocal(current, node.name, parsed(node.element, value));
|
|
240
322
|
const iterationScope = node.kind === "fold" ? withLocal(elementScope, node.accumulator, accumulator) : elementScope;
|
|
241
|
-
const
|
|
323
|
+
const around = distinguishing;
|
|
324
|
+
const steps = [];
|
|
325
|
+
distinguishing = (distinction, outcome) => steps.push({ distinction, outcome });
|
|
326
|
+
let answer;
|
|
327
|
+
try {
|
|
328
|
+
answer = yield* read(node.body, iterationScope);
|
|
329
|
+
}
|
|
330
|
+
finally {
|
|
331
|
+
// An element whose body fails took the way it failed on.
|
|
332
|
+
distinguishing = around;
|
|
333
|
+
options.iterate?.(node, steps);
|
|
334
|
+
}
|
|
335
|
+
const next = parsed(node.output, answer);
|
|
242
336
|
if (node.kind === "fold")
|
|
243
337
|
accumulator = next;
|
|
244
338
|
else
|
|
@@ -249,21 +343,26 @@ export function interpret(template, scope, options = {}) {
|
|
|
249
343
|
if (node?.kind === "call") {
|
|
250
344
|
if (!options.invoke)
|
|
251
345
|
throw new Error("Dependency calls require an execution environment");
|
|
252
|
-
|
|
346
|
+
const answer = options.invoke(dependencyName(node.dependency), yield* read(node.input, current));
|
|
347
|
+
return isPromiseLike(answer) ? yield answer : answer;
|
|
253
348
|
}
|
|
254
349
|
if (node?.kind === "choose") {
|
|
255
|
-
const outcome = holds(node.condition, current, options.observe,
|
|
350
|
+
const outcome = holds(node.condition, current, options.observe, distinguishing);
|
|
256
351
|
options.arm?.(choices.indexOf(node), outcome);
|
|
257
|
-
return read(outcome ? node.yes : node.no, current);
|
|
352
|
+
return yield* read(outcome ? node.yes : node.no, current);
|
|
258
353
|
}
|
|
259
354
|
if (node?.kind === "construct") {
|
|
260
|
-
const parsed = node.schema.parse(read(node.value, current));
|
|
355
|
+
const parsed = node.schema.parse(yield* read(node.value, current));
|
|
261
356
|
if (!parsed.success)
|
|
262
357
|
throw new Error(`Invalid construction: ${parsed.issues.map(issue => `${issue.path}: ${issue.message}`).join("; ")}`);
|
|
263
358
|
return parsed.value;
|
|
264
359
|
}
|
|
360
|
+
if (node?.kind === "temporal") {
|
|
361
|
+
const left = yield* read(node.left, current), right = yield* read(node.right, current);
|
|
362
|
+
return node.operator === "between" ? countBetween(left, right, node.unit) : moveTemporal(node.operator, left, right, node.unit, node.overflow);
|
|
363
|
+
}
|
|
265
364
|
if (node?.kind === "operation") {
|
|
266
|
-
const left = read(node.left, current), right = read(node.right, current);
|
|
365
|
+
const left = yield* read(node.left, current), right = yield* read(node.right, current);
|
|
267
366
|
if (node.operator === "concat") {
|
|
268
367
|
if (typeof left !== "string" || typeof right !== "string")
|
|
269
368
|
throw new Error("concat expects strings");
|
|
@@ -293,9 +392,41 @@ export function interpret(template, scope, options = {}) {
|
|
|
293
392
|
}
|
|
294
393
|
if (atom(value))
|
|
295
394
|
return value;
|
|
296
|
-
|
|
395
|
+
if (Array.isArray(value)) {
|
|
396
|
+
const elements = [];
|
|
397
|
+
for (const child of value)
|
|
398
|
+
elements.push(yield* read(child, current));
|
|
399
|
+
return elements;
|
|
400
|
+
}
|
|
401
|
+
const entries = [];
|
|
402
|
+
for (const [key, child] of Object.entries(value))
|
|
403
|
+
entries.push([key, yield* read(child, current)]);
|
|
404
|
+
return Object.fromEntries(entries);
|
|
405
|
+
}
|
|
406
|
+
const evaluation = read(template);
|
|
407
|
+
const first = evaluation.next();
|
|
408
|
+
if (first.done)
|
|
409
|
+
return first.value;
|
|
410
|
+
if (options.onPending !== undefined) {
|
|
411
|
+
evaluation.return(undefined);
|
|
412
|
+
return options.onPending(first.value);
|
|
413
|
+
}
|
|
414
|
+
return resume(evaluation, first.value);
|
|
415
|
+
}
|
|
416
|
+
async function resume(evaluation, pending) {
|
|
417
|
+
for (;;) {
|
|
418
|
+
let settled;
|
|
419
|
+
try {
|
|
420
|
+
settled = { value: await pending };
|
|
421
|
+
}
|
|
422
|
+
catch (error) {
|
|
423
|
+
settled = { error };
|
|
424
|
+
}
|
|
425
|
+
const step = "error" in settled ? evaluation.throw(settled.error) : evaluation.next(settled.value);
|
|
426
|
+
if (step.done)
|
|
427
|
+
return step.value;
|
|
428
|
+
pending = step.value;
|
|
297
429
|
}
|
|
298
|
-
return read(template);
|
|
299
430
|
}
|
|
300
431
|
export function* modelPaths(template) {
|
|
301
432
|
const node = nodeOf(template);
|
|
@@ -336,8 +467,312 @@ export function replaceChildren(template, values) {
|
|
|
336
467
|
return expression({ ...node, input: values[0] });
|
|
337
468
|
if (node?.kind === "construct")
|
|
338
469
|
return expression({ ...node, value: values[0] });
|
|
339
|
-
if (node?.kind === "operation")
|
|
470
|
+
if (node?.kind === "operation" || node?.kind === "temporal")
|
|
340
471
|
return expression({ ...node, left: values[0], right: values[1] });
|
|
341
472
|
return Array.isArray(template) ? values : Object.fromEntries(Object.keys(template).map((key, index) => [key, values[index]]));
|
|
342
473
|
}
|
|
474
|
+
// What a model binds, read where the binding is read, so its choices are
|
|
475
|
+
// conditions on the input and measured like any guard:
|
|
476
|
+
// - a field of the input is the field itself; bound under another schema than
|
|
477
|
+
// the field's, the binding is kept to parse the field with it;
|
|
478
|
+
// - a sum or difference of input numbers, a multiple of one by a whole number,
|
|
479
|
+
// a constant, or an object of such values is read as that expression, unless
|
|
480
|
+
// it is computed and the schema it is bound under has invariants of its own.
|
|
481
|
+
// A binding of anything else (a quotient, a concatenation, a temporal value,
|
|
482
|
+
// an iteration's answer) is left as it is and read as a value of its own.
|
|
483
|
+
export function inlineInputBindings(template, schemaAt) {
|
|
484
|
+
let inlined = false;
|
|
485
|
+
// Integers and decimals are added exactly at run time as in an expression;
|
|
486
|
+
// a number is added in floating point, so a sum of numbers is not read.
|
|
487
|
+
const kindAt = (path) => schemaAt(path)?.kind;
|
|
488
|
+
const aliasOf = (value) => {
|
|
489
|
+
if (isTerm(value)) {
|
|
490
|
+
const data = termData(value);
|
|
491
|
+
if (data.kind === "position") {
|
|
492
|
+
return data.measure === "value" ? rest => ({ with: rest.length === 0 ? value : positionTerm([...data.path, ...rest], "value") }) : undefined;
|
|
493
|
+
}
|
|
494
|
+
return rest => (rest.length === 0 ? { with: value } : undefined);
|
|
495
|
+
}
|
|
496
|
+
const node = nodeOf(value);
|
|
497
|
+
if (node === undefined) {
|
|
498
|
+
if (atom(value))
|
|
499
|
+
return rest => (rest.length === 0 ? { with: value } : undefined);
|
|
500
|
+
return rest => {
|
|
501
|
+
const [key, ...more] = rest;
|
|
502
|
+
if (key === undefined || !Object.hasOwn(value, key))
|
|
503
|
+
return undefined;
|
|
504
|
+
return aliasOf(value[key])?.(more);
|
|
505
|
+
};
|
|
506
|
+
}
|
|
507
|
+
if (node.kind === "construct")
|
|
508
|
+
return aliasOf(node.value);
|
|
509
|
+
if (node.kind !== "operation" || !["add", "subtract", "multiply", "quotient"].includes(node.operator))
|
|
510
|
+
return undefined;
|
|
511
|
+
const kindOf = (side) => {
|
|
512
|
+
if (typeof side === "number")
|
|
513
|
+
return Number.isSafeInteger(side) ? "either" : undefined;
|
|
514
|
+
if (isDecimal(side))
|
|
515
|
+
return "decimal";
|
|
516
|
+
if (!isTerm(side))
|
|
517
|
+
return undefined;
|
|
518
|
+
const data = termData(side);
|
|
519
|
+
const kinds = new Set((data.kind === "position" ? [data.path] : data.parts.map(part => part.path)).map(path => (path[0].startsWith(LOCAL) ? undefined : kindAt(path))));
|
|
520
|
+
if (data.kind === "linear")
|
|
521
|
+
kinds.add(isDecimal(data.constant) ? "decimal" : "integer");
|
|
522
|
+
return kinds.size === 1 && (kinds.has("integer") || kinds.has("decimal")) ? [...kinds][0] : undefined;
|
|
523
|
+
};
|
|
524
|
+
const left = aliasOf(node.left)?.([]), right = aliasOf(node.right)?.([]);
|
|
525
|
+
if (left === undefined || right === undefined || left.over !== undefined || right.over !== undefined)
|
|
526
|
+
return undefined;
|
|
527
|
+
const [leftKind, rightKind] = [kindOf(left.with), kindOf(right.with)];
|
|
528
|
+
if (leftKind === undefined || rightKind === undefined)
|
|
529
|
+
return undefined;
|
|
530
|
+
// A decimal and a plain number are no sum the model computes as written.
|
|
531
|
+
if (leftKind !== rightKind && leftKind !== "either" && rightKind !== "either")
|
|
532
|
+
return undefined;
|
|
533
|
+
if (node.operator !== "multiply" && (leftKind === "decimal" || rightKind === "decimal") && (leftKind === "either" || rightKind === "either"))
|
|
534
|
+
return undefined;
|
|
535
|
+
if (node.operator === "quotient") {
|
|
536
|
+
// A quotient by a whole number stands in a comparison multiplied out.
|
|
537
|
+
const divisor = right.with;
|
|
538
|
+
return typeof divisor === "number" && Number.isSafeInteger(divisor) && divisor !== 0
|
|
539
|
+
? rest => (rest.length === 0 ? { with: left.with, over: divisor } : undefined)
|
|
540
|
+
: undefined;
|
|
541
|
+
}
|
|
542
|
+
const combined = node.operator === "multiply"
|
|
543
|
+
? (Number.isSafeInteger(right.with) ? linearCombination([{ operand: left.with, coefficient: right.with }])
|
|
544
|
+
: Number.isSafeInteger(left.with) ? linearCombination([{ operand: right.with, coefficient: left.with }]) : undefined)
|
|
545
|
+
: linearCombination([{ operand: left.with, coefficient: 1 }, { operand: right.with, coefficient: node.operator === "add" ? 1 : -1 }]);
|
|
546
|
+
if (combined === undefined)
|
|
547
|
+
return undefined;
|
|
548
|
+
const decimal = leftKind === "decimal" || rightKind === "decimal";
|
|
549
|
+
const exact = decimal && typeof combined === "number" ? decimalOf(fractionOf(combined)) : combined;
|
|
550
|
+
return rest => (rest.length === 0 ? { with: exact } : undefined);
|
|
551
|
+
};
|
|
552
|
+
// A local is bound once, so a condition or a node written in two places is
|
|
553
|
+
// rewritten alike in both, and stands for one rewritten object.
|
|
554
|
+
const rewrittenRules = new Map();
|
|
555
|
+
const rewrittenNodes = new Map();
|
|
556
|
+
const visit = (value, aliases) => {
|
|
557
|
+
const node = nodeOf(value);
|
|
558
|
+
if (node === undefined)
|
|
559
|
+
return rewrite(value, aliases);
|
|
560
|
+
if (!rewrittenNodes.has(node))
|
|
561
|
+
rewrittenNodes.set(node, rewrite(value, aliases));
|
|
562
|
+
return rewrittenNodes.get(node);
|
|
563
|
+
};
|
|
564
|
+
const rewrite = (value, aliases) => {
|
|
565
|
+
const replace = (path) => (path.length > 0 ? aliases.get(path[0])?.(path.slice(1)) : undefined);
|
|
566
|
+
if (isTerm(value)) {
|
|
567
|
+
if (aliases.size === 0)
|
|
568
|
+
return value;
|
|
569
|
+
const found = substitutedOperand(value, replace);
|
|
570
|
+
return found === undefined || found.over !== undefined ? value : found.with;
|
|
571
|
+
}
|
|
572
|
+
const node = nodeOf(value);
|
|
573
|
+
if (node === undefined) {
|
|
574
|
+
if (atom(value))
|
|
575
|
+
return value;
|
|
576
|
+
return Array.isArray(value) ? value.map(item => visit(item, aliases))
|
|
577
|
+
: Object.fromEntries(Object.entries(value).map(([key, child]) => [key, visit(child, aliases)]));
|
|
578
|
+
}
|
|
579
|
+
switch (node.kind) {
|
|
580
|
+
case "bind": {
|
|
581
|
+
const bound = visit(node.value, aliases);
|
|
582
|
+
const position = isTerm(bound) ? positionData(bound) : undefined;
|
|
583
|
+
if (position !== undefined && position.measure === "value" && position.path.length > 0 && !position.path[0].startsWith(LOCAL)) {
|
|
584
|
+
inlined = true;
|
|
585
|
+
// The binding is kept, so the field is still parsed with its schema
|
|
586
|
+
// and a read the field cannot stand in for still reads the local.
|
|
587
|
+
const body = visit(node.body, new Map([...aliases, [node.name, rest => ({ with: positionTerm([...position.path, ...rest], "value") })]]));
|
|
588
|
+
return expression({ ...node, value: bound, body });
|
|
589
|
+
}
|
|
590
|
+
// A computed value bound under a schema with invariants may be one the
|
|
591
|
+
// schema refuses at run time, which the expression it would stand for
|
|
592
|
+
// does not say, so it stays a local of its own.
|
|
593
|
+
const refusable = nodeOf(bound) !== undefined && node.schema.invariants.length > 0;
|
|
594
|
+
const alias = isAnswer(node.name) || refusable ? undefined : aliasOf(bound);
|
|
595
|
+
if (alias !== undefined)
|
|
596
|
+
inlined = true;
|
|
597
|
+
return expression({ ...node, value: bound, body: visit(node.body, alias === undefined ? aliases : new Map([...aliases, [node.name, alias]])) });
|
|
598
|
+
}
|
|
599
|
+
case "choose": {
|
|
600
|
+
if (!rewrittenRules.has(node.condition))
|
|
601
|
+
rewrittenRules.set(node.condition, aliases.size === 0 ? node.condition : substitutedRule(node.condition, replace) ?? node.condition);
|
|
602
|
+
const condition = rewrittenRules.get(node.condition);
|
|
603
|
+
return expression({ ...node, condition, yes: visit(node.yes, aliases), no: visit(node.no, aliases) });
|
|
604
|
+
}
|
|
605
|
+
case "map":
|
|
606
|
+
return expression({ ...node, values: visit(node.values, aliases), body: visit(node.body, aliases) });
|
|
607
|
+
case "fold":
|
|
608
|
+
return expression({ ...node, values: visit(node.values, aliases), initial: visit(node.initial, aliases), body: visit(node.body, aliases) });
|
|
609
|
+
case "call":
|
|
610
|
+
return expression({ ...node, input: visit(node.input, aliases) });
|
|
611
|
+
case "construct":
|
|
612
|
+
return expression({ ...node, value: visit(node.value, aliases) });
|
|
613
|
+
case "operation":
|
|
614
|
+
case "temporal":
|
|
615
|
+
return expression({ ...node, left: visit(node.left, aliases), right: visit(node.right, aliases) });
|
|
616
|
+
}
|
|
617
|
+
};
|
|
618
|
+
const result = visit(template, new Map());
|
|
619
|
+
return inlined ? result : template;
|
|
620
|
+
}
|
|
621
|
+
export function guardsOf(template) {
|
|
622
|
+
return choicesOf(template).map(node => ({ kind: "guard", condition: node.condition, orElse: () => { throw new Error("Expression guards are interpreted"); } }));
|
|
623
|
+
}
|
|
624
|
+
// The calls a model makes, by dependency, with the argument each is written with.
|
|
625
|
+
export function callsIn(template) {
|
|
626
|
+
const node = nodeOf(template);
|
|
627
|
+
const own = node?.kind === "call" ? [{ dependency: dependencyName(node.dependency), input: node.input }] : [];
|
|
628
|
+
return [...own, ...childrenOf(template).flatMap(callsIn)];
|
|
629
|
+
}
|
|
630
|
+
// The input with an argument written so it reads `value`: each field of the
|
|
631
|
+
// input the argument reads takes the part of `value` it stands at, and a
|
|
632
|
+
// constant must already be `value`. Undefined where the argument is computed
|
|
633
|
+
// or reads anything but the input.
|
|
634
|
+
export function writtenArgument(input, argument, value) {
|
|
635
|
+
if (isTerm(argument)) {
|
|
636
|
+
const position = positionData(argument);
|
|
637
|
+
if (position === undefined || position.measure !== "value")
|
|
638
|
+
return undefined;
|
|
639
|
+
const [first] = position.path;
|
|
640
|
+
if (first !== undefined && (first === DEPS || first.startsWith(LOCAL)))
|
|
641
|
+
return undefined;
|
|
642
|
+
return writePath(input, position.path, value);
|
|
643
|
+
}
|
|
644
|
+
if (nodeOf(argument) !== undefined)
|
|
645
|
+
return undefined;
|
|
646
|
+
if (atom(argument))
|
|
647
|
+
return deepEqualValue(argument, value) ? input : undefined;
|
|
648
|
+
if (typeof value !== "object" || value === null || Array.isArray(argument) !== Array.isArray(value))
|
|
649
|
+
return undefined;
|
|
650
|
+
const keys = Object.keys(argument);
|
|
651
|
+
if (keys.length !== Object.keys(value).length)
|
|
652
|
+
return undefined;
|
|
653
|
+
let written = input;
|
|
654
|
+
for (const key of keys) {
|
|
655
|
+
if (!Object.hasOwn(value, key))
|
|
656
|
+
return undefined;
|
|
657
|
+
written = writtenArgument(written, argument[key], value[key]);
|
|
658
|
+
if (written === undefined)
|
|
659
|
+
return undefined;
|
|
660
|
+
}
|
|
661
|
+
return written;
|
|
662
|
+
}
|
|
663
|
+
function writePath(value, path, leaf) {
|
|
664
|
+
const [key, ...rest] = path;
|
|
665
|
+
if (key === undefined)
|
|
666
|
+
return leaf;
|
|
667
|
+
const record = (typeof value === "object" && value !== null ? value : {});
|
|
668
|
+
return { ...record, [key]: writePath(record[key], rest, leaf) };
|
|
669
|
+
}
|
|
670
|
+
function deepEqualValue(left, right) {
|
|
671
|
+
return left === right || (isDecimal(left) && isDecimal(right) && left.equals(right));
|
|
672
|
+
}
|
|
673
|
+
export function* iterationEntries(template, steps = []) {
|
|
674
|
+
const node = nodeOf(template);
|
|
675
|
+
if (node?.kind === "choose") {
|
|
676
|
+
// A choice whose branches hold no iteration is not expanded: its outcomes may be far more than any iteration needs.
|
|
677
|
+
if (iterationsOf(node.yes).length === 0 && iterationsOf(node.no).length === 0)
|
|
678
|
+
return;
|
|
679
|
+
for (const outcome of outcomesOf(node.condition))
|
|
680
|
+
yield* iterationEntries(outcome.result ? node.yes : node.no, [...steps, ...outcome.steps]);
|
|
681
|
+
return;
|
|
682
|
+
}
|
|
683
|
+
if (node?.kind === "map" || node?.kind === "fold")
|
|
684
|
+
yield { node, steps };
|
|
685
|
+
for (const child of childrenOf(template))
|
|
686
|
+
yield* iterationEntries(child, steps);
|
|
687
|
+
}
|
|
688
|
+
// Every map and fold in a model, each with the body one element is read in.
|
|
689
|
+
export function iterationsOf(template) {
|
|
690
|
+
const node = nodeOf(template);
|
|
691
|
+
const own = node?.kind === "map" || node?.kind === "fold" ? [node] : [];
|
|
692
|
+
return [...own, ...childrenOf(template).flatMap(iterationsOf)];
|
|
693
|
+
}
|
|
694
|
+
// The values a model reads that no input field holds, each under the schema it
|
|
695
|
+
// takes, besides a dependency's answer: what a bind holds that is read as a
|
|
696
|
+
// value of its own, an element of a map or a fold, and a fold's accumulator.
|
|
697
|
+
// `opaque` where the input settles the value in a way no position shows, so a
|
|
698
|
+
// way reading it is told only by a row taking it: a computed value, an
|
|
699
|
+
// accumulator, and an element of anything but an array the input holds.
|
|
700
|
+
export function localsOf(template, opaque = new Set()) {
|
|
701
|
+
const node = nodeOf(template);
|
|
702
|
+
const rootedIn = (value, seen) => {
|
|
703
|
+
const position = isTerm(value) ? positionData(value) : undefined;
|
|
704
|
+
const first = position?.path[0];
|
|
705
|
+
return position !== undefined && position.measure === "value" && first !== undefined && first !== DEPS && !isAnswer(first) && !seen.has(first);
|
|
706
|
+
};
|
|
707
|
+
if (node?.kind === "bind" && !isAnswer(node.name)) {
|
|
708
|
+
const inner = new Set([...opaque, node.name]);
|
|
709
|
+
return [{ name: node.name, schema: node.schema, opaque: true }, ...childrenOf(template).flatMap(child => localsOf(child, inner))];
|
|
710
|
+
}
|
|
711
|
+
if (node?.kind === "map" || node?.kind === "fold") {
|
|
712
|
+
const elementOpaque = !rootedIn(node.values, opaque);
|
|
713
|
+
const own = [{ name: node.name, schema: node.element, opaque: elementOpaque }, ...(node.kind === "fold" ? [{ name: node.accumulator, schema: node.output, opaque: true }] : [])];
|
|
714
|
+
const inner = new Set([...opaque, ...own.filter(local => local.opaque).map(local => local.name)]);
|
|
715
|
+
return [...own, ...childrenOf(template).flatMap(child => localsOf(child, inner))];
|
|
716
|
+
}
|
|
717
|
+
return childrenOf(template).flatMap(child => localsOf(child, opaque));
|
|
718
|
+
}
|
|
719
|
+
// The top-level input fields a run of the model may turn on: every field it
|
|
720
|
+
// reads, since a value computed before a choice may throw on one, less what a
|
|
721
|
+
// dependency is asked where `matters` says neither its answer nor its refusal
|
|
722
|
+
// of the argument differs with it. Undefined where the model reads the whole
|
|
723
|
+
// input.
|
|
724
|
+
export function fieldsTurnedOn(template, matters = () => true) {
|
|
725
|
+
const fields = new Set();
|
|
726
|
+
let whole = false;
|
|
727
|
+
const add = (path) => {
|
|
728
|
+
if (path.length === 0)
|
|
729
|
+
whole = true;
|
|
730
|
+
else if (!path[0].startsWith(LOCAL) && path[0] !== DEPS)
|
|
731
|
+
fields.add(path[0]);
|
|
732
|
+
};
|
|
733
|
+
const visit = (value) => {
|
|
734
|
+
if (isTerm(value)) {
|
|
735
|
+
const data = termData(value);
|
|
736
|
+
(data.kind === "position" ? [data.path] : data.parts.map(part => part.path)).forEach(add);
|
|
737
|
+
return;
|
|
738
|
+
}
|
|
739
|
+
const node = nodeOf(value);
|
|
740
|
+
if (node?.kind === "choose")
|
|
741
|
+
pathsReadOfRule(node.condition).forEach(add);
|
|
742
|
+
if (node?.kind === "call" && !matters(dependencyName(node.dependency), node.input))
|
|
743
|
+
return;
|
|
744
|
+
childrenOf(value).forEach(visit);
|
|
745
|
+
};
|
|
746
|
+
visit(template);
|
|
747
|
+
return whole ? undefined : fields;
|
|
748
|
+
}
|
|
749
|
+
export function translationOf(written, rewritten) {
|
|
750
|
+
const rules = new Map();
|
|
751
|
+
const nodes = new Map();
|
|
752
|
+
const pairRules = (a, b) => {
|
|
753
|
+
if (a === b)
|
|
754
|
+
return;
|
|
755
|
+
rules.set(a, b);
|
|
756
|
+
if ((a.kind === "and" || a.kind === "or") && (b.kind === "and" || b.kind === "or"))
|
|
757
|
+
a.rules.forEach((part, index) => b.rules[index] && pairRules(part, b.rules[index]));
|
|
758
|
+
if (a.kind === "not" && b.kind === "not")
|
|
759
|
+
pairRules(a.rule, b.rule);
|
|
760
|
+
if ((a.kind === "all" || a.kind === "any") && (b.kind === "all" || b.kind === "any"))
|
|
761
|
+
pairRules(a.each, b.each);
|
|
762
|
+
};
|
|
763
|
+
const walk = (a, b) => {
|
|
764
|
+
if (a === b)
|
|
765
|
+
return;
|
|
766
|
+
const left = nodeOf(a), right = nodeOf(b);
|
|
767
|
+
if (left !== undefined && right !== undefined) {
|
|
768
|
+
nodes.set(left, right);
|
|
769
|
+
if (left.kind === "choose" && right.kind === "choose")
|
|
770
|
+
pairRules(left.condition, right.condition);
|
|
771
|
+
}
|
|
772
|
+
const [first, second] = [childrenOf(a), childrenOf(b)];
|
|
773
|
+
first.forEach((child, index) => walk(child, second[index]));
|
|
774
|
+
};
|
|
775
|
+
walk(written, rewritten);
|
|
776
|
+
return { rules, nodes };
|
|
777
|
+
}
|
|
343
778
|
//# sourceMappingURL=model.js.map
|