@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,2123 @@
1
+ import { answersOf, callsIn, childrenOf, fieldsTurnedOn, iterationsOf, nodeOf, localRoots, localsOf, writtenArgument } from "./model.js";
2
+ import { rangeOf } from "./interval.js";
3
+ import { fractionOf } from "./exact.js";
4
+ import { selectedTag, taggedCase, verify } from "./proof.js";
5
+ import { constantsOf, domainOf } from "./domain.js";
6
+ import { pairCoverage, PAIR_LIMIT } from "./pairs.js";
7
+ import { deepEqual } from "./equal.js";
8
+ import { WAY_LIMIT, describeWay, eachWayOf, sameSteps } from "./ways.js";
9
+ import { answerFrom, fakeIssuesOf, fakeWarningsOf } from "./dependency.js";
10
+ import { answerSchema } from "./guard-scope.js";
11
+ import { comparisonsNotReadOf, ensuresBordersOf, invariantContradictionsOf, mayBeLeftOut, invariantPairBordersOf, guardBordersOf, guardPartitionsOf, feasibilityScope, } from "./guard-borders.js";
12
+ import { SpecificationError, TodoDecision, brokenEnsures, comparisonsReached, isCaseOnly, isTodo, perform, runTraced, traceSync, } from "./behavior.js";
13
+ import { DEPS, localLabel, describeRule, describeTerm, differenceOf, holds, withDeps, isTerm, positionData, positionOf, positionTerm, termData, termPaths, pathsRead } from "./rule.js";
14
+ import { emptiedBy, normalize } from "./border.js";
15
+ import { FEASIBILITY_COMBINATION_LIMIT, feasibilityOf, finiteReach, keepingInvariants, keepingOrderings, refusedJointly, tooManyWays, unreached, witnessesOf } from "./feasibility.js";
16
+ import { readEnsures } from "./ensures.js";
17
+ import { allOnOneSide, lineTheRowsAllow, partingsOf, spelled } from "./beside.js";
18
+ import { coordinatesIn, excludedCases, positionsOf, writeExactly } from "./partition.js";
19
+ import { isVariantsSchema, object, schemaAtPath, tagOf } from "./schema.js";
20
+ async function runAndCompare(definition, name, given, expected, subject) {
21
+ try {
22
+ const actual = await subject(given);
23
+ return {
24
+ actual,
25
+ failure: answers(definition, expected, actual)
26
+ ? undefined
27
+ : {
28
+ name,
29
+ message: `Expected ${JSON.stringify(expected, (_, value) => typeof value === "bigint" ? `${value}n` : value)}, received ${JSON.stringify(actual, (_, value) => typeof value === "bigint" ? `${value}n` : value)}`,
30
+ },
31
+ };
32
+ }
33
+ catch (error) {
34
+ return {
35
+ actual: undefined,
36
+ failure: { name, message: error instanceof Error ? error.message : String(error) },
37
+ error,
38
+ };
39
+ }
40
+ }
41
+ function answers(definition, expected, actual) {
42
+ const canonicalEffects = (effects) => effects.map(effect => {
43
+ const parsed = definition.effects.parse(effect);
44
+ return parsed.success ? parsed.value : effect;
45
+ });
46
+ const received = actual;
47
+ if (isCaseOnly(expected.result)) {
48
+ return isVariantsSchema(definition.result) && tagOf(definition.result, received.result) === expected.result.case &&
49
+ deepEqual(canonicalEffects(received.effects), canonicalEffects(expected.effects));
50
+ }
51
+ const result = definition.result.parse(received.result);
52
+ const answer = definition.result.parse(expected.result);
53
+ return result.success && answer.success && deepEqual(result.value, answer.value) &&
54
+ deepEqual(canonicalEffects(received.effects), canonicalEffects(expected.effects));
55
+ }
56
+ export function example(_definition, row) {
57
+ return row;
58
+ }
59
+ export function examples(behavior, table) {
60
+ return {
61
+ kind: "example-set",
62
+ behavior,
63
+ rows: Object.entries(table).map(([name, row]) => ({ kind: "example", name, ...row })),
64
+ };
65
+ }
66
+ export function spec(name, options) {
67
+ return {
68
+ kind: "specification",
69
+ name,
70
+ examples: options.examples,
71
+ implementation: options.implementation,
72
+ fakes: options.fakes ?? [],
73
+ };
74
+ }
75
+ export function isSpecification(value) {
76
+ return (typeof value === "object" &&
77
+ value !== null &&
78
+ value.kind === "specification");
79
+ }
80
+ export async function check(specification, options = {}) {
81
+ const limits = {
82
+ combinations: positiveLimit("disregards.combinations", options.disregards?.combinations, DISREGARD_COMBINATION_LIMIT),
83
+ candidates: positiveLimit("disregards.candidates", options.disregards?.candidates, DISREGARD_CANDIDATE_LIMIT),
84
+ };
85
+ const combinations = positiveLimit("feasibility.combinations", options.feasibility?.combinations, FEASIBILITY_COMBINATION_LIMIT);
86
+ const definition = specification.examples.behavior;
87
+ const wayLimit = positiveLimit("feasibility.ways", options.feasibility?.ways, WAY_LIMIT);
88
+ const coveredInputs = new Set();
89
+ const coveredResults = new Set();
90
+ const coveredEffects = new Set();
91
+ const failures = [];
92
+ const unansweredRows = [];
93
+ const executedInputs = new Set();
94
+ const verifiedInputs = new Set();
95
+ const observedResults = new Set();
96
+ const verifiedResults = new Set();
97
+ const observedEffects = new Set();
98
+ const verifiedEffects = new Set();
99
+ const guardPartitions = specification.implementation === undefined
100
+ ? []
101
+ : guardPartitionsOf(specification.implementation);
102
+ const positions = measuredPositionsOf(definition, new Set(guardPartitions.map(partition => trailKey(partition.segments))), guardReadSegmentsOf(specification.implementation), combinations);
103
+ const coveredClasses = positions.map(() => new Set());
104
+ const answeredGivens = [];
105
+ const armsMet = [];
106
+ const armsOwed = [];
107
+ const reached = [];
108
+ const waysMet = [];
109
+ const waysOwed = [];
110
+ const fakeIssues = fakeIssuesOf(definition.dependencies, definition.name, specification.fakes);
111
+ const tables = new Map(specification.fakes
112
+ .filter(table => !fakeIssues.some(item => item.table.dependency === table.dependency))
113
+ .map(table => [table.dependency, answerFrom(table)]));
114
+ const usableFakes = specification.fakes.filter(table => tables.has(table.dependency));
115
+ const standIns = (row) => ({
116
+ ...Object.fromEntries(tables),
117
+ ...(row.with ?? {}),
118
+ });
119
+ const incompleteness = [];
120
+ const externals = externalsIn(specification.implementation);
121
+ const notRunFor = (row) => {
122
+ if (externals.length === 0) {
123
+ return false;
124
+ }
125
+ incompleteness.push({
126
+ kind: "row not run",
127
+ subject: row.name,
128
+ reason: `外部の段のため実行できない(${externals.join("、")})`,
129
+ });
130
+ return true;
131
+ };
132
+ const unstoodFor = (row) => {
133
+ const written = (row.with ?? {});
134
+ for (const [name, value] of Object.entries(written)) {
135
+ const declared = definition.dependencies[name];
136
+ if (declared === undefined) {
137
+ return `with ${name} names no dependency of ${definition.name}`;
138
+ }
139
+ const parsed = declared.output.parse(value);
140
+ if (!parsed.success) {
141
+ return `with ${name} is not a value the dependency answers: ${parsed.issues[0].message}`;
142
+ }
143
+ }
144
+ const missing = Object.keys(definition.dependencies).find(name => !(name in written) && !tables.has(name));
145
+ return missing === undefined ? undefined : `No stand-in for dependency ${missing}`;
146
+ };
147
+ const observe = (inputTag, actual) => {
148
+ executedInputs.add(inputTag);
149
+ const execution = actual;
150
+ const result = isVariantsSchema(definition.result)
151
+ ? tagOf(definition.result, execution.result)
152
+ : undefined;
153
+ if (result !== undefined) {
154
+ observedResults.add(result);
155
+ }
156
+ const effects = new Set(execution.effects
157
+ .map(effect => tagOf(definition.effects, effect))
158
+ .filter((tag) => tag !== undefined));
159
+ for (const effect of effects) {
160
+ observedEffects.add(effect);
161
+ }
162
+ return { result, effects };
163
+ };
164
+ for (const row of specification.examples.rows) {
165
+ const inputValidation = definition.input.parse(row.given);
166
+ const inputTag = tagOf(definition.input, row.given);
167
+ if (!inputValidation.success) {
168
+ failures.push({ name: row.name, message: "Example input is invalid" });
169
+ continue;
170
+ }
171
+ if (isTodo(row.expect)) {
172
+ unansweredRows.push({
173
+ name: row.name,
174
+ variant: inputTag,
175
+ reason: row.expect.reason,
176
+ });
177
+ const implementation = specification.implementation;
178
+ const decision = implementation === undefined || inputTag === undefined
179
+ ? undefined
180
+ : implementation.cases[inputTag];
181
+ const unstoodOwed = unstoodFor(row);
182
+ if (implementation !== undefined && notRunFor(row)) {
183
+ continue;
184
+ }
185
+ if (implementation !== undefined && unstoodOwed !== undefined) {
186
+ failures.push({ name: row.name, message: unstoodOwed });
187
+ incompleteness.push({ kind: "row not run", subject: row.name, reason: unstoodOwed });
188
+ }
189
+ else if (implementation !== undefined &&
190
+ (implementation.pipeline !== undefined ||
191
+ (decision !== undefined && decision.kind !== "todo"))) {
192
+ try {
193
+ const traced = await runTraced(implementation, row.given, standIns(row));
194
+ observe(inputTag, traced.execution);
195
+ armsOwed.push(...traced.arms);
196
+ if (traced.way !== undefined) {
197
+ waysOwed.push(traced.way);
198
+ }
199
+ waysOwed.push(...traced.iterations);
200
+ }
201
+ catch (error) {
202
+ const open = openDecisionIn(implementation, error);
203
+ if (open !== undefined) {
204
+ incompleteness.push({ kind: "row not run", subject: row.name, reason: `判断が未定(${open})` });
205
+ }
206
+ else {
207
+ const message = error instanceof Error ? error.message : String(error);
208
+ failures.push({ name: row.name, message });
209
+ incompleteness.push({ kind: "row did not come back", subject: row.name, reason: message });
210
+ }
211
+ }
212
+ }
213
+ continue;
214
+ }
215
+ if (inputTag !== undefined) {
216
+ coveredInputs.add(inputTag);
217
+ }
218
+ answeredGivens.push(row.given);
219
+ positions.forEach((position, index) => {
220
+ if (position.kind === "divided") {
221
+ for (const found of position.classify(row.given)) {
222
+ coveredClasses[index].add(found);
223
+ }
224
+ }
225
+ });
226
+ const caseOnly = isCaseOnly(row.expect.result) ? row.expect.result.case : undefined;
227
+ const resultValid = caseOnly === undefined
228
+ ? definition.result.parse(row.expect.result).success
229
+ : isVariantsSchema(definition.result) && definition.result.variantTags.includes(caseOnly);
230
+ if (!resultValid) {
231
+ failures.push({ name: row.name, message: "Expected result is invalid" });
232
+ continue;
233
+ }
234
+ // Not held where only the case is written: every clause reads the answer,
235
+ // and nothing wrote the value it would be read against.
236
+ const broken = caseOnly === undefined ? brokenEnsures(definition, row.given, row.expect.result) : undefined;
237
+ if (broken !== undefined) {
238
+ failures.push({
239
+ name: row.name,
240
+ message: `Example breaks ensures ${broken.name}: ${describeRule(broken.rule, "")}`,
241
+ });
242
+ }
243
+ const resultTag = caseOnly ?? (isVariantsSchema(definition.result) ? tagOf(definition.result, row.expect.result) : undefined);
244
+ if (resultTag !== undefined) {
245
+ coveredResults.add(resultTag);
246
+ }
247
+ for (const effect of row.expect.effects) {
248
+ const effectTag = tagOf(definition.effects, effect);
249
+ if (effectTag !== undefined) {
250
+ coveredEffects.add(effectTag);
251
+ }
252
+ }
253
+ const implementation = specification.implementation;
254
+ const unstood = unstoodFor(row);
255
+ if (implementation !== undefined && notRunFor(row)) {
256
+ continue;
257
+ }
258
+ if (implementation !== undefined && unstood !== undefined) {
259
+ failures.push({ name: row.name, message: unstood });
260
+ incompleteness.push({ kind: "row not run", subject: row.name, reason: unstood });
261
+ }
262
+ else if (implementation !== undefined) {
263
+ const { actual, failure, error } = await runAndCompare(definition, row.name, row.given, row.expect, async (input) => {
264
+ const traced = await runTraced(implementation, input, standIns(row));
265
+ armsMet.push(...traced.arms);
266
+ reached.push(...traced.comparisons.map(comparison => ({
267
+ tag: tagOf(definition.input, input),
268
+ comparison,
269
+ given: input,
270
+ deps: standIns(row),
271
+ })));
272
+ if (traced.way !== undefined) {
273
+ waysMet.push(traced.way);
274
+ }
275
+ waysMet.push(...traced.iterations);
276
+ return traced.execution;
277
+ });
278
+ if (actual !== undefined && inputTag !== undefined) {
279
+ const observed = observe(inputTag, actual);
280
+ if (observed.result !== undefined && observed.result === resultTag) {
281
+ verifiedResults.add(observed.result);
282
+ }
283
+ for (const effect of row.expect.effects) {
284
+ const effectTag = tagOf(definition.effects, effect);
285
+ if (effectTag !== undefined && observed.effects.has(effectTag)) {
286
+ verifiedEffects.add(effectTag);
287
+ }
288
+ }
289
+ if (failure === undefined) {
290
+ verifiedInputs.add(inputTag);
291
+ const disregard = await disregardBroken(implementation, row, actual, standIns(row), limits);
292
+ if (disregard.kind === "broken") {
293
+ failures.push(disregard.failure);
294
+ }
295
+ else if (disregard.kind === "not checked") {
296
+ incompleteness.push(disregard.incompleteness);
297
+ }
298
+ }
299
+ }
300
+ const open = openDecisionIn(implementation, error);
301
+ if (open !== undefined) {
302
+ incompleteness.push({ kind: "row not run", subject: row.name, reason: `判断が未定(${open})` });
303
+ }
304
+ else if (failure !== undefined) {
305
+ failures.push(failure);
306
+ if (actual === undefined) {
307
+ incompleteness.push({
308
+ kind: "row did not come back",
309
+ subject: row.name,
310
+ reason: failure.message,
311
+ });
312
+ }
313
+ }
314
+ }
315
+ }
316
+ const pendingDecisions = todoDecisionsIn(specification.implementation);
317
+ const controlGaps = specification.implementation === undefined
318
+ ? []
319
+ : definition.effects.variantTags.flatMap(effect => {
320
+ const control = specification.implementation?.controls[effect];
321
+ if (control === undefined) {
322
+ return [{ effect, reason: "control policy is missing" }];
323
+ }
324
+ return "kind" in control && control.kind === "todo"
325
+ ? [{ effect, reason: control.reason }]
326
+ : [];
327
+ });
328
+ const refusedInputs = excludedCases(definition.input);
329
+ const input = coverage(definition.input.variantTags, coveredInputs, refusedInputs);
330
+ const result = isVariantsSchema(definition.result)
331
+ ? coverage(definition.result.variantTags, coveredResults)
332
+ : coverage([], new Set());
333
+ const effects = coverage(definition.effects.variantTags, coveredEffects);
334
+ const pairGroups = new Map();
335
+ for (const drawn of invariantPairBordersOf(definition)) {
336
+ // One form however it is written: the same paths in different weights, as
337
+ // x − y beside x + y, bound different coordinates.
338
+ const weighed = differenceOf(drawn.comparison).parts;
339
+ const entries = (drawn.reads ?? [])
340
+ .map((segments, index) => ({
341
+ at: JSON.stringify([segments, weighed[index]?.measure]),
342
+ coefficient: weighed[index]?.coefficient ?? 0,
343
+ }))
344
+ .sort((left, right) => (left.at < right.at ? -1 : left.at > right.at ? 1 : 0));
345
+ const sign = (entries[0]?.coefficient ?? 1) < 0 ? -1 : 1;
346
+ const key = JSON.stringify(entries.map(entry => [entry.at, sign * entry.coefficient]));
347
+ pairGroups.set(key, [...(pairGroups.get(key) ?? []), drawn]);
348
+ }
349
+ const modelIssues = [
350
+ ...positionsOf(definition.input).map(position => ({ path: position.path, borders: position.borders })),
351
+ ...[...pairGroups.values()]
352
+ .filter(group => !(group[0].reads ?? []).some(segments => mayBeLeftOut(definition, segments)))
353
+ .map(group => ({ path: group[0].path, borders: group.map(drawn => drawn.border) })),
354
+ ].flatMap(({ path, borders }) => {
355
+ const emptied = emptiedBy(borders);
356
+ return emptied === undefined
357
+ ? []
358
+ : [`${path}: 不変条件を満たす値がありません (${emptied.map(border => border.rule).join(", ")})`];
359
+ }).concat(invariantContradictionsOf(definition));
360
+ const partitions = positions.map((position, index) => {
361
+ const drawn = guardPartitions.find(partition => deepEqual(partition.segments, position.segments));
362
+ if (drawn !== undefined && position.kind !== "divided") {
363
+ const values = answeredGivens.flatMap(given => position.valuesIn(given));
364
+ const names = drawn.classes.map(item => item.name);
365
+ const reached = new Set(drawn.classes
366
+ .filter(item => values.some(value => value !== undefined && item.contains(value)))
367
+ .map(item => item.name));
368
+ const { covered, missing } = coverage(names, reached);
369
+ return {
370
+ path: position.path,
371
+ kind: "divided",
372
+ covered,
373
+ missing,
374
+ excluded: drawn.excluded,
375
+ };
376
+ }
377
+ if (position.kind !== "divided") {
378
+ return { path: position.path, kind: position.kind };
379
+ }
380
+ const { covered, missing } = coverage(position.classes.filter(className => !position.excluded.includes(className)), coveredClasses[index]);
381
+ return {
382
+ path: position.path,
383
+ kind: "divided",
384
+ covered,
385
+ missing,
386
+ excluded: position.excluded,
387
+ };
388
+ });
389
+ const borders = positions.flatMap(position => position.borders.map((border) => {
390
+ const coordinates = answeredGivens.flatMap(given => coordinatesIn(position, border.measure, given));
391
+ return {
392
+ path: position.path,
393
+ rule: border.rule,
394
+ points: border.points.map(point => ({
395
+ role: point.role,
396
+ relation: point.relation,
397
+ status: point.status !== "owed"
398
+ ? point.status
399
+ : coordinates.some(value => point.contains(value))
400
+ ? "met"
401
+ : "gap",
402
+ })),
403
+ };
404
+ }));
405
+ const guardBorders = (specification.implementation === undefined ? [] : guardBordersOf(specification.implementation)).map((drawn) => {
406
+ const reachedIt = reached.filter(item => item.comparison.rule === drawn.comparison && item.tag === drawn.origin?.tag);
407
+ const coordinates = reachedIt.map(item => drawn.coordinateOf(item.comparison));
408
+ const points = drawn.border.points.map(point => {
409
+ const base = { role: point.role, relation: point.relation };
410
+ if (point.status !== "owed") {
411
+ return { ...base, status: point.status };
412
+ }
413
+ if (coordinates.some(value => point.contains(value))) {
414
+ return { ...base, status: "met" };
415
+ }
416
+ return { ...base, ...unmetStatus(pointFeasibility(drawn, point, specification.implementation, combinations, wayLimit, usableFakes)) };
417
+ });
418
+ const owed = drawn.border.points.flatMap((point, index) => (point.status === "owed" ? [points[index]] : []));
419
+ const due = drawn.form !== undefined &&
420
+ owed.some(point => point.status === "met") &&
421
+ owed.every(point => point.status === "met" || point.status === "no row owed");
422
+ const beside = due ? besideOf(definition, specification.implementation, drawn, reachedIt).beside : undefined;
423
+ return {
424
+ path: drawn.path,
425
+ rule: drawn.border.rule,
426
+ points,
427
+ ...(beside === undefined ? {} : { beside }),
428
+ };
429
+ });
430
+ borders.push(...guardBorders);
431
+ // Not met by reaching a comparison, as a guard border is: what an ensures
432
+ // clause or an input invariant states holds of every input of the case.
433
+ const writtenCoverage = (drawn) => {
434
+ const coordinates = answeredGivens
435
+ .filter(given => drawn.segments[0] === `@${tagOf(definition.input, given)}`)
436
+ .map(given => drawn.coordinateOf({ rule: drawn.comparison, scope: given }));
437
+ return {
438
+ path: drawn.path,
439
+ rule: drawn.border.rule,
440
+ points: drawn.border.points.map(point => ({
441
+ role: point.role,
442
+ relation: point.relation,
443
+ status: point.status !== "owed"
444
+ ? point.status
445
+ : coordinates.some(value => value !== undefined && point.contains(value))
446
+ ? "met"
447
+ : "gap",
448
+ })),
449
+ };
450
+ };
451
+ borders.push(...[...ensuresBordersOf(definition), ...invariantPairBordersOf(definition)]
452
+ .filter(drawn => !disregardsBorder(definition, drawn))
453
+ .map(writtenCoverage));
454
+ const pairAnalysis = pairCoverage(definition, specification.implementation, positions, guardPartitions, specification.examples.rows, {
455
+ obligations: positiveLimit("pairs.obligations", options.pairs?.obligations, PAIR_LIMIT),
456
+ candidates: positiveLimit("pairs.candidates", options.pairs?.candidates, combinations),
457
+ });
458
+ const pairGap = pairAnalysis.measure.obligations.some(pair => pair.status === "gap" || pair.status === "answer owed");
459
+ const adequate = !pairGap &&
460
+ fakeIssues.length === 0 &&
461
+ specification.implementation !== undefined &&
462
+ failures.length === 0 &&
463
+ unansweredRows.length === 0 &&
464
+ pendingDecisions.length === 0 &&
465
+ controlGaps.length === 0 &&
466
+ modelIssues.length === 0 &&
467
+ input.missing.length === 0 &&
468
+ result.missing.length === 0 &&
469
+ effects.missing.length === 0 &&
470
+ partitions.every(partition => partition.kind !== "divided" || partition.missing.length === 0) &&
471
+ borders.every(border => border.points.every(point => point.status !== "gap")) &&
472
+ borders.every(border => border.beside?.status !== "not told");
473
+ const plans = plansOf(specification.implementation, combinations, wayLimit);
474
+ const arms = measureArms(specification.implementation, armsMet, armsOwed, combinations, plans, usableFakes);
475
+ const rulesMeasure = measureRules(specification.implementation, waysMet, waysOwed, combinations, plans, usableFakes);
476
+ const lines = [
477
+ ...(arms.status === "unavailable" ? [] : arms.arms),
478
+ ...(rulesMeasure.status === "unavailable" ? [] : rulesMeasure.rules),
479
+ ];
480
+ const armGap = lines.some(line => line.status === "gap" || line.status === "answer owed");
481
+ const armUndecided = lines.some(line => line.status === "undecided") ||
482
+ borders.some(border => border.points.some(point => point.status === "undecided") || border.beside?.status === "undecided");
483
+ const unreadComparisons = specification.implementation === undefined
484
+ ? []
485
+ : comparisonsNotReadOf(specification.implementation);
486
+ const comparisons = unreadComparisons.length === 0
487
+ ? { status: "complete" }
488
+ : { status: "partial", notRead: unreadComparisons };
489
+ const constructions = specification.implementation === undefined ? { status: "undetermined", decisions: [] } : verify(specification.implementation, { candidates: combinations, ways: wayLimit });
490
+ const verdict = !adequate || armGap || constructions.status === "refuted"
491
+ ? "not_satisfied"
492
+ : constructions.status !== "verified" || comparisons.status === "partial" ||
493
+ pairAnalysis.measure.status === "partial" ||
494
+ armUndecided ||
495
+ externals.length > 0 ||
496
+ incompleteness.some(item => item.kind === "disregards not checked")
497
+ ? "undetermined"
498
+ : arms.status === "complete" ||
499
+ (arms.status === "unavailable" && arms.reason === "not applicable")
500
+ ? "satisfied"
501
+ : "undetermined";
502
+ return {
503
+ specification: specification.name,
504
+ behavior: definition.name,
505
+ input,
506
+ result,
507
+ effects,
508
+ implementation: specification.implementation === undefined ? "missing" : "present",
509
+ unanswered: unansweredRows,
510
+ pendingDecisions,
511
+ controlGaps,
512
+ modelIssues,
513
+ incompleteness,
514
+ ensures: readEnsures(definition),
515
+ failures,
516
+ partitions,
517
+ borders,
518
+ pairs: countPairs(pairablesOf(positions, guardPartitions), answeredGivens),
519
+ fakeIssues: fakeIssues.map(item => item.issue),
520
+ fakeWarnings: fakeWarningsOf(definition.dependencies, specification.fakes),
521
+ evidence: {
522
+ input: definition.input.variantTags.filter(tag => !refusedInputs.includes(tag)).map(tag => ({
523
+ case: tag,
524
+ specified: coveredInputs.has(tag),
525
+ executed: executedInputs.has(tag),
526
+ verified: verifiedInputs.has(tag),
527
+ })),
528
+ result: isVariantsSchema(definition.result)
529
+ ? definition.result.variantTags.map(tag => ({
530
+ case: tag,
531
+ specified: coveredResults.has(tag),
532
+ observed: observedResults.has(tag),
533
+ verified: verifiedResults.has(tag),
534
+ }))
535
+ : [],
536
+ effects: definition.effects.variantTags.map(tag => ({
537
+ case: tag,
538
+ specified: coveredEffects.has(tag),
539
+ observed: observedEffects.has(tag),
540
+ verified: verifiedEffects.has(tag),
541
+ })),
542
+ },
543
+ measures: { arms, rules: rulesMeasure, comparisons, pairs: pairAnalysis.measure, constructions },
544
+ adequate: verdict === "satisfied",
545
+ verdict,
546
+ };
547
+ }
548
+ export function generate(target, implementation, options = {}) {
549
+ const combinations = positiveLimit("feasibility.combinations", options.feasibility?.combinations, FEASIBILITY_COMBINATION_LIMIT);
550
+ const definition = target.kind === "behavior" ? target : target.behavior;
551
+ const wayLimit = positiveLimit("feasibility.ways", options.feasibility?.ways, WAY_LIMIT);
552
+ const rows = target.kind === "behavior" ? [] : target.rows.filter(row => definition.input.parse(row.given).success);
553
+ const existing = new Set(rows
554
+ .map(row => tagOf(definition.input, row.given))
555
+ .filter((tag) => tag !== undefined));
556
+ const answeredRows = rows.filter(row => !isTodo(row.expect));
557
+ const origins = answeredRows.map(row => row.given);
558
+ const standIns = Object.fromEntries(Object.entries(definition.dependencies)
559
+ .filter(([, declared]) => declared.takes === "nothing")
560
+ .map(([name, declared]) => [name, declared.output.placeholder(name)]));
561
+ // Stand-ins a search ran a row it found with, which the row is offered with.
562
+ const searchedStandIns = new Map();
563
+ const withFrom = (origin) => {
564
+ const searchedWith = searchedStandIns.get(origin);
565
+ if (searchedWith !== undefined)
566
+ return { with: searchedWith };
567
+ const written = answeredRows.find(row => row.given === origin)?.with;
568
+ const standing = { ...standIns, ...written };
569
+ return Object.keys(standing).length === 0 && written === undefined ? {} : { with: standing };
570
+ };
571
+ const originFor = (position) => origins.find(given => position.valuesIn(given).length > 0) ??
572
+ definition.input.placeholder();
573
+ const fakeTables = new Map((options.fakes ?? [])
574
+ .filter(table => table.behavior === definition.name)
575
+ .filter(table => !fakeIssuesOf(definition.dependencies, definition.name, options.fakes ?? []).some(item => item.table.dependency === table.dependency))
576
+ .map(table => [table.dependency, table]));
577
+ const usableFakes = [...fakeTables.values()];
578
+ const answering = Object.fromEntries([...fakeTables].map(([name, table]) => [name, answerFrom(table)]));
579
+ const tracedWith = (stand) => ({ ...answering, ...stand });
580
+ // A row asking each dependency what one of its fake rows asks: the call's
581
+ // argument written into the input where the argument reads the input.
582
+ const askingFakes = (tag, decision, origins, reaches) => {
583
+ const expression = decision.expression;
584
+ if (expression === undefined)
585
+ return undefined;
586
+ for (const call of callsIn(expression)) {
587
+ const table = fakeTables.get(call.dependency);
588
+ for (const [asked] of table?.rows ?? []) {
589
+ for (const origin of origins) {
590
+ const given = writtenArgument(origin, call.input, asked);
591
+ if (given !== undefined && tagOf(definition.input, given) === tag && definition.input.parse(given).success && reaches(given)) {
592
+ return given;
593
+ }
594
+ }
595
+ }
596
+ }
597
+ const calls = callsIn(expression);
598
+ for (const origin of origins) {
599
+ for (const given of askingTogether(origin, calls, dependency => (fakeTables.get(dependency)?.rows ?? []).map(([asked]) => asked))) {
600
+ if (tagOf(definition.input, given) === tag && definition.input.parse(given).success && reaches(given))
601
+ return given;
602
+ }
603
+ }
604
+ return undefined;
605
+ };
606
+ // What a point or a way that turns on a dependency's answer still needs: a
607
+ // fake row answering there, asked by an input the row can write.
608
+ const askedOf = (locals) => {
609
+ const called = [...new Set(locals.map(localLabel).filter(label => label.endsWith("()")))];
610
+ return called.length === 0 ? "" : ` — ${called.join("・")}がそう答えるfakeの行がない`;
611
+ };
612
+ const generated = [];
613
+ const notComposed = [];
614
+ // A row moved from `from` that breaks an invariant relating finite positions
615
+ // is offered with the other positions chosen again to keep it.
616
+ const offer = (row, from) => {
617
+ const parsed = definition.input.parse(row.given);
618
+ if (parsed.success) {
619
+ generated.push(row);
620
+ return;
621
+ }
622
+ const tag = tagOf(definition.input, row.given);
623
+ const scope = tag === undefined ? undefined : feasibilityScope(definition, tag);
624
+ const finite = from === undefined || scope === undefined ? undefined : keepingInvariants(scope, from, row.given, combinations);
625
+ const kept = finite === undefined || definition.input.parse(finite).success
626
+ ? finite
627
+ : keepingOrderings(scope, from, finite);
628
+ if (kept !== undefined && definition.input.parse(kept).success) {
629
+ generated.push({ ...row, given: kept });
630
+ }
631
+ else {
632
+ notComposed.push(`${row.name}: ${parsed.issues[0].message}`);
633
+ }
634
+ };
635
+ const guardDivided = new Set((implementation === undefined ? [] : guardPartitionsOf(implementation)).map(partition => trailKey(partition.segments)));
636
+ const guardRead = guardReadSegmentsOf(implementation);
637
+ const refused = excludedCases(definition.input);
638
+ for (const tag of definition.input.variantTags.filter(tag => !existing.has(tag) && !refused.includes(tag))) {
639
+ const given = definition.input.placeholderFor(tag);
640
+ offer({ name: `${definition.name}: ${tag}`, given, reason: `${tag}の期待結果を人間が決める必要があります`, ...withFrom(given) }, given);
641
+ }
642
+ for (const position of measuredPositionsOf(definition, guardDivided, guardRead, combinations)) {
643
+ if (position.kind !== "divided") {
644
+ continue;
645
+ }
646
+ for (const className of position.classes) {
647
+ if (position.excluded.includes(className)) {
648
+ continue;
649
+ }
650
+ const standsIn = [...rows, ...generated].some(row => position.classify(row.given).includes(className));
651
+ if (!standsIn) {
652
+ const origin = originFor(position);
653
+ offer({
654
+ name: `${definition.name}: ${position.path} = ${className}`,
655
+ given: position.place(origin, className),
656
+ reason: `${position.path}が${className}の期待結果を人間が決める必要があります`,
657
+ ...withFrom(origin),
658
+ }, origin);
659
+ }
660
+ }
661
+ }
662
+ for (const position of measuredPositionsOf(definition, guardDivided, guardRead, combinations)) {
663
+ for (const border of position.borders) {
664
+ for (const point of border.points) {
665
+ if (point.status !== "owed" || point.witness === undefined) {
666
+ continue;
667
+ }
668
+ const standsAt = [...rows, ...generated].some(row => coordinatesIn(position, border.measure, row.given).some(value => point.contains(value)));
669
+ if (!standsAt) {
670
+ const origin = originFor(position);
671
+ const given = writeExactly(position, origin, border.measure, point.witness);
672
+ if (given === undefined) {
673
+ notComposed.push(`${position.path} ${point.role} (${point.relation})`);
674
+ continue;
675
+ }
676
+ offer({
677
+ name: `${definition.name}: ${position.path} ${point.role} (${point.relation})`,
678
+ given,
679
+ reason: `${position.path}の${point.role}点(${point.relation})の期待結果を人間が決める必要があります`,
680
+ ...withFrom(origin),
681
+ }, origin);
682
+ }
683
+ }
684
+ }
685
+ }
686
+ const positionsByPath = new Map(positionsOf(definition.input).map(position => [trailKey(position.segments), position]));
687
+ for (const drawn of implementation === undefined ? [] : guardPartitionsOf(implementation)) {
688
+ const position = positionsByPath.get(trailKey(drawn.segments));
689
+ if (position === undefined) {
690
+ continue;
691
+ }
692
+ for (const item of drawn.classes) {
693
+ const standsIn = [...rows, ...generated].some(row => position.valuesIn(row.given).some(value => value !== undefined && item.contains(value)));
694
+ if (!standsIn) {
695
+ const origin = originFor(position);
696
+ offer({
697
+ name: `${definition.name}: ${drawn.path} = ${item.name}`,
698
+ given: position.write(origin, "value", item.witness),
699
+ reason: `${drawn.path}が${item.name}の期待結果を人間が決める必要があります`,
700
+ ...withFrom(origin),
701
+ }, origin);
702
+ }
703
+ }
704
+ }
705
+ for (const drawn of implementation === undefined ? [] : guardBordersOf(implementation)) {
706
+ const reachedBy = (given, deps) => tagOf(definition.input, given) === drawn.origin?.tag
707
+ ? comparisonsReached(implementation, given, tracedWith(deps)).filter(item => item.rule === drawn.comparison)
708
+ : [];
709
+ for (const point of drawn.border.points) {
710
+ if (point.status !== "owed" || point.witness === undefined) {
711
+ continue;
712
+ }
713
+ const standsAt = [...rows, ...generated].some(row => reachedBy(row.given, row.with).some(item => point.contains(drawn.coordinateOf(item))));
714
+ if (standsAt || unmetStatus(pointFeasibility(drawn, point, implementation, combinations, wayLimit, usableFakes)).status === "no row owed") {
715
+ continue;
716
+ }
717
+ const origin = origins.find(given => reachedBy(given, withFrom(given).with).length > 0) ??
718
+ definition.input.placeholder();
719
+ const candidates = sidesOf(drawn)
720
+ .map(side => drawn.compose(origin, point.witness, withFrom(origin).with, side))
721
+ .filter(candidate => candidate !== undefined);
722
+ // A row the input takes stands at the point only once the guards before
723
+ // the comparison let it through, which moving another part may not.
724
+ const reaches = (candidate) => reachedBy(candidate, withFrom(origin).with).some(item => point.contains(drawn.coordinateOf(item)));
725
+ // A comparison on a value the model computes cannot be written, but an input the search ran may reach it at the point.
726
+ const searchedPoint = () => {
727
+ if (drawn.origin === undefined || drawn.origin.decision.expression === undefined)
728
+ return undefined;
729
+ const hit = searchedWays(implementation, drawn.origin.tag, drawn.origin.decision, combinations, usableFakes).witnessed
730
+ .find(item => item.comparison.rule === drawn.comparison && point.contains(drawn.coordinateOf(item.comparison)) && definition.input.parse(item.given).success);
731
+ if (hit === undefined)
732
+ return undefined;
733
+ if (hit.with !== undefined)
734
+ searchedStandIns.set(hit.given, hit.with);
735
+ return hit.given;
736
+ };
737
+ const given = candidates.find(candidate => definition.input.parse(candidate).success && reaches(candidate)) ??
738
+ askingFakes(drawn.origin?.tag ?? "", drawn.origin?.decision, [
739
+ ...origins.filter(candidate => tagOf(definition.input, candidate) === drawn.origin?.tag),
740
+ ...(drawn.origin === undefined ? [] : [definition.input.placeholderFor(drawn.origin.tag)]),
741
+ ], reaches) ??
742
+ searchedPoint() ??
743
+ candidates.find(candidate => !definition.input.parse(candidate).success) ??
744
+ candidates.find(candidate => definition.input.parse(candidate).success);
745
+ if (given === undefined) {
746
+ notComposed.push(`${drawn.path} ${point.role} (${point.relation})${askedOf(drawn.segments.flatMap(segment => segment.startsWith(".#local:") ? [segment.slice(1)] : []))}`);
747
+ }
748
+ else {
749
+ offer({
750
+ name: `${definition.name}: ${drawn.path} ${point.role} (${point.relation})`,
751
+ given,
752
+ reason: `${drawn.path}の${point.role}点(${point.relation})の期待結果を人間が決める必要があります`,
753
+ ...withFrom(searchedStandIns.has(given) ? given : origin),
754
+ }, origin);
755
+ }
756
+ }
757
+ if (drawn.form === undefined) {
758
+ continue;
759
+ }
760
+ const items = rows.flatMap(row => reachedBy(row.given, row.with).map(comparison => ({ comparison, given: row.given, deps: row.with })));
761
+ const owed = drawn.border.points.filter(point => point.status === "owed");
762
+ const standsAt = (point) => items.some(item => point.contains(drawn.coordinateOf(item.comparison)));
763
+ const due = owed.some(standsAt) &&
764
+ owed.every(point => standsAt(point) || unmetStatus(pointFeasibility(drawn, point, implementation, combinations, wayLimit, usableFakes)).status === "no row owed");
765
+ const found = due ? besideOf(definition, implementation, drawn, items) : undefined;
766
+ if (found?.beside.status !== "not told") {
767
+ continue;
768
+ }
769
+ const label = `${drawn.path} 隣の線 (${found.beside.another})`;
770
+ if (found.given === undefined) {
771
+ notComposed.push(label);
772
+ }
773
+ else {
774
+ offer({
775
+ name: `${definition.name}: ${label}`,
776
+ given: found.given,
777
+ reason: `${drawn.path}を${found.beside.another}と見分ける行の期待結果を人間が決める必要があります`,
778
+ ...(found.deps === undefined ? withFrom(found.given) : { with: { ...standIns, ...found.deps } }),
779
+ });
780
+ }
781
+ }
782
+ for (const drawn of invariantPairBordersOf(definition).filter(drawn => !disregardsBorder(definition, drawn))) {
783
+ const under = (given) => drawn.segments[0] === `@${tagOf(definition.input, given)}`;
784
+ for (const point of drawn.border.points) {
785
+ if (point.status !== "owed" || point.witness === undefined) {
786
+ continue;
787
+ }
788
+ const standsAt = [...rows, ...generated].some(row => under(row.given) && point.contains(drawn.coordinateOf({ rule: drawn.comparison, scope: row.given })));
789
+ if (standsAt) {
790
+ continue;
791
+ }
792
+ const origin = origins.find(under) ?? definition.input.placeholderFor(drawn.segments[0].slice(1));
793
+ const candidates = sidesOf(drawn)
794
+ .map(side => drawn.compose(origin, point.witness, withFrom(origin).with, side))
795
+ .filter(candidate => candidate !== undefined);
796
+ const given = candidates.find(candidate => definition.input.parse(candidate).success) ?? candidates[0];
797
+ if (given === undefined) {
798
+ notComposed.push(`${drawn.path} ${point.role} (${point.relation})`);
799
+ }
800
+ else {
801
+ offer({
802
+ name: `${definition.name}: ${drawn.path} ${point.role} (${point.relation})`,
803
+ given,
804
+ reason: `${drawn.path}の${point.role}点(${point.relation})の期待結果を人間が決める必要があります`,
805
+ ...withFrom(origin),
806
+ }, origin);
807
+ }
808
+ }
809
+ }
810
+ const plans = plansOf(implementation, combinations, wayLimit);
811
+ for (const [tag, decision] of Object.entries(implementation?.cases ?? {})) {
812
+ if (decision.kind !== "rules") {
813
+ continue;
814
+ }
815
+ const wayOf = (given, deps) => traceSync(implementation, given, tracedWith(deps)).way;
816
+ const takes = (given, deps, way) => {
817
+ if (way.within !== undefined) {
818
+ return traceSync(implementation, given, tracedWith(deps)).iterations.some(taken => taken.within === way.within && sameSteps(taken.steps, way.steps));
819
+ }
820
+ const taken = wayOf(given, deps);
821
+ return taken !== undefined && sameSteps(taken.steps, way.steps);
822
+ };
823
+ const { discriminant } = definition.input;
824
+ // Not a lookup by the term's own trail: a term steps through an optional
825
+ // without naming it, so that trail finds whether the field is left out.
826
+ const at = (path) => {
827
+ const wanted = trailKey([`@${tag}`, ...path.map(key => `.${key}`)]);
828
+ return [...positionsByPath.values()]
829
+ .filter(position => trailKey(position.segments.filter(step => step !== "?")) === wanted)
830
+ .sort((left, right) => right.segments.length - left.segments.length)[0];
831
+ };
832
+ const leftOut = (path) => positionsByPath.get(trailKey([`@${tag}`, ...path.map(key => `.${key}`)]));
833
+ const placed = (origin, witnessed) => {
834
+ let given = origin;
835
+ for (const { path, value } of witnessed) {
836
+ if (path.length === 1 && path[0] === discriminant) {
837
+ continue;
838
+ }
839
+ const position = value === undefined ? leftOut(path) : (at(path) ?? at(path.slice(0, -1)));
840
+ if (position?.kind !== "divided") {
841
+ return undefined;
842
+ }
843
+ given = position.place(given, value === undefined ? "なし" : String(value));
844
+ }
845
+ return given;
846
+ };
847
+ const origins_ = [
848
+ ...origins.filter(given => tagOf(definition.input, given) === tag),
849
+ definition.input.placeholderFor(tag),
850
+ ];
851
+ const plan = plans.get(decision);
852
+ if (plan?.kind === "too many") {
853
+ notComposed.push(`${decision.id}: ${tooManyWays(wayLimit)}ため組み立てない`);
854
+ continue;
855
+ }
856
+ const candidates = plan?.kind === "finite"
857
+ ? plan.reached.filter(item => item.tag === tag)
858
+ : (plan?.ways ?? []).map(way => ({ way, witness: undefined }));
859
+ for (const { way, witness } of candidates) {
860
+ if ([...rows, ...generated].some(row => takes(row.given, row.with, way))) {
861
+ continue;
862
+ }
863
+ if (witness === undefined &&
864
+ wayFeasibility(way, implementation, tag, decision, combinations, usableFakes).kind === "infeasible") {
865
+ continue;
866
+ }
867
+ const taken = (candidate) => candidate !== undefined && takes(candidate.given, withFrom(candidate.origin).with, way)
868
+ ? candidate
869
+ : undefined;
870
+ const throughFakes = askingFakes(tag, decision, origins_, given => takes(given, withFrom(given).with, way));
871
+ const composed = (throughFakes === undefined ? undefined : { given: throughFakes, origin: throughFakes }) ??
872
+ (way.within === undefined ? undefined : composeElement(way)) ??
873
+ taken(searched(way)) ??
874
+ taken(composeForWay(way, tag)) ??
875
+ (options.ways !== true
876
+ ? undefined
877
+ : witness === undefined
878
+ ? taken(composeFromWitnesses(way))
879
+ : composeFromReach(way, witness));
880
+ if (composed !== undefined) {
881
+ offer({
882
+ name: `${definition.name}: ${decision.id} ${describeWay(way)}`,
883
+ given: composed.given,
884
+ reason: `${decision.id}の道筋(${describeWay(way)})の期待結果を人間が決める必要があります`,
885
+ ...withFrom(composed.origin),
886
+ });
887
+ }
888
+ else {
889
+ notComposed.push(`${decision.id}: ${describeWay(way)}${askedOf(way.steps.flatMap(step => localRoots(step.distinction)))}`);
890
+ }
891
+ }
892
+ // A way one element takes through an iteration's body: a row whose array
893
+ // holds that one element, taken from what the rows hold or moved into each
894
+ // class of the element's positions.
895
+ function composeElement(way) {
896
+ const values = way.within?.values;
897
+ const position = isTerm(values) ? positionData(values) : undefined;
898
+ if (position === undefined || position.measure !== "value" || position.path.some(key => key.startsWith("#")))
899
+ return undefined;
900
+ const read = (given) => position.path.reduce((at, key) => (at !== null && typeof at === "object" ? at[key] : undefined), given);
901
+ const held = [...rows, ...generated].flatMap(row => {
902
+ const array = read(row.given);
903
+ return Array.isArray(array) ? array : [];
904
+ });
905
+ const trail = [`@${tag}`, ...position.path.map(key => `.${key}`), "[]"];
906
+ const moved = [...positionsByPath.values()].filter(at => at.kind === "divided" && trailKey(at.segments.slice(0, trail.length)) === trailKey(trail));
907
+ for (const origin of origins_) {
908
+ const candidates = [
909
+ ...held.map(element => writtenArgument(origin, values, [element])),
910
+ ...moved.flatMap(at => at.kind === "divided" ? at.classes.map(name => at.place(writtenArgument(origin, values, held.slice(0, 1)) ?? origin, name)) : []),
911
+ ];
912
+ for (const given of candidates) {
913
+ if (given !== undefined && definition.input.parse(given).success && takes(given, withFrom(origin).with, way))
914
+ return { given, origin };
915
+ }
916
+ }
917
+ return undefined;
918
+ }
919
+ // A way through a value the model computes, from an input the search found
920
+ // taking it.
921
+ function searched(way) {
922
+ if (opaqueRead(way, decision).length === 0)
923
+ return undefined;
924
+ const factored = factoredWitness(way, implementation, tag, decision, combinations)?.given;
925
+ const found = searchedWitness(way, implementation, tag, decision, combinations, usableFakes)
926
+ ?? (factored === undefined ? undefined : { given: factored });
927
+ if (found === undefined)
928
+ return undefined;
929
+ if (found.with !== undefined)
930
+ searchedStandIns.set(found.given, found.with);
931
+ return { given: found.given, origin: found.given };
932
+ }
933
+ function composeFromReach(way, witness) {
934
+ const witnessed = [...witness].map(([key, value]) => ({ path: JSON.parse(key), value }));
935
+ for (const origin of origins_) {
936
+ const given = placed(origin, witnessed);
937
+ if (given !== undefined && definition.input.parse(given).success && takes(given, withFrom(origin).with, way)) {
938
+ return { given, origin };
939
+ }
940
+ }
941
+ return undefined;
942
+ }
943
+ function composeFromWitnesses(way) {
944
+ for (const origin of origins_) {
945
+ const witnesses = witnessesOf(way, scopeOf(implementation, tag, decision), { discriminant, tag }, combinations);
946
+ if (witnesses === undefined) {
947
+ break;
948
+ }
949
+ for (const witnessed of witnesses) {
950
+ const given = placed(origin, witnessed);
951
+ if (given !== undefined && definition.input.parse(given).success && takes(given, withFrom(origin).with, way)) {
952
+ return { given, origin };
953
+ }
954
+ }
955
+ }
956
+ const searched = domainOf(definition.input, combinations, constantsOf(decision.kind === "rules" ? decision.guards.map(guard => guard.condition) : []));
957
+ for (const given of searched.values) {
958
+ if (takes(given, withFrom(given).with, way))
959
+ return { given, origin: given };
960
+ }
961
+ return undefined;
962
+ }
963
+ function composeForWay(way, caseTag) {
964
+ const last = way.steps[way.steps.length - 1];
965
+ if (last === undefined || last.distinction.kind !== "match") {
966
+ return undefined;
967
+ }
968
+ const matched = last.distinction;
969
+ const keys = positionOf(matched.on).path;
970
+ // A match on an enum selects the position itself; one on a sum field's
971
+ // discriminant selects the field holding it.
972
+ const at = (path) => positionsByPath.get(trailKey([`@${caseTag}`, ...path.map(key => `.${key}`)]));
973
+ const position = at(keys) ?? at(keys.slice(0, -1));
974
+ const origin = origins.find(given => wayOf(given, withFrom(given).with)?.steps.some(step => step.distinction === matched));
975
+ return position?.kind === "divided" && origin !== undefined
976
+ ? { given: position.place(origin, String(last.outcome)), origin }
977
+ : undefined;
978
+ }
979
+ }
980
+ const pairs = pairCoverage(definition, implementation, measuredPositionsOf(definition, guardDivided, guardRead, combinations), implementation === undefined ? [] : guardPartitionsOf(implementation), [...rows, ...generated.map(row => ({ ...row, kind: "example", expect: { kind: "todo", reason: row.reason } }))], { obligations: positiveLimit("pairs.obligations", options.pairs?.obligations, PAIR_LIMIT), candidates: positiveLimit("pairs.candidates", options.pairs?.candidates, combinations) });
981
+ for (const { obligation, given } of pairs.witnesses) {
982
+ if (generated.some(row => deepEqual(row.given, given)))
983
+ continue;
984
+ offer({ name: `${definition.name}: ${obligation.positions[0]} = ${obligation.classes[0]} × ${obligation.positions[1]} = ${obligation.classes[1]}`, given,
985
+ reason: "組み合わせの期待結果を人間が決める必要があります", ...withFrom(given) });
986
+ }
987
+ notComposed.push(...pairs.measure.notRead, ...pairs.measure.obligations.filter(pair => pair.status === "undecided").map(pair => `${pair.positions.join(" × ")}: ${pair.classes.join(" × ")} (${pair.reason})`));
988
+ return { rows: generated, notComposed };
989
+ }
990
+ export async function evaluate(exampleSet, name, subject) {
991
+ const row = exampleSet.rows.find(row => row.name === name);
992
+ if (row === undefined) {
993
+ throw new SpecificationError(`No example named ${name} in ${exampleSet.behavior.name}`);
994
+ }
995
+ return evaluateRow(exampleSet.behavior, row, subject);
996
+ }
997
+ async function evaluateRow(definition, row, subject) {
998
+ const name = row.name;
999
+ if (isTodo(row.expect)) {
1000
+ return { name, status: "skipped", reason: row.expect.reason };
1001
+ }
1002
+ let actual;
1003
+ try {
1004
+ const input = definition.input.parse(row.given);
1005
+ if (!input.success) {
1006
+ throw new SpecificationError(`Example input is invalid: ${input.issues[0].message}`);
1007
+ }
1008
+ const expected = row.expect;
1009
+ assertExecution(definition, expected, true);
1010
+ if (!isCaseOnly(expected.result)) {
1011
+ assertEnsures(definition, row.given, expected.result, "Example");
1012
+ }
1013
+ const outcome = await runAndCompare(definition, name, input.value, expected, async (given) => {
1014
+ actual = await subject(given);
1015
+ assertExecution(definition, actual, false);
1016
+ assertEnsures(definition, row.given, actual.result, "Answer");
1017
+ return actual;
1018
+ });
1019
+ if (outcome.failure !== undefined) {
1020
+ return { name, status: "failed", message: outcome.failure.message, ...(actual === undefined ? {} : { actual }) };
1021
+ }
1022
+ return { name, status: "passed", actual: actual };
1023
+ }
1024
+ catch (error) {
1025
+ return { name, status: "failed", message: error instanceof Error ? error.message : String(error) };
1026
+ }
1027
+ }
1028
+ function assertExecution(definition, execution, expected) {
1029
+ if (typeof execution !== "object" || execution === null ||
1030
+ !("result" in execution) || !("effects" in execution) || !Array.isArray(execution.effects)) {
1031
+ throw new SpecificationError(`${expected ? "Expected execution" : "Execution"} is invalid: expected result and an effects array`);
1032
+ }
1033
+ if (expected && isCaseOnly(execution.result)) {
1034
+ if (!isVariantsSchema(definition.result) || !definition.result.variantTags.includes(execution.result.case)) {
1035
+ throw new SpecificationError("Expected result is invalid: unknown case");
1036
+ }
1037
+ }
1038
+ else {
1039
+ const result = definition.result.parse(execution.result);
1040
+ if (!result.success) {
1041
+ throw new SpecificationError(`${expected ? "Expected result" : "Result"} is invalid: ${result.issues[0].message}`);
1042
+ }
1043
+ }
1044
+ for (const [index, effect] of execution.effects.entries()) {
1045
+ const parsed = definition.effects.parse(effect, `$.effects[${index}]`);
1046
+ if (!parsed.success) {
1047
+ throw new SpecificationError(`${expected ? "Expected effect" : `Effect ${index}`} is invalid: ${parsed.issues[0].message}`);
1048
+ }
1049
+ }
1050
+ }
1051
+ function assertEnsures(definition, input, result, source) {
1052
+ const broken = brokenEnsures(definition, input, result);
1053
+ if (broken !== undefined) {
1054
+ throw new SpecificationError(`${source} breaks ensures ${broken.name}: ${describeRule(broken.rule, "")}`);
1055
+ }
1056
+ }
1057
+ export async function test(exampleSet, subject) {
1058
+ const failures = [];
1059
+ const skipped = [];
1060
+ for (const row of exampleSet.rows) {
1061
+ const outcome = await evaluateRow(exampleSet.behavior, row, subject);
1062
+ if (outcome.status === "failed") {
1063
+ failures.push({ name: outcome.name, message: outcome.message });
1064
+ }
1065
+ else if (outcome.status === "skipped") {
1066
+ skipped.push({ name: outcome.name, reason: outcome.reason });
1067
+ }
1068
+ }
1069
+ return { failures, skipped };
1070
+ }
1071
+ function pairablesOf(positions, guardPartitions) {
1072
+ return positions.flatMap((position) => {
1073
+ if (position.kind === "divided") {
1074
+ return [
1075
+ {
1076
+ path: position.path,
1077
+ classes: position.classes.filter(name => !position.excluded.includes(name)),
1078
+ classify: given => position.classify(given),
1079
+ },
1080
+ ];
1081
+ }
1082
+ const drawn = guardPartitions.find(partition => deepEqual(partition.segments, position.segments));
1083
+ if (drawn === undefined) {
1084
+ return [];
1085
+ }
1086
+ return [
1087
+ {
1088
+ path: position.path,
1089
+ classes: drawn.classes.map(item => item.name),
1090
+ classify: given => position
1091
+ .valuesIn(given)
1092
+ .flatMap(value => value === undefined
1093
+ ? []
1094
+ : drawn.classes.filter(item => item.contains(value)).map(item => item.name)),
1095
+ },
1096
+ ];
1097
+ });
1098
+ }
1099
+ function countPairs(pairables, givens) {
1100
+ const pairs = [];
1101
+ pairables.forEach((left, index) => {
1102
+ for (const right of pairables.slice(index + 1)) {
1103
+ if (!combine(left.path, right.path)) {
1104
+ continue;
1105
+ }
1106
+ const reached = new Set(givens.flatMap(given => left
1107
+ .classify(given)
1108
+ .flatMap(first => right.classify(given).map(second => `${first}\u0000${second}`))));
1109
+ pairs.push({
1110
+ positions: [left.path, right.path],
1111
+ reached: reached.size,
1112
+ total: left.classes.length * right.classes.length,
1113
+ });
1114
+ }
1115
+ });
1116
+ return pairs;
1117
+ }
1118
+ function combine(left, right) {
1119
+ if (right.startsWith(`${left}@`) || left.startsWith(`${right}@`)) {
1120
+ return false;
1121
+ }
1122
+ const narrowings = (path) => [...path.matchAll(/@([^.@\[\]{}?]+)/g)].map(found => ({
1123
+ before: path.slice(0, found.index),
1124
+ tag: found[1],
1125
+ }));
1126
+ const rightNarrowings = narrowings(right);
1127
+ return narrowings(left).every(narrowing => rightNarrowings.every(other => other.before !== narrowing.before || other.tag === narrowing.tag));
1128
+ }
1129
+ function measureRules(implementation, met, owed, combinations, plans, fakes) {
1130
+ if (implementation === undefined || implementation.pipeline !== undefined) {
1131
+ return { status: "unavailable", reason: "not applicable" };
1132
+ }
1133
+ if (implementation.external !== undefined) {
1134
+ return { status: "unavailable", reason: "not measured", notRead: [implementation.behavior.name] };
1135
+ }
1136
+ const decided = decisionsWithCases(implementation);
1137
+ const notRead = decided.flatMap(([decision]) => decision.kind === "decision" || (decision.kind === "rules" && plans.get(decision)?.kind === "too many")
1138
+ ? [decision.id]
1139
+ : []);
1140
+ const took = (taken, decision, way) => taken.some(item => item.decision === decision && item.within === way.within && sameSteps(item.steps, way.steps));
1141
+ const rules = decided.flatMap(([decision, tags]) => {
1142
+ const plan = plans.get(decision);
1143
+ if (decision.kind !== "rules" || plan === undefined || plan.kind === "too many") {
1144
+ return [];
1145
+ }
1146
+ const ways = plan.kind === "finite" ? plan.reached.map(item => item.way) : plan.ways;
1147
+ return ways.map((way) => {
1148
+ const base = { decision: decision.id, way: describeWay(way) };
1149
+ if (took(met, decision.id, way)) {
1150
+ return { ...base, status: "met" };
1151
+ }
1152
+ if (took(owed, decision.id, way)) {
1153
+ return { ...base, status: "answer owed" };
1154
+ }
1155
+ return plan.kind === "finite"
1156
+ ? { ...base, status: "gap" }
1157
+ : {
1158
+ ...base,
1159
+ ...unmetStatus(tags.map(tag => wayFeasibility(way, implementation, tag, decision, combinations, fakes))),
1160
+ };
1161
+ });
1162
+ });
1163
+ if (notRead.length === 0) {
1164
+ return { status: "complete", rules };
1165
+ }
1166
+ return rules.length === 0
1167
+ ? { status: "unavailable", reason: "not measured", notRead }
1168
+ : { status: "partial", rules, notRead };
1169
+ }
1170
+ function measureArms(implementation, met, owed, combinations, plans, fakes) {
1171
+ if (implementation === undefined || implementation.pipeline !== undefined) {
1172
+ return { status: "unavailable", reason: "not applicable" };
1173
+ }
1174
+ if (implementation.external !== undefined) {
1175
+ return { status: "unavailable", reason: "not measured", notRead: [implementation.behavior.name] };
1176
+ }
1177
+ const decided = decisionsWithCases(implementation);
1178
+ const notRead = decided.flatMap(([decision]) => decision.kind === "decision" || (decision.kind === "rules" && plans.get(decision)?.kind === "too many")
1179
+ ? [decision.id]
1180
+ : []);
1181
+ const took = (taken, decision, guard, arm) => taken.some(item => item.decision === decision && item.guard === guard && item.arm === arm);
1182
+ const arms = decided.flatMap(([decision, tags]) => {
1183
+ const plan = plans.get(decision);
1184
+ if (decision.kind !== "rules" || plan === undefined || plan.kind === "too many") {
1185
+ return [];
1186
+ }
1187
+ const ways = plan.kind === "finite"
1188
+ ? plan.reached.map(({ way }) => ({ way, feasibility: { kind: "feasible" } }))
1189
+ : tags.flatMap(tag => plan.ways.map(way => ({
1190
+ way,
1191
+ feasibility: wayFeasibility(way, implementation, tag, decision, combinations, fakes),
1192
+ })));
1193
+ const through = (index, arm) => ways.filter(({ way }) => decision.expression !== undefined
1194
+ ? way.choices?.some(choice => choice.condition === decision.guards[index]?.condition && choice.outcome === (arm === "holds"))
1195
+ : index === decision.guards.length
1196
+ ? way.exit === "case" && way.steps[way.steps.length - 1]?.outcome === arm
1197
+ : arm === "else"
1198
+ ? way.exit === index
1199
+ : typeof way.exit !== "number" || way.exit > index);
1200
+ const statusOf = (index, arm) => took(met, decision.id, index, arm)
1201
+ ? { status: "met" }
1202
+ : took(owed, decision.id, index, arm)
1203
+ ? { status: "answer owed" }
1204
+ : plan.kind === "finite" && through(index, arm).length === 0
1205
+ ? { status: "no row owed", reason: unreached }
1206
+ : unmetStatus(through(index, arm).map(item => item.feasibility));
1207
+ const guarded = decision.guards.flatMap((candidate, index) => ["holds", "else"].map((arm) => ({
1208
+ decision: decision.id,
1209
+ guard: describeRule(candidate.condition),
1210
+ arm,
1211
+ ...statusOf(index, arm),
1212
+ })));
1213
+ const { otherwise } = decision;
1214
+ const matched = typeof otherwise === "function"
1215
+ ? []
1216
+ : Object.keys(otherwise.cases).map((arm) => ({
1217
+ decision: decision.id,
1218
+ guard: `match ${describeTerm(otherwise.on)}`,
1219
+ arm,
1220
+ ...statusOf(decision.guards.length, arm),
1221
+ }));
1222
+ return [...guarded, ...matched];
1223
+ });
1224
+ if (notRead.length === 0) {
1225
+ return { status: "complete", arms };
1226
+ }
1227
+ return arms.length === 0
1228
+ ? { status: "unavailable", reason: "not measured", notRead }
1229
+ : { status: "partial", arms, notRead };
1230
+ }
1231
+ // Not one entry per case: $default hands one decision to several cases, and
1232
+ // listing it per case would owe each of its arms once for every case it decides.
1233
+ function decisionsWithCases(implementation) {
1234
+ const grouped = new Map();
1235
+ for (const [tag, decision] of Object.entries(implementation.cases)) {
1236
+ grouped.set(decision, [...(grouped.get(decision) ?? []), tag]);
1237
+ }
1238
+ return [...grouped];
1239
+ }
1240
+ function stagesOf(implementation) {
1241
+ return implementation.pipeline === undefined
1242
+ ? [implementation]
1243
+ : implementation.pipeline.flatMap(stagesOf);
1244
+ }
1245
+ function todoDecisionsIn(implementation) {
1246
+ if (implementation === undefined) {
1247
+ return [];
1248
+ }
1249
+ const composed = implementation.pipeline !== undefined;
1250
+ return stagesOf(implementation).flatMap(stage => Object.entries(stage.cases).flatMap(([variant, decision]) => decision.kind === "todo"
1251
+ ? [{ variant: composed ? `${stage.behavior.name}: ${variant}` : variant, reason: decision.reason }]
1252
+ : []));
1253
+ }
1254
+ function openDecisionIn(implementation, error) {
1255
+ if (!(error instanceof TodoDecision)) {
1256
+ return undefined;
1257
+ }
1258
+ return implementation.pipeline === undefined
1259
+ ? error.variant
1260
+ : `${error.behavior}: ${error.variant}`;
1261
+ }
1262
+ export function externalsIn(implementation) {
1263
+ if (implementation === undefined) {
1264
+ return [];
1265
+ }
1266
+ if (implementation.external !== undefined) {
1267
+ return [`${implementation.behavior.name}: ${implementation.external.reason}`];
1268
+ }
1269
+ return implementation.pipeline === undefined
1270
+ ? []
1271
+ : implementation.pipeline.flatMap(stage => externalsIn(stage));
1272
+ }
1273
+ const searches = new WeakMap();
1274
+ const tableIds = new WeakMap();
1275
+ let tableCount = 0;
1276
+ const IMPOSSIBLE = Symbol("an answer the dependency's contract refuses");
1277
+ function searchedWays(implementation, tag, decision, combinations, fakes = []) {
1278
+ const definition = implementation.behavior;
1279
+ // Keyed by the tables themselves, not the array holding them, which every check builds anew.
1280
+ if (!tableIds.has(definition))
1281
+ tableIds.set(definition, ++tableCount);
1282
+ const key = `${tableIds.get(definition)}\u0000${tag}\u0000${combinations}\u0000${fakes.map(table => {
1283
+ if (!tableIds.has(table))
1284
+ tableIds.set(table, ++tableCount);
1285
+ return tableIds.get(table);
1286
+ }).join(",")}`;
1287
+ const cached = searches.get(decision)?.get(key);
1288
+ if (cached !== undefined)
1289
+ return cached;
1290
+ const answering = Object.fromEntries(fakes.map(table => [table.dependency, answerFrom(table)]));
1291
+ const rules = Object.values(implementation.cases).flatMap(item => item.kind === "rules" ? item.guards.map(guard => guard.condition) : []);
1292
+ const values = Object.entries(definition.dependencies).filter(([, declared]) => declared.takes === "nothing");
1293
+ const expression = decision.expression;
1294
+ // Only the fields the ways turn on are tried, the rest held at a placeholder,
1295
+ // where no invariant of the case relates the two.
1296
+ const variant = definition.input.variants[tag];
1297
+ const turned = expression === undefined ? undefined : fieldsTurnedOn(expression, argumentMatters(definition, variant.shape));
1298
+ const caseRules = [...variant.invariants, ...definition.input.invariants];
1299
+ const projected = turned !== undefined && caseRules.every(rule => pathsRead(rule).every(path => path.length > 0 && turned.has(path[0])))
1300
+ ? object(Object.fromEntries(Object.entries(variant.shape).filter(([key]) => turned.has(key))))
1301
+ : undefined;
1302
+ const placeholder = definition.input.placeholderFor(tag);
1303
+ const inputSchema = projected ?? definition.input;
1304
+ const schema = values.length === 0
1305
+ ? inputSchema
1306
+ : object({ input: inputSchema, deps: object(Object.fromEntries(values.map(([name, declared]) => [name, declared.output]))) });
1307
+ const raw = domainOf(schema, combinations, constantsOf(rules));
1308
+ const filled = (input) => (projected === undefined ? input : { ...placeholder, ...input, [definition.input.discriminant]: tag });
1309
+ const domain = {
1310
+ exhaustive: raw.exhaustive,
1311
+ values: raw.values.map(value => (values.length === 0 ? filled(value) : { ...value, input: filled(value.input) })),
1312
+ };
1313
+ const calls = expression === undefined ? [] : callsIn(expression);
1314
+ const inputOf = (candidate) => (values.length === 0 ? candidate : candidate.input);
1315
+ const standOf = (candidate) => (values.length === 0 ? undefined : candidate.deps);
1316
+ // Each input also asks every call what a fake row asks, where the argument
1317
+ // reads the input, so an answer a fake gives is reached.
1318
+ const asking = (candidate) => calls.flatMap(call => (fakes.find(table => table.dependency === call.dependency)?.rows ?? []).flatMap(([asked]) => {
1319
+ const written = writtenArgument(inputOf(candidate), call.input, asked);
1320
+ return written === undefined ? [] : [values.length === 0 ? written : { ...candidate, input: written }];
1321
+ }));
1322
+ const askingMore = (candidate) => askingTogether(inputOf(candidate), calls, dependency => (fakes.find(table => table.dependency === dependency)?.rows ?? []).map(([asked]) => asked))
1323
+ .map(written => (values.length === 0 ? written : { ...candidate, input: written }));
1324
+ const candidates = [...domain.values, ...domain.values.flatMap(asking), ...(calls.length < 2 ? [] : domain.values.flatMap(askingMore))].filter(candidate => tagOf(definition.input, inputOf(candidate)) === tag);
1325
+ const taken = [];
1326
+ const witnessed = [];
1327
+ const possible = [];
1328
+ const reached = [];
1329
+ const note = (ways, way) => {
1330
+ if (!ways.some(item => item.within === way.within && sameSteps(item.steps, way.steps)))
1331
+ ways.push(way);
1332
+ };
1333
+ for (const candidate of candidates) {
1334
+ const traced = traceSync(implementation, inputOf(candidate), { ...answering, ...standOf(candidate) });
1335
+ // A run that fails took the way it failed on: a row there shows the failure.
1336
+ if (traced.ended !== true && traced.error === undefined)
1337
+ continue;
1338
+ for (const comparison of traced.comparisons) {
1339
+ witnessed.push({ comparison, given: inputOf(candidate), ...(standOf(candidate) === undefined ? {} : { with: standOf(candidate) }) });
1340
+ }
1341
+ for (const way of [...(traced.way === undefined ? [] : [traced.way]), ...traced.iterations]) {
1342
+ if (!taken.some(item => item.way.within === way.within && sameSteps(item.way.steps, way.steps))) {
1343
+ taken.push({ way, given: inputOf(candidate), ...(standOf(candidate) === undefined ? {} : { with: standOf(candidate) }) });
1344
+ }
1345
+ }
1346
+ }
1347
+ // Every answer the contract allows: one answer for each dependency called, so
1348
+ // the runs are every answer only where each is called at one place, not in an
1349
+ // iteration.
1350
+ const called = [...new Set(calls.map(call => call.dependency))];
1351
+ const answers = called.map(name => {
1352
+ const declared = Object.hasOwn(definition.dependencies, name) ? definition.dependencies[name] : undefined;
1353
+ const bound = expression === undefined ? undefined : answersOf(expression).find(answer => answer.dependency === name)?.schema;
1354
+ if (declared?.takes !== "input")
1355
+ return { values: [], exhaustive: false };
1356
+ return domainOf(bound === undefined ? declared.output : answerSchema(declared.output, bound), combinations);
1357
+ });
1358
+ const once = called.every(name => calls.filter(call => call.dependency === name).length === 1) &&
1359
+ (expression === undefined || iterationsOf(expression).every(iteration => callsIn(iteration.body).length === 0));
1360
+ let exhaustive = domain.exhaustive && answers.every(answer => answer.exhaustive) && once;
1361
+ let budget = combinations;
1362
+ const assignments = function* (index, chosen) {
1363
+ if (index === answers.length) {
1364
+ yield chosen;
1365
+ return;
1366
+ }
1367
+ for (const value of answers[index].values)
1368
+ yield* assignments(index + 1, [...chosen, value]);
1369
+ };
1370
+ search: for (const candidate of domain.values.filter(value => tagOf(definition.input, inputOf(value)) === tag)) {
1371
+ for (const assignment of assignments(0, [])) {
1372
+ if (--budget < 0) {
1373
+ exhaustive = false;
1374
+ break search;
1375
+ }
1376
+ const answer = Object.fromEntries(called.map((name, index) => [name, (argument) => {
1377
+ const declared = definition.dependencies[name];
1378
+ const injected = declared.takes === "input" ? declared.injected?.behavior : undefined;
1379
+ if (injected !== undefined && brokenEnsures(injected, argument, assignment[index]) !== undefined)
1380
+ throw IMPOSSIBLE;
1381
+ return assignment[index];
1382
+ }]));
1383
+ const traced = traceSync(implementation, inputOf(candidate), { ...answer, ...standOf(candidate) });
1384
+ if (traced.error === IMPOSSIBLE)
1385
+ continue;
1386
+ // A run answering a promise was not followed to its end.
1387
+ if (traced.ended !== true && traced.error === undefined) {
1388
+ exhaustive = false;
1389
+ continue;
1390
+ }
1391
+ for (const way of [...(traced.way === undefined ? [] : [traced.way]), ...traced.iterations])
1392
+ note(possible, way);
1393
+ reached.push(...traced.comparisons);
1394
+ }
1395
+ }
1396
+ for (const item of taken)
1397
+ note(possible, item.way);
1398
+ const searched = { taken, possible, reached, witnessed, exhaustive };
1399
+ const byTag = searches.get(decision) ?? new Map();
1400
+ byTag.set(key, searched);
1401
+ searches.set(decision, byTag);
1402
+ return searched;
1403
+ }
1404
+ function searchedWitness(way, implementation, tag, decision, combinations, fakes) {
1405
+ return searchedWays(implementation, tag, decision, combinations, fakes).taken
1406
+ .find(item => item.way.within === way.within && sameSteps(item.way.steps, way.steps));
1407
+ }
1408
+ // Inputs written so two or more calls are each asked what one of their fake
1409
+ // rows asks, the later written over the earlier where they share a field, so a
1410
+ // way that turns on several dependencies' answers is reached. Asking one call
1411
+ // is left to the callers; the rows stop at ASKED_TOGETHER_LIMIT.
1412
+ const ASKED_TOGETHER_LIMIT = 256;
1413
+ function askingTogether(input, calls, askedBy) {
1414
+ const found = [];
1415
+ let level = [{ value: input, after: -1 }];
1416
+ for (let size = 1; size <= calls.length && found.length < ASKED_TOGETHER_LIMIT; size++) {
1417
+ const next = [];
1418
+ grow: for (const { value, after } of level) {
1419
+ for (let index = after + 1; index < calls.length; index++) {
1420
+ for (const asked of askedBy(calls[index].dependency)) {
1421
+ if (next.length >= ASKED_TOGETHER_LIMIT)
1422
+ break grow;
1423
+ const written = writtenArgument(value, calls[index].input, asked);
1424
+ if (written !== undefined)
1425
+ next.push({ value: written, after: index });
1426
+ }
1427
+ }
1428
+ }
1429
+ if (size >= 2)
1430
+ for (const item of next)
1431
+ if (found.length < ASKED_TOGETHER_LIMIT)
1432
+ found.push(item.value);
1433
+ level = next;
1434
+ }
1435
+ return found;
1436
+ }
1437
+ // A way through the body of an iteration over a field is taken only by an input
1438
+ // whose array holds an element, so the way also asks for one.
1439
+ function withEntry(way, entered = []) {
1440
+ const values = way.within?.values;
1441
+ const position = isTerm(values) ? positionData(values) : undefined;
1442
+ if (position === undefined || position.measure !== "value")
1443
+ return entered.length === 0 ? way : { ...way, steps: [...way.steps, ...entered] };
1444
+ const holdsOne = { kind: "compare", operator: ">=", left: positionTerm(position.path, "length"), right: 1 };
1445
+ return { ...way, steps: [...way.steps, ...entered, { distinction: holdsOne, outcome: true }] };
1446
+ }
1447
+ // Whether some row could take a way: a way reading a value the model computes
1448
+ // (`localsOf`'s opaque locals) is settled by running the case's inputs through
1449
+ // the decision, as far as they are few enough to try.
1450
+ function wayFeasibility(way, implementation, tag, decision, combinations, fakes) {
1451
+ const settled = way.steps.find(step => step.distinction.kind !== "match" && termPaths(step.distinction).length === 0 && holds(step.distinction, {}) !== step.outcome);
1452
+ if (settled !== undefined)
1453
+ return { kind: "infeasible", reason: "値を読まない条件で、この結果にならない" };
1454
+ // An iteration entered several ways is reachable where any of them is.
1455
+ const entries = (way.entered ?? [[]]).map(entered => {
1456
+ const entering = withEntry(way, entered);
1457
+ return feasibilityOf(entering, scopeOf(implementation, tag, decision, entering), undefined, combinations);
1458
+ });
1459
+ const found = entries.find(item => item.kind === "feasible") ?? entries.find(item => item.kind === "undecided") ?? entries[0];
1460
+ if (found.kind === "feasible" && way.entryUnlisted === true)
1461
+ return { kind: "undecided", reason: "反復に入る道筋が多すぎて、すべては調べきれない" };
1462
+ const expression = decision.expression;
1463
+ if (found.kind !== "feasible" || expression === undefined)
1464
+ return found;
1465
+ const read = opaqueRead(way, decision);
1466
+ if (read.length === 0)
1467
+ return found;
1468
+ const outside = outsideRange(way, implementation, tag, decision);
1469
+ if (outside !== undefined)
1470
+ return { kind: "infeasible", reason: outside };
1471
+ const searched = searchedWays(implementation, tag, decision, combinations, fakes);
1472
+ if (searched.possible.some(item => item.within === way.within && sameSteps(item.steps, way.steps)))
1473
+ return found;
1474
+ if (searched.exhaustive) {
1475
+ return { kind: "infeasible", reason: "入力の全値を試し、この道筋を通る値がない" };
1476
+ }
1477
+ const factored = factoredSearch(way, implementation, tag, decision, combinations);
1478
+ if (factored === "found")
1479
+ return found;
1480
+ if (factored === "none")
1481
+ return { kind: "infeasible", reason: "積が定数になる因数の組をすべて試し、この道筋を通るものがない" };
1482
+ return { kind: "undecided", reason: `${[...new Set(read.map(localLabel))].join("・")}はモデルが計算する値で、試した入力ではこの道筋を通らない` };
1483
+ }
1484
+ // Whether what a dependency is asked may change what a way takes: unless its
1485
+ // ensures say nothing of the argument and it takes every value the input field
1486
+ // asked of it may hold.
1487
+ function argumentMatters(definition, shape) {
1488
+ const plain = new Set(["string", "boolean", "number", "integer"]);
1489
+ return (name, argument) => {
1490
+ const declared = Object.hasOwn(definition.dependencies, name) ? definition.dependencies[name] : undefined;
1491
+ if (declared?.takes !== "input" || (declared.injected?.behavior.ensures.length ?? 0) > 0)
1492
+ return true;
1493
+ const position = isTerm(argument) ? positionData(argument) : undefined;
1494
+ if (position === undefined || position.measure !== "value" || position.path.length !== 1 || !Object.hasOwn(shape, position.path[0]))
1495
+ return true;
1496
+ const field = shape[position.path[0]], taken = declared.input;
1497
+ return !(plain.has(field.kind) && field.kind === taken.kind && field.invariants.length === 0 && taken.invariants.length === 0);
1498
+ };
1499
+ }
1500
+ // What a bind holds, by its local's name.
1501
+ function boundValueOf(template, name) {
1502
+ const node = nodeOf(template);
1503
+ if (node?.kind === "bind" && node.name === name)
1504
+ return node.value;
1505
+ for (const child of childrenOf(template)) {
1506
+ const found = boundValueOf(child, name);
1507
+ if (found !== undefined)
1508
+ return found;
1509
+ }
1510
+ return undefined;
1511
+ }
1512
+ // A step comparing a computed sum, difference or product with a constant, where
1513
+ // the bounds of what it reads leave it no value that takes the step's outcome
1514
+ // (two inputs of at least 2 never multiply to less than 4): why, or undefined.
1515
+ function outsideRange(way, implementation, tag, decision) {
1516
+ const expression = decision.expression;
1517
+ if (expression === undefined)
1518
+ return undefined;
1519
+ const scope = scopeOf(implementation, tag, decision, way);
1520
+ for (const step of way.steps) {
1521
+ const rule = step.distinction;
1522
+ if (rule.kind !== "compare" || typeof step.outcome !== "boolean")
1523
+ continue;
1524
+ const [term, constant, operator] = isTerm(rule.left) && !isTerm(rule.right)
1525
+ ? [rule.left, rule.right, rule.operator]
1526
+ : isTerm(rule.right) && !isTerm(rule.left) ? [rule.right, rule.left, mirroredOperator(rule.operator)] : [undefined, undefined, rule.operator];
1527
+ const position = term === undefined ? undefined : positionData(term);
1528
+ if (position === undefined || position.measure !== "value" || position.path.length !== 1)
1529
+ continue;
1530
+ const value = boundValueOf(expression, position.path[0]);
1531
+ if (value === undefined)
1532
+ continue;
1533
+ const range = rangeOf(value, scope, way.steps.filter(other => other !== step));
1534
+ let bound;
1535
+ try {
1536
+ bound = fractionOf(constant);
1537
+ }
1538
+ catch {
1539
+ continue;
1540
+ }
1541
+ if (range === undefined)
1542
+ continue;
1543
+ const meets = (holdsIt) => {
1544
+ const wanted = holdsIt ? operator : negated[operator];
1545
+ const { low, high } = range;
1546
+ switch (wanted) {
1547
+ case "<": return low.comparedTo(bound) < 0;
1548
+ case "<=": return low.comparedTo(bound) <= 0;
1549
+ case ">": return high.comparedTo(bound) > 0;
1550
+ case ">=": return high.comparedTo(bound) >= 0;
1551
+ case "==": return low.comparedTo(bound) <= 0 && high.comparedTo(bound) >= 0;
1552
+ case "!=": return !(low.comparedTo(bound) === 0 && high.comparedTo(bound) === 0);
1553
+ }
1554
+ };
1555
+ if (!meets(step.outcome)) {
1556
+ return `${localLabel(position.path[0])}が取りうる範囲(${String(range.low)}〜${String(range.high)})では、この結果にならない`;
1557
+ }
1558
+ }
1559
+ return undefined;
1560
+ }
1561
+ const negated = { "<": ">=", "<=": ">", ">": "<=", ">=": "<", "==": "!=", "!=": "==" };
1562
+ function mirroredOperator(operator) {
1563
+ return { "<": ">", "<=": ">=", ">": "<", ">=": "<=", "==": "==", "!=": "!=" }[operator];
1564
+ }
1565
+ // A way whose step holds that a product of two integer inputs equals a whole
1566
+ // number N other than 0 is taken only by inputs whose two factors are a
1567
+ // divisor pair of N. Those pairs, with every value of the other fields the ways
1568
+ // turn on, are every input that could take it: "found" where one does, "none"
1569
+ // where none does and the rest were all tried, undefined where it cannot tell.
1570
+ const FACTOR_LIMIT = 10 ** 12;
1571
+ function factoredSearch(way, implementation, tag, decision, combinations) {
1572
+ const found = factoredWitness(way, implementation, tag, decision, combinations);
1573
+ return found === undefined ? undefined : found.given !== undefined ? "found" : found.exhaustive ? "none" : undefined;
1574
+ }
1575
+ function factoredWitness(way, implementation, tag, decision, combinations) {
1576
+ const expression = decision.expression;
1577
+ const definition = implementation.behavior;
1578
+ if (expression === undefined || Object.keys(definition.dependencies).length > 0)
1579
+ return undefined;
1580
+ for (const step of way.steps) {
1581
+ const rule = step.distinction;
1582
+ if (rule.kind !== "compare" || step.outcome !== (rule.operator === "==") || (rule.operator !== "==" && rule.operator !== "!="))
1583
+ continue;
1584
+ const [term, constant] = isTerm(rule.left) ? [rule.left, rule.right] : [rule.right, rule.left];
1585
+ const position = isTerm(term) ? positionData(term) : undefined;
1586
+ if (position === undefined || position.measure !== "value" || position.path.length !== 1 || typeof constant !== "number" || !Number.isSafeInteger(constant) || constant === 0 || Math.abs(constant) > FACTOR_LIMIT)
1587
+ continue;
1588
+ const product = nodeOf(boundValueOf(expression, position.path[0]));
1589
+ if (product?.kind !== "operation" || product.operator !== "multiply")
1590
+ continue;
1591
+ const [first, second] = [product.left, product.right].map(side => (isTerm(side) ? positionData(side) : undefined));
1592
+ const variant = definition.input.variants[tag];
1593
+ if (first === undefined || second === undefined || first.path.length !== 1 || second.path.length !== 1 || first.path[0] === second.path[0])
1594
+ continue;
1595
+ if ([first, second].some(side => side.measure !== "value" || variant.shape[side.path[0]]?.kind !== "integer"))
1596
+ continue;
1597
+ const divisors = [];
1598
+ for (let d = 1; d * d <= Math.abs(constant); d++) {
1599
+ if (constant % d === 0)
1600
+ divisors.push(d, -d, constant / d, -constant / d);
1601
+ }
1602
+ const pairs = [...new Set(divisors)].map(d => [d, constant / d]);
1603
+ const turned = fieldsTurnedOn(expression, argumentMatters(definition, variant.shape));
1604
+ const others = Object.fromEntries(Object.entries(variant.shape).filter(([key]) => (turned === undefined || turned.has(key)) && key !== first.path[0] && key !== second.path[0]));
1605
+ const caseRules = [...variant.invariants, ...definition.input.invariants];
1606
+ const separate = turned !== undefined && caseRules.every(rule => pathsRead(rule).every(path => path.length > 0 && turned.has(path[0])));
1607
+ const rest = domainOf(object(others), combinations);
1608
+ const placeholder = definition.input.placeholderFor(tag);
1609
+ let tried = 0;
1610
+ let refused = false;
1611
+ for (const [a, b] of pairs) {
1612
+ for (const other of rest.values) {
1613
+ if (++tried > combinations)
1614
+ return { exhaustive: false };
1615
+ const given = { ...placeholder, ...other, [first.path[0]]: a, [second.path[0]]: b, [definition.input.discriminant]: tag };
1616
+ if (!definition.input.parse(given).success) {
1617
+ // A pair a factor's own bounds refuse is no input. One they take, in an input refused for what else it holds, may be refused only by the placeholder: the search then proves nothing.
1618
+ if (variant.shape[first.path[0]].parse(a).success && variant.shape[second.path[0]].parse(b).success)
1619
+ refused = true;
1620
+ continue;
1621
+ }
1622
+ const traced = traceSync(implementation, given);
1623
+ if ([...(traced.way === undefined ? [] : [traced.way]), ...traced.iterations].some(taken => taken.within === way.within && sameSteps(taken.steps, way.steps)))
1624
+ return { given, exhaustive: true };
1625
+ }
1626
+ }
1627
+ return { exhaustive: rest.exhaustive && separate && !refused };
1628
+ }
1629
+ return undefined;
1630
+ }
1631
+ // The values a way reads that the model computes and no expression of the input
1632
+ // stands for.
1633
+ function opaqueRead(way, decision) {
1634
+ const expression = decision.expression;
1635
+ if (expression === undefined)
1636
+ return [];
1637
+ const opaque = new Set(localsOf(expression).filter(local => local.opaque).map(local => local.name));
1638
+ return way.steps.flatMap(step => step.distinction.kind === "match" ? [] : localRoots(step.distinction)).filter(name => opaque.has(name));
1639
+ }
1640
+ function unmetStatus(feasibilities) {
1641
+ if (feasibilities.length === 0 || feasibilities.some(item => item.kind === "feasible")) {
1642
+ return { status: "gap" };
1643
+ }
1644
+ const undecided = feasibilities.find(item => item.kind === "undecided");
1645
+ if (undecided !== undefined) {
1646
+ return { status: "undecided", reason: undecided.reason };
1647
+ }
1648
+ return { status: "no row owed", reason: feasibilities[0].reason };
1649
+ }
1650
+ function besideOf(definition, implementation, drawn, reachedIt) {
1651
+ const parts = [...drawn.form.parts].sort((left, right) => left.path < right.path ? -1 : left.path > right.path ? 1 : 0);
1652
+ const rows = reachedIt.filter(item => drawn.coordinateOf(item.comparison) !== undefined).flatMap(item => {
1653
+ const values = parts.map(part => part.valueOf(item.comparison.scope));
1654
+ return values.every(value => value !== undefined)
1655
+ ? [{ values, kept: holds(drawn.comparison, item.comparison.scope), given: item.given, deps: item.deps }]
1656
+ : [];
1657
+ });
1658
+ const kept = rows.filter(row => row.kept).map(row => row.values);
1659
+ if (kept.length === 0) {
1660
+ return { beside: { status: "undecided", reason: allOnOneSide } };
1661
+ }
1662
+ const keptBelow = drawn.comparison.operator === "<" || drawn.comparison.operator === "<=";
1663
+ const line = lineTheRowsAllow(parts.map(part => part.coefficient), keptBelow, kept, rows.filter(row => !row.kept).map(row => row.values));
1664
+ if (line === undefined) {
1665
+ return { beside: { status: "told" } };
1666
+ }
1667
+ const others = (drawn.origin?.decision.guards ?? []).filter(guard => !mentions(guard.condition, drawn.comparison));
1668
+ const shown = partingsOf(parts.map(part => part.coefficient), line, keptBelow, rows)
1669
+ .flatMap(parting => {
1670
+ const given = parts.reduce((written, part, index) => (written === undefined ? undefined : part.write(written, parting.values[index])), rows[parting.from].given);
1671
+ const deps = rows[parting.from].deps;
1672
+ // Writing one part can move another that reads the same field, as
1673
+ // `length($.code)` and `length(trim($.code))` both read $.code, so the
1674
+ // row is kept only where it reaches the comparison at the parting itself.
1675
+ const reaches = given !== undefined &&
1676
+ definition.input.parse(given).success &&
1677
+ comparisonsReached(implementation, given, deps).some(item => item.rule === drawn.comparison &&
1678
+ drawn.coordinateOf(item) !== undefined &&
1679
+ parts.every((part, index) => part.valueOf(item.scope) === parting.values[index]));
1680
+ if (!reaches) {
1681
+ return [];
1682
+ }
1683
+ const visible = others.every(guard => holds(guard.condition, withDeps(given, deps)));
1684
+ return [{ parting, given, rank: [visible ? 0 : 1, Math.abs(parting.steps)] }];
1685
+ })
1686
+ .reduce((best, candidate) => best === undefined ||
1687
+ candidate.rank[0] < best.rank[0] ||
1688
+ (candidate.rank[0] === best.rank[0] && candidate.rank[1] < best.rank[1])
1689
+ ? candidate
1690
+ : best, undefined);
1691
+ const another = spelled(parts.map(part => part.path), line);
1692
+ return shown === undefined
1693
+ ? { beside: { status: "not told", another } }
1694
+ : {
1695
+ beside: {
1696
+ status: "not told",
1697
+ another,
1698
+ input: parts.map((part, index) => `${part.path} = ${shown.parting.values[index]}`).join(", "),
1699
+ },
1700
+ given: shown.given,
1701
+ deps: rows[shown.parting.from].deps,
1702
+ };
1703
+ }
1704
+ function sidesOf(drawn) {
1705
+ return Array.from({ length: drawn.sides ?? 2 }, (_, side) => side);
1706
+ }
1707
+ function mentions(rule, target) {
1708
+ if (rule === target) {
1709
+ return true;
1710
+ }
1711
+ switch (rule.kind) {
1712
+ case "and":
1713
+ case "or":
1714
+ return rule.rules.some(part => mentions(part, target));
1715
+ case "not":
1716
+ return mentions(rule.rule, target);
1717
+ case "all":
1718
+ case "any":
1719
+ return mentions(rule.each, target);
1720
+ default:
1721
+ return false;
1722
+ }
1723
+ }
1724
+ // Whether some row could stand at a guard border point. A comparison reading a
1725
+ // value the model computes is settled by the search's runs: one reaching it at
1726
+ // the point makes it feasible, and runs of every input and answer none of which
1727
+ // do make it infeasible.
1728
+ function pointFeasibility(drawn, point, implementation, combinations, wayLimit, fakes) {
1729
+ const origin = drawn.origin;
1730
+ const expression = origin?.decision?.expression;
1731
+ if (origin === undefined || expression === undefined)
1732
+ return reachOf(drawn, point, combinations, wayLimit);
1733
+ const opaque = new Set(localsOf(expression).filter(local => local.opaque).map(local => local.name));
1734
+ const read = localRoots(drawn.comparison).filter(name => opaque.has(name));
1735
+ if (read.length === 0)
1736
+ return reachOf(drawn, point, combinations, wayLimit);
1737
+ const searched = searchedWays(implementation, origin.tag, origin.decision, combinations, fakes);
1738
+ if ([...searched.reached, ...searched.witnessed.map(item => item.comparison)].some(item => item.rule === drawn.comparison && point.contains(drawn.coordinateOf(item))))
1739
+ return [{ kind: "feasible" }];
1740
+ if (searched.exhaustive)
1741
+ return [{ kind: "infeasible", reason: "入力と依存の答えの全値を試し、この点に届く値がない" }];
1742
+ return [{ kind: "undecided", reason: `${[...new Set(read.map(localLabel))].join("・")}はモデルが計算する値で、試した入力ではこの点に届かない` }];
1743
+ }
1744
+ function reachOf(drawn, point, combinations, wayLimit) {
1745
+ const normalized = normalize(drawn.comparison);
1746
+ const { left, right } = drawn.comparison;
1747
+ if (drawn.origin === undefined || point.region === undefined) {
1748
+ return [{ kind: "feasible" }];
1749
+ }
1750
+ const { decision, scope } = drawn.origin;
1751
+ let placement;
1752
+ if (normalized !== undefined) {
1753
+ const term = (isTerm(left) ? left : right);
1754
+ placement = { path: positionOf(term).path, measure: normalized.measure, ...point.region };
1755
+ }
1756
+ else if (isTerm(left) &&
1757
+ isTerm(right) &&
1758
+ positionData(left) !== undefined &&
1759
+ positionData(right) !== undefined) {
1760
+ const side = (term) => ({ path: positionOf(term).path, measure: positionOf(term).measure });
1761
+ placement = { between: [side(left), side(right)], ...point.region };
1762
+ }
1763
+ else if ([left, right].some(operand => isTerm(operand))) {
1764
+ placement = { form: differenceOf(drawn.comparison), ...point.region };
1765
+ }
1766
+ else {
1767
+ return [{ kind: "feasible" }];
1768
+ }
1769
+ const prefixes = [];
1770
+ let unlisted = false;
1771
+ let followed = 0;
1772
+ for (const way of eachWayOf(decision)) {
1773
+ followed += 1;
1774
+ if (followed > wayLimit) {
1775
+ return [{ kind: "undecided", reason: tooManyWays(wayLimit) }];
1776
+ }
1777
+ const index = way.steps.findIndex(step => step.distinction === drawn.comparison);
1778
+ if (index !== -1) {
1779
+ // A comparison in an iteration's body is reached only through the iteration, entered and over an array that holds an element.
1780
+ for (const entered of way.entered ?? [[]]) {
1781
+ prefixes.push([...way.steps.slice(0, index), ...withEntry(way, entered).steps.slice(way.steps.length)]);
1782
+ if (way.entryUnlisted === true)
1783
+ unlisted = true;
1784
+ }
1785
+ }
1786
+ }
1787
+ // A row at the border is of the case it is drawn under.
1788
+ const inCases = (drawn.cases ?? []).map(item => ({
1789
+ distinction: { kind: "compare", operator: "==", left: positionTerm([...item.at, item.discriminant], "value"), right: item.tag },
1790
+ outcome: true,
1791
+ }));
1792
+ return prefixes.length === 0
1793
+ ? [{ kind: "feasible" }]
1794
+ : prefixes.map(steps => feasibilityOf({ steps: [...steps, ...inCases] }, scope, placement, combinations))
1795
+ .map((found) => unlisted && found.kind === "feasible" ? { kind: "undecided", reason: "反復に入る道筋が多すぎて、すべては調べきれない" } : found);
1796
+ }
1797
+ function scopeOf(implementation, tag, decision, way) {
1798
+ const scope = feasibilityScope(implementation.behavior, tag, decision, way?.steps ?? []);
1799
+ return way === undefined ? scope : settledBy(scope, way.steps);
1800
+ }
1801
+ // The scope with each sum field the way settles to one case read as that case,
1802
+ // so a field of the case is read with the kind it has there.
1803
+ function settledBy(scope, steps, path = []) {
1804
+ if (scope.kind !== "object")
1805
+ return scope;
1806
+ const { shape } = scope;
1807
+ let changed = false;
1808
+ const settled = Object.fromEntries(Object.entries(shape).map(([key, field]) => {
1809
+ const at = [...path, key];
1810
+ const tag = isVariantsSchema(field) ? selectedTag(field, at, steps) : undefined;
1811
+ const next = tag === undefined ? settledBy(field, steps, at) : settledBy(taggedCase(field, tag), steps, at);
1812
+ if (next !== field)
1813
+ changed = true;
1814
+ return [key, next];
1815
+ }));
1816
+ return changed ? { ...scope, shape: settled } : scope;
1817
+ }
1818
+ function coverage(all, covered, excluded = []) {
1819
+ const counted = all.filter(value => !excluded.includes(value));
1820
+ return {
1821
+ covered: counted.filter(value => covered.has(value)),
1822
+ missing: counted.filter(value => !covered.has(value)),
1823
+ excluded: all.filter(value => excluded.includes(value)),
1824
+ total: counted.length,
1825
+ };
1826
+ }
1827
+ function disregardsBorder(definition, drawn) {
1828
+ return [drawn.segments, ...(drawn.reads ?? [])].some(segments => isDisregarded(definition, { segments }));
1829
+ }
1830
+ function isDisregarded(definition, position) {
1831
+ return Object.entries(definition.disregards).some(([tag, paths]) => paths.some(keys => isUnder(position, [`@${tag}`, ...keys.map(key => `.${key}`)])));
1832
+ }
1833
+ // A term steps through an optional or a nested case without naming it, so the
1834
+ // markers for those are left out before its keys are compared with a position's.
1835
+ // Positions are keyed by their segments, not their rendered path, since a key
1836
+ // holding "." renders the same as the nested path it spells.
1837
+ function trailKey(segments) {
1838
+ return JSON.stringify(segments);
1839
+ }
1840
+ function isUnder(position, prefix) {
1841
+ const named = namedSegments(position);
1842
+ return prefix.every((segment, index) => named[index] === segment);
1843
+ }
1844
+ // An element name maps to its trail, or to undefined when the quantifier ranges
1845
+ // over something other than the input, such as a value dependency.
1846
+ function segmentsRead(rule, root, elements) {
1847
+ const trailsOf = (term) => isTerm(term)
1848
+ ? termPaths({ kind: "compare", operator: "==", left: term, right: 0 }).flatMap(path => {
1849
+ const trail = trailAt(path);
1850
+ return trail === undefined ? [] : [trail];
1851
+ })
1852
+ : [];
1853
+ const trailOf = (term) => isTerm(term) ? trailAt(positionOf(term).path) : undefined;
1854
+ const trailAt = (path) => {
1855
+ const [head, ...rest] = path;
1856
+ if (head === undefined || head === DEPS) {
1857
+ return undefined;
1858
+ }
1859
+ if (elements.has(head)) {
1860
+ const base = elements.get(head);
1861
+ return base === undefined ? undefined : [...base, ...rest.map(key => `.${key}`)];
1862
+ }
1863
+ return [...root, `.${head}`, ...rest.map(key => `.${key}`)];
1864
+ };
1865
+ switch (rule.kind) {
1866
+ case "compare":
1867
+ return [rule.left, rule.right].flatMap(trailsOf);
1868
+ case "all":
1869
+ case "any": {
1870
+ const of = trailOf(rule.of);
1871
+ const inner = segmentsRead(rule.each, root, new Map([...elements, [rule.element, of === undefined ? undefined : [...of, "[]"]]]));
1872
+ return of === undefined ? inner : [of, ...inner];
1873
+ }
1874
+ case "and":
1875
+ case "or":
1876
+ return rule.rules.flatMap(inner => segmentsRead(inner, root, elements));
1877
+ case "not":
1878
+ return segmentsRead(rule.rule, root, elements);
1879
+ }
1880
+ }
1881
+ function guardReadSegmentsOf(implementation) {
1882
+ if (implementation === undefined) {
1883
+ return [];
1884
+ }
1885
+ return Object.entries(implementation.cases).flatMap(([tag, decision]) => {
1886
+ if (decision.kind !== "rules") {
1887
+ return [];
1888
+ }
1889
+ const root = [`@${tag}`];
1890
+ const matched = typeof decision.otherwise === "function"
1891
+ ? []
1892
+ : [[...root, ...positionOf(decision.otherwise.on).path.map(key => `.${key}`)]];
1893
+ return [...decision.guards.flatMap(item => segmentsRead(item.condition, root, new Map())), ...matched];
1894
+ });
1895
+ }
1896
+ function namedSegments(position) {
1897
+ const [inputCase, ...rest] = position.segments;
1898
+ return [inputCase, ...rest.filter(segment => segment !== "?" && !segment.startsWith("@"))];
1899
+ }
1900
+ // A disregarded position a guard reads is kept rather than dropped, since the
1901
+ // guard's classes are attached to it; only what its type and invariants owe goes.
1902
+ function measuredPositionsOf(definition, guardDivided = new Set(), guardRead = [], combinations = FEASIBILITY_COMBINATION_LIMIT) {
1903
+ return positionsOf(definition.input).map(position => withJointExclusions(definition, position, combinations)).flatMap((position) => {
1904
+ if (!isDisregarded(definition, position)) {
1905
+ return [position];
1906
+ }
1907
+ const named = namedSegments(position);
1908
+ if (guardRead.some(trail => named.every((segment, index) => trail[index] === segment))) {
1909
+ return [{ ...position, borders: [] }];
1910
+ }
1911
+ if (!guardDivided.has(trailKey(position.segments))) {
1912
+ return [];
1913
+ }
1914
+ return [
1915
+ position.kind === "divided"
1916
+ ? { ...position, classes: [], excluded: [], borders: [] }
1917
+ : { ...position, borders: [] },
1918
+ ];
1919
+ });
1920
+ }
1921
+ const DISREGARD_COMBINATION_LIMIT = 255;
1922
+ // Not the combinations alone: moves are tried before a combination is known to
1923
+ // be one the input can hold, so the candidates tried that way are bounded too.
1924
+ const DISREGARD_CANDIDATE_LIMIT = 4096;
1925
+ export function positiveLimit(name, given, fallback) {
1926
+ if (given === undefined) {
1927
+ return fallback;
1928
+ }
1929
+ if (!Number.isSafeInteger(given) || given <= 0) {
1930
+ throw new SpecificationError(`${name} must be a positive integer, but was ${given}`);
1931
+ }
1932
+ return given;
1933
+ }
1934
+ async function disregardBroken(implementation, row, answered, standIns, limits) {
1935
+ const definition = implementation.behavior;
1936
+ const tag = tagOf(definition.input, row.given);
1937
+ const kept = positionsOf(definition.input).filter(position => isUnder(position, [`@${tag}`]) && !isDisregarded(definition, position));
1938
+ const readKept = (given) => kept.map(position => [
1939
+ position.kind === "divided" ? position.classify(given) : [],
1940
+ position.borders.map(border => coordinatesIn(position, border.measure, given)),
1941
+ ]);
1942
+ const keptOriginally = readKept(row.given);
1943
+ const axes = positionsOf(definition.input).flatMap(position => {
1944
+ if (!isUnder(position, [`@${tag}`]) || !isDisregarded(definition, position)) {
1945
+ return [];
1946
+ }
1947
+ return position.instancesIn(row.given).flatMap(instance => {
1948
+ const classes = position.kind === "divided" ? position : undefined;
1949
+ const located = instance;
1950
+ const classified = (given) => (classes === undefined ? [] : located.classify(given));
1951
+ const taken = classified(row.given);
1952
+ const coordinates = (given) => position.borders.map(border => coordinatesIn(instance, border.measure, given));
1953
+ const original = coordinates(row.given);
1954
+ const classMoves = classes === undefined
1955
+ ? []
1956
+ : classes.classes
1957
+ .filter(className => !taken.includes(className) && !classes.excluded.includes(className))
1958
+ .map(className => ({
1959
+ label: className,
1960
+ apply: given => located.place(given, className),
1961
+ reached: varied => located.classify(varied).includes(className),
1962
+ }));
1963
+ const pointMoves = position.borders.flatMap((border, index) => border.points.flatMap(point => point.status !== "owed" ||
1964
+ point.witness === undefined ||
1965
+ original[index].some(value => point.contains(value))
1966
+ ? []
1967
+ : [
1968
+ {
1969
+ label: `${point.role} (${point.relation})`,
1970
+ apply: (given) => instance.write(given, border.measure, point.witness),
1971
+ reached: (varied) => coordinatesIn(instance, border.measure, varied).some(value => point.contains(value)),
1972
+ },
1973
+ ]));
1974
+ const moves = [...classMoves, ...pointMoves];
1975
+ return moves.length === 0
1976
+ ? []
1977
+ : [
1978
+ {
1979
+ path: instance.path,
1980
+ moves,
1981
+ unmoved: (varied) => (deepEqual(classified(varied), taken) &&
1982
+ deepEqual(coordinates(varied), original)) ||
1983
+ (classified(varied).length === 0 && coordinates(varied).every(values => values.length === 0)),
1984
+ },
1985
+ ];
1986
+ });
1987
+ });
1988
+ const candidates = axes.reduce((total, axis) => total * (axis.moves.length + 1), 1) - 1;
1989
+ if (candidates > limits.candidates) {
1990
+ return {
1991
+ kind: "not checked",
1992
+ incompleteness: {
1993
+ kind: "disregards not checked",
1994
+ subject: row.name,
1995
+ reason: `disregardsの組み合わせの候補が${candidates}通りあり、上限の${limits.candidates}通りを超えるため数えていない`,
1996
+ },
1997
+ };
1998
+ }
1999
+ const combinations = axes
2000
+ .reduce((partial, axis) => partial.flatMap(choice => [undefined, ...axis.moves].map(move => [...choice, move])), [[]])
2001
+ .filter(choice => choice.some(move => move !== undefined))
2002
+ .flatMap(choice => {
2003
+ const varied = choice.reduce((given, move) => (move === undefined ? given : move.apply(given)), row.given);
2004
+ const holds = axes.every((axis, index) => {
2005
+ const move = choice[index];
2006
+ return move === undefined ? axis.unmoved(varied) : move.reached(varied);
2007
+ });
2008
+ return holds &&
2009
+ deepEqual(readKept(varied), keptOriginally) &&
2010
+ definition.input.parse(varied).success
2011
+ ? [{ choice, varied }]
2012
+ : [];
2013
+ })
2014
+ .sort((left, right) => {
2015
+ const moved = (choice) => choice.flatMap((move, index) => (move === undefined ? [] : [index]));
2016
+ const [a, b] = [moved(left.choice), moved(right.choice)];
2017
+ const first = a.findIndex((index, at) => index !== b[at]);
2018
+ return a.length - b.length || (first === -1 ? 0 : a[first] - b[first]);
2019
+ });
2020
+ if (combinations.length > limits.combinations) {
2021
+ return {
2022
+ kind: "not checked",
2023
+ incompleteness: {
2024
+ kind: "disregards not checked",
2025
+ subject: row.name,
2026
+ reason: `disregardsの組み合わせが${combinations.length}通りあり、上限の${limits.combinations}通りを超えるため確かめていない`,
2027
+ },
2028
+ };
2029
+ }
2030
+ for (const { choice, varied } of combinations) {
2031
+ const outcome = await runTraced(implementation, varied, standIns).then((traced) => deepEqual(traced.execution, answered) ? undefined : { text: "its answer changed" }, (error) => ({ text: "it threw", error: error instanceof Error ? error.message : String(error) }));
2032
+ if (outcome !== undefined) {
2033
+ const moved = axes.flatMap((axis, index) => {
2034
+ const move = choice[index];
2035
+ return move === undefined ? [] : [{ path: axis.path, label: move.label }];
2036
+ });
2037
+ return {
2038
+ kind: "broken",
2039
+ failure: {
2040
+ name: row.name,
2041
+ message: `${definition.name} disregards ${moved.map(item => item.path).join(", ")}, but ${outcome.text} when ${moved
2042
+ .map(item => `${item.path} was ${item.label}`)
2043
+ .join(" and ")}${outcome.error === undefined ? "" : `: ${outcome.error}`}`,
2044
+ },
2045
+ };
2046
+ }
2047
+ }
2048
+ return { kind: "held" };
2049
+ }
2050
+ // A class of a boolean, an enum or a sum field that no combination of values
2051
+ // the invariants relating finite positions keep can take is excluded, like
2052
+ // one a rule on the position alone refuses.
2053
+ function withJointExclusions(definition, position, combinations) {
2054
+ if (position.kind !== "divided") {
2055
+ return position;
2056
+ }
2057
+ const refused = position.classes.filter(className => {
2058
+ if (position.excluded.includes(className)) {
2059
+ return true;
2060
+ }
2061
+ const at = finiteCoordinateOf(definition, position, className);
2062
+ return at !== undefined && refusedJointly(at.scope, at.path, at.value, combinations);
2063
+ });
2064
+ return refused.length === position.excluded.length ? position : { ...position, excluded: refused };
2065
+ }
2066
+ // Where a class of a boolean, an enum or a sum field directly under an input
2067
+ // case sits for the joint invariant search: the case's scope, the field's keys
2068
+ // in it and the value the class stands for.
2069
+ export function finiteCoordinateOf(definition, position, className) {
2070
+ const [head, ...rest] = position.segments;
2071
+ if (head === undefined || rest.length === 0 || !rest.every(step => step.startsWith("."))) {
2072
+ return undefined;
2073
+ }
2074
+ const tag = head.slice(1);
2075
+ const scope = feasibilityScope(definition, tag);
2076
+ const keys = rest.map(step => step.slice(1));
2077
+ const field = schemaAtPath(scope, keys);
2078
+ switch (field?.kind) {
2079
+ case "boolean":
2080
+ return { tag, scope, path: keys, value: className === "true" };
2081
+ case "enum":
2082
+ return { tag, scope, path: keys, value: className };
2083
+ case "variants":
2084
+ return { tag, scope, path: [...keys, field.discriminant], value: className };
2085
+ default:
2086
+ return undefined;
2087
+ }
2088
+ }
2089
+ function plansOf(implementation, combinations, wayLimit) {
2090
+ const plans = new Map();
2091
+ for (const [decision, tags] of implementation === undefined ? [] : decisionsWithCases(implementation)) {
2092
+ if (decision.kind !== "rules") {
2093
+ continue;
2094
+ }
2095
+ const reaches = tags.map(tag => ({
2096
+ tag,
2097
+ reached: decision.expression !== undefined ? undefined : finiteReach(decision, scopeOf(implementation, tag), combinations, [[implementation.behavior.input.discriminant]]),
2098
+ }));
2099
+ if (reaches.every(item => item.reached !== undefined)) {
2100
+ const reached = new Map();
2101
+ for (const { tag, reached: each } of reaches) {
2102
+ for (const item of each) {
2103
+ const key = describeWay(item.way);
2104
+ if (!reached.has(key)) {
2105
+ reached.set(key, { ...item, tag });
2106
+ }
2107
+ }
2108
+ }
2109
+ plans.set(decision, { kind: "finite", reached: [...reached.values()] });
2110
+ continue;
2111
+ }
2112
+ const ways = [];
2113
+ for (const way of eachWayOf(decision)) {
2114
+ ways.push(way);
2115
+ if (ways.length > wayLimit) {
2116
+ break;
2117
+ }
2118
+ }
2119
+ plans.set(decision, ways.length > wayLimit ? { kind: "too many" } : { kind: "ways", ways });
2120
+ }
2121
+ return plans;
2122
+ }
2123
+ //# sourceMappingURL=specification.js.map