@toiroakr/chisel 0.0.0-stage → 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.
Files changed (129) hide show
  1. package/README.md +693 -2
  2. package/dist/absence.d.ts +27 -0
  3. package/dist/absence.js +228 -0
  4. package/dist/absence.js.map +1 -0
  5. package/dist/behavior.d.ts +193 -0
  6. package/dist/behavior.js +589 -0
  7. package/dist/behavior.js.map +1 -0
  8. package/dist/beside.d.ts +27 -0
  9. package/dist/beside.js +88 -0
  10. package/dist/beside.js.map +1 -0
  11. package/dist/border.d.ts +61 -0
  12. package/dist/border.js +434 -0
  13. package/dist/border.js.map +1 -0
  14. package/dist/bounds.d.ts +1 -0
  15. package/dist/bounds.js +26 -0
  16. package/dist/bounds.js.map +1 -0
  17. package/dist/cli.d.ts +7 -0
  18. package/dist/cli.js +835 -0
  19. package/dist/cli.js.map +1 -0
  20. package/dist/codec.d.ts +6 -0
  21. package/dist/codec.js +86 -0
  22. package/dist/codec.js.map +1 -0
  23. package/dist/codegen.d.ts +2 -0
  24. package/dist/codegen.js +61 -0
  25. package/dist/codegen.js.map +1 -0
  26. package/dist/composition.d.ts +38 -0
  27. package/dist/composition.js +242 -0
  28. package/dist/composition.js.map +1 -0
  29. package/dist/data.d.ts +17 -0
  30. package/dist/data.js +51 -0
  31. package/dist/data.js.map +1 -0
  32. package/dist/dependency.d.ts +101 -0
  33. package/dist/dependency.js +161 -0
  34. package/dist/dependency.js.map +1 -0
  35. package/dist/domain.d.ts +12 -0
  36. package/dist/domain.js +217 -0
  37. package/dist/domain.js.map +1 -0
  38. package/dist/ensures.d.ts +15 -0
  39. package/dist/ensures.js +88 -0
  40. package/dist/ensures.js.map +1 -0
  41. package/dist/equal.d.ts +1 -0
  42. package/dist/equal.js +135 -0
  43. package/dist/equal.js.map +1 -0
  44. package/dist/exact.d.ts +21 -0
  45. package/dist/exact.js +80 -0
  46. package/dist/exact.js.map +1 -0
  47. package/dist/feasibility.d.ts +63 -0
  48. package/dist/feasibility.js +1053 -0
  49. package/dist/feasibility.js.map +1 -0
  50. package/dist/guard-borders.d.ts +57 -0
  51. package/dist/guard-borders.js +760 -0
  52. package/dist/guard-borders.js.map +1 -0
  53. package/dist/guard-scope.d.ts +61 -0
  54. package/dist/guard-scope.js +364 -0
  55. package/dist/guard-scope.js.map +1 -0
  56. package/dist/index.d.ts +48 -0
  57. package/dist/index.js +24 -0
  58. package/dist/index.js.map +1 -0
  59. package/dist/interleave.d.ts +31 -0
  60. package/dist/interleave.js +202 -0
  61. package/dist/interleave.js.map +1 -0
  62. package/dist/interval.d.ts +10 -0
  63. package/dist/interval.js +311 -0
  64. package/dist/interval.js.map +1 -0
  65. package/dist/isolated.d.ts +9 -0
  66. package/dist/isolated.js +41 -0
  67. package/dist/isolated.js.map +1 -0
  68. package/dist/machine-check.d.ts +73 -0
  69. package/dist/machine-check.js +215 -0
  70. package/dist/machine-check.js.map +1 -0
  71. package/dist/machine.d.ts +97 -0
  72. package/dist/machine.js +200 -0
  73. package/dist/machine.js.map +1 -0
  74. package/dist/model.d.ts +160 -0
  75. package/dist/model.js +778 -0
  76. package/dist/model.js.map +1 -0
  77. package/dist/outcomes.d.ts +7 -0
  78. package/dist/outcomes.js +38 -0
  79. package/dist/outcomes.js.map +1 -0
  80. package/dist/pairs.d.ts +26 -0
  81. package/dist/pairs.js +115 -0
  82. package/dist/pairs.js.map +1 -0
  83. package/dist/partition.d.ts +45 -0
  84. package/dist/partition.js +354 -0
  85. package/dist/partition.js.map +1 -0
  86. package/dist/proof.d.ts +21 -0
  87. package/dist/proof.js +556 -0
  88. package/dist/proof.js.map +1 -0
  89. package/dist/replay.d.ts +45 -0
  90. package/dist/replay.js +157 -0
  91. package/dist/replay.js.map +1 -0
  92. package/dist/report-json.d.ts +11 -0
  93. package/dist/report-json.js +94 -0
  94. package/dist/report-json.js.map +1 -0
  95. package/dist/rule.d.ts +186 -0
  96. package/dist/rule.js +866 -0
  97. package/dist/rule.js.map +1 -0
  98. package/dist/runtime.d.ts +12 -0
  99. package/dist/runtime.js +8 -0
  100. package/dist/runtime.js.map +1 -0
  101. package/dist/schema.d.ts +163 -0
  102. package/dist/schema.js +528 -0
  103. package/dist/schema.js.map +1 -0
  104. package/dist/specification.d.ts +266 -0
  105. package/dist/specification.js +2123 -0
  106. package/dist/specification.js.map +1 -0
  107. package/dist/temporal-global.d.ts +4 -0
  108. package/dist/temporal-global.js +11 -0
  109. package/dist/temporal-global.js.map +1 -0
  110. package/dist/temporal.d.ts +22 -0
  111. package/dist/temporal.js +113 -0
  112. package/dist/temporal.js.map +1 -0
  113. package/dist/text.d.ts +1 -0
  114. package/dist/text.js +11 -0
  115. package/dist/text.js.map +1 -0
  116. package/dist/tla.d.ts +54 -0
  117. package/dist/tla.js +579 -0
  118. package/dist/tla.js.map +1 -0
  119. package/dist/verification.d.ts +7 -0
  120. package/dist/verification.js +5 -0
  121. package/dist/verification.js.map +1 -0
  122. package/dist/ways.d.ts +28 -0
  123. package/dist/ways.js +86 -0
  124. package/dist/ways.js.map +1 -0
  125. package/dist/world.d.ts +98 -0
  126. package/dist/world.js +467 -0
  127. package/dist/world.js.map +1 -0
  128. package/package.json +76 -4
  129. package/schema/report.schema.json +1062 -0
