@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
@@ -0,0 +1,1053 @@
1
+ import { compatibleBound } from "./interval.js";
2
+ import { deepEqual } from "./equal.js";
3
+ import { integerCarrier, normalize, numberCarrier } from "./border.js";
4
+ import { inheritedAt } from "./guard-scope.js";
5
+ import { carrierOf } from "./partition.js";
6
+ import { DEPS, boundTermPath, conjuncts, describeRule, differenceOf, holds, isTerm, positionData, positionOf, readOperand, termData, termPaths, counts, partsOfMeasure, positionTerm } from "./rule.js";
7
+ import { isVariantsSchema, schemaAtPath } from "./schema.js";
8
+ const negated = {
9
+ "<": ">=",
10
+ "<=": ">",
11
+ ">": "<=",
12
+ ">=": "<",
13
+ "==": "!=",
14
+ "!=": "==",
15
+ };
16
+ const mirrored = {
17
+ "<": ">",
18
+ "<=": ">=",
19
+ ">": "<",
20
+ ">=": "<=",
21
+ "==": "==",
22
+ "!=": "!=",
23
+ };
24
+ export const contradicts = "ガードの条件がこの値について両立しない";
25
+ export const unreadable = "読めない条件が同じ値を読む別の条件と重なる";
26
+ export const unreached = "どの値の組もこの分岐を通らない";
27
+ // How many combinations of finite values feasibility tries against the
28
+ // invariants relating them, before leaving a way or a point undecided.
29
+ export const FEASIBILITY_COMBINATION_LIMIT = 4096;
30
+ export function tooManyWays(limit) {
31
+ return `道筋が上限の${limit}本を超える`;
32
+ }
33
+ export function tooManyCombinations(limit) {
34
+ return `不変条件とあわせて調べる値の組が上限の${limit}通りを超える`;
35
+ }
36
+ export function feasibilityOf(way, scope, placement, combinations = FEASIBILITY_COMBINATION_LIMIT) {
37
+ const groups = new Map();
38
+ const relations = [];
39
+ const opaque = [];
40
+ const outcomes = new Map();
41
+ const groupFor = (path, measure) => {
42
+ const key = JSON.stringify([path, measure]);
43
+ if (!groups.has(key)) {
44
+ groups.set(key, { path, measure, constraints: [] });
45
+ }
46
+ return key;
47
+ };
48
+ const forms = new Map();
49
+ let constant = true;
50
+ const constrain = (weighed, operator, bound, onlyKnown = false) => {
51
+ const merged = new Map();
52
+ for (const { key, coefficient } of weighed) {
53
+ merged.set(key, (merged.get(key) ?? 0) + coefficient);
54
+ }
55
+ const parts = [...merged]
56
+ .filter(([, coefficient]) => coefficient !== 0)
57
+ .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))
58
+ .map(([key, coefficient]) => ({ key, coefficient }));
59
+ if (parts.length === 0) {
60
+ constant &&= holds({ kind: "compare", left: 0, operator, right: bound }, undefined);
61
+ return;
62
+ }
63
+ const sign = parts[0].coefficient < 0 ? -1 : 1;
64
+ const canonical = parts.map(part => ({ key: part.key, coefficient: sign * part.coefficient }));
65
+ const key = JSON.stringify(canonical);
66
+ if (onlyKnown && !forms.has(key)) {
67
+ return;
68
+ }
69
+ if (!forms.has(key)) {
70
+ forms.set(key, { parts: canonical, constraints: [] });
71
+ }
72
+ forms
73
+ .get(key)
74
+ .constraints.push(sign === 1 ? { operator, bound } : { operator: mirrored[operator], bound: -bound });
75
+ };
76
+ const differ = (left, right, operator, bound) => constrain([
77
+ { key: left, coefficient: 1 },
78
+ { key: right, coefficient: -1 },
79
+ ], operator, bound);
80
+ const constrainForm = (form, operator, bound, onlyKnown = false) => constrain(form.parts.map(part => ({ key: groupFor(part.path, part.measure), coefficient: part.coefficient })), operator, bound - form.constant, onlyKnown);
81
+ if (placement !== undefined && "between" in placement) {
82
+ const [left, right] = placement.between;
83
+ differ(groupFor(left.path, left.measure), groupFor(right.path, right.measure), placement.operator, placement.bound);
84
+ }
85
+ else if (placement !== undefined && "form" in placement) {
86
+ constrainForm(placement.form, placement.operator, placement.bound);
87
+ }
88
+ else if (placement !== undefined) {
89
+ groups
90
+ .get(groupFor(placement.path, placement.measure))
91
+ .constraints.push({ operator: placement.operator, bound: placement.bound });
92
+ }
93
+ for (const step of way.steps) {
94
+ const identity = stepIdentity(step);
95
+ const key = step.distinction.kind === "match" ? JSON.stringify(["match", positionData(step.distinction.on)?.path]) : describeRule(step.distinction);
96
+ const bucket = outcomes.get(key) ?? [];
97
+ const seen = bucket.find(previous => deepEqual(previous.identity, identity));
98
+ if (seen !== undefined) {
99
+ if (seen.outcome !== step.outcome) {
100
+ return { kind: "infeasible", reason: contradicts };
101
+ }
102
+ continue;
103
+ }
104
+ bucket.push({ identity, outcome: step.outcome });
105
+ outcomes.set(key, bucket);
106
+ const placed = placedConstraintOf(step, scope);
107
+ if (placed !== undefined) {
108
+ groups.get(groupFor(placed.path, placed.measure)).constraints.push(...placed.constraints);
109
+ continue;
110
+ }
111
+ const { distinction, outcome } = step;
112
+ if (distinction.kind === "all" || distinction.kind === "any") {
113
+ opaque.push(termPaths(distinction));
114
+ continue;
115
+ }
116
+ if (distinction.kind !== "compare") {
117
+ continue;
118
+ }
119
+ const operator = outcome === true ? distinction.operator : negated[distinction.operator];
120
+ const form = readableFormOf(distinction, scope);
121
+ if (form !== undefined) {
122
+ constrainForm(form, operator, 0);
123
+ continue;
124
+ }
125
+ const relation = relationOf(distinction, operator, groupFor);
126
+ if (relation === undefined) {
127
+ opaque.push(termPaths(distinction));
128
+ }
129
+ else {
130
+ relations.push(relation);
131
+ differ(relation.left, relation.right, relation.operator, 0);
132
+ }
133
+ }
134
+ // An input invariant ordering numbers holds on every way, so it bounds a form
135
+ // the way constrains. Not added to a form of its own: one more form sharing
136
+ // the way's positions would leave forms that are settled now undecided.
137
+ for (const { prefix, rule } of scopedInvariants(scope, [])) {
138
+ const form = numericFormOf(rule, scope, prefix);
139
+ if (form !== undefined && form.parts.every(part => groups.has(JSON.stringify([part.path, part.measure])))) {
140
+ constrainForm(form, rule.operator, 0, true);
141
+ }
142
+ }
143
+ const intervals = new Map();
144
+ let unsettled = false;
145
+ for (const [key, group] of groups) {
146
+ const settled = settle(group, scope);
147
+ if (settled === false) {
148
+ return { kind: "infeasible", reason: contradicts };
149
+ }
150
+ intervals.set(key, typeof settled === "object" ? settled : undefined);
151
+ unsettled ||= settled === undefined && group.constraints.length > 1;
152
+ }
153
+ const joint = jointAssignment([...groups.values()], scope, combinations);
154
+ if (joint === "none") {
155
+ return { kind: "infeasible", reason: contradicts };
156
+ }
157
+ if (joint === "too many") {
158
+ return { kind: "undecided", reason: tooManyCombinations(combinations) };
159
+ }
160
+ if (!constant) {
161
+ return { kind: "infeasible", reason: contradicts };
162
+ }
163
+ const related = [...forms.values()].flatMap(form => form.parts.map(part => part.key));
164
+ for (const form of forms.values()) {
165
+ const carrier = differenceCarrierOf(form.parts.map(part => groups.get(part.key)), scope);
166
+ if (carrier === undefined) {
167
+ unsettled ||= form.constraints.length > 1;
168
+ continue;
169
+ }
170
+ if (ordered(form.constraints, carrier) === false) {
171
+ return { kind: "infeasible", reason: contradicts };
172
+ }
173
+ const alone = form.parts.every(part => related.filter(other => other === part.key).length === 1 && intervals.get(part.key) !== undefined);
174
+ // A pair shared with another form is still settled on its intervals below,
175
+ // as a relation, so only one it alone constrains is read on its range here.
176
+ if (isPair(form)) {
177
+ if (alone && ordered([...form.constraints, ...rangeOf(form, intervals, carrier)], carrier) === false) {
178
+ return { kind: "infeasible", reason: contradicts };
179
+ }
180
+ continue;
181
+ }
182
+ const free = form.parts.every(part => intervals.get(part.key)?.lower === undefined && intervals.get(part.key)?.upper === undefined);
183
+ if (alone && free) {
184
+ unsettled ||= carrier === integerCarrier && !form.parts.some(part => Math.abs(part.coefficient) === 1);
185
+ continue;
186
+ }
187
+ // Integers weighed by more than one leave gaps in the values their sum takes,
188
+ // so only a sum of whole steps is read as the one interval it fills.
189
+ const range = alone && (carrier !== integerCarrier || form.parts.every(part => Math.abs(part.coefficient) === 1))
190
+ ? rangeOf(form, intervals, carrier)
191
+ : undefined;
192
+ if (range === undefined) {
193
+ unsettled = true;
194
+ continue;
195
+ }
196
+ if (ordered([...form.constraints, ...range], carrier) === false) {
197
+ return { kind: "infeasible", reason: contradicts };
198
+ }
199
+ }
200
+ for (const relation of relations) {
201
+ const left = intervals.get(relation.left);
202
+ const right = intervals.get(relation.right);
203
+ const shared = [relation.left, relation.right].some(key => related.filter(other => other === key).length > 1);
204
+ if (left === undefined || right === undefined || shared) {
205
+ unsettled = true;
206
+ continue;
207
+ }
208
+ if (!admitsRelation(relation.operator, left, right)) {
209
+ return { kind: "infeasible", reason: contradicts };
210
+ }
211
+ }
212
+ const readPaths = [...groups.values()].map(group => group.path);
213
+ const overlaps = opaque.some((paths, index) => paths.some(path => [...readPaths, ...opaque.filter((_, other) => other !== index).flat()].some(other => sharesValue(path, other))));
214
+ return overlaps || unsettled
215
+ ? { kind: "undecided", reason: unreadable }
216
+ : { kind: "feasible" };
217
+ }
218
+ // The constraints a step puts on one coordinate: a match, or a comparison with a constant.
219
+ function placedConstraintOf(step, scope) {
220
+ const { distinction, outcome } = step;
221
+ if (distinction.kind === "match") {
222
+ return { path: positionOf(distinction.on).path, measure: "value", constraints: [{ operator: "==", bound: outcome }] };
223
+ }
224
+ if (distinction.kind !== "compare") {
225
+ return undefined;
226
+ }
227
+ const normalized = normalize(distinction);
228
+ if (normalized === undefined) {
229
+ return undefined;
230
+ }
231
+ const path = positionOf((isTerm(distinction.left) ? distinction.left : distinction.right)).path;
232
+ const constraint = {
233
+ operator: outcome === true ? normalized.operator : negated[normalized.operator],
234
+ bound: normalized.bound,
235
+ };
236
+ // A transformed read of a finite position, `lowercase($.level)` of an enum,
237
+ // is read off each of its values: the step refuses the values whose reading
238
+ // the constraint does not keep, so it is settled with the value's own steps.
239
+ const { transforms, reading } = partsOfMeasure(normalized.measure);
240
+ const domain = transforms.length > 0 && reading === "value" ? finiteDomainAt(scope, path) : undefined;
241
+ if (domain !== undefined) {
242
+ const kept = { kind: "compare", left: positionTerm([], normalized.measure), operator: constraint.operator, right: constraint.bound };
243
+ return {
244
+ path,
245
+ measure: "value",
246
+ constraints: domain.filter(value => !holds(kept, value)).map(value => ({ operator: "!=", bound: value })),
247
+ };
248
+ }
249
+ return { path, measure: normalized.measure, constraints: [constraint] };
250
+ }
251
+ function stepIdentity(step) {
252
+ return step.distinction.kind === "match"
253
+ ? ["match", termData(step.distinction.on)]
254
+ : ruleIdentity(step.distinction);
255
+ }
256
+ function ruleIdentity(rule) {
257
+ const operand = (value) => isTerm(value) ? ["term", termData(value)] : ["constant", value];
258
+ switch (rule.kind) {
259
+ case "compare": return [rule.kind, rule.operator, operand(rule.left), operand(rule.right)];
260
+ case "all":
261
+ case "any": return [rule.kind, operand(rule.of), rule.element, ruleIdentity(rule.each)];
262
+ case "not": return [rule.kind, ruleIdentity(rule.rule)];
263
+ case "and":
264
+ case "or": return [rule.kind, rule.rules.map(ruleIdentity)];
265
+ }
266
+ }
267
+ // The values a form takes as each of its parts ranges over its own interval,
268
+ // as the constraints that bound it.
269
+ function rangeOf(form, intervals, carrier) {
270
+ const whole = (edge, direction) => edge === undefined || edge.inclusive || carrier !== integerCarrier
271
+ ? edge
272
+ : { value: edge.value + direction, inclusive: true };
273
+ const end = (side) => form.parts.reduce((total, { key, coefficient }) => {
274
+ const interval = intervals.get(key);
275
+ const taken = (coefficient > 0) === (side === "lower") ? "lower" : "upper";
276
+ const edge = whole(interval[taken], taken === "lower" ? 1 : -1);
277
+ return total === undefined || edge === undefined
278
+ ? undefined
279
+ : {
280
+ value: total.value + coefficient * edge.value,
281
+ inclusive: total.inclusive && edge.inclusive,
282
+ };
283
+ }, { value: 0, inclusive: true });
284
+ const lower = end("lower");
285
+ const upper = end("upper");
286
+ return [
287
+ ...(lower === undefined ? [] : [{ operator: lower.inclusive ? ">=" : ">", bound: lower.value }]),
288
+ ...(upper === undefined ? [] : [{ operator: upper.inclusive ? "<=" : "<", bound: upper.value }]),
289
+ ];
290
+ }
291
+ function isPair(form) {
292
+ return form.parts.length === 2 && form.parts[0].coefficient === 1 && form.parts[1].coefficient === -1;
293
+ }
294
+ // An invariant comparing two or more integer or number positions that are never
295
+ // left out, read as one form over paths from the scope's root.
296
+ function numericFormOf(rule, scope, prefix) {
297
+ if (rule.kind !== "compare" ||
298
+ rule.operator === "==" ||
299
+ rule.operator === "!=" ||
300
+ ![rule.left, rule.right].every(operand => isTerm(operand) || typeof operand === "number")) {
301
+ return undefined;
302
+ }
303
+ const form = differenceOf(rule);
304
+ const parts = form.parts.map(part => ({ ...part, path: [...prefix, ...part.path] }));
305
+ const kept = parts.every(part => part.measure === "value" &&
306
+ !leftOutAlong(scope, part.path) &&
307
+ ["integer", "number"].includes(schemaAtPath(scope, part.path)?.kind ?? ""));
308
+ return parts.length >= 2 && kept && typeof form.constant === "number" ? { ...form, parts } : undefined;
309
+ }
310
+ function leftOutAlong(scope, path) {
311
+ return path.some((_, index) => {
312
+ const parent = schemaAtPath(scope, path.slice(0, index));
313
+ const field = parent?.kind === "object" ? parent.shape[path[index]] : undefined;
314
+ return field?.kind === "optional";
315
+ });
316
+ }
317
+ // An expression of integer or number positions, read as the left side less the
318
+ // right; a decimal or another kind of part leaves the comparison unread.
319
+ function readableFormOf(rule, scope) {
320
+ if (![rule.left, rule.right].some(operand => isTerm(operand) && positionData(operand) === undefined)) {
321
+ return undefined;
322
+ }
323
+ const form = differenceOf(rule);
324
+ const kinds = form.parts.map(part => counts(part.measure) ? "integer" : schemaAtPath(scope, part.path)?.kind);
325
+ // A part that may be left out is not one: the comparison holds without it.
326
+ return typeof form.constant === "number" &&
327
+ kinds.every(kind => kind === "integer" || kind === "number") &&
328
+ !form.parts.some(part => leftOutAlong(scope, part.path))
329
+ ? form
330
+ : undefined;
331
+ }
332
+ function relationOf(rule, operator, groupFor) {
333
+ if (!isTerm(rule.left) || !isTerm(rule.right)) {
334
+ return undefined;
335
+ }
336
+ const left = positionData(rule.left);
337
+ const right = positionData(rule.right);
338
+ if (left === undefined || right === undefined) {
339
+ return undefined;
340
+ }
341
+ return {
342
+ left: groupFor(left.path, left.measure),
343
+ right: groupFor(right.path, right.measure),
344
+ operator,
345
+ };
346
+ }
347
+ // Only a difference counted in whole steps or in plain numbers is settled here;
348
+ // two decimals or two instants differ in units their readers convert to, which
349
+ // the steps of a way do not carry.
350
+ function differenceCarrierOf(sides, scope) {
351
+ const kinds = sides.map(side => counts(side.measure) ? "integer" : schemaAtPath(scope, side.path)?.kind);
352
+ if (kinds.every(kind => kind === "integer")) {
353
+ return integerCarrier;
354
+ }
355
+ return kinds.every(kind => kind === "integer" || kind === "number") ? numberCarrier : undefined;
356
+ }
357
+ function sharesValue(left, right) {
358
+ const length = Math.min(left.length, right.length);
359
+ return left.slice(0, length).every((key, index) => key === right[index]);
360
+ }
361
+ function settle(group, scope) {
362
+ const { path, measure } = group;
363
+ const domain = measure === "value" ? finiteDomainAt(scope, path) : undefined;
364
+ if (domain !== undefined) {
365
+ return finite(domain, group.constraints);
366
+ }
367
+ const schema = schemaAtPath(scope, path);
368
+ if (schema === undefined) {
369
+ return undefined;
370
+ }
371
+ const carrier = carrierOf(schema, measure);
372
+ if (carrier === undefined) {
373
+ return undefined;
374
+ }
375
+ const invariants = [...schema.invariants, ...inheritedAt(scope, path)]
376
+ .flatMap(conjuncts)
377
+ .flatMap((rule) => {
378
+ if (boundTermPath(rule)?.length !== 0) {
379
+ return [];
380
+ }
381
+ const normalized = normalize(rule);
382
+ return normalized === undefined || normalized.measure !== measure
383
+ ? []
384
+ : [{ operator: normalized.operator, bound: normalized.bound }];
385
+ });
386
+ const constraints = [...group.constraints, ...invariants];
387
+ if (constraints.some(item => !compatibleBound(item.bound, counts(measure) ? "number" : schema.kind)))
388
+ return undefined;
389
+ return ordered(constraints, carrier);
390
+ }
391
+ // The values of a finite domain the position's own invariants keep, the way its
392
+ // classes leave out the ones an invariant refuses.
393
+ function admittedBy(domain, schema, scope, path) {
394
+ const own = [...schema.invariants, ...inheritedAt(scope, path)]
395
+ .flatMap(conjuncts)
396
+ .filter(rule => boundTermPath(rule)?.length === 0);
397
+ return domain.filter(value => own.every(rule => holds(rule, value)));
398
+ }
399
+ function sumOwning(scope, path) {
400
+ const owner = schemaAtPath(scope, path.slice(0, -1));
401
+ return owner !== undefined && isVariantsSchema(owner) && owner.discriminant === path[path.length - 1]
402
+ ? owner
403
+ : undefined;
404
+ }
405
+ function finite(domain, constraints) {
406
+ if (constraints.some(item => item.operator !== "==" && item.operator !== "!=")) {
407
+ return undefined;
408
+ }
409
+ return domain.some(value => constraints.every(item => (value === item.bound) === (item.operator === "==")));
410
+ }
411
+ // Strings lying between two bounds, nearest the lower first: the lower bound with
412
+ // the lowest code point after it ("a" to "a!" holds "a\u0000"), and the bounds'
413
+ // common prefix followed by each code point between theirs where they part ("Z"
414
+ // to "a" holds "[" and "_"), so a range holding a transformed value is found.
415
+ const BETWEEN_LIMIT = 256;
416
+ function stringsBetween(lower, upper) {
417
+ if (typeof lower !== "string" || typeof upper !== "string") {
418
+ return [];
419
+ }
420
+ const low = [...lower.normalize("NFC")];
421
+ const high = [...upper.normalize("NFC")];
422
+ let common = 0;
423
+ while (common < Math.min(low.length, high.length) && low[common] === high[common]) {
424
+ common += 1;
425
+ }
426
+ const prefix = low.slice(0, common).join("");
427
+ const from = common < low.length ? low[common].codePointAt(0) + 1 : 0;
428
+ const to = common < high.length ? high[common].codePointAt(0) : 0;
429
+ const parted = [];
430
+ for (let point = from; point < Math.min(to, from + BETWEEN_LIMIT); point += 1) {
431
+ if (point < 0xd800 || point > 0xdfff) {
432
+ parted.push(prefix + String.fromCodePoint(point));
433
+ }
434
+ }
435
+ return [`${lower}\u0000`, ...parted];
436
+ }
437
+ function ordered(constraints, carrier) {
438
+ let lower = carrier.floor === undefined ? undefined : { value: carrier.floor.value, inclusive: true };
439
+ let upper = carrier.ceiling === undefined ? undefined : { value: carrier.ceiling.value, inclusive: true };
440
+ const equal = [];
441
+ const unequal = [];
442
+ for (const { operator, bound } of constraints) {
443
+ const edge = { value: bound, inclusive: operator === ">=" || operator === "<=" };
444
+ if (operator === ">" || operator === ">=") {
445
+ lower = tighter(lower, edge, 1, carrier);
446
+ }
447
+ else if (operator === "<" || operator === "<=") {
448
+ upper = tighter(upper, edge, -1, carrier);
449
+ }
450
+ else if (operator === "==") {
451
+ equal.push(bound);
452
+ }
453
+ else {
454
+ unequal.push(bound);
455
+ }
456
+ }
457
+ // A value nothing reads as is never held: lowercase($) == "ABC" never holds.
458
+ const within = (value) => carrier.produces?.(value) !== false &&
459
+ above(value, lower, carrier) &&
460
+ below(value, upper, carrier) &&
461
+ unequal.every(refused => carrier.compare(value, refused) !== 0);
462
+ if (equal.length > 0) {
463
+ const [value] = equal;
464
+ return equal.every(other => carrier.compare(other, value) === 0) && within(value)
465
+ ? { carrier, lower: { value, inclusive: true }, upper: { value, inclusive: true } }
466
+ : false;
467
+ }
468
+ const interval = { carrier, lower, upper };
469
+ if (lower === undefined || upper === undefined) {
470
+ return interval;
471
+ }
472
+ const { step } = carrier;
473
+ if (step === undefined) {
474
+ const order = carrier.compare(lower.value, upper.value);
475
+ if (!(order < 0 || (order === 0 && within(lower.value)))) {
476
+ return false;
477
+ }
478
+ if (carrier.produces === undefined) {
479
+ return interval;
480
+ }
481
+ // A transformed string reads only as what its transforms give back, and a
482
+ // range may hold none of them (no lowercased string lies from "A" to "Z"):
483
+ // it is settled only where a value is found in it.
484
+ const found = [
485
+ lower.inclusive ? lower.value : undefined,
486
+ carrier.past?.(lower.value, 1),
487
+ upper.inclusive ? upper.value : undefined,
488
+ carrier.past?.(upper.value, -1),
489
+ ...stringsBetween(lower.value, upper.value),
490
+ ].some(value => value !== undefined && within(value));
491
+ return found ? interval : undefined;
492
+ }
493
+ let candidate = lower.inclusive ? lower.value : step(lower.value, 1);
494
+ for (let tried = 0; tried <= unequal.length; tried += 1) {
495
+ if (candidate === undefined || !below(candidate, upper, carrier)) {
496
+ return false;
497
+ }
498
+ if (within(candidate)) {
499
+ return interval;
500
+ }
501
+ candidate = step(candidate, 1);
502
+ }
503
+ return false;
504
+ }
505
+ function admitsRelation(operator, left, right) {
506
+ const { carrier } = left;
507
+ switch (operator) {
508
+ case "==":
509
+ return reaches(left.lower, right.upper, carrier) && reaches(right.lower, left.upper, carrier);
510
+ case "!=":
511
+ return !(single(left) &&
512
+ single(right) &&
513
+ carrier.compare(left.lower.value, right.lower.value) === 0);
514
+ case "<":
515
+ return strictlyReaches(left.lower, right.upper, carrier);
516
+ case "<=":
517
+ return reaches(left.lower, right.upper, carrier);
518
+ case ">":
519
+ case ">=":
520
+ return admitsRelation(mirrored[operator], right, left);
521
+ }
522
+ }
523
+ function reaches(low, high, carrier) {
524
+ if (low === undefined || high === undefined) {
525
+ return true;
526
+ }
527
+ const order = carrier.compare(low.value, high.value);
528
+ return order < 0 || (order === 0 && low.inclusive && high.inclusive);
529
+ }
530
+ function strictlyReaches(low, high, carrier) {
531
+ return low === undefined || high === undefined || carrier.compare(low.value, high.value) < 0;
532
+ }
533
+ function single(interval) {
534
+ return (interval.lower !== undefined &&
535
+ interval.upper !== undefined &&
536
+ interval.carrier.compare(interval.lower.value, interval.upper.value) === 0);
537
+ }
538
+ function above(value, lower, carrier) {
539
+ if (lower === undefined) {
540
+ return true;
541
+ }
542
+ const order = carrier.compare(value, lower.value);
543
+ return order > 0 || (lower.inclusive && order === 0);
544
+ }
545
+ function below(value, upper, carrier) {
546
+ if (upper === undefined) {
547
+ return true;
548
+ }
549
+ const order = carrier.compare(value, upper.value);
550
+ return order < 0 || (upper.inclusive && order === 0);
551
+ }
552
+ function tighter(current, next, direction, carrier) {
553
+ if (current === undefined) {
554
+ return next;
555
+ }
556
+ const order = carrier.compare(next.value, current.value) * direction;
557
+ if (order > 0) {
558
+ return next;
559
+ }
560
+ if (order < 0) {
561
+ return current;
562
+ }
563
+ return current.inclusive ? next : current;
564
+ }
565
+ // The combinations of values a way's finite positions can take together with
566
+ // the finite positions an invariant relates them to, keeping those
567
+ // invariants; undefined when a step reads anything else or there are more
568
+ // combinations to try than the limit.
569
+ export function witnessesOf(way, scope, inputCase, combinations = FEASIBILITY_COMBINATION_LIMIT) {
570
+ const groups = new Map();
571
+ const constrain = (path, constraint) => {
572
+ const key = JSON.stringify(path);
573
+ if (!groups.has(key)) {
574
+ groups.set(key, { path, measure: "value", constraints: [] });
575
+ }
576
+ groups.get(key).constraints.push(constraint);
577
+ };
578
+ for (const step of way.steps) {
579
+ const placed = placedConstraintOf(step, scope);
580
+ if (placed === undefined ||
581
+ placed.measure !== "value" ||
582
+ placed.constraints.some(constraint => constraint.operator !== "==" && constraint.operator !== "!=") ||
583
+ finiteDomainAt(scope, placed.path) === undefined) {
584
+ return undefined;
585
+ }
586
+ for (const constraint of placed.constraints) {
587
+ constrain(placed.path, constraint);
588
+ }
589
+ }
590
+ if (inputCase !== undefined && groups.has(JSON.stringify([inputCase.discriminant]))) {
591
+ constrain([inputCase.discriminant], { operator: "==", bound: inputCase.tag });
592
+ }
593
+ const tried = jointAssignments([...groups.values()], scope, combinations, undefined, true);
594
+ if (tried === "too many") {
595
+ return undefined;
596
+ }
597
+ return (function* () {
598
+ for (const assignment of tried) {
599
+ yield [...assignment].map(([key, value]) => ({ path: JSON.parse(key), value }));
600
+ }
601
+ })();
602
+ }
603
+ function finiteDomainAt(scope, path) {
604
+ const discriminated = sumOwning(scope, path);
605
+ if (discriminated !== undefined) {
606
+ // A case the sum's invariants refuse is no value the discriminant can take.
607
+ const discriminant = path[path.length - 1];
608
+ const refusing = [...discriminated.invariants, ...inheritedAt(scope, path.slice(0, -1))]
609
+ .flatMap(conjuncts)
610
+ .filter(rule => deepEqual(boundTermPath(rule), [discriminant]));
611
+ return discriminated.variantTags.filter(tag => refusing.every(rule => holds(rule, { [discriminant]: tag })));
612
+ }
613
+ const schema = schemaAtPath(scope, path);
614
+ if (schema?.kind === "boolean") {
615
+ return admittedBy([true, false], schema, scope, path);
616
+ }
617
+ if (schema?.kind === "enum") {
618
+ return admittedBy(schema.values, schema, scope, path);
619
+ }
620
+ return undefined;
621
+ }
622
+ // A rule over finite positions: each comparison reads one of them, or what
623
+ // its transforms make of it, against a constant with == or !=, combined with and/or/not. Its positions, or
624
+ // undefined when any part of it reads something else.
625
+ function finitePathsOf(rule, scope, prefix) {
626
+ switch (rule.kind) {
627
+ case "compare": {
628
+ if (isTerm(rule.left) && isTerm(rule.right)) {
629
+ const sides = [rule.left, rule.right].map(side => positionData(side));
630
+ if (sides.some(side => side === undefined)) {
631
+ return undefined;
632
+ }
633
+ const paths = sides.map(side => [...prefix, ...side.path]);
634
+ return (rule.operator === "==" || rule.operator === "!=") &&
635
+ sides.every(side => !counts(side.measure)) &&
636
+ paths.every(path => finiteDomainAt(scope, path) !== undefined)
637
+ ? paths
638
+ : undefined;
639
+ }
640
+ const normalized = normalize(rule);
641
+ // A transformed value, `lowercase($.level)`, is read off each value the
642
+ // combinations try, as the invariant is held with `holds`.
643
+ if (normalized === undefined || counts(normalized.measure)) {
644
+ return undefined;
645
+ }
646
+ if (normalized.operator !== "==" && normalized.operator !== "!=") {
647
+ return undefined;
648
+ }
649
+ const term = (isTerm(rule.left) ? rule.left : rule.right);
650
+ const path = [...prefix, ...positionOf(term).path];
651
+ return finiteDomainAt(scope, path) === undefined ? undefined : [path];
652
+ }
653
+ case "not":
654
+ return finitePathsOf(rule.rule, scope, prefix);
655
+ case "and":
656
+ case "or": {
657
+ const parts = rule.rules.map(part => finitePathsOf(part, scope, prefix));
658
+ return parts.some(part => part === undefined) ? undefined : parts.flat();
659
+ }
660
+ default:
661
+ return undefined;
662
+ }
663
+ }
664
+ // The combinations of values for the finite positions the groups constrain,
665
+ // together with every finite position an invariant relating two or more of
666
+ // them reaches, that keep those invariants, in the order of `prefer`; "too
667
+ // many" when there are more combinations to try than the limit. Unless
668
+ // `whole`, positions no such invariant reaches are left out, and nothing is
669
+ // tried when there are none.
670
+ function jointAssignments(groups, scope, combinations, prefer = () => undefined, whole = false) {
671
+ const joint = jointInvariantsOf(scope);
672
+ const constrained = groups.filter(group => group.measure === "value" && finiteDomainAt(scope, group.path) !== undefined);
673
+ const component = new Map(constrained.map(group => [JSON.stringify(group.path), group.path]));
674
+ const involved = [];
675
+ for (let grew = true; grew;) {
676
+ grew = false;
677
+ for (const invariant of joint) {
678
+ const { paths } = invariant;
679
+ if (!involved.includes(invariant) && paths.some(path => component.has(JSON.stringify(path)))) {
680
+ involved.push(invariant);
681
+ for (const path of paths) {
682
+ component.set(JSON.stringify(path), path);
683
+ }
684
+ grew = true;
685
+ }
686
+ }
687
+ }
688
+ const positions = [...component.values()];
689
+ if (involved.length === 0 && !whole) {
690
+ return [new Map()];
691
+ }
692
+ const domains = positions.map(path => {
693
+ const keeps = constrained.filter(group => JSON.stringify(group.path) === JSON.stringify(path));
694
+ const kept = finiteDomainAt(scope, path).filter(value => keeps.every(group => group.constraints.every(item => (value === item.bound) === (item.operator === "=="))));
695
+ const preferred = prefer(path);
696
+ return kept.includes(preferred) ? [preferred, ...kept.filter(value => value !== preferred)] : kept;
697
+ });
698
+ if (domains.reduce((product, domain) => product * domain.length, 1) > combinations) {
699
+ return "too many";
700
+ }
701
+ function* from(index, chosen) {
702
+ if (index === positions.length) {
703
+ const value = positions.reduce((built, path, at) => writeAt(built, path, chosen[at]), {});
704
+ if (involved.every(({ prefix, rule }) => holds(rule, readAt(value, prefix)))) {
705
+ yield new Map(positions.map((path, at) => [JSON.stringify(path), chosen[at]]));
706
+ }
707
+ return;
708
+ }
709
+ for (const candidate of domains[index]) {
710
+ yield* from(index + 1, [...chosen, candidate]);
711
+ }
712
+ }
713
+ return from(0, []);
714
+ }
715
+ // The first of the combinations jointAssignments tries, or "none".
716
+ function jointAssignment(groups, scope, combinations, prefer) {
717
+ const tried = jointAssignments(groups, scope, combinations, prefer);
718
+ if (tried === "too many") {
719
+ return "too many";
720
+ }
721
+ for (const first of tried) {
722
+ return first;
723
+ }
724
+ return "none";
725
+ }
726
+ function writeAt(value, path, leaf) {
727
+ const [key, ...rest] = path;
728
+ if (key === undefined) {
729
+ return leaf;
730
+ }
731
+ const record = (typeof value === "object" && value !== null ? value : {});
732
+ return { ...record, [key]: writeAt(record[key], rest, leaf) };
733
+ }
734
+ // Every invariant written on the scope or on an object its fields hold, with
735
+ // the path of the object it is written on.
736
+ function scopedInvariants(schema, prefix) {
737
+ if (schema.kind !== "object") {
738
+ return [];
739
+ }
740
+ const { shape } = schema;
741
+ return [
742
+ ...schema.invariants.map(rule => ({ prefix, rule })),
743
+ ...Object.entries(shape).flatMap(([key, field]) => scopedInvariants(field, [...prefix, key])),
744
+ ];
745
+ }
746
+ function readAt(value, path) {
747
+ return path.reduce((current, key) => typeof current === "object" && current !== null
748
+ ? current[key]
749
+ : undefined, value);
750
+ }
751
+ // The value `after` becomes when the finite positions an invariant relates,
752
+ // other than those `after` moved away from `before`, are chosen again so every
753
+ // such invariant holds, keeping what `after` holds wherever it can; undefined
754
+ // when no choice keeps them, when there are more combinations than the limit,
755
+ // or when it would take another case of a sum field.
756
+ export function keepingInvariants(scope, before, after, combinations = FEASIBILITY_COMBINATION_LIMIT) {
757
+ const related = distinctPaths(jointInvariantsOf(scope).flatMap(invariant => invariant.paths));
758
+ const groups = related.map((path) => ({
759
+ path,
760
+ measure: "value",
761
+ constraints: deepEqual(readAt(before, path), readAt(after, path))
762
+ ? []
763
+ : [{ operator: "==", bound: readAt(after, path) }],
764
+ }));
765
+ const assignment = jointAssignment(groups, scope, combinations, path => readAt(after, path));
766
+ if (typeof assignment === "string") {
767
+ return undefined;
768
+ }
769
+ let kept = after;
770
+ for (const [key, value] of assignment) {
771
+ const path = JSON.parse(key);
772
+ if (readAt(kept, path) === value) {
773
+ continue;
774
+ }
775
+ if (sumOwning(scope, path) !== undefined) {
776
+ return undefined;
777
+ }
778
+ kept = writeAt(kept, path, value);
779
+ }
780
+ return kept;
781
+ }
782
+ // The value `after` becomes when each invariant ordering two or more integer or
783
+ // number positions that it breaks is kept by moving one of its positions weighed
784
+ // by one, and one `after` did not move away from `before`, to the nearest value
785
+ // that keeps it; undefined when an invariant is left broken.
786
+ export function keepingOrderings(scope, before, after) {
787
+ const orderings = scopedInvariants(scope, []).flatMap(({ prefix, rule }) => {
788
+ if (rule.kind !== "compare" || ![rule.left, rule.right].every(operand => isTerm(operand) || typeof operand === "number")) {
789
+ return [];
790
+ }
791
+ const form = differenceOf(rule);
792
+ const parts = form.parts.map(part => ({ ...part, path: [...prefix, ...part.path] }));
793
+ const numeric = parts.every(part => part.measure === "value" && ["integer", "number"].includes(schemaAtPath(scope, part.path)?.kind ?? ""));
794
+ return parts.length >= 2 && numeric && typeof form.constant === "number"
795
+ ? [{ rule: rule, parts, constant: form.constant }]
796
+ : [];
797
+ });
798
+ let kept = after;
799
+ // A part moved once stays: moving it again to keep a later ordering would
800
+ // break the one it was moved for, so a chain is kept by moving its next part.
801
+ const moved = new Set();
802
+ for (let round = 0; round <= orderings.length; round++) {
803
+ const broken = orderings.find(({ rule, parts, constant }) => {
804
+ const values = parts.map(part => readAt(kept, part.path));
805
+ return (values.every(value => typeof value === "number") &&
806
+ !holds({ ...rule, left: parts.reduce((total, part, index) => total + part.coefficient * values[index], constant), right: 0 }, undefined));
807
+ });
808
+ if (broken === undefined) {
809
+ return kept;
810
+ }
811
+ const moving = broken.parts.find(part => Math.abs(part.coefficient) === 1 &&
812
+ !moved.has(JSON.stringify(part.path)) &&
813
+ deepEqual(readAt(before, part.path), readAt(after, part.path)));
814
+ if (moving === undefined) {
815
+ return undefined;
816
+ }
817
+ const rest = broken.parts.reduce((total, part) => (part === moving ? total : total + part.coefficient * readAt(kept, part.path)), broken.constant);
818
+ // coefficient * x + rest <operator> 0, read as a bound on x itself.
819
+ const operator = moving.coefficient === 1 ? broken.rule.operator : mirrored[broken.rule.operator];
820
+ const bound = -rest * moving.coefficient;
821
+ const current = readAt(kept, moving.path);
822
+ const nearest = operator === "!=" ? current + 1 : nearestKeeping(scope, moving.path, operator, bound);
823
+ if (nearest === undefined) {
824
+ return undefined;
825
+ }
826
+ kept = writeAt(kept, moving.path, nearest);
827
+ moved.add(JSON.stringify(moving.path));
828
+ }
829
+ return undefined;
830
+ }
831
+ // The value nearest `bound` on the side `operator` keeps that the position's
832
+ // own bounds admit: an integer steps by one, and a number, which has no step,
833
+ // takes the middle of what is left when less than one is.
834
+ function nearestKeeping(scope, path, operator, bound) {
835
+ const settled = settle({ path, measure: "value", constraints: [{ operator, bound }] }, scope);
836
+ if (typeof settled !== "object") {
837
+ return settled === false ? undefined : bound;
838
+ }
839
+ const lower = settled.lower?.value;
840
+ const upper = settled.upper?.value;
841
+ if (operator === ">" || operator === ">=") {
842
+ const from = lower ?? bound;
843
+ if (settled.carrier === integerCarrier || settled.lower?.inclusive !== false) {
844
+ return settled.lower?.inclusive === false ? from + 1 : from;
845
+ }
846
+ return upper !== undefined && upper - from <= 1 ? (from + upper) / 2 : from + 1;
847
+ }
848
+ if (operator === "<" || operator === "<=") {
849
+ const from = upper ?? bound;
850
+ if (settled.carrier === integerCarrier || settled.upper?.inclusive !== false) {
851
+ return settled.upper?.inclusive === false ? from - 1 : from;
852
+ }
853
+ return lower !== undefined && from - lower <= 1 ? (from + lower) / 2 : from - 1;
854
+ }
855
+ return bound;
856
+ }
857
+ // Whether no combination the invariants relating finite positions keep gives
858
+ // the position at `path` this value.
859
+ export function refusedJointly(scope, path, value, combinations = FEASIBILITY_COMBINATION_LIMIT) {
860
+ return refusedTogether(scope, [{ path, value }], combinations);
861
+ }
862
+ // No combination the invariants relating finite positions keep gives every
863
+ // one of these finite positions its value.
864
+ export function refusedTogether(scope, coordinates, combinations = FEASIBILITY_COMBINATION_LIMIT) {
865
+ return (coordinates.every(({ path }) => finiteDomainAt(scope, path) !== undefined) &&
866
+ jointAssignment(coordinates.map(({ path, value }) => ({ path, measure: "value", constraints: [{ operator: "==", bound: value }] })), scope, combinations) === "none");
867
+ }
868
+ // The invariants the scope holds that relate two or more finite positions,
869
+ // each with the positions it reads.
870
+ function jointInvariantsOf(scope) {
871
+ return scopedInvariants(scope, []).flatMap(({ prefix, rule }) => {
872
+ const paths = finitePathsOf(rule, scope, prefix);
873
+ const distinct = paths === undefined ? [] : distinctPaths(paths);
874
+ return distinct.length < 2 ? [] : [{ prefix, rule, paths: distinct }];
875
+ });
876
+ }
877
+ function distinctPaths(paths) {
878
+ return [...new Map(paths.map(path => [JSON.stringify(path), path])).values()];
879
+ }
880
+ // When every position a decision's guards and match read is finite (a
881
+ // boolean, an enum or a sum's discriminant, an optional one only where the
882
+ // field itself may be left out) and their combinations, together with the
883
+ // finite positions an invariant on only finite positions connects to them,
884
+ // are within the limit: the ways those combinations take, each with one
885
+ // combination taking it, of the combinations that keep every such invariant.
886
+ // Undefined otherwise.
887
+ export function finiteReach(decision, scope, combinations, fixed = []) {
888
+ const read = decisionPaths(decision);
889
+ if (read === undefined) {
890
+ return undefined;
891
+ }
892
+ const positions = [...distinctPaths([...read, ...fixed])];
893
+ const invariants = fieldInvariants(scope, []);
894
+ const has = (path) => positions.some(other => deepEqual(other, path));
895
+ for (let grew = true; grew;) {
896
+ grew = false;
897
+ for (const { prefix, rule } of invariants) {
898
+ const paths = termPaths(rule).map(path => [...prefix, ...path]);
899
+ if (!paths.some(has) || !paths.every(path => domainWithAbsence(scope, path) !== undefined)) {
900
+ continue;
901
+ }
902
+ for (const path of paths.filter(path => !has(path))) {
903
+ positions.push(path);
904
+ grew = true;
905
+ }
906
+ }
907
+ }
908
+ const domains = positions.map(path => domainWithAbsence(scope, path));
909
+ if (domains.some(domain => domain === undefined)) {
910
+ return undefined;
911
+ }
912
+ if (domains.reduce((product, domain) => product * domain.length, 1) > combinations) {
913
+ return undefined;
914
+ }
915
+ const keys = new Set(positions.map(path => JSON.stringify(path)));
916
+ const kept = invariants.filter(({ prefix, rule }) => termPaths(rule).every(path => keys.has(JSON.stringify([...prefix, ...path]))));
917
+ const reached = new Map();
918
+ const chosen = [];
919
+ const visit = (index) => {
920
+ if (index === positions.length) {
921
+ const value = positions.reduce((built, path, at) => (chosen[at] === undefined ? built : writeAt(built, path, chosen[at])), {});
922
+ if (!kept.every(({ prefix, rule }) => holds(rule, readAt(value, prefix)))) {
923
+ return;
924
+ }
925
+ const way = traceFinite(decision, value);
926
+ const key = JSON.stringify(way.steps.map(step => [describeStep(step), step.outcome]).concat([[String(way.exit)]]));
927
+ if (!reached.has(key)) {
928
+ reached.set(key, { way, witness: new Map(positions.map((path, at) => [JSON.stringify(path), chosen[at]])) });
929
+ }
930
+ return;
931
+ }
932
+ for (const candidate of domains[index]) {
933
+ chosen[index] = candidate;
934
+ visit(index + 1);
935
+ }
936
+ };
937
+ visit(0);
938
+ return [...reached.values()].sort((left, right) => inWayOrder(left.way, right.way));
939
+ }
940
+ // The order waysOf lists ways in: depth first, a condition holding before it
941
+ // fails, a match's cases as written.
942
+ function inWayOrder(left, right) {
943
+ const rank = (step) => {
944
+ if (step.distinction.kind === "match") {
945
+ return Object.keys(step.distinction.cases).indexOf(String(step.outcome));
946
+ }
947
+ return step.outcome === true ? 0 : 1;
948
+ };
949
+ for (let index = 0; index < Math.min(left.steps.length, right.steps.length); index++) {
950
+ const difference = rank(left.steps[index]) - rank(right.steps[index]);
951
+ if (difference !== 0) {
952
+ return difference;
953
+ }
954
+ }
955
+ return left.steps.length - right.steps.length;
956
+ }
957
+ function describeStep(step) {
958
+ return step.distinction.kind === "match" ? `match ${positionOf(step.distinction.on).path.join(".")}` : describeRule(step.distinction);
959
+ }
960
+ function decisionPaths(decision) {
961
+ const paths = [];
962
+ const collect = (rule) => {
963
+ switch (rule.kind) {
964
+ case "compare":
965
+ return [rule.left, rule.right].filter(isTerm).every(side => {
966
+ const data = positionData(side);
967
+ if (data === undefined) {
968
+ return false;
969
+ }
970
+ paths.push(data.path);
971
+ // A transformed value is read off each value of the domain as the guard
972
+ // reads it (`lowercase($.level)` of each case of an enum); a string
973
+ // has no domain, so its transformed read stays out of the plan.
974
+ return !counts(data.measure);
975
+ });
976
+ case "not":
977
+ return collect(rule.rule);
978
+ case "and":
979
+ case "or":
980
+ return rule.rules.every(collect);
981
+ default:
982
+ return false;
983
+ }
984
+ };
985
+ if (!decision.guards.every(candidate => collect(candidate.condition))) {
986
+ return undefined;
987
+ }
988
+ const { otherwise } = decision;
989
+ if (typeof otherwise !== "function") {
990
+ paths.push(positionOf(otherwise.on).path);
991
+ }
992
+ return paths.some(path => path[0] === DEPS) ? undefined : paths;
993
+ }
994
+ function domainWithAbsence(scope, path) {
995
+ const parent = rawAt(scope, path.slice(0, -1));
996
+ const last = path[path.length - 1];
997
+ const domain = finiteDomainAt(scope, path);
998
+ if (parent === undefined || last === undefined || domain === undefined) {
999
+ return undefined;
1000
+ }
1001
+ if (isVariantsSchema(parent)) {
1002
+ return parent.discriminant === last ? domain : undefined;
1003
+ }
1004
+ if (parent.kind !== "object") {
1005
+ return undefined;
1006
+ }
1007
+ const field = parent.shape[last];
1008
+ return field?.kind === "optional" ? [...domain, undefined] : domain;
1009
+ }
1010
+ // The schema at a path without stepping through an optional, which a
1011
+ // combination could not write a field under.
1012
+ function rawAt(schema, keys) {
1013
+ const [key, ...rest] = keys;
1014
+ if (key === undefined) {
1015
+ return schema;
1016
+ }
1017
+ if (schema.kind !== "object") {
1018
+ return undefined;
1019
+ }
1020
+ const field = schema.shape[key];
1021
+ return field === undefined ? undefined : rawAt(field, rest);
1022
+ }
1023
+ // Every invariant written on the scope, an object or a field it holds, or
1024
+ // what an optional field holds, with the path of what it is written on.
1025
+ function fieldInvariants(schema, prefix) {
1026
+ const own = schema.invariants.map(rule => ({ prefix, rule }));
1027
+ if (schema.kind === "optional") {
1028
+ return [...own, ...fieldInvariants(schema.schema, prefix)];
1029
+ }
1030
+ if (schema.kind !== "object") {
1031
+ return own;
1032
+ }
1033
+ const { shape } = schema;
1034
+ return [...own, ...Object.entries(shape).flatMap(([key, field]) => fieldInvariants(field, [...prefix, key]))];
1035
+ }
1036
+ function traceFinite(decision, value) {
1037
+ const steps = [];
1038
+ const distinguish = (distinction, outcome) => {
1039
+ steps.push({ distinction, outcome });
1040
+ };
1041
+ for (const [index, candidate] of decision.guards.entries()) {
1042
+ if (!holds(candidate.condition, value, undefined, distinguish)) {
1043
+ return { steps, exit: index };
1044
+ }
1045
+ }
1046
+ const { otherwise } = decision;
1047
+ if (typeof otherwise === "function") {
1048
+ return { steps, exit: "otherwise" };
1049
+ }
1050
+ steps.push({ distinction: otherwise, outcome: String(readOperand(otherwise.on, value)) });
1051
+ return { steps, exit: "case" };
1052
+ }
1053
+ //# sourceMappingURL=feasibility.js.map