@toiroakr/chisel 0.0.0-stage → 0.1.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 (84) hide show
  1. package/README.md +464 -2
  2. package/dist/behavior.d.ts +181 -0
  3. package/dist/behavior.js +422 -0
  4. package/dist/behavior.js.map +1 -0
  5. package/dist/beside.d.ts +27 -0
  6. package/dist/beside.js +88 -0
  7. package/dist/beside.js.map +1 -0
  8. package/dist/border.d.ts +64 -0
  9. package/dist/border.js +426 -0
  10. package/dist/border.js.map +1 -0
  11. package/dist/cli.d.ts +5 -0
  12. package/dist/cli.js +567 -0
  13. package/dist/cli.js.map +1 -0
  14. package/dist/codec.d.ts +6 -0
  15. package/dist/codec.js +83 -0
  16. package/dist/codec.js.map +1 -0
  17. package/dist/codegen.d.ts +2 -0
  18. package/dist/codegen.js +65 -0
  19. package/dist/codegen.js.map +1 -0
  20. package/dist/composition.d.ts +38 -0
  21. package/dist/composition.js +242 -0
  22. package/dist/composition.js.map +1 -0
  23. package/dist/data.d.ts +16 -0
  24. package/dist/data.js +49 -0
  25. package/dist/data.js.map +1 -0
  26. package/dist/dependency.d.ts +98 -0
  27. package/dist/dependency.js +155 -0
  28. package/dist/dependency.js.map +1 -0
  29. package/dist/domain.d.ts +8 -0
  30. package/dist/domain.js +217 -0
  31. package/dist/domain.js.map +1 -0
  32. package/dist/ensures.d.ts +15 -0
  33. package/dist/ensures.js +88 -0
  34. package/dist/ensures.js.map +1 -0
  35. package/dist/exact.d.ts +21 -0
  36. package/dist/exact.js +80 -0
  37. package/dist/exact.js.map +1 -0
  38. package/dist/feasibility.d.ts +61 -0
  39. package/dist/feasibility.js +984 -0
  40. package/dist/feasibility.js.map +1 -0
  41. package/dist/guard-borders.d.ts +50 -0
  42. package/dist/guard-borders.js +809 -0
  43. package/dist/guard-borders.js.map +1 -0
  44. package/dist/index.d.ts +37 -0
  45. package/dist/index.js +19 -0
  46. package/dist/index.js.map +1 -0
  47. package/dist/interval.d.ts +3 -0
  48. package/dist/interval.js +161 -0
  49. package/dist/interval.js.map +1 -0
  50. package/dist/isolated.d.ts +9 -0
  51. package/dist/isolated.js +41 -0
  52. package/dist/isolated.js.map +1 -0
  53. package/dist/model.d.ts +95 -0
  54. package/dist/model.js +343 -0
  55. package/dist/model.js.map +1 -0
  56. package/dist/pairs.d.ts +26 -0
  57. package/dist/pairs.js +107 -0
  58. package/dist/pairs.js.map +1 -0
  59. package/dist/partition.d.ts +44 -0
  60. package/dist/partition.js +275 -0
  61. package/dist/partition.js.map +1 -0
  62. package/dist/proof.d.ts +15 -0
  63. package/dist/proof.js +482 -0
  64. package/dist/proof.js.map +1 -0
  65. package/dist/report-json.d.ts +11 -0
  66. package/dist/report-json.js +94 -0
  67. package/dist/report-json.js.map +1 -0
  68. package/dist/rule.d.ts +146 -0
  69. package/dist/rule.js +599 -0
  70. package/dist/rule.js.map +1 -0
  71. package/dist/schema.d.ts +163 -0
  72. package/dist/schema.js +524 -0
  73. package/dist/schema.js.map +1 -0
  74. package/dist/specification.d.ts +256 -0
  75. package/dist/specification.js +1583 -0
  76. package/dist/specification.js.map +1 -0
  77. package/dist/text.d.ts +1 -0
  78. package/dist/text.js +11 -0
  79. package/dist/text.js.map +1 -0
  80. package/dist/ways.d.ts +25 -0
  81. package/dist/ways.js +95 -0
  82. package/dist/ways.js.map +1 -0
  83. package/package.json +53 -4
  84. package/schema/report.schema.json +1062 -0