package/dist/model.js ADDED
@@ -0,0 +1,778 @@
1
+ import { isPromiseLike, snapshotValue } from "./data.js";
2
+ import { Rational, isRational, fractionOf, decimalOf, EvaluationLimit } 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 { isVariantsSchema } from "./schema.js";
5
+ import { outcomesOf } from "./outcomes.js";
6
+ import { countBetween, moveTemporal } from "./temporal.js";
7
+ const EXPRESSION = Symbol.for("chisel.expression");
8
+ function expression(node) {
9
+ return Object.freeze({ [EXPRESSION]: Object.freeze(node) });
10
+ }
11
+ const LOCAL = "#local:";
12
+ let nextLocal = 0;
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
+ }
48
+ export function bind(schema, value, build) {
49
+ const name = localName(value);
50
+ return expression({ kind: "bind", name, schema: schema, value, body: build(rootTerm(name)) });
51
+ }
52
+ export function matchValue(schema, value, cases) {
53
+ const tags = schema.variantTags;
54
+ if (tags.length === 0 || Object.keys(cases).length !== tags.length || tags.some(tag => !Object.hasOwn(cases, tag) || typeof cases[tag] !== "function"))
55
+ throw new Error("matchValue requires exactly one body for every variant");
56
+ const name = localName(value);
57
+ const handlers = cases;
58
+ const bodies = tags.map(tag => handlers[tag](rootTerm(name)));
59
+ let body = bodies.at(-1);
60
+ for (let index = tags.length - 2; index >= 0; index--)
61
+ body = expression({ kind: "choose", condition: { kind: "compare", left: positionTerm([name, schema.discriminant], "value"), operator: "==", right: tags[index] }, yes: bodies[index], no: body });
62
+ return expression({ kind: "bind", name, schema, value, body });
63
+ }
64
+ export function map(element, output, values, build) {
65
+ const name = localName(values, "element");
66
+ return expression({ kind: "map", name, element: element, output: output, values, body: build(rootTerm(name)) });
67
+ }
68
+ export function fold(element, output, values, initial, build) {
69
+ const name = localName(values, "element"), accumulator = localName(undefined, "accumulator");
70
+ return expression({ kind: "fold", name, accumulator, element: element, output: output, values, initial, body: build(rootTerm(accumulator), rootTerm(name)) });
71
+ }
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)];
87
+ }
88
+ export function localRoots(value) {
89
+ if (isTerm(value)) {
90
+ const data = termData(value);
91
+ return (data.kind === "position" ? [data.path] : data.parts.map(part => part.path)).flatMap(path => path[0]?.startsWith(LOCAL) ? [path[0]] : []);
92
+ }
93
+ return childrenOf(value).flatMap(localRoots);
94
+ }
95
+ export function choose(condition, yes, no) {
96
+ return expression({ kind: "choose", condition, yes, no });
97
+ }
98
+ export function construct(schema, value) {
99
+ return expression({ kind: "construct", schema: schema, value });
100
+ }
101
+ export function call(dependency, input) {
102
+ dependencyName(dependency);
103
+ return expression({ kind: "call", dependency, input });
104
+ }
105
+ export function dependencyName(dependency) {
106
+ const position = positionData(dependency);
107
+ if (!position || position.measure !== "value" || position.path.length !== 2 || position.path[0] !== DEPS)
108
+ throw new Error("call expects a declared function dependency");
109
+ return position.path[1];
110
+ }
111
+ export function concat(left, right) {
112
+ return expression({ kind: "operation", operator: "concat", left, right });
113
+ }
114
+ export function arithmetic(operator, left, right) {
115
+ return expression({ kind: "operation", operator, left, right });
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
+ }
133
+ export function quotient(left, right) {
134
+ return expression({ kind: "operation", operator: "quotient", left, right });
135
+ }
136
+ export function nodeOf(value) {
137
+ return typeof value === "object" && value !== null && !isTerm(value)
138
+ ? value[EXPRESSION] : undefined;
139
+ }
140
+ export function childrenOf(value) {
141
+ const node = nodeOf(value);
142
+ if (node?.kind === "bind")
143
+ return [node.value, node.body];
144
+ if (node?.kind === "map")
145
+ return [node.values, node.body];
146
+ if (node?.kind === "fold")
147
+ return [node.values, node.initial, node.body];
148
+ if (node?.kind === "call")
149
+ return [node.input];
150
+ if (node?.kind === "choose")
151
+ return [node.yes, node.no];
152
+ if (node?.kind === "construct")
153
+ return [node.value];
154
+ if (node?.kind === "operation" || node?.kind === "temporal")
155
+ return [node.left, node.right];
156
+ if (isTerm(value) || atom(value))
157
+ return [];
158
+ return Object.values(value);
159
+ }
160
+ export function modelDependencyIssue(template, definition, tags) {
161
+ const inputOwnsRoot = Object.keys(definition.dependencies).length === 0 && tags.every(tag => definition.input.discriminant === DEPS || Object.hasOwn(definition.input.variants[tag].shape, DEPS));
162
+ const declared = new Set();
163
+ if (tags.some(tag => definition.input.discriminant.startsWith(LOCAL) || Object.keys(definition.input.variants[tag].shape).some(key => key.startsWith(LOCAL))))
164
+ return "Model input uses a reserved local name";
165
+ function inspect(value, locals = new Set()) {
166
+ if (isTerm(value) && localRoots(value).some(name => !locals.has(name)))
167
+ return "Model local reference escapes its binding";
168
+ if (isTerm(value) && !inputOwnsRoot) {
169
+ const data = termData(value);
170
+ const paths = data.kind === "position" ? [data.path] : data.parts.map(part => part.path);
171
+ for (const path of paths) {
172
+ if (path[0] !== DEPS)
173
+ continue;
174
+ const name = path[1];
175
+ if (name === undefined || !Object.hasOwn(definition.dependencies, name) || definition.dependencies[name]?.takes !== "nothing")
176
+ return `Model requires a declared value dependency ${name ?? "<root>"}`;
177
+ }
178
+ }
179
+ const node = nodeOf(value);
180
+ if (node?.kind === "call") {
181
+ const name = dependencyName(node.dependency);
182
+ if (!Object.hasOwn(definition.dependencies, name) || definition.dependencies[name]?.takes !== "input")
183
+ return "call requires a declared function dependency";
184
+ }
185
+ if (node?.kind === "bind" || node?.kind === "map" || node?.kind === "fold") {
186
+ const names = node.kind === "fold" ? [node.name, node.accumulator] : [node.name];
187
+ if (names.some(name => declared.has(name)))
188
+ return "Model binding cannot be reused; declare a separate binding for each evaluation";
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;
193
+ const before = node.kind === "bind" ? [node.value] : node.kind === "map" ? [node.values] : [node.values, node.initial];
194
+ for (const child of before) {
195
+ const issue = inspect(child, locals);
196
+ if (issue)
197
+ return issue;
198
+ }
199
+ return inspect(node.body, new Set([...locals, ...names]));
200
+ }
201
+ if (node?.kind === "choose") {
202
+ const issue = inspect(node.condition, locals);
203
+ if (issue)
204
+ return issue;
205
+ }
206
+ for (const child of childrenOf(value)) {
207
+ const issue = inspect(child, locals);
208
+ if (issue)
209
+ return issue;
210
+ }
211
+ return undefined;
212
+ }
213
+ return inspect(template);
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
+ }
228
+ function atom(value) {
229
+ return value === null || typeof value !== "object" || isDecimal(value) ||
230
+ Object.getPrototypeOf(value) !== Object.prototype && !Array.isArray(value);
231
+ }
232
+ export function choicesOf(template) {
233
+ const nodes = [];
234
+ function visit(value) {
235
+ const node = nodeOf(value);
236
+ if (node?.kind === "choose" && !nodes.includes(node))
237
+ nodes.push(node);
238
+ childrenOf(value).forEach(visit);
239
+ }
240
+ visit(template);
241
+ return nodes;
242
+ }
243
+ function checkedTemplate(value, ancestors = new Set(), remaining = { value: 10000 }) {
244
+ if (--remaining.value < 0)
245
+ throw new Error("Model declaration exceeds 10000 nodes");
246
+ if (typeof value === "function" || typeof value === "symbol")
247
+ throw new Error("Model expressions cannot contain callbacks or symbols");
248
+ if (isTerm(value))
249
+ return value;
250
+ if (atom(value)) {
251
+ if (isDecimal(value))
252
+ return snapshotValue(value);
253
+ if (typeof value === "string") {
254
+ if (!value.isWellFormed())
255
+ throw new Error("Model text must be well-formed Unicode");
256
+ return value.normalize("NFC");
257
+ }
258
+ if (value && typeof value === "object" && !isDecimal(value) && !isRational(value) && !String(value.constructor?.name).startsWith("Plain") && value.constructor?.name !== "Instant")
259
+ throw new Error("Unsupported model constant");
260
+ return value;
261
+ }
262
+ if (ancestors.has(value))
263
+ throw new Error("Model expressions cannot contain cycles");
264
+ const parents = new Set([...ancestors, value]);
265
+ const check = (child) => checkedTemplate(child, parents, remaining);
266
+ const node = nodeOf(value);
267
+ if (node?.kind === "bind")
268
+ return expression({ ...node, value: check(node.value), body: check(node.body) });
269
+ if (node?.kind === "map")
270
+ return expression({ ...node, values: check(node.values), body: check(node.body) });
271
+ if (node?.kind === "fold")
272
+ return expression({ ...node, values: check(node.values), initial: check(node.initial), body: check(node.body) });
273
+ if (node?.kind === "call")
274
+ return expression({ ...node, input: check(node.input) });
275
+ if (node?.kind === "choose")
276
+ return expression({ ...node, yes: check(node.yes), no: check(node.no) });
277
+ if (node?.kind === "construct")
278
+ return expression({ ...node, value: check(node.value) });
279
+ if (node?.kind === "operation" || node?.kind === "temporal")
280
+ return expression({ ...node, left: check(node.left), right: check(node.right) });
281
+ return Object.freeze(Array.isArray(value) ? value.map(check) : Object.fromEntries(Object.entries(value).map(([key, child]) => [key, check(child)])));
282
+ }
283
+ export function model(id, build) {
284
+ const template = checkedTemplate(build(selfTerm(), depsTerm()));
285
+ return Object.freeze({
286
+ kind: "rules", id, expression: template,
287
+ guards: guardsOf(template),
288
+ otherwise: () => { throw new Error("Expression models are interpreted"); },
289
+ });
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.
296
+ export function interpret(template, scope, options = {}) {
297
+ let remaining = options.steps ?? 100000;
298
+ const choices = choicesOf(template);
299
+ let distinguishing = options.distinguish;
300
+ function parsed(schema, value) {
301
+ const result = schema.parse(value);
302
+ if (!result.success)
303
+ throw new Error(`Invalid local construction: ${result.issues.map(issue => `${issue.path}: ${issue.message}`).join("; ")}`);
304
+ return snapshotValue(result.value);
305
+ }
306
+ function* read(value, current = scope) {
307
+ if (--remaining < 0)
308
+ throw new EvaluationLimit("Model evaluation step budget exceeded");
309
+ if (isTerm(value))
310
+ return readOperand(value, current);
311
+ const node = nodeOf(value);
312
+ if (node?.kind === "bind")
313
+ return yield* read(node.body, withLocal(current, node.name, parsed(node.schema, yield* read(node.value, current))));
314
+ if (node?.kind === "map" || node?.kind === "fold") {
315
+ const values = yield* read(node.values, current);
316
+ if (!Array.isArray(values))
317
+ throw new Error("Iteration expects an array");
318
+ let accumulator = node.kind === "fold" ? parsed(node.output, yield* read(node.initial, current)) : undefined;
319
+ const result = [];
320
+ for (const value of values) {
321
+ const elementScope = withLocal(current, node.name, parsed(node.element, value));
322
+ const iterationScope = node.kind === "fold" ? withLocal(elementScope, node.accumulator, accumulator) : elementScope;
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);
336
+ if (node.kind === "fold")
337
+ accumulator = next;
338
+ else
339
+ result.push(next);
340
+ }
341
+ return node.kind === "fold" ? accumulator : result;
342
+ }
343
+ if (node?.kind === "call") {
344
+ if (!options.invoke)
345
+ throw new Error("Dependency calls require an execution environment");
346
+ const answer = options.invoke(dependencyName(node.dependency), yield* read(node.input, current));
347
+ return isPromiseLike(answer) ? yield answer : answer;
348
+ }
349
+ if (node?.kind === "choose") {
350
+ const outcome = holds(node.condition, current, options.observe, distinguishing);
351
+ options.arm?.(choices.indexOf(node), outcome);
352
+ return yield* read(outcome ? node.yes : node.no, current);
353
+ }
354
+ if (node?.kind === "construct") {
355
+ const parsed = node.schema.parse(yield* read(node.value, current));
356
+ if (!parsed.success)
357
+ throw new Error(`Invalid construction: ${parsed.issues.map(issue => `${issue.path}: ${issue.message}`).join("; ")}`);
358
+ return parsed.value;
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
+ }
364
+ if (node?.kind === "operation") {
365
+ const left = yield* read(node.left, current), right = yield* read(node.right, current);
366
+ if (node.operator === "concat") {
367
+ if (typeof left !== "string" || typeof right !== "string")
368
+ throw new Error("concat expects strings");
369
+ return (left + right).normalize("NFC");
370
+ }
371
+ if (node.operator === "quotient")
372
+ return fractionOf(left).dividedBy(fractionOf(right));
373
+ if (isDecimal(left) && isDecimal(right)) {
374
+ const a = fractionOf(left), b = fractionOf(right);
375
+ return decimalOf(node.operator === "add" ? a.plus(b) : node.operator === "subtract" ? a.minus(b) : node.operator === "multiply" ? a.times(b) : a.dividedBy(b));
376
+ }
377
+ if (isRational(left) && isRational(right))
378
+ return node.operator === "add" ? left.plus(right) : node.operator === "subtract" ? left.minus(right) : node.operator === "multiply" ? left.times(right) : left.dividedBy(right);
379
+ if (typeof left === "bigint" && typeof right === "bigint") {
380
+ if (node.operator === "divide" && (right === 0n || left % right !== 0n))
381
+ throw new Error("Integer division must be exact and nonzero");
382
+ return node.operator === "add" ? left + right : node.operator === "subtract" ? left - right : node.operator === "multiply" ? left * right : left / right;
383
+ }
384
+ if (typeof left !== "number" || typeof right !== "number")
385
+ throw new Error("Arithmetic expects matching numeric types");
386
+ if (node.operator === "divide" && right === 0)
387
+ throw new Error("Division by zero");
388
+ const result = node.operator === "add" ? left + right : node.operator === "subtract" ? left - right : node.operator === "multiply" ? left * right : left / right;
389
+ if (!Number.isFinite(result) || Number.isInteger(result) && !Number.isSafeInteger(result))
390
+ throw new Error("Arithmetic result is outside the exact number range");
391
+ return result;
392
+ }
393
+ if (atom(value))
394
+ return value;
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;
429
+ }
430
+ }
431
+ export function* modelPaths(template) {
432
+ const node = nodeOf(template);
433
+ if (node?.kind === "choose") {
434
+ for (const outcome of outcomesOf(node.condition))
435
+ for (const branch of modelPaths(outcome.result ? node.yes : node.no)) {
436
+ yield { value: branch.value, steps: [...outcome.steps, ...branch.steps], choices: [{ condition: node.condition, outcome: outcome.result }, ...branch.choices] };
437
+ }
438
+ return;
439
+ }
440
+ const children = node?.kind === "map" ? [node.values] : node?.kind === "fold" ? [node.values, node.initial] : childrenOf(template);
441
+ if (children.length === 0) {
442
+ yield { value: template, steps: [], choices: [] };
443
+ return;
444
+ }
445
+ function* product(index, before) {
446
+ if (index === children.length) {
447
+ yield before;
448
+ return;
449
+ }
450
+ for (const child of modelPaths(children[index]))
451
+ yield* product(index + 1, { value: undefined, values: [...before.values, child.value], steps: [...before.steps, ...child.steps], choices: [...before.choices, ...child.choices] });
452
+ }
453
+ for (const path of product(0, { value: undefined, values: [], steps: [], choices: [] })) {
454
+ const value = replaceChildren(template, path.values);
455
+ yield { value, steps: path.steps, choices: path.choices };
456
+ }
457
+ }
458
+ export function replaceChildren(template, values) {
459
+ const node = nodeOf(template);
460
+ if (node?.kind === "bind")
461
+ return expression({ ...node, value: values[0], body: values[1] });
462
+ if (node?.kind === "map")
463
+ return expression({ ...node, values: values[0], body: values.length > 1 ? values[1] : node.body });
464
+ if (node?.kind === "fold")
465
+ return expression({ ...node, values: values[0], initial: values[1], body: values.length > 2 ? values[2] : node.body });
466
+ if (node?.kind === "call")
467
+ return expression({ ...node, input: values[0] });
468
+ if (node?.kind === "construct")
469
+ return expression({ ...node, value: values[0] });
470
+ if (node?.kind === "operation" || node?.kind === "temporal")
471
+ return expression({ ...node, left: values[0], right: values[1] });
472
+ return Array.isArray(template) ? values : Object.fromEntries(Object.keys(template).map((key, index) => [key, values[index]]));
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
+ }
778
+ //# sourceMappingURL=model.js.map