@@ -0,0 +1,1583 @@
1
+ import { hasScopedChoices } from "./model.js";
2
+ import { verify } from "./proof.js";
3
+ import { constantsOf, domainOf } from "./domain.js";
4
+ import { pairCoverage, PAIR_LIMIT } from "./pairs.js";
5
+ import { isDeepStrictEqual } from "node:util";
6
+ import { WAY_LIMIT, describeWay, eachWayOf, sameSteps } from "./ways.js";
7
+ import { answerFrom, fakeIssuesOf, fakeWarningsOf } from "./dependency.js";
8
+ import { comparisonsNotReadOf, ensuresBordersOf, invariantContradictionsOf, mayBeLeftOut, invariantPairBordersOf, guardBordersOf, guardPartitionsOf, feasibilityScope, } from "./guard-borders.js";
9
+ import { SpecificationError, TodoDecision, brokenEnsures, comparisonsReached, isCaseOnly, isTodo, perform, runTraced, traceSync, } from "./behavior.js";
10
+ import { DEPS, describeRule, describeTerm, differenceOf, holds, withDeps, isTerm, positionData, positionOf, termData, termPaths } from "./rule.js";
11
+ import { emptiedBy, normalize } from "./border.js";
12
+ import { FEASIBILITY_COMBINATION_LIMIT, feasibilityOf, finiteReach, keepingInvariants, keepingOrderings, refusedJointly, tooManyWays, unreached, witnessesOf } from "./feasibility.js";
13
+ import { readEnsures } from "./ensures.js";
14
+ import { allOnOneSide, lineTheRowsAllow, partingsOf, spelled } from "./beside.js";
15
+ import { coordinatesIn, excludedCases, positionsOf } from "./partition.js";
16
+ import { isVariantsSchema, schemaAtPath, tagOf } from "./schema.js";
17
+ async function runAndCompare(definition, name, given, expected, subject) {
18
+ try {
19
+ const actual = await subject(given);
20
+ return {
21
+ actual,
22
+ failure: answers(definition, expected, actual)
23
+ ? undefined
24
+ : {
25
+ name,
26
+ message: `Expected ${JSON.stringify(expected, (_, value) => typeof value === "bigint" ? `${value}n` : value)}, received ${JSON.stringify(actual, (_, value) => typeof value === "bigint" ? `${value}n` : value)}`,
27
+ },
28
+ };
29
+ }
30
+ catch (error) {
31
+ return {
32
+ actual: undefined,
33
+ failure: { name, message: error instanceof Error ? error.message : String(error) },
34
+ error,
35
+ };
36
+ }
37
+ }
38
+ function answers(definition, expected, actual) {
39
+ const canonicalEffects = (effects) => effects.map(effect => {
40
+ const parsed = definition.effects.parse(effect);
41
+ return parsed.success ? parsed.value : effect;
42
+ });
43
+ const received = actual;
44
+ if (isCaseOnly(expected.result)) {
45
+ return isVariantsSchema(definition.result) && tagOf(definition.result, received.result) === expected.result.case &&
46
+ isDeepStrictEqual(canonicalEffects(received.effects), canonicalEffects(expected.effects));
47
+ }
48
+ const result = definition.result.parse(received.result);
49
+ const answer = definition.result.parse(expected.result);
50
+ return result.success && answer.success && isDeepStrictEqual(result.value, answer.value) &&
51
+ isDeepStrictEqual(canonicalEffects(received.effects), canonicalEffects(expected.effects));
52
+ }
53
+ export function example(_definition, row) {
54
+ return row;
55
+ }
56
+ export function examples(behavior, table) {
57
+ return {
58
+ kind: "example-set",
59
+ behavior,
60
+ rows: Object.entries(table).map(([name, row]) => ({ kind: "example", name, ...row })),
61
+ };
62
+ }
63
+ export function spec(name, options) {
64
+ return {
65
+ kind: "specification",
66
+ name,
67
+ examples: options.examples,
68
+ implementation: options.implementation,
69
+ fakes: options.fakes ?? [],
70
+ };
71
+ }
72
+ export function isSpecification(value) {
73
+ return (typeof value === "object" &&
74
+ value !== null &&
75
+ value.kind === "specification");
76
+ }
77
+ export async function check(specification, options = {}) {
78
+ const limits = {
79
+ combinations: positiveLimit("disregards.combinations", options.disregards?.combinations, DISREGARD_COMBINATION_LIMIT),
80
+ candidates: positiveLimit("disregards.candidates", options.disregards?.candidates, DISREGARD_CANDIDATE_LIMIT),
81
+ };
82
+ const combinations = positiveLimit("feasibility.combinations", options.feasibility?.combinations, FEASIBILITY_COMBINATION_LIMIT);
83
+ const definition = specification.examples.behavior;
84
+ const wayLimit = positiveLimit("feasibility.ways", options.feasibility?.ways, WAY_LIMIT);
85
+ const coveredInputs = new Set();
86
+ const coveredResults = new Set();
87
+ const coveredEffects = new Set();
88
+ const failures = [];
89
+ const unansweredRows = [];
90
+ const executedInputs = new Set();
91
+ const verifiedInputs = new Set();
92
+ const observedResults = new Set();
93
+ const verifiedResults = new Set();
94
+ const observedEffects = new Set();
95
+ const verifiedEffects = new Set();
96
+ const guardPartitions = specification.implementation === undefined
97
+ ? []
98
+ : guardPartitionsOf(specification.implementation);
99
+ const positions = measuredPositionsOf(definition, new Set(guardPartitions.map(partition => trailKey(partition.segments))), guardReadSegmentsOf(specification.implementation), combinations);
100
+ const coveredClasses = positions.map(() => new Set());
101
+ const answeredGivens = [];
102
+ const armsMet = [];
103
+ const armsOwed = [];
104
+ const reached = [];
105
+ const waysMet = [];
106
+ const waysOwed = [];
107
+ const fakeIssues = fakeIssuesOf(definition.requires, definition.name, specification.fakes);
108
+ const tables = new Map(specification.fakes
109
+ .filter(table => !fakeIssues.some(item => item.table.dependency === table.dependency))
110
+ .map(table => [table.dependency, answerFrom(table)]));
111
+ const standIns = (row) => ({
112
+ ...Object.fromEntries(tables),
113
+ ...(row.with ?? {}),
114
+ });
115
+ const incompleteness = [];
116
+ const externals = externalsIn(specification.implementation);
117
+ const notRunFor = (row) => {
118
+ if (externals.length === 0) {
119
+ return false;
120
+ }
121
+ incompleteness.push({
122
+ kind: "row not run",
123
+ subject: row.name,
124
+ reason: `外部の段のため実行できない(${externals.join("、")})`,
125
+ });
126
+ return true;
127
+ };
128
+ const unstoodFor = (row) => {
129
+ const written = (row.with ?? {});
130
+ for (const [name, value] of Object.entries(written)) {
131
+ const declared = definition.requires[name];
132
+ if (declared === undefined) {
133
+ return `with ${name} names no dependency of ${definition.name}`;
134
+ }
135
+ const parsed = declared.output.parse(value);
136
+ if (!parsed.success) {
137
+ return `with ${name} is not a value the dependency answers: ${parsed.issues[0].message}`;
138
+ }
139
+ }
140
+ const missing = Object.keys(definition.requires).find(name => !(name in written) && !tables.has(name));
141
+ return missing === undefined ? undefined : `No stand-in for dependency ${missing}`;
142
+ };
143
+ const observe = (inputTag, actual) => {
144
+ executedInputs.add(inputTag);
145
+ const execution = actual;
146
+ const result = isVariantsSchema(definition.result)
147
+ ? tagOf(definition.result, execution.result)
148
+ : undefined;
149
+ if (result !== undefined) {
150
+ observedResults.add(result);
151
+ }
152
+ const effects = new Set(execution.effects
153
+ .map(effect => tagOf(definition.effects, effect))
154
+ .filter((tag) => tag !== undefined));
155
+ for (const effect of effects) {
156
+ observedEffects.add(effect);
157
+ }
158
+ return { result, effects };
159
+ };
160
+ for (const row of specification.examples.rows) {
161
+ const inputValidation = definition.input.parse(row.given);
162
+ const inputTag = tagOf(definition.input, row.given);
163
+ if (!inputValidation.success) {
164
+ failures.push({ name: row.name, message: "Example input is invalid" });
165
+ continue;
166
+ }
167
+ if (isTodo(row.expect)) {
168
+ unansweredRows.push({
169
+ name: row.name,
170
+ variant: inputTag,
171
+ reason: row.expect.reason,
172
+ });
173
+ const implementation = specification.implementation;
174
+ const decision = implementation === undefined || inputTag === undefined
175
+ ? undefined
176
+ : implementation.cases[inputTag];
177
+ const unstoodOwed = unstoodFor(row);
178
+ if (implementation !== undefined && notRunFor(row)) {
179
+ continue;
180
+ }
181
+ if (implementation !== undefined && unstoodOwed !== undefined) {
182
+ failures.push({ name: row.name, message: unstoodOwed });
183
+ incompleteness.push({ kind: "row not run", subject: row.name, reason: unstoodOwed });
184
+ }
185
+ else if (implementation !== undefined &&
186
+ (implementation.pipeline !== undefined ||
187
+ (decision !== undefined && decision.kind !== "todo"))) {
188
+ try {
189
+ const traced = await runTraced(implementation, row.given, standIns(row));
190
+ observe(inputTag, traced.execution);
191
+ armsOwed.push(...traced.arms);
192
+ if (traced.way !== undefined) {
193
+ waysOwed.push(traced.way);
194
+ }
195
+ }
196
+ catch (error) {
197
+ const open = openDecisionIn(implementation, error);
198
+ if (open !== undefined) {
199
+ incompleteness.push({ kind: "row not run", subject: row.name, reason: `判断が未定(${open})` });
200
+ }
201
+ else {
202
+ const message = error instanceof Error ? error.message : String(error);
203
+ failures.push({ name: row.name, message });
204
+ incompleteness.push({ kind: "row did not come back", subject: row.name, reason: message });
205
+ }
206
+ }
207
+ }
208
+ continue;
209
+ }
210
+ if (inputTag !== undefined) {
211
+ coveredInputs.add(inputTag);
212
+ }
213
+ answeredGivens.push(row.given);
214
+ positions.forEach((position, index) => {
215
+ if (position.kind === "divided") {
216
+ for (const found of position.classify(row.given)) {
217
+ coveredClasses[index].add(found);
218
+ }
219
+ }
220
+ });
221
+ const caseOnly = isCaseOnly(row.expect.result) ? row.expect.result.case : undefined;
222
+ const resultValid = caseOnly === undefined
223
+ ? definition.result.parse(row.expect.result).success
224
+ : isVariantsSchema(definition.result) && definition.result.variantTags.includes(caseOnly);
225
+ if (!resultValid) {
226
+ failures.push({ name: row.name, message: "Expected result is invalid" });
227
+ continue;
228
+ }
229
+ // Not held where only the case is written: every clause reads the answer,
230
+ // and nothing wrote the value it would be read against.
231
+ const broken = caseOnly === undefined ? brokenEnsures(definition, row.given, row.expect.result) : undefined;
232
+ if (broken !== undefined) {
233
+ failures.push({
234
+ name: row.name,
235
+ message: `Example breaks ensures ${broken.name}: ${describeRule(broken.rule, "")}`,
236
+ });
237
+ }
238
+ const resultTag = caseOnly ?? (isVariantsSchema(definition.result) ? tagOf(definition.result, row.expect.result) : undefined);
239
+ if (resultTag !== undefined) {
240
+ coveredResults.add(resultTag);
241
+ }
242
+ for (const effect of row.expect.effects) {
243
+ const effectTag = tagOf(definition.effects, effect);
244
+ if (effectTag !== undefined) {
245
+ coveredEffects.add(effectTag);
246
+ }
247
+ }
248
+ const implementation = specification.implementation;
249
+ const unstood = unstoodFor(row);
250
+ if (implementation !== undefined && notRunFor(row)) {
251
+ continue;
252
+ }
253
+ if (implementation !== undefined && unstood !== undefined) {
254
+ failures.push({ name: row.name, message: unstood });
255
+ incompleteness.push({ kind: "row not run", subject: row.name, reason: unstood });
256
+ }
257
+ else if (implementation !== undefined) {
258
+ const { actual, failure, error } = await runAndCompare(definition, row.name, row.given, row.expect, async (input) => {
259
+ const traced = await runTraced(implementation, input, standIns(row));
260
+ armsMet.push(...traced.arms);
261
+ reached.push(...traced.comparisons.map(comparison => ({
262
+ tag: tagOf(definition.input, input),
263
+ comparison,
264
+ given: input,
265
+ deps: standIns(row),
266
+ })));
267
+ if (traced.way !== undefined) {
268
+ waysMet.push(traced.way);
269
+ }
270
+ return traced.execution;
271
+ });
272
+ if (actual !== undefined && inputTag !== undefined) {
273
+ const observed = observe(inputTag, actual);
274
+ if (observed.result !== undefined && observed.result === resultTag) {
275
+ verifiedResults.add(observed.result);
276
+ }
277
+ for (const effect of row.expect.effects) {
278
+ const effectTag = tagOf(definition.effects, effect);
279
+ if (effectTag !== undefined && observed.effects.has(effectTag)) {
280
+ verifiedEffects.add(effectTag);
281
+ }
282
+ }
283
+ if (failure === undefined) {
284
+ verifiedInputs.add(inputTag);
285
+ const disregard = await disregardBroken(implementation, row, actual, standIns(row), limits);
286
+ if (disregard.kind === "broken") {
287
+ failures.push(disregard.failure);
288
+ }
289
+ else if (disregard.kind === "not checked") {
290
+ incompleteness.push(disregard.incompleteness);
291
+ }
292
+ }
293
+ }
294
+ const open = openDecisionIn(implementation, error);
295
+ if (open !== undefined) {
296
+ incompleteness.push({ kind: "row not run", subject: row.name, reason: `判断が未定(${open})` });
297
+ }
298
+ else if (failure !== undefined) {
299
+ failures.push(failure);
300
+ if (actual === undefined) {
301
+ incompleteness.push({
302
+ kind: "row did not come back",
303
+ subject: row.name,
304
+ reason: failure.message,
305
+ });
306
+ }
307
+ }
308
+ }
309
+ }
310
+ const pendingDecisions = todoDecisionsIn(specification.implementation);
311
+ const controlGaps = specification.implementation === undefined
312
+ ? []
313
+ : definition.effects.variantTags.flatMap(effect => {
314
+ const control = specification.implementation?.controls[effect];
315
+ if (control === undefined) {
316
+ return [{ effect, reason: "control policy is missing" }];
317
+ }
318
+ return "kind" in control && control.kind === "todo"
319
+ ? [{ effect, reason: control.reason }]
320
+ : [];
321
+ });
322
+ const refusedInputs = excludedCases(definition.input);
323
+ const input = coverage(definition.input.variantTags, coveredInputs, refusedInputs);
324
+ const result = isVariantsSchema(definition.result)
325
+ ? coverage(definition.result.variantTags, coveredResults)
326
+ : coverage([], new Set());
327
+ const effects = coverage(definition.effects.variantTags, coveredEffects);
328
+ const pairGroups = new Map();
329
+ for (const drawn of invariantPairBordersOf(definition)) {
330
+ // One form however it is written: the same paths in different weights, as
331
+ // x − y beside x + y, bound different coordinates.
332
+ const weighed = differenceOf(drawn.comparison).parts;
333
+ const entries = (drawn.reads ?? [])
334
+ .map((segments, index) => ({
335
+ at: JSON.stringify([segments, weighed[index]?.measure]),
336
+ coefficient: weighed[index]?.coefficient ?? 0,
337
+ }))
338
+ .sort((left, right) => (left.at < right.at ? -1 : left.at > right.at ? 1 : 0));
339
+ const sign = (entries[0]?.coefficient ?? 1) < 0 ? -1 : 1;
340
+ const key = JSON.stringify(entries.map(entry => [entry.at, sign * entry.coefficient]));
341
+ pairGroups.set(key, [...(pairGroups.get(key) ?? []), drawn]);
342
+ }
343
+ const modelIssues = [
344
+ ...positionsOf(definition.input).map(position => ({ path: position.path, borders: position.borders })),
345
+ ...[...pairGroups.values()]
346
+ .filter(group => !(group[0].reads ?? []).some(segments => mayBeLeftOut(definition, segments)))
347
+ .map(group => ({ path: group[0].path, borders: group.map(drawn => drawn.border) })),
348
+ ].flatMap(({ path, borders }) => {
349
+ const emptied = emptiedBy(borders);
350
+ return emptied === undefined
351
+ ? []
352
+ : [`${path}: 不変条件を満たす値がありません (${emptied.map(border => border.rule).join(", ")})`];
353
+ }).concat(invariantContradictionsOf(definition));
354
+ const partitions = positions.map((position, index) => {
355
+ const drawn = guardPartitions.find(partition => isDeepStrictEqual(partition.segments, position.segments));
356
+ if (drawn !== undefined && position.kind !== "divided") {
357
+ const values = answeredGivens.flatMap(given => position.valuesIn(given));
358
+ const names = drawn.classes.map(item => item.name);
359
+ const reached = new Set(drawn.classes
360
+ .filter(item => values.some(value => value !== undefined && item.contains(value)))
361
+ .map(item => item.name));
362
+ const { covered, missing } = coverage(names, reached);
363
+ return {
364
+ path: position.path,
365
+ kind: "divided",
366
+ covered,
367
+ missing,
368
+ excluded: drawn.excluded,
369
+ };
370
+ }
371
+ if (position.kind !== "divided") {
372
+ return { path: position.path, kind: position.kind };
373
+ }
374
+ const { covered, missing } = coverage(position.classes.filter(className => !position.excluded.includes(className)), coveredClasses[index]);
375
+ return {
376
+ path: position.path,
377
+ kind: "divided",
378
+ covered,
379
+ missing,
380
+ excluded: position.excluded,
381
+ };
382
+ });
383
+ const borders = positions.flatMap(position => position.borders.map((border) => {
384
+ const coordinates = answeredGivens.flatMap(given => coordinatesIn(position, border.measure, given));
385
+ return {
386
+ path: position.path,
387
+ rule: border.rule,
388
+ points: border.points.map(point => ({
389
+ role: point.role,
390
+ relation: point.relation,
391
+ status: point.status !== "owed"
392
+ ? point.status
393
+ : coordinates.some(value => point.contains(value))
394
+ ? "met"
395
+ : "gap",
396
+ })),
397
+ };
398
+ }));
399
+ const guardBorders = (specification.implementation === undefined ? [] : guardBordersOf(specification.implementation)).map((drawn) => {
400
+ const reachedIt = reached.filter(item => item.comparison.rule === drawn.comparison && item.tag === drawn.origin?.tag);
401
+ const coordinates = reachedIt.map(item => drawn.coordinateOf(item.comparison));
402
+ const points = drawn.border.points.map(point => {
403
+ const base = { role: point.role, relation: point.relation };
404
+ if (point.status !== "owed") {
405
+ return { ...base, status: point.status };
406
+ }
407
+ if (coordinates.some(value => point.contains(value))) {
408
+ return { ...base, status: "met" };
409
+ }
410
+ return { ...base, ...unmetStatus(reachOf(drawn, point, combinations, wayLimit)) };
411
+ });
412
+ const owed = drawn.border.points.flatMap((point, index) => (point.status === "owed" ? [points[index]] : []));
413
+ const due = drawn.form !== undefined &&
414
+ owed.some(point => point.status === "met") &&
415
+ owed.every(point => point.status === "met" || point.status === "no row owed");
416
+ const beside = due ? besideOf(definition, specification.implementation, drawn, reachedIt).beside : undefined;
417
+ return {
418
+ path: drawn.path,
419
+ rule: drawn.border.rule,
420
+ points,
421
+ ...(beside === undefined ? {} : { beside }),
422
+ };
423
+ });
424
+ borders.push(...guardBorders);
425
+ // Not met by reaching a comparison, as a guard border is: what an ensures
426
+ // clause or an input invariant states holds of every input of the case.
427
+ const writtenCoverage = (drawn) => {
428
+ const coordinates = answeredGivens
429
+ .filter(given => drawn.segments[0] === `@${tagOf(definition.input, given)}`)
430
+ .map(given => drawn.coordinateOf({ rule: drawn.comparison, scope: given }));
431
+ return {
432
+ path: drawn.path,
433
+ rule: drawn.border.rule,
434
+ points: drawn.border.points.map(point => ({
435
+ role: point.role,
436
+ relation: point.relation,
437
+ status: point.status !== "owed"
438
+ ? point.status
439
+ : coordinates.some(value => value !== undefined && point.contains(value))
440
+ ? "met"
441
+ : "gap",
442
+ })),
443
+ };
444
+ };
445
+ borders.push(...[...ensuresBordersOf(definition), ...invariantPairBordersOf(definition)]
446
+ .filter(drawn => !disregardsBorder(definition, drawn))
447
+ .map(writtenCoverage));
448
+ const pairAnalysis = pairCoverage(definition, specification.implementation, positions, guardPartitions, specification.examples.rows, {
449
+ obligations: positiveLimit("pairs.obligations", options.pairs?.obligations, PAIR_LIMIT),
450
+ candidates: positiveLimit("pairs.candidates", options.pairs?.candidates, combinations),
451
+ });
452
+ const pairGap = pairAnalysis.measure.obligations.some(pair => pair.status === "gap" || pair.status === "answer owed");
453
+ const adequate = !pairGap &&
454
+ fakeIssues.length === 0 &&
455
+ specification.implementation !== undefined &&
456
+ failures.length === 0 &&
457
+ unansweredRows.length === 0 &&
458
+ pendingDecisions.length === 0 &&
459
+ controlGaps.length === 0 &&
460
+ modelIssues.length === 0 &&
461
+ input.missing.length === 0 &&
462
+ result.missing.length === 0 &&
463
+ effects.missing.length === 0 &&
464
+ partitions.every(partition => partition.kind !== "divided" || partition.missing.length === 0) &&
465
+ borders.every(border => border.points.every(point => point.status !== "gap")) &&
466
+ borders.every(border => border.beside?.status !== "not told");
467
+ const plans = plansOf(specification.implementation, combinations, wayLimit);
468
+ const arms = measureArms(specification.implementation, armsMet, armsOwed, combinations, plans);
469
+ const rulesMeasure = measureRules(specification.implementation, waysMet, waysOwed, combinations, plans);
470
+ const lines = [
471
+ ...(arms.status === "unavailable" ? [] : arms.arms),
472
+ ...(rulesMeasure.status === "unavailable" ? [] : rulesMeasure.rules),
473
+ ];
474
+ const armGap = lines.some(line => line.status === "gap" || line.status === "answer owed");
475
+ const armUndecided = lines.some(line => line.status === "undecided") ||
476
+ borders.some(border => border.points.some(point => point.status === "undecided") || border.beside?.status === "undecided");
477
+ const unreadComparisons = specification.implementation === undefined
478
+ ? []
479
+ : comparisonsNotReadOf(specification.implementation);
480
+ const comparisons = unreadComparisons.length === 0
481
+ ? { status: "complete" }
482
+ : { status: "partial", notRead: unreadComparisons };
483
+ const constructions = specification.implementation === undefined ? { status: "undetermined", decisions: [] } : verify(specification.implementation, { candidates: combinations, ways: wayLimit });
484
+ const verdict = !adequate || armGap || constructions.status === "refuted"
485
+ ? "not_satisfied"
486
+ : constructions.status !== "verified" || comparisons.status === "partial" ||
487
+ pairAnalysis.measure.status === "partial" ||
488
+ armUndecided ||
489
+ externals.length > 0 ||
490
+ incompleteness.some(item => item.kind === "disregards not checked")
491
+ ? "undetermined"
492
+ : arms.status === "complete" ||
493
+ (arms.status === "unavailable" && arms.reason === "not applicable")
494
+ ? "satisfied"
495
+ : "undetermined";
496
+ return {
497
+ specification: specification.name,
498
+ behavior: definition.name,
499
+ input,
500
+ result,
501
+ effects,
502
+ implementation: specification.implementation === undefined ? "missing" : "present",
503
+ unanswered: unansweredRows,
504
+ pendingDecisions,
505
+ controlGaps,
506
+ modelIssues,
507
+ incompleteness,
508
+ ensures: readEnsures(definition),
509
+ failures,
510
+ partitions,
511
+ borders,
512
+ pairs: countPairs(pairablesOf(positions, guardPartitions), answeredGivens),
513
+ fakeIssues: fakeIssues.map(item => item.issue),
514
+ fakeWarnings: fakeWarningsOf(definition.requires, specification.fakes),
515
+ evidence: {
516
+ input: definition.input.variantTags.filter(tag => !refusedInputs.includes(tag)).map(tag => ({
517
+ case: tag,
518
+ specified: coveredInputs.has(tag),
519
+ executed: executedInputs.has(tag),
520
+ verified: verifiedInputs.has(tag),
521
+ })),
522
+ result: isVariantsSchema(definition.result)
523
+ ? definition.result.variantTags.map(tag => ({
524
+ case: tag,
525
+ specified: coveredResults.has(tag),
526
+ observed: observedResults.has(tag),
527
+ verified: verifiedResults.has(tag),
528
+ }))
529
+ : [],
530
+ effects: definition.effects.variantTags.map(tag => ({
531
+ case: tag,
532
+ specified: coveredEffects.has(tag),
533
+ observed: observedEffects.has(tag),
534
+ verified: verifiedEffects.has(tag),
535
+ })),
536
+ },
537
+ measures: { arms, rules: rulesMeasure, comparisons, pairs: pairAnalysis.measure, constructions },
538
+ adequate: verdict === "satisfied",
539
+ verdict,
540
+ };
541
+ }
542
+ export function generate(target, implementation, options = {}) {
543
+ const combinations = positiveLimit("feasibility.combinations", options.feasibility?.combinations, FEASIBILITY_COMBINATION_LIMIT);
544
+ const definition = target.kind === "behavior" ? target : target.behavior;
545
+ const wayLimit = positiveLimit("feasibility.ways", options.feasibility?.ways, WAY_LIMIT);
546
+ const rows = target.kind === "behavior" ? [] : target.rows.filter(row => definition.input.parse(row.given).success);
547
+ const existing = new Set(rows
548
+ .map(row => tagOf(definition.input, row.given))
549
+ .filter((tag) => tag !== undefined));
550
+ const answeredRows = rows.filter(row => !isTodo(row.expect));
551
+ const origins = answeredRows.map(row => row.given);
552
+ const standIns = Object.fromEntries(Object.entries(definition.requires)
553
+ .filter(([, declared]) => declared.takes === "nothing")
554
+ .map(([name, declared]) => [name, declared.output.placeholder(name)]));
555
+ const withFrom = (origin) => {
556
+ const written = answeredRows.find(row => row.given === origin)?.with;
557
+ const standing = { ...standIns, ...written };
558
+ return Object.keys(standing).length === 0 && written === undefined ? {} : { with: standing };
559
+ };
560
+ const originFor = (position) => origins.find(given => position.valuesIn(given).length > 0) ??
561
+ definition.input.placeholder();
562
+ const generated = [];
563
+ const notComposed = [];
564
+ // A row moved from `from` that breaks an invariant relating finite positions
565
+ // is offered with the other positions chosen again to keep it.
566
+ const offer = (row, from) => {
567
+ const parsed = definition.input.parse(row.given);
568
+ if (parsed.success) {
569
+ generated.push(row);
570
+ return;
571
+ }
572
+ const tag = tagOf(definition.input, row.given);
573
+ const scope = tag === undefined ? undefined : feasibilityScope(definition, tag);
574
+ const finite = from === undefined || scope === undefined ? undefined : keepingInvariants(scope, from, row.given, combinations);
575
+ const kept = finite === undefined || definition.input.parse(finite).success
576
+ ? finite
577
+ : keepingOrderings(scope, from, finite);
578
+ if (kept !== undefined && definition.input.parse(kept).success) {
579
+ generated.push({ ...row, given: kept });
580
+ }
581
+ else {
582
+ notComposed.push(`${row.name}: ${parsed.issues[0].message}`);
583
+ }
584
+ };
585
+ const guardDivided = new Set((implementation === undefined ? [] : guardPartitionsOf(implementation)).map(partition => trailKey(partition.segments)));
586
+ const guardRead = guardReadSegmentsOf(implementation);
587
+ const refused = excludedCases(definition.input);
588
+ for (const tag of definition.input.variantTags.filter(tag => !existing.has(tag) && !refused.includes(tag))) {
589
+ const given = definition.input.placeholderFor(tag);
590
+ offer({ name: `${definition.name}: ${tag}`, given, reason: `${tag}の期待結果を人間が決める必要があります`, ...withFrom(given) }, given);
591
+ }
592
+ for (const position of measuredPositionsOf(definition, guardDivided, guardRead, combinations)) {
593
+ if (position.kind !== "divided") {
594
+ continue;
595
+ }
596
+ for (const className of position.classes) {
597
+ if (position.excluded.includes(className)) {
598
+ continue;
599
+ }
600
+ const standsIn = [...rows, ...generated].some(row => position.classify(row.given).includes(className));
601
+ if (!standsIn) {
602
+ const origin = originFor(position);
603
+ offer({
604
+ name: `${definition.name}: ${position.path} = ${className}`,
605
+ given: position.place(origin, className),
606
+ reason: `${position.path}が${className}の期待結果を人間が決める必要があります`,
607
+ ...withFrom(origin),
608
+ }, origin);
609
+ }
610
+ }
611
+ }
612
+ for (const position of measuredPositionsOf(definition, guardDivided, guardRead, combinations)) {
613
+ for (const border of position.borders) {
614
+ for (const point of border.points) {
615
+ if (point.status !== "owed" || point.witness === undefined) {
616
+ continue;
617
+ }
618
+ const standsAt = [...rows, ...generated].some(row => coordinatesIn(position, border.measure, row.given).some(value => point.contains(value)));
619
+ if (!standsAt) {
620
+ const origin = originFor(position);
621
+ offer({
622
+ name: `${definition.name}: ${position.path} ${point.role} (${point.relation})`,
623
+ given: position.write(origin, border.measure, point.witness),
624
+ reason: `${position.path}の${point.role}点(${point.relation})の期待結果を人間が決める必要があります`,
625
+ ...withFrom(origin),
626
+ }, origin);
627
+ }
628
+ }
629
+ }
630
+ }
631
+ const positionsByPath = new Map(positionsOf(definition.input).map(position => [trailKey(position.segments), position]));
632
+ for (const drawn of implementation === undefined ? [] : guardPartitionsOf(implementation)) {
633
+ const position = positionsByPath.get(trailKey(drawn.segments));
634
+ if (position === undefined) {
635
+ continue;
636
+ }
637
+ for (const item of drawn.classes) {
638
+ const standsIn = [...rows, ...generated].some(row => position.valuesIn(row.given).some(value => value !== undefined && item.contains(value)));
639
+ if (!standsIn) {
640
+ const origin = originFor(position);
641
+ offer({
642
+ name: `${definition.name}: ${drawn.path} = ${item.name}`,
643
+ given: position.write(origin, "value", item.witness),
644
+ reason: `${drawn.path}が${item.name}の期待結果を人間が決める必要があります`,
645
+ ...withFrom(origin),
646
+ }, origin);
647
+ }
648
+ }
649
+ }
650
+ for (const drawn of implementation === undefined ? [] : guardBordersOf(implementation)) {
651
+ const reachedBy = (given, deps) => tagOf(definition.input, given) === drawn.origin?.tag
652
+ ? comparisonsReached(implementation, given, deps).filter(item => item.rule === drawn.comparison)
653
+ : [];
654
+ for (const point of drawn.border.points) {
655
+ if (point.status !== "owed" || point.witness === undefined) {
656
+ continue;
657
+ }
658
+ const standsAt = [...rows, ...generated].some(row => reachedBy(row.given, row.with).some(item => point.contains(drawn.coordinateOf(item))));
659
+ if (standsAt || unmetStatus(reachOf(drawn, point, combinations, wayLimit)).status === "no row owed") {
660
+ continue;
661
+ }
662
+ const origin = origins.find(given => reachedBy(given, withFrom(given).with).length > 0) ??
663
+ definition.input.placeholder();
664
+ const candidates = sidesOf(drawn)
665
+ .map(side => drawn.compose(origin, point.witness, withFrom(origin).with, side))
666
+ .filter(candidate => candidate !== undefined);
667
+ // A row the input takes stands at the point only once the guards before
668
+ // the comparison let it through, which moving another part may not.
669
+ const reaches = (candidate) => reachedBy(candidate, withFrom(origin).with).some(item => point.contains(drawn.coordinateOf(item)));
670
+ const given = candidates.find(candidate => definition.input.parse(candidate).success && reaches(candidate)) ??
671
+ candidates.find(candidate => !definition.input.parse(candidate).success) ??
672
+ candidates.find(candidate => definition.input.parse(candidate).success);
673
+ if (given === undefined) {
674
+ notComposed.push(`${drawn.path} ${point.role} (${point.relation})`);
675
+ }
676
+ else {
677
+ offer({
678
+ name: `${definition.name}: ${drawn.path} ${point.role} (${point.relation})`,
679
+ given,
680
+ reason: `${drawn.path}の${point.role}点(${point.relation})の期待結果を人間が決める必要があります`,
681
+ ...withFrom(origin),
682
+ }, origin);
683
+ }
684
+ }
685
+ if (drawn.form === undefined) {
686
+ continue;
687
+ }
688
+ const items = rows.flatMap(row => reachedBy(row.given, row.with).map(comparison => ({ comparison, given: row.given, deps: row.with })));
689
+ const owed = drawn.border.points.filter(point => point.status === "owed");
690
+ const standsAt = (point) => items.some(item => point.contains(drawn.coordinateOf(item.comparison)));
691
+ const due = owed.some(standsAt) &&
692
+ owed.every(point => standsAt(point) || unmetStatus(reachOf(drawn, point, combinations, wayLimit)).status === "no row owed");
693
+ const found = due ? besideOf(definition, implementation, drawn, items) : undefined;
694
+ if (found?.beside.status !== "not told") {
695
+ continue;
696
+ }
697
+ const label = `${drawn.path} 隣の線 (${found.beside.another})`;
698
+ if (found.given === undefined) {
699
+ notComposed.push(label);
700
+ }
701
+ else {
702
+ offer({
703
+ name: `${definition.name}: ${label}`,
704
+ given: found.given,
705
+ reason: `${drawn.path}を${found.beside.another}と見分ける行の期待結果を人間が決める必要があります`,
706
+ ...(found.deps === undefined ? withFrom(found.given) : { with: { ...standIns, ...found.deps } }),
707
+ });
708
+ }
709
+ }
710
+ for (const drawn of invariantPairBordersOf(definition).filter(drawn => !disregardsBorder(definition, drawn))) {
711
+ const under = (given) => drawn.segments[0] === `@${tagOf(definition.input, given)}`;
712
+ for (const point of drawn.border.points) {
713
+ if (point.status !== "owed" || point.witness === undefined) {
714
+ continue;
715
+ }
716
+ const standsAt = [...rows, ...generated].some(row => under(row.given) && point.contains(drawn.coordinateOf({ rule: drawn.comparison, scope: row.given })));
717
+ if (standsAt) {
718
+ continue;
719
+ }
720
+ const origin = origins.find(under) ?? definition.input.placeholderFor(drawn.segments[0].slice(1));
721
+ const candidates = sidesOf(drawn)
722
+ .map(side => drawn.compose(origin, point.witness, withFrom(origin).with, side))
723
+ .filter(candidate => candidate !== undefined);
724
+ const given = candidates.find(candidate => definition.input.parse(candidate).success) ?? candidates[0];
725
+ if (given === undefined) {
726
+ notComposed.push(`${drawn.path} ${point.role} (${point.relation})`);
727
+ }
728
+ else {
729
+ offer({
730
+ name: `${definition.name}: ${drawn.path} ${point.role} (${point.relation})`,
731
+ given,
732
+ reason: `${drawn.path}の${point.role}点(${point.relation})の期待結果を人間が決める必要があります`,
733
+ ...withFrom(origin),
734
+ }, origin);
735
+ }
736
+ }
737
+ }
738
+ const plans = plansOf(implementation, combinations, wayLimit);
739
+ for (const [tag, decision] of Object.entries(implementation?.cases ?? {})) {
740
+ if (decision.kind !== "rules") {
741
+ continue;
742
+ }
743
+ const wayOf = (given, deps) => traceSync(implementation, given, deps).way;
744
+ const takes = (given, deps, way) => {
745
+ const taken = wayOf(given, deps);
746
+ return taken !== undefined && sameSteps(taken.steps, way.steps);
747
+ };
748
+ const { discriminant } = definition.input;
749
+ // Not a lookup by the term's own trail: a term steps through an optional
750
+ // without naming it, so that trail finds whether the field is left out.
751
+ const at = (path) => {
752
+ const wanted = trailKey([`@${tag}`, ...path.map(key => `.${key}`)]);
753
+ return [...positionsByPath.values()]
754
+ .filter(position => trailKey(position.segments.filter(step => step !== "?")) === wanted)
755
+ .sort((left, right) => right.segments.length - left.segments.length)[0];
756
+ };
757
+ const leftOut = (path) => positionsByPath.get(trailKey([`@${tag}`, ...path.map(key => `.${key}`)]));
758
+ const placed = (origin, witnessed) => {
759
+ let given = origin;
760
+ for (const { path, value } of witnessed) {
761
+ if (path.length === 1 && path[0] === discriminant) {
762
+ continue;
763
+ }
764
+ const position = value === undefined ? leftOut(path) : (at(path) ?? at(path.slice(0, -1)));
765
+ if (position?.kind !== "divided") {
766
+ return undefined;
767
+ }
768
+ given = position.place(given, value === undefined ? "なし" : String(value));
769
+ }
770
+ return given;
771
+ };
772
+ const origins_ = [
773
+ ...origins.filter(given => tagOf(definition.input, given) === tag),
774
+ definition.input.placeholderFor(tag),
775
+ ];
776
+ const plan = plans.get(decision);
777
+ if (plan?.kind === "scoped") {
778
+ notComposed.push(`${decision.id}: local and iteration branch coverage is not yet supported`);
779
+ continue;
780
+ }
781
+ if (plan?.kind === "too many") {
782
+ notComposed.push(`${decision.id}: ${tooManyWays(wayLimit)}ため組み立てない`);
783
+ continue;
784
+ }
785
+ const candidates = plan?.kind === "finite"
786
+ ? plan.reached.filter(item => item.tag === tag)
787
+ : (plan?.ways ?? []).map(way => ({ way, witness: undefined }));
788
+ for (const { way, witness } of candidates) {
789
+ if ([...rows, ...generated].some(row => takes(row.given, row.with, way))) {
790
+ continue;
791
+ }
792
+ if (witness === undefined &&
793
+ feasibilityOf(way, scopeOf(implementation, tag), undefined, combinations).kind === "infeasible") {
794
+ continue;
795
+ }
796
+ const taken = (candidate) => candidate !== undefined && takes(candidate.given, withFrom(candidate.origin).with, way)
797
+ ? candidate
798
+ : undefined;
799
+ const composed = taken(composeForWay(way, tag)) ??
800
+ (options.ways !== true
801
+ ? undefined
802
+ : witness === undefined
803
+ ? taken(composeFromWitnesses(way))
804
+ : composeFromReach(way, witness));
805
+ if (composed !== undefined) {
806
+ offer({
807
+ name: `${definition.name}: ${decision.id} ${describeWay(way)}`,
808
+ given: composed.given,
809
+ reason: `${decision.id}の道筋(${describeWay(way)})の期待結果を人間が決める必要があります`,
810
+ ...withFrom(composed.origin),
811
+ });
812
+ }
813
+ else {
814
+ notComposed.push(`${decision.id}: ${describeWay(way)}`);
815
+ }
816
+ }
817
+ function composeFromReach(way, witness) {
818
+ const witnessed = [...witness].map(([key, value]) => ({ path: JSON.parse(key), value }));
819
+ for (const origin of origins_) {
820
+ const given = placed(origin, witnessed);
821
+ if (given !== undefined && definition.input.parse(given).success && takes(given, withFrom(origin).with, way)) {
822
+ return { given, origin };
823
+ }
824
+ }
825
+ return undefined;
826
+ }
827
+ function composeFromWitnesses(way) {
828
+ for (const origin of origins_) {
829
+ const witnesses = witnessesOf(way, scopeOf(implementation, tag), { discriminant, tag }, combinations);
830
+ if (witnesses === undefined) {
831
+ break;
832
+ }
833
+ for (const witnessed of witnesses) {
834
+ const given = placed(origin, witnessed);
835
+ if (given !== undefined && definition.input.parse(given).success && takes(given, withFrom(origin).with, way)) {
836
+ return { given, origin };
837
+ }
838
+ }
839
+ }
840
+ const searched = domainOf(definition.input, combinations, constantsOf(decision.kind === "rules" ? decision.guards.map(guard => guard.condition) : []));
841
+ for (const given of searched.values) {
842
+ if (takes(given, withFrom(given).with, way))
843
+ return { given, origin: given };
844
+ }
845
+ return undefined;
846
+ }
847
+ function composeForWay(way, caseTag) {
848
+ const last = way.steps[way.steps.length - 1];
849
+ if (last === undefined || last.distinction.kind !== "match") {
850
+ return undefined;
851
+ }
852
+ const matched = last.distinction;
853
+ const keys = positionOf(matched.on).path;
854
+ // A match on an enum selects the position itself; one on a sum field's
855
+ // discriminant selects the field holding it.
856
+ const at = (path) => positionsByPath.get(trailKey([`@${caseTag}`, ...path.map(key => `.${key}`)]));
857
+ const position = at(keys) ?? at(keys.slice(0, -1));
858
+ const origin = origins.find(given => wayOf(given, withFrom(given).with)?.steps.some(step => step.distinction === matched));
859
+ return position?.kind === "divided" && origin !== undefined
860
+ ? { given: position.place(origin, String(last.outcome)), origin }
861
+ : undefined;
862
+ }
863
+ }
864
+ 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) });
865
+ for (const { obligation, given } of pairs.witnesses) {
866
+ if (generated.some(row => isDeepStrictEqual(row.given, given)))
867
+ continue;
868
+ offer({ name: `${definition.name}: ${obligation.positions[0]} = ${obligation.classes[0]} × ${obligation.positions[1]} = ${obligation.classes[1]}`, given,
869
+ reason: "組み合わせの期待結果を人間が決める必要があります", ...withFrom(given) });
870
+ }
871
+ notComposed.push(...pairs.measure.notRead, ...pairs.measure.obligations.filter(pair => pair.status === "undecided").map(pair => `${pair.positions.join(" × ")}: ${pair.classes.join(" × ")} (${pair.reason})`));
872
+ return { rows: generated, notComposed };
873
+ }
874
+ export async function evaluate(exampleSet, name, subject) {
875
+ const row = exampleSet.rows.find(row => row.name === name);
876
+ if (row === undefined) {
877
+ throw new SpecificationError(`No example named ${name} in ${exampleSet.behavior.name}`);
878
+ }
879
+ return evaluateRow(exampleSet.behavior, row, subject);
880
+ }
881
+ async function evaluateRow(definition, row, subject) {
882
+ const name = row.name;
883
+ if (isTodo(row.expect)) {
884
+ return { name, status: "skipped", reason: row.expect.reason };
885
+ }
886
+ let actual;
887
+ try {
888
+ const input = definition.input.parse(row.given);
889
+ if (!input.success) {
890
+ throw new SpecificationError(`Example input is invalid: ${input.issues[0].message}`);
891
+ }
892
+ const expected = row.expect;
893
+ assertExecution(definition, expected, true);
894
+ if (!isCaseOnly(expected.result)) {
895
+ assertEnsures(definition, row.given, expected.result, "Example");
896
+ }
897
+ const outcome = await runAndCompare(definition, name, input.value, expected, async (given) => {
898
+ actual = await subject(given);
899
+ assertExecution(definition, actual, false);
900
+ assertEnsures(definition, row.given, actual.result, "Answer");
901
+ return actual;
902
+ });
903
+ if (outcome.failure !== undefined) {
904
+ return { name, status: "failed", message: outcome.failure.message, ...(actual === undefined ? {} : { actual }) };
905
+ }
906
+ return { name, status: "passed", actual: actual };
907
+ }
908
+ catch (error) {
909
+ return { name, status: "failed", message: error instanceof Error ? error.message : String(error) };
910
+ }
911
+ }
912
+ function assertExecution(definition, execution, expected) {
913
+ if (typeof execution !== "object" || execution === null ||
914
+ !("result" in execution) || !("effects" in execution) || !Array.isArray(execution.effects)) {
915
+ throw new SpecificationError(`${expected ? "Expected execution" : "Execution"} is invalid: expected result and an effects array`);
916
+ }
917
+ if (expected && isCaseOnly(execution.result)) {
918
+ if (!isVariantsSchema(definition.result) || !definition.result.variantTags.includes(execution.result.case)) {
919
+ throw new SpecificationError("Expected result is invalid: unknown case");
920
+ }
921
+ }
922
+ else {
923
+ const result = definition.result.parse(execution.result);
924
+ if (!result.success) {
925
+ throw new SpecificationError(`${expected ? "Expected result" : "Result"} is invalid: ${result.issues[0].message}`);
926
+ }
927
+ }
928
+ for (const [index, effect] of execution.effects.entries()) {
929
+ const parsed = definition.effects.parse(effect, `$.effects[${index}]`);
930
+ if (!parsed.success) {
931
+ throw new SpecificationError(`${expected ? "Expected effect" : `Effect ${index}`} is invalid: ${parsed.issues[0].message}`);
932
+ }
933
+ }
934
+ }
935
+ function assertEnsures(definition, input, result, source) {
936
+ const broken = brokenEnsures(definition, input, result);
937
+ if (broken !== undefined) {
938
+ throw new SpecificationError(`${source} breaks ensures ${broken.name}: ${describeRule(broken.rule, "")}`);
939
+ }
940
+ }
941
+ export async function test(exampleSet, subject) {
942
+ const failures = [];
943
+ const skipped = [];
944
+ for (const row of exampleSet.rows) {
945
+ const outcome = await evaluateRow(exampleSet.behavior, row, subject);
946
+ if (outcome.status === "failed") {
947
+ failures.push({ name: outcome.name, message: outcome.message });
948
+ }
949
+ else if (outcome.status === "skipped") {
950
+ skipped.push({ name: outcome.name, reason: outcome.reason });
951
+ }
952
+ }
953
+ return { failures, skipped };
954
+ }
955
+ function pairablesOf(positions, guardPartitions) {
956
+ return positions.flatMap((position) => {
957
+ if (position.kind === "divided") {
958
+ return [
959
+ {
960
+ path: position.path,
961
+ classes: position.classes.filter(name => !position.excluded.includes(name)),
962
+ classify: given => position.classify(given),
963
+ },
964
+ ];
965
+ }
966
+ const drawn = guardPartitions.find(partition => isDeepStrictEqual(partition.segments, position.segments));
967
+ if (drawn === undefined) {
968
+ return [];
969
+ }
970
+ return [
971
+ {
972
+ path: position.path,
973
+ classes: drawn.classes.map(item => item.name),
974
+ classify: given => position
975
+ .valuesIn(given)
976
+ .flatMap(value => value === undefined
977
+ ? []
978
+ : drawn.classes.filter(item => item.contains(value)).map(item => item.name)),
979
+ },
980
+ ];
981
+ });
982
+ }
983
+ function countPairs(pairables, givens) {
984
+ const pairs = [];
985
+ pairables.forEach((left, index) => {
986
+ for (const right of pairables.slice(index + 1)) {
987
+ if (!combine(left.path, right.path)) {
988
+ continue;
989
+ }
990
+ const reached = new Set(givens.flatMap(given => left
991
+ .classify(given)
992
+ .flatMap(first => right.classify(given).map(second => `${first}\u0000${second}`))));
993
+ pairs.push({
994
+ positions: [left.path, right.path],
995
+ reached: reached.size,
996
+ total: left.classes.length * right.classes.length,
997
+ });
998
+ }
999
+ });
1000
+ return pairs;
1001
+ }
1002
+ function combine(left, right) {
1003
+ if (right.startsWith(`${left}@`) || left.startsWith(`${right}@`)) {
1004
+ return false;
1005
+ }
1006
+ const narrowings = (path) => [...path.matchAll(/@([^.@\[\]{}?]+)/g)].map(found => ({
1007
+ before: path.slice(0, found.index),
1008
+ tag: found[1],
1009
+ }));
1010
+ const rightNarrowings = narrowings(right);
1011
+ return narrowings(left).every(narrowing => rightNarrowings.every(other => other.before !== narrowing.before || other.tag === narrowing.tag));
1012
+ }
1013
+ function measureRules(implementation, met, owed, combinations, plans) {
1014
+ if (implementation === undefined || implementation.pipeline !== undefined) {
1015
+ return { status: "unavailable", reason: "not applicable" };
1016
+ }
1017
+ if (implementation.external !== undefined) {
1018
+ return { status: "unavailable", reason: "not measured", notRead: [implementation.behavior.name] };
1019
+ }
1020
+ const decided = decisionsWithCases(implementation);
1021
+ const notRead = decided.flatMap(([decision]) => decision.kind === "decision" || (decision.kind === "rules" && ["too many", "scoped"].includes(plans.get(decision)?.kind ?? ""))
1022
+ ? [decision.id]
1023
+ : []);
1024
+ const took = (taken, decision, steps) => taken.some(item => item.decision === decision && sameSteps(item.steps, steps));
1025
+ const rules = decided.flatMap(([decision, tags]) => {
1026
+ const plan = plans.get(decision);
1027
+ if (decision.kind !== "rules" || plan === undefined || (plan.kind === "too many" || plan.kind === "scoped")) {
1028
+ return [];
1029
+ }
1030
+ const ways = plan.kind === "finite" ? plan.reached.map(item => item.way) : plan.ways;
1031
+ return ways.map((way) => {
1032
+ const base = { decision: decision.id, way: describeWay(way) };
1033
+ if (took(met, decision.id, way.steps)) {
1034
+ return { ...base, status: "met" };
1035
+ }
1036
+ if (took(owed, decision.id, way.steps)) {
1037
+ return { ...base, status: "answer owed" };
1038
+ }
1039
+ return plan.kind === "finite"
1040
+ ? { ...base, status: "gap" }
1041
+ : {
1042
+ ...base,
1043
+ ...unmetStatus(tags.map(tag => feasibilityOf(way, scopeOf(implementation, tag), undefined, combinations))),
1044
+ };
1045
+ });
1046
+ });
1047
+ if (notRead.length === 0) {
1048
+ return { status: "complete", rules };
1049
+ }
1050
+ return rules.length === 0
1051
+ ? { status: "unavailable", reason: "not measured", notRead }
1052
+ : { status: "partial", rules, notRead };
1053
+ }
1054
+ function measureArms(implementation, met, owed, combinations, plans) {
1055
+ if (implementation === undefined || implementation.pipeline !== undefined) {
1056
+ return { status: "unavailable", reason: "not applicable" };
1057
+ }
1058
+ if (implementation.external !== undefined) {
1059
+ return { status: "unavailable", reason: "not measured", notRead: [implementation.behavior.name] };
1060
+ }
1061
+ const decided = decisionsWithCases(implementation);
1062
+ const notRead = decided.flatMap(([decision]) => decision.kind === "decision" || (decision.kind === "rules" && ["too many", "scoped"].includes(plans.get(decision)?.kind ?? ""))
1063
+ ? [decision.id]
1064
+ : []);
1065
+ const took = (taken, decision, guard, arm) => taken.some(item => item.decision === decision && item.guard === guard && item.arm === arm);
1066
+ const arms = decided.flatMap(([decision, tags]) => {
1067
+ const plan = plans.get(decision);
1068
+ if (decision.kind !== "rules" || plan === undefined || (plan.kind === "too many" || plan.kind === "scoped")) {
1069
+ return [];
1070
+ }
1071
+ const ways = plan.kind === "finite"
1072
+ ? plan.reached.map(({ way }) => ({ way, feasibility: { kind: "feasible" } }))
1073
+ : tags.flatMap(tag => plan.ways.map(way => ({
1074
+ way,
1075
+ feasibility: feasibilityOf(way, scopeOf(implementation, tag), undefined, combinations),
1076
+ })));
1077
+ const through = (index, arm) => ways.filter(({ way }) => decision.expression !== undefined
1078
+ ? way.choices?.some(choice => choice.condition === decision.guards[index]?.condition && choice.outcome === (arm === "holds"))
1079
+ : index === decision.guards.length
1080
+ ? way.exit === "case" && way.steps[way.steps.length - 1]?.outcome === arm
1081
+ : arm === "else"
1082
+ ? way.exit === index
1083
+ : typeof way.exit !== "number" || way.exit > index);
1084
+ const statusOf = (index, arm) => took(met, decision.id, index, arm)
1085
+ ? { status: "met" }
1086
+ : took(owed, decision.id, index, arm)
1087
+ ? { status: "answer owed" }
1088
+ : plan.kind === "finite" && through(index, arm).length === 0
1089
+ ? { status: "no row owed", reason: unreached }
1090
+ : unmetStatus(through(index, arm).map(item => item.feasibility));
1091
+ const guarded = decision.guards.flatMap((candidate, index) => ["holds", "else"].map((arm) => ({
1092
+ decision: decision.id,
1093
+ guard: describeRule(candidate.condition),
1094
+ arm,
1095
+ ...statusOf(index, arm),
1096
+ })));
1097
+ const { otherwise } = decision;
1098
+ const matched = typeof otherwise === "function"
1099
+ ? []
1100
+ : Object.keys(otherwise.cases).map((arm) => ({
1101
+ decision: decision.id,
1102
+ guard: `match ${describeTerm(otherwise.on)}`,
1103
+ arm,
1104
+ ...statusOf(decision.guards.length, arm),
1105
+ }));
1106
+ return [...guarded, ...matched];
1107
+ });
1108
+ if (notRead.length === 0) {
1109
+ return { status: "complete", arms };
1110
+ }
1111
+ return arms.length === 0
1112
+ ? { status: "unavailable", reason: "not measured", notRead }
1113
+ : { status: "partial", arms, notRead };
1114
+ }
1115
+ // Not one entry per case: $default hands one decision to several cases, and
1116
+ // listing it per case would owe each of its arms once for every case it decides.
1117
+ function decisionsWithCases(implementation) {
1118
+ const grouped = new Map();
1119
+ for (const [tag, decision] of Object.entries(implementation.cases)) {
1120
+ grouped.set(decision, [...(grouped.get(decision) ?? []), tag]);
1121
+ }
1122
+ return [...grouped];
1123
+ }
1124
+ function stagesOf(implementation) {
1125
+ return implementation.pipeline === undefined
1126
+ ? [implementation]
1127
+ : implementation.pipeline.flatMap(stagesOf);
1128
+ }
1129
+ function todoDecisionsIn(implementation) {
1130
+ if (implementation === undefined) {
1131
+ return [];
1132
+ }
1133
+ const composed = implementation.pipeline !== undefined;
1134
+ return stagesOf(implementation).flatMap(stage => Object.entries(stage.cases).flatMap(([variant, decision]) => decision.kind === "todo"
1135
+ ? [{ variant: composed ? `${stage.behavior.name}: ${variant}` : variant, reason: decision.reason }]
1136
+ : []));
1137
+ }
1138
+ function openDecisionIn(implementation, error) {
1139
+ if (!(error instanceof TodoDecision)) {
1140
+ return undefined;
1141
+ }
1142
+ return implementation.pipeline === undefined
1143
+ ? error.variant
1144
+ : `${error.behavior}: ${error.variant}`;
1145
+ }
1146
+ function externalsIn(implementation) {
1147
+ if (implementation === undefined) {
1148
+ return [];
1149
+ }
1150
+ if (implementation.external !== undefined) {
1151
+ return [`${implementation.behavior.name}: ${implementation.external.reason}`];
1152
+ }
1153
+ return implementation.pipeline === undefined
1154
+ ? []
1155
+ : implementation.pipeline.flatMap(stage => externalsIn(stage));
1156
+ }
1157
+ function unmetStatus(feasibilities) {
1158
+ if (feasibilities.length === 0 || feasibilities.some(item => item.kind === "feasible")) {
1159
+ return { status: "gap" };
1160
+ }
1161
+ const undecided = feasibilities.find(item => item.kind === "undecided");
1162
+ if (undecided !== undefined) {
1163
+ return { status: "undecided", reason: undecided.reason };
1164
+ }
1165
+ return { status: "no row owed", reason: feasibilities[0].reason };
1166
+ }
1167
+ function besideOf(definition, implementation, drawn, reachedIt) {
1168
+ const parts = [...drawn.form.parts].sort((left, right) => left.path < right.path ? -1 : left.path > right.path ? 1 : 0);
1169
+ const rows = reachedIt.flatMap(item => {
1170
+ const values = parts.map(part => part.valueOf(item.comparison.scope));
1171
+ return values.every(value => value !== undefined)
1172
+ ? [{ values, kept: holds(drawn.comparison, item.comparison.scope), given: item.given, deps: item.deps }]
1173
+ : [];
1174
+ });
1175
+ const kept = rows.filter(row => row.kept).map(row => row.values);
1176
+ if (kept.length === 0) {
1177
+ return { beside: { status: "undecided", reason: allOnOneSide } };
1178
+ }
1179
+ const keptBelow = drawn.comparison.operator === "<" || drawn.comparison.operator === "<=";
1180
+ const line = lineTheRowsAllow(parts.map(part => part.coefficient), keptBelow, kept, rows.filter(row => !row.kept).map(row => row.values));
1181
+ if (line === undefined) {
1182
+ return { beside: { status: "told" } };
1183
+ }
1184
+ const others = (drawn.origin?.decision.guards ?? []).filter(guard => !mentions(guard.condition, drawn.comparison));
1185
+ const shown = partingsOf(parts.map(part => part.coefficient), line, keptBelow, rows)
1186
+ .flatMap(parting => {
1187
+ const given = parts.reduce((written, part, index) => (written === undefined ? undefined : part.write(written, parting.values[index])), rows[parting.from].given);
1188
+ const deps = rows[parting.from].deps;
1189
+ const reaches = given !== undefined &&
1190
+ definition.input.parse(given).success &&
1191
+ comparisonsReached(implementation, given, deps).some(item => item.rule === drawn.comparison);
1192
+ if (!reaches) {
1193
+ return [];
1194
+ }
1195
+ const visible = others.every(guard => holds(guard.condition, withDeps(given, deps)));
1196
+ return [{ parting, given, rank: [visible ? 0 : 1, Math.abs(parting.steps)] }];
1197
+ })
1198
+ .reduce((best, candidate) => best === undefined ||
1199
+ candidate.rank[0] < best.rank[0] ||
1200
+ (candidate.rank[0] === best.rank[0] && candidate.rank[1] < best.rank[1])
1201
+ ? candidate
1202
+ : best, undefined);
1203
+ const another = spelled(parts.map(part => part.path), line);
1204
+ return shown === undefined
1205
+ ? { beside: { status: "not told", another } }
1206
+ : {
1207
+ beside: {
1208
+ status: "not told",
1209
+ another,
1210
+ input: parts.map((part, index) => `${part.path} = ${shown.parting.values[index]}`).join(", "),
1211
+ },
1212
+ given: shown.given,
1213
+ deps: rows[shown.parting.from].deps,
1214
+ };
1215
+ }
1216
+ function sidesOf(drawn) {
1217
+ return Array.from({ length: drawn.sides ?? 2 }, (_, side) => side);
1218
+ }
1219
+ function mentions(rule, target) {
1220
+ if (rule === target) {
1221
+ return true;
1222
+ }
1223
+ switch (rule.kind) {
1224
+ case "and":
1225
+ case "or":
1226
+ return rule.rules.some(part => mentions(part, target));
1227
+ case "not":
1228
+ return mentions(rule.rule, target);
1229
+ case "all":
1230
+ case "any":
1231
+ return mentions(rule.each, target);
1232
+ default:
1233
+ return false;
1234
+ }
1235
+ }
1236
+ function reachOf(drawn, point, combinations, wayLimit) {
1237
+ const normalized = normalize(drawn.comparison);
1238
+ const { left, right } = drawn.comparison;
1239
+ if (drawn.origin === undefined || point.region === undefined) {
1240
+ return [{ kind: "feasible" }];
1241
+ }
1242
+ const { decision, scope } = drawn.origin;
1243
+ let placement;
1244
+ if (normalized !== undefined) {
1245
+ const term = (isTerm(left) ? left : right);
1246
+ placement = { path: positionOf(term).path, measure: normalized.measure, ...point.region };
1247
+ }
1248
+ else if (isTerm(left) &&
1249
+ isTerm(right) &&
1250
+ positionData(left) !== undefined &&
1251
+ positionData(right) !== undefined) {
1252
+ const side = (term) => ({ path: positionOf(term).path, measure: positionOf(term).measure });
1253
+ placement = { between: [side(left), side(right)], ...point.region };
1254
+ }
1255
+ else if ([left, right].some(operand => isTerm(operand))) {
1256
+ placement = { form: differenceOf(drawn.comparison), ...point.region };
1257
+ }
1258
+ else {
1259
+ return [{ kind: "feasible" }];
1260
+ }
1261
+ const prefixes = [];
1262
+ let followed = 0;
1263
+ for (const way of eachWayOf(decision)) {
1264
+ followed += 1;
1265
+ if (followed > wayLimit) {
1266
+ return [{ kind: "undecided", reason: tooManyWays(wayLimit) }];
1267
+ }
1268
+ const index = way.steps.findIndex(step => step.distinction === drawn.comparison);
1269
+ if (index !== -1) {
1270
+ prefixes.push(way.steps.slice(0, index));
1271
+ }
1272
+ }
1273
+ return prefixes.length === 0
1274
+ ? [{ kind: "feasible" }]
1275
+ : prefixes.map(steps => feasibilityOf({ steps }, scope, placement, combinations));
1276
+ }
1277
+ function scopeOf(implementation, tag) {
1278
+ return feasibilityScope(implementation.behavior, tag);
1279
+ }
1280
+ function coverage(all, covered, excluded = []) {
1281
+ const counted = all.filter(value => !excluded.includes(value));
1282
+ return {
1283
+ covered: counted.filter(value => covered.has(value)),
1284
+ missing: counted.filter(value => !covered.has(value)),
1285
+ excluded: all.filter(value => excluded.includes(value)),
1286
+ total: counted.length,
1287
+ };
1288
+ }
1289
+ function disregardsBorder(definition, drawn) {
1290
+ return [drawn.segments, ...(drawn.reads ?? [])].some(segments => isDisregarded(definition, { segments }));
1291
+ }
1292
+ function isDisregarded(definition, position) {
1293
+ return Object.entries(definition.disregards).some(([tag, paths]) => paths.some(keys => isUnder(position, [`@${tag}`, ...keys.map(key => `.${key}`)])));
1294
+ }
1295
+ // A term steps through an optional or a nested case without naming it, so the
1296
+ // markers for those are left out before its keys are compared with a position's.
1297
+ // Positions are keyed by their segments, not their rendered path, since a key
1298
+ // holding "." renders the same as the nested path it spells.
1299
+ function trailKey(segments) {
1300
+ return JSON.stringify(segments);
1301
+ }
1302
+ function isUnder(position, prefix) {
1303
+ const named = namedSegments(position);
1304
+ return prefix.every((segment, index) => named[index] === segment);
1305
+ }
1306
+ // An element name maps to its trail, or to undefined when the quantifier ranges
1307
+ // over something other than the input, such as a value dependency.
1308
+ function segmentsRead(rule, root, elements) {
1309
+ const trailsOf = (term) => isTerm(term)
1310
+ ? termPaths({ kind: "compare", operator: "==", left: term, right: 0 }).flatMap(path => {
1311
+ const trail = trailAt(path);
1312
+ return trail === undefined ? [] : [trail];
1313
+ })
1314
+ : [];
1315
+ const trailOf = (term) => isTerm(term) ? trailAt(positionOf(term).path) : undefined;
1316
+ const trailAt = (path) => {
1317
+ const [head, ...rest] = path;
1318
+ if (head === undefined || head === DEPS) {
1319
+ return undefined;
1320
+ }
1321
+ if (elements.has(head)) {
1322
+ const base = elements.get(head);
1323
+ return base === undefined ? undefined : [...base, ...rest.map(key => `.${key}`)];
1324
+ }
1325
+ return [...root, `.${head}`, ...rest.map(key => `.${key}`)];
1326
+ };
1327
+ switch (rule.kind) {
1328
+ case "compare":
1329
+ return [rule.left, rule.right].flatMap(trailsOf);
1330
+ case "all":
1331
+ case "any": {
1332
+ const of = trailOf(rule.of);
1333
+ const inner = segmentsRead(rule.each, root, new Map([...elements, [rule.element, of === undefined ? undefined : [...of, "[]"]]]));
1334
+ return of === undefined ? inner : [of, ...inner];
1335
+ }
1336
+ case "and":
1337
+ case "or":
1338
+ return rule.rules.flatMap(inner => segmentsRead(inner, root, elements));
1339
+ case "not":
1340
+ return segmentsRead(rule.rule, root, elements);
1341
+ }
1342
+ }
1343
+ function guardReadSegmentsOf(implementation) {
1344
+ if (implementation === undefined) {
1345
+ return [];
1346
+ }
1347
+ return Object.entries(implementation.cases).flatMap(([tag, decision]) => {
1348
+ if (decision.kind !== "rules") {
1349
+ return [];
1350
+ }
1351
+ const root = [`@${tag}`];
1352
+ const matched = typeof decision.otherwise === "function"
1353
+ ? []
1354
+ : [[...root, ...positionOf(decision.otherwise.on).path.map(key => `.${key}`)]];
1355
+ return [...decision.guards.flatMap(item => segmentsRead(item.condition, root, new Map())), ...matched];
1356
+ });
1357
+ }
1358
+ function namedSegments(position) {
1359
+ const [inputCase, ...rest] = position.segments;
1360
+ return [inputCase, ...rest.filter(segment => segment !== "?" && !segment.startsWith("@"))];
1361
+ }
1362
+ // A disregarded position a guard reads is kept rather than dropped, since the
1363
+ // guard's classes are attached to it; only what its type and invariants owe goes.
1364
+ function measuredPositionsOf(definition, guardDivided = new Set(), guardRead = [], combinations = FEASIBILITY_COMBINATION_LIMIT) {
1365
+ return positionsOf(definition.input).map(position => withJointExclusions(definition, position, combinations)).flatMap((position) => {
1366
+ if (!isDisregarded(definition, position)) {
1367
+ return [position];
1368
+ }
1369
+ const named = namedSegments(position);
1370
+ if (guardRead.some(trail => named.every((segment, index) => trail[index] === segment))) {
1371
+ return [{ ...position, borders: [] }];
1372
+ }
1373
+ if (!guardDivided.has(trailKey(position.segments))) {
1374
+ return [];
1375
+ }
1376
+ return [
1377
+ position.kind === "divided"
1378
+ ? { ...position, classes: [], excluded: [], borders: [] }
1379
+ : { ...position, borders: [] },
1380
+ ];
1381
+ });
1382
+ }
1383
+ const DISREGARD_COMBINATION_LIMIT = 255;
1384
+ // Not the combinations alone: moves are tried before a combination is known to
1385
+ // be one the input can hold, so the candidates tried that way are bounded too.
1386
+ const DISREGARD_CANDIDATE_LIMIT = 4096;
1387
+ function positiveLimit(name, given, fallback) {
1388
+ if (given === undefined) {
1389
+ return fallback;
1390
+ }
1391
+ if (!Number.isSafeInteger(given) || given <= 0) {
1392
+ throw new SpecificationError(`${name} must be a positive integer, but was ${given}`);
1393
+ }
1394
+ return given;
1395
+ }
1396
+ async function disregardBroken(implementation, row, answered, standIns, limits) {
1397
+ const definition = implementation.behavior;
1398
+ const tag = tagOf(definition.input, row.given);
1399
+ const kept = positionsOf(definition.input).filter(position => isUnder(position, [`@${tag}`]) && !isDisregarded(definition, position));
1400
+ const readKept = (given) => kept.map(position => [
1401
+ position.kind === "divided" ? position.classify(given) : [],
1402
+ position.borders.map(border => coordinatesIn(position, border.measure, given)),
1403
+ ]);
1404
+ const keptOriginally = readKept(row.given);
1405
+ const axes = positionsOf(definition.input).flatMap(position => {
1406
+ if (!isUnder(position, [`@${tag}`]) || !isDisregarded(definition, position)) {
1407
+ return [];
1408
+ }
1409
+ return position.instancesIn(row.given).flatMap(instance => {
1410
+ const classes = position.kind === "divided" ? position : undefined;
1411
+ const located = instance;
1412
+ const classified = (given) => (classes === undefined ? [] : located.classify(given));
1413
+ const taken = classified(row.given);
1414
+ const coordinates = (given) => position.borders.map(border => coordinatesIn(instance, border.measure, given));
1415
+ const original = coordinates(row.given);
1416
+ const classMoves = classes === undefined
1417
+ ? []
1418
+ : classes.classes
1419
+ .filter(className => !taken.includes(className) && !classes.excluded.includes(className))
1420
+ .map(className => ({
1421
+ label: className,
1422
+ apply: given => located.place(given, className),
1423
+ reached: varied => located.classify(varied).includes(className),
1424
+ }));
1425
+ const pointMoves = position.borders.flatMap((border, index) => border.points.flatMap(point => point.status !== "owed" ||
1426
+ point.witness === undefined ||
1427
+ original[index].some(value => point.contains(value))
1428
+ ? []
1429
+ : [
1430
+ {
1431
+ label: `${point.role} (${point.relation})`,
1432
+ apply: (given) => instance.write(given, border.measure, point.witness),
1433
+ reached: (varied) => coordinatesIn(instance, border.measure, varied).some(value => point.contains(value)),
1434
+ },
1435
+ ]));
1436
+ const moves = [...classMoves, ...pointMoves];
1437
+ return moves.length === 0
1438
+ ? []
1439
+ : [
1440
+ {
1441
+ path: instance.path,
1442
+ moves,
1443
+ unmoved: (varied) => (isDeepStrictEqual(classified(varied), taken) &&
1444
+ isDeepStrictEqual(coordinates(varied), original)) ||
1445
+ (classified(varied).length === 0 && coordinates(varied).every(values => values.length === 0)),
1446
+ },
1447
+ ];
1448
+ });
1449
+ });
1450
+ const candidates = axes.reduce((total, axis) => total * (axis.moves.length + 1), 1) - 1;
1451
+ if (candidates > limits.candidates) {
1452
+ return {
1453
+ kind: "not checked",
1454
+ incompleteness: {
1455
+ kind: "disregards not checked",
1456
+ subject: row.name,
1457
+ reason: `disregardsの組み合わせの候補が${candidates}通りあり、上限の${limits.candidates}通りを超えるため数えていない`,
1458
+ },
1459
+ };
1460
+ }
1461
+ const combinations = axes
1462
+ .reduce((partial, axis) => partial.flatMap(choice => [undefined, ...axis.moves].map(move => [...choice, move])), [[]])
1463
+ .filter(choice => choice.some(move => move !== undefined))
1464
+ .flatMap(choice => {
1465
+ const varied = choice.reduce((given, move) => (move === undefined ? given : move.apply(given)), row.given);
1466
+ const holds = axes.every((axis, index) => {
1467
+ const move = choice[index];
1468
+ return move === undefined ? axis.unmoved(varied) : move.reached(varied);
1469
+ });
1470
+ return holds &&
1471
+ isDeepStrictEqual(readKept(varied), keptOriginally) &&
1472
+ definition.input.parse(varied).success
1473
+ ? [{ choice, varied }]
1474
+ : [];
1475
+ })
1476
+ .sort((left, right) => {
1477
+ const moved = (choice) => choice.flatMap((move, index) => (move === undefined ? [] : [index]));
1478
+ const [a, b] = [moved(left.choice), moved(right.choice)];
1479
+ const first = a.findIndex((index, at) => index !== b[at]);
1480
+ return a.length - b.length || (first === -1 ? 0 : a[first] - b[first]);
1481
+ });
1482
+ if (combinations.length > limits.combinations) {
1483
+ return {
1484
+ kind: "not checked",
1485
+ incompleteness: {
1486
+ kind: "disregards not checked",
1487
+ subject: row.name,
1488
+ reason: `disregardsの組み合わせが${combinations.length}通りあり、上限の${limits.combinations}通りを超えるため確かめていない`,
1489
+ },
1490
+ };
1491
+ }
1492
+ for (const { choice, varied } of combinations) {
1493
+ const outcome = await runTraced(implementation, varied, standIns).then((traced) => isDeepStrictEqual(traced.execution, answered) ? undefined : { text: "its answer changed" }, (error) => ({ text: "it threw", error: error instanceof Error ? error.message : String(error) }));
1494
+ if (outcome !== undefined) {
1495
+ const moved = axes.flatMap((axis, index) => {
1496
+ const move = choice[index];
1497
+ return move === undefined ? [] : [{ path: axis.path, label: move.label }];
1498
+ });
1499
+ return {
1500
+ kind: "broken",
1501
+ failure: {
1502
+ name: row.name,
1503
+ message: `${definition.name} disregards ${moved.map(item => item.path).join(", ")}, but ${outcome.text} when ${moved
1504
+ .map(item => `${item.path} was ${item.label}`)
1505
+ .join(" and ")}${outcome.error === undefined ? "" : `: ${outcome.error}`}`,
1506
+ },
1507
+ };
1508
+ }
1509
+ }
1510
+ return { kind: "held" };
1511
+ }
1512
+ // A class of a boolean, an enum or a sum field that no combination of values
1513
+ // the invariants relating finite positions keep can take is excluded, like
1514
+ // one a rule on the position alone refuses.
1515
+ function withJointExclusions(definition, position, combinations) {
1516
+ const [head, ...rest] = position.segments;
1517
+ if (position.kind !== "divided" || head === undefined || rest.length === 0 || !rest.every(step => step.startsWith("."))) {
1518
+ return position;
1519
+ }
1520
+ const tag = head.slice(1);
1521
+ const scope = feasibilityScope(definition, tag);
1522
+ const keys = rest.map(step => step.slice(1));
1523
+ const field = schemaAtPath(scope, keys);
1524
+ const coordinate = (className) => {
1525
+ switch (field?.kind) {
1526
+ case "boolean":
1527
+ return { path: keys, value: className === "true" };
1528
+ case "enum":
1529
+ return { path: keys, value: className };
1530
+ case "variants":
1531
+ return { path: [...keys, field.discriminant], value: className };
1532
+ default:
1533
+ return undefined;
1534
+ }
1535
+ };
1536
+ const refused = position.classes.filter(className => {
1537
+ if (position.excluded.includes(className)) {
1538
+ return true;
1539
+ }
1540
+ const at = coordinate(className);
1541
+ return at !== undefined && refusedJointly(scope, at.path, at.value, combinations);
1542
+ });
1543
+ return refused.length === position.excluded.length ? position : { ...position, excluded: refused };
1544
+ }
1545
+ function plansOf(implementation, combinations, wayLimit) {
1546
+ const plans = new Map();
1547
+ for (const [decision, tags] of implementation === undefined ? [] : decisionsWithCases(implementation)) {
1548
+ if (decision.kind !== "rules") {
1549
+ continue;
1550
+ }
1551
+ if (hasScopedChoices(decision.expression)) {
1552
+ plans.set(decision, { kind: "scoped" });
1553
+ continue;
1554
+ }
1555
+ const reaches = tags.map(tag => ({
1556
+ tag,
1557
+ reached: decision.expression !== undefined ? undefined : finiteReach(decision, scopeOf(implementation, tag), combinations, [[implementation.behavior.input.discriminant]]),
1558
+ }));
1559
+ if (reaches.every(item => item.reached !== undefined)) {
1560
+ const reached = new Map();
1561
+ for (const { tag, reached: each } of reaches) {
1562
+ for (const item of each) {
1563
+ const key = describeWay(item.way);
1564
+ if (!reached.has(key)) {
1565
+ reached.set(key, { ...item, tag });
1566
+ }
1567
+ }
1568
+ }
1569
+ plans.set(decision, { kind: "finite", reached: [...reached.values()] });
1570
+ continue;
1571
+ }
1572
+ const ways = [];
1573
+ for (const way of eachWayOf(decision)) {
1574
+ ways.push(way);
1575
+ if (ways.length > wayLimit) {
1576
+ break;
1577
+ }
1578
+ }
1579
+ plans.set(decision, ways.length > wayLimit ? { kind: "too many" } : { kind: "ways", ways });
1580
+ }
1581
+ return plans;
1582
+ }
1583
+ //# sourceMappingURL=specification.js.map