@toiroakr/chisel 0.1.0 → 0.3.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 (191) hide show
  1. package/README.md +354 -21
  2. package/dist/absence.d.ts +28 -0
  3. package/dist/absence.js +266 -0
  4. package/dist/absence.js.map +1 -0
  5. package/dist/behavior.d.ts +26 -19
  6. package/dist/behavior.js +193 -203
  7. package/dist/behavior.js.map +1 -1
  8. package/dist/beside.d.ts +5 -0
  9. package/dist/beside.js +10 -0
  10. package/dist/beside.js.map +1 -1
  11. package/dist/border.d.ts +7 -8
  12. package/dist/border.js +88 -36
  13. package/dist/border.js.map +1 -1
  14. package/dist/bounds.d.ts +1 -0
  15. package/dist/bounds.js +27 -0
  16. package/dist/bounds.js.map +1 -0
  17. package/dist/changes.d.ts +23 -0
  18. package/dist/changes.js +355 -0
  19. package/dist/changes.js.map +1 -0
  20. package/dist/checks.d.ts +1 -0
  21. package/dist/checks.js +295 -0
  22. package/dist/checks.js.map +1 -0
  23. package/dist/cli.d.ts +4 -0
  24. package/dist/cli.js +351 -14
  25. package/dist/cli.js.map +1 -1
  26. package/dist/codec.js +16 -7
  27. package/dist/codec.js.map +1 -1
  28. package/dist/codegen.js +6 -8
  29. package/dist/codegen.js.map +1 -1
  30. package/dist/composition.d.ts +3 -3
  31. package/dist/composition.js +9 -8
  32. package/dist/composition.js.map +1 -1
  33. package/dist/conformance.d.ts +24 -0
  34. package/dist/conformance.js +44 -0
  35. package/dist/conformance.js.map +1 -0
  36. package/dist/data.d.ts +3 -2
  37. package/dist/data.js +7 -3
  38. package/dist/data.js.map +1 -1
  39. package/dist/decimal-js.d.ts +2 -0
  40. package/dist/decimal-js.js +5 -0
  41. package/dist/decimal-js.js.map +1 -0
  42. package/dist/decimal.d.ts +2 -0
  43. package/dist/decimal.js +3 -0
  44. package/dist/decimal.js.map +1 -0
  45. package/dist/dependency.d.ts +9 -6
  46. package/dist/dependency.js +23 -17
  47. package/dist/dependency.js.map +1 -1
  48. package/dist/domain.d.ts +6 -2
  49. package/dist/domain.js +65 -25
  50. package/dist/domain.js.map +1 -1
  51. package/dist/ensures.js +3 -3
  52. package/dist/ensures.js.map +1 -1
  53. package/dist/equal.d.ts +1 -0
  54. package/dist/equal.js +135 -0
  55. package/dist/equal.js.map +1 -0
  56. package/dist/errors.d.ts +18 -0
  57. package/dist/errors.js +25 -0
  58. package/dist/errors.js.map +1 -0
  59. package/dist/exact.d.ts +13 -1
  60. package/dist/exact.js +52 -3
  61. package/dist/exact.js.map +1 -1
  62. package/dist/feasibility.d.ts +5 -3
  63. package/dist/feasibility.js +309 -53
  64. package/dist/feasibility.js.map +1 -1
  65. package/dist/guard-borders.d.ts +14 -5
  66. package/dist/guard-borders.js +229 -190
  67. package/dist/guard-borders.js.map +1 -1
  68. package/dist/guard-scope.d.ts +65 -0
  69. package/dist/guard-scope.js +384 -0
  70. package/dist/guard-scope.js.map +1 -0
  71. package/dist/hooks.d.ts +22 -0
  72. package/dist/hooks.js +2 -0
  73. package/dist/hooks.js.map +1 -0
  74. package/dist/index.d.ts +30 -8
  75. package/dist/index.js +18 -5
  76. package/dist/index.js.map +1 -1
  77. package/dist/interleave.d.ts +31 -0
  78. package/dist/interleave.js +202 -0
  79. package/dist/interleave.js.map +1 -0
  80. package/dist/interval.d.ts +8 -0
  81. package/dist/interval.js +213 -23
  82. package/dist/interval.js.map +1 -1
  83. package/dist/isolated.d.ts +7 -1
  84. package/dist/isolated.js +53 -5
  85. package/dist/isolated.js.map +1 -1
  86. package/dist/kinds/decimal.d.ts +1 -0
  87. package/dist/kinds/decimal.js +16 -0
  88. package/dist/kinds/decimal.js.map +1 -0
  89. package/dist/kinds/rational.d.ts +1 -0
  90. package/dist/kinds/rational.js +13 -0
  91. package/dist/kinds/rational.js.map +1 -0
  92. package/dist/kinds/temporal.d.ts +1 -0
  93. package/dist/kinds/temporal.js +15 -0
  94. package/dist/kinds/temporal.js.map +1 -0
  95. package/dist/lean/behavior.d.ts +29 -0
  96. package/dist/lean/behavior.js +76 -0
  97. package/dist/lean/behavior.js.map +1 -0
  98. package/dist/lean/given.d.ts +10 -0
  99. package/dist/lean/given.js +15 -0
  100. package/dist/lean/given.js.map +1 -0
  101. package/dist/lean/index.d.ts +11 -0
  102. package/dist/lean/index.js +8 -0
  103. package/dist/lean/index.js.map +1 -0
  104. package/dist/lean/model.d.ts +20 -0
  105. package/dist/lean/model.js +133 -0
  106. package/dist/lean/model.js.map +1 -0
  107. package/dist/lean/protocol.d.ts +14 -0
  108. package/dist/lean/protocol.js +34 -0
  109. package/dist/lean/protocol.js.map +1 -0
  110. package/dist/lean/rule.d.ts +54 -0
  111. package/dist/lean/rule.js +149 -0
  112. package/dist/lean/rule.js.map +1 -0
  113. package/dist/lean/schema.d.ts +46 -0
  114. package/dist/lean/schema.js +155 -0
  115. package/dist/lean/schema.js.map +1 -0
  116. package/dist/machine-check.d.ts +73 -0
  117. package/dist/machine-check.js +215 -0
  118. package/dist/machine-check.js.map +1 -0
  119. package/dist/machine.d.ts +122 -0
  120. package/dist/machine.js +271 -0
  121. package/dist/machine.js.map +1 -0
  122. package/dist/model.d.ts +110 -11
  123. package/dist/model.js +724 -80
  124. package/dist/model.js.map +1 -1
  125. package/dist/off-grid.d.ts +4 -0
  126. package/dist/off-grid.js +92 -0
  127. package/dist/off-grid.js.map +1 -0
  128. package/dist/outcomes.d.ts +15 -0
  129. package/dist/outcomes.js +120 -0
  130. package/dist/outcomes.js.map +1 -0
  131. package/dist/pairs.js +14 -5
  132. package/dist/pairs.js.map +1 -1
  133. package/dist/partition.d.ts +1 -0
  134. package/dist/partition.js +101 -19
  135. package/dist/partition.js.map +1 -1
  136. package/dist/placeholders.d.ts +3 -0
  137. package/dist/placeholders.js +44 -0
  138. package/dist/placeholders.js.map +1 -0
  139. package/dist/proof.d.ts +6 -0
  140. package/dist/proof.js +282 -56
  141. package/dist/proof.js.map +1 -1
  142. package/dist/protocol.d.ts +22 -0
  143. package/dist/protocol.js +12 -0
  144. package/dist/protocol.js.map +1 -0
  145. package/dist/relations.d.ts +30 -0
  146. package/dist/relations.js +235 -0
  147. package/dist/relations.js.map +1 -0
  148. package/dist/replay.d.ts +45 -0
  149. package/dist/replay.js +157 -0
  150. package/dist/replay.js.map +1 -0
  151. package/dist/rewrites.d.ts +41 -0
  152. package/dist/rewrites.js +180 -0
  153. package/dist/rewrites.js.map +1 -0
  154. package/dist/rule.d.ts +74 -11
  155. package/dist/rule.js +429 -22
  156. package/dist/rule.js.map +1 -1
  157. package/dist/runtime.d.ts +12 -0
  158. package/dist/runtime.js +8 -0
  159. package/dist/runtime.js.map +1 -0
  160. package/dist/schema.d.ts +44 -28
  161. package/dist/schema.js +50 -113
  162. package/dist/schema.js.map +1 -1
  163. package/dist/specification.d.ts +23 -3
  164. package/dist/specification.js +1001 -96
  165. package/dist/specification.js.map +1 -1
  166. package/dist/stops.d.ts +20 -0
  167. package/dist/stops.js +221 -0
  168. package/dist/stops.js.map +1 -0
  169. package/dist/temporal-global.d.ts +4 -0
  170. package/dist/temporal-global.js +11 -0
  171. package/dist/temporal-global.js.map +1 -0
  172. package/dist/temporal.d.ts +22 -0
  173. package/dist/temporal.js +113 -0
  174. package/dist/temporal.js.map +1 -0
  175. package/dist/tla-validate.d.ts +31 -0
  176. package/dist/tla-validate.js +151 -0
  177. package/dist/tla-validate.js.map +1 -0
  178. package/dist/tla.d.ts +61 -0
  179. package/dist/tla.js +722 -0
  180. package/dist/tla.js.map +1 -0
  181. package/dist/verification.d.ts +9 -0
  182. package/dist/verification.js +7 -0
  183. package/dist/verification.js.map +1 -0
  184. package/dist/ways.d.ts +11 -5
  185. package/dist/ways.js +51 -45
  186. package/dist/ways.js.map +1 -1
  187. package/dist/world.d.ts +98 -0
  188. package/dist/world.js +463 -0
  189. package/dist/world.js.map +1 -0
  190. package/package.json +49 -10
  191. package/schema/report.schema.json +169 -1
@@ -1,19 +1,29 @@
1
- import { hasScopedChoices } from "./model.js";
2
- import { verify } from "./proof.js";
1
+ import { placeholderForOf, placeholderOf } from "./placeholders.js";
2
+ import { answersOf, callsIn, childrenOf, fieldsTurnedOn, isIteration, iterationsOf, nodeOf, localRoots, localsOf, writtenArgument } from "./model.js";
3
+ import { rangeOf } from "./interval.js";
4
+ import { fractionOf } from "./exact.js";
5
+ import { selectedTag, taggedCase, verify } from "./proof.js";
3
6
  import { constantsOf, domainOf } from "./domain.js";
4
7
  import { pairCoverage, PAIR_LIMIT } from "./pairs.js";
5
- import { isDeepStrictEqual } from "node:util";
8
+ import { deepEqual } from "./equal.js";
6
9
  import { WAY_LIMIT, describeWay, eachWayOf, sameSteps } from "./ways.js";
10
+ import { changeOf } from "./changes.js";
11
+ import { isOutOfRoom } from "./exact.js";
12
+ import { foldsOf, runWalk, tells, tookSecond, walks as walkRewrites, walksOf } from "./rewrites.js";
13
+ import { stopsOf } from "./stops.js";
7
14
  import { answerFrom, fakeIssuesOf, fakeWarningsOf } from "./dependency.js";
15
+ import { answerSchema } from "./guard-scope.js";
8
16
  import { comparisonsNotReadOf, ensuresBordersOf, invariantContradictionsOf, mayBeLeftOut, invariantPairBordersOf, guardBordersOf, guardPartitionsOf, feasibilityScope, } from "./guard-borders.js";
17
+ import { brokenProtocol } from "./protocol.js";
9
18
  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";
19
+ import { isDecimal } from "./rule.js";
20
+ import { DEPS, localLabel, describeRule, describeTerm, differenceOf, holds, withDeps, isTerm, positionData, positionOf, positionTerm, termData, termPaths, pathsRead } from "./rule.js";
11
21
  import { emptiedBy, normalize } from "./border.js";
12
22
  import { FEASIBILITY_COMBINATION_LIMIT, feasibilityOf, finiteReach, keepingInvariants, keepingOrderings, refusedJointly, tooManyWays, unreached, witnessesOf } from "./feasibility.js";
13
23
  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";
24
+ import { allOnOneSide, computationOf, lineTheRowsAllow, partingsOf, spelled } from "./beside.js";
25
+ import { coordinatesIn, excludedCases, positionsOf, writeExactly } from "./partition.js";
26
+ import { isVariantsSchema, object, schemaAtPath, tagOf } from "./schema.js";
17
27
  async function runAndCompare(definition, name, given, expected, subject) {
18
28
  try {
19
29
  const actual = await subject(given);
@@ -43,12 +53,12 @@ function answers(definition, expected, actual) {
43
53
  const received = actual;
44
54
  if (isCaseOnly(expected.result)) {
45
55
  return isVariantsSchema(definition.result) && tagOf(definition.result, received.result) === expected.result.case &&
46
- isDeepStrictEqual(canonicalEffects(received.effects), canonicalEffects(expected.effects));
56
+ deepEqual(canonicalEffects(received.effects), canonicalEffects(expected.effects));
47
57
  }
48
58
  const result = definition.result.parse(received.result);
49
59
  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));
60
+ return result.success && answer.success && deepEqual(result.value, answer.value) &&
61
+ deepEqual(canonicalEffects(received.effects), canonicalEffects(expected.effects));
52
62
  }
53
63
  export function example(_definition, row) {
54
64
  return row;
@@ -82,6 +92,10 @@ export async function check(specification, options = {}) {
82
92
  const combinations = positiveLimit("feasibility.combinations", options.feasibility?.combinations, FEASIBILITY_COMBINATION_LIMIT);
83
93
  const definition = specification.examples.behavior;
84
94
  const wayLimit = positiveLimit("feasibility.ways", options.feasibility?.ways, WAY_LIMIT);
95
+ const progress = (phase) => options.progress?.(`${definition.name}: ${phase}`);
96
+ progress("例の行を実行中");
97
+ const walkRows = [];
98
+ const stopRows = [];
85
99
  const coveredInputs = new Set();
86
100
  const coveredResults = new Set();
87
101
  const coveredEffects = new Set();
@@ -104,10 +118,11 @@ export async function check(specification, options = {}) {
104
118
  const reached = [];
105
119
  const waysMet = [];
106
120
  const waysOwed = [];
107
- const fakeIssues = fakeIssuesOf(definition.requires, definition.name, specification.fakes);
121
+ const fakeIssues = fakeIssuesOf(definition.dependencies, definition.name, specification.fakes);
108
122
  const tables = new Map(specification.fakes
109
123
  .filter(table => !fakeIssues.some(item => item.table.dependency === table.dependency))
110
124
  .map(table => [table.dependency, answerFrom(table)]));
125
+ const usableFakes = specification.fakes.filter(table => tables.has(table.dependency));
111
126
  const standIns = (row) => ({
112
127
  ...Object.fromEntries(tables),
113
128
  ...(row.with ?? {}),
@@ -128,7 +143,7 @@ export async function check(specification, options = {}) {
128
143
  const unstoodFor = (row) => {
129
144
  const written = (row.with ?? {});
130
145
  for (const [name, value] of Object.entries(written)) {
131
- const declared = definition.requires[name];
146
+ const declared = definition.dependencies[name];
132
147
  if (declared === undefined) {
133
148
  return `with ${name} names no dependency of ${definition.name}`;
134
149
  }
@@ -137,7 +152,7 @@ export async function check(specification, options = {}) {
137
152
  return `with ${name} is not a value the dependency answers: ${parsed.issues[0].message}`;
138
153
  }
139
154
  }
140
- const missing = Object.keys(definition.requires).find(name => !(name in written) && !tables.has(name));
155
+ const missing = Object.keys(definition.dependencies).find(name => !(name in written) && !tables.has(name));
141
156
  return missing === undefined ? undefined : `No stand-in for dependency ${missing}`;
142
157
  };
143
158
  const observe = (inputTag, actual) => {
@@ -192,12 +207,16 @@ export async function check(specification, options = {}) {
192
207
  if (traced.way !== undefined) {
193
208
  waysOwed.push(traced.way);
194
209
  }
210
+ waysOwed.push(...traced.iterations);
195
211
  }
196
212
  catch (error) {
197
213
  const open = openDecisionIn(implementation, error);
198
214
  if (open !== undefined) {
199
215
  incompleteness.push({ kind: "row not run", subject: row.name, reason: `判断が未定(${open})` });
200
216
  }
217
+ else if (isOutOfRoom(error)) {
218
+ incompleteness.push({ kind: "out of room", subject: row.name, reason: error.message });
219
+ }
201
220
  else {
202
221
  const message = error instanceof Error ? error.message : String(error);
203
222
  failures.push({ name: row.name, message });
@@ -235,6 +254,10 @@ export async function check(specification, options = {}) {
235
254
  message: `Example breaks ensures ${broken.name}: ${describeRule(broken.rule, "")}`,
236
255
  });
237
256
  }
257
+ const expected = row.expect;
258
+ const unkept = brokenProtocol(definition.protocol, expected.effects.map(effect => (isVariantsSchema(definition.effects) ? tagOf(definition.effects, effect) : undefined) ?? ""), rule => holds(rule, { input: row.given, value: expected.result }));
259
+ if (unkept !== undefined)
260
+ failures.push({ name: row.name, message: `Example breaks protocol ${unkept.name}` });
238
261
  const resultTag = caseOnly ?? (isVariantsSchema(definition.result) ? tagOf(definition.result, row.expect.result) : undefined);
239
262
  if (resultTag !== undefined) {
240
263
  coveredResults.add(resultTag);
@@ -255,6 +278,7 @@ export async function check(specification, options = {}) {
255
278
  incompleteness.push({ kind: "row not run", subject: row.name, reason: unstood });
256
279
  }
257
280
  else if (implementation !== undefined) {
281
+ stopRows.push({ given: row.given, deps: standIns(row) });
258
282
  const { actual, failure, error } = await runAndCompare(definition, row.name, row.given, row.expect, async (input) => {
259
283
  const traced = await runTraced(implementation, input, standIns(row));
260
284
  armsMet.push(...traced.arms);
@@ -267,6 +291,7 @@ export async function check(specification, options = {}) {
267
291
  if (traced.way !== undefined) {
268
292
  waysMet.push(traced.way);
269
293
  }
294
+ waysMet.push(...traced.iterations);
270
295
  return traced.execution;
271
296
  });
272
297
  if (actual !== undefined && inputTag !== undefined) {
@@ -282,6 +307,7 @@ export async function check(specification, options = {}) {
282
307
  }
283
308
  if (failure === undefined) {
284
309
  verifiedInputs.add(inputTag);
310
+ walkRows.push({ name: row.name, given: row.given, deps: standIns(row), expected: row.expect });
285
311
  const disregard = await disregardBroken(implementation, row, actual, standIns(row), limits);
286
312
  if (disregard.kind === "broken") {
287
313
  failures.push(disregard.failure);
@@ -295,6 +321,9 @@ export async function check(specification, options = {}) {
295
321
  if (open !== undefined) {
296
322
  incompleteness.push({ kind: "row not run", subject: row.name, reason: `判断が未定(${open})` });
297
323
  }
324
+ else if (isOutOfRoom(error)) {
325
+ incompleteness.push({ kind: "out of room", subject: row.name, reason: error.message });
326
+ }
298
327
  else if (failure !== undefined) {
299
328
  failures.push(failure);
300
329
  if (actual === undefined) {
@@ -352,7 +381,7 @@ export async function check(specification, options = {}) {
352
381
  : [`${path}: 不変条件を満たす値がありません (${emptied.map(border => border.rule).join(", ")})`];
353
382
  }).concat(invariantContradictionsOf(definition));
354
383
  const partitions = positions.map((position, index) => {
355
- const drawn = guardPartitions.find(partition => isDeepStrictEqual(partition.segments, position.segments));
384
+ const drawn = guardPartitions.find(partition => deepEqual(partition.segments, position.segments));
356
385
  if (drawn !== undefined && position.kind !== "divided") {
357
386
  const values = answeredGivens.flatMap(given => position.valuesIn(given));
358
387
  const names = drawn.classes.map(item => item.name);
@@ -396,7 +425,8 @@ export async function check(specification, options = {}) {
396
425
  })),
397
426
  };
398
427
  }));
399
- const guardBorders = (specification.implementation === undefined ? [] : guardBordersOf(specification.implementation)).map((drawn) => {
428
+ const guardDrawn = specification.implementation === undefined ? [] : guardBordersOf(specification.implementation);
429
+ const guardBorders = guardDrawn.map((drawn) => {
400
430
  const reachedIt = reached.filter(item => item.comparison.rule === drawn.comparison && item.tag === drawn.origin?.tag);
401
431
  const coordinates = reachedIt.map(item => drawn.coordinateOf(item.comparison));
402
432
  const points = drawn.border.points.map(point => {
@@ -407,7 +437,7 @@ export async function check(specification, options = {}) {
407
437
  if (coordinates.some(value => point.contains(value))) {
408
438
  return { ...base, status: "met" };
409
439
  }
410
- return { ...base, ...unmetStatus(reachOf(drawn, point, combinations, wayLimit)) };
440
+ return { ...base, ...unmetStatus(pointFeasibility(drawn, point, specification.implementation, combinations, wayLimit, usableFakes)) };
411
441
  });
412
442
  const owed = drawn.border.points.flatMap((point, index) => (point.status === "owed" ? [points[index]] : []));
413
443
  const due = drawn.form !== undefined &&
@@ -421,7 +451,7 @@ export async function check(specification, options = {}) {
421
451
  ...(beside === undefined ? {} : { beside }),
422
452
  };
423
453
  });
424
- borders.push(...guardBorders);
454
+ borders.push(...toldOnce(guardBorders, guardDrawn));
425
455
  // Not met by reaching a comparison, as a guard border is: what an ensures
426
456
  // clause or an input invariant states holds of every input of the case.
427
457
  const writtenCoverage = (drawn) => {
@@ -464,9 +494,13 @@ export async function check(specification, options = {}) {
464
494
  partitions.every(partition => partition.kind !== "divided" || partition.missing.length === 0) &&
465
495
  borders.every(border => border.points.every(point => point.status !== "gap")) &&
466
496
  borders.every(border => border.beside?.status !== "not told");
497
+ progress("分岐と道筋を計測中");
467
498
  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);
499
+ const toBeChangedFirst = changesFrom(specification.implementation, plans, wayLimit);
500
+ progress("foldの書き換えを確かめ中");
501
+ const walks = walksOf(specification.implementation, walkRows, (expected, actual) => answers(definition, expected, actual), given => tagOf(definition.input, given));
502
+ const arms = measureArms(specification.implementation, armsMet, armsOwed, combinations, plans, usableFakes);
503
+ const rulesMeasure = measureRules(specification.implementation, waysMet, waysOwed, combinations, plans, usableFakes);
470
504
  const lines = [
471
505
  ...(arms.status === "unavailable" ? [] : arms.arms),
472
506
  ...(rulesMeasure.status === "unavailable" ? [] : rulesMeasure.rules),
@@ -480,14 +514,19 @@ export async function check(specification, options = {}) {
480
514
  const comparisons = unreadComparisons.length === 0
481
515
  ? { status: "complete" }
482
516
  : { status: "partial", notRead: unreadComparisons };
517
+ progress("構築を証明中");
483
518
  const constructions = specification.implementation === undefined ? { status: "undetermined", decisions: [] } : verify(specification.implementation, { candidates: combinations, ways: wayLimit });
484
- const verdict = !adequate || armGap || constructions.status === "refuted"
519
+ progress("停止を調べ中");
520
+ const stops = stopsOf(specification.implementation, stopRows, { candidates: combinations, proof: constructions });
521
+ const verdict = !adequate || armGap || constructions.status === "refuted" || walks.some(walk => walk.status === "not told") || stops.some(stop => stop.status === "may stop")
485
522
  ? "not_satisfied"
486
523
  : constructions.status !== "verified" || comparisons.status === "partial" ||
487
524
  pairAnalysis.measure.status === "partial" ||
488
525
  armUndecided ||
526
+ walks.some(walk => walk.status === "undecided") ||
527
+ stops.some(stop => stop.status === "not resolved") ||
489
528
  externals.length > 0 ||
490
- incompleteness.some(item => item.kind === "disregards not checked")
529
+ incompleteness.some(item => item.kind === "disregards not checked" || item.kind === "out of room")
491
530
  ? "undetermined"
492
531
  : arms.status === "complete" ||
493
532
  (arms.status === "unavailable" && arms.reason === "not applicable")
@@ -511,7 +550,10 @@ export async function check(specification, options = {}) {
511
550
  borders,
512
551
  pairs: countPairs(pairablesOf(positions, guardPartitions), answeredGivens),
513
552
  fakeIssues: fakeIssues.map(item => item.issue),
514
- fakeWarnings: fakeWarningsOf(definition.requires, specification.fakes),
553
+ fakeWarnings: fakeWarningsOf(definition.dependencies, specification.fakes),
554
+ toBeChangedFirst,
555
+ walks,
556
+ stops,
515
557
  evidence: {
516
558
  input: definition.input.variantTags.filter(tag => !refusedInputs.includes(tag)).map(tag => ({
517
559
  case: tag,
@@ -539,26 +581,91 @@ export async function check(specification, options = {}) {
539
581
  verdict,
540
582
  };
541
583
  }
584
+ // What to change in the model before measuring it: the decisions `check`
585
+ // would leave unmeasured for having more ways than the limit, each with where
586
+ // its ways multiply and which part, declared as a behavior of its own, leaves
587
+ // the rest within the limit. Read off the shape of the model, without running
588
+ // a row, so it can be said before the measurement and is not changed by it.
589
+ export function modelChanges(specification, options = {}) {
590
+ const combinations = positiveLimit("feasibility.combinations", options.feasibility?.combinations, FEASIBILITY_COMBINATION_LIMIT);
591
+ const wayLimit = positiveLimit("feasibility.ways", options.feasibility?.ways, WAY_LIMIT);
592
+ return changesFrom(specification.implementation, plansOf(specification.implementation, combinations, wayLimit), wayLimit);
593
+ }
594
+ function changesFrom(implementation, plans, wayLimit) {
595
+ if (implementation === undefined || implementation.pipeline !== undefined || implementation.external !== undefined)
596
+ return [];
597
+ return decisionsWithCases(implementation).flatMap(([decision]) => {
598
+ if (decision.kind !== "rules" || plans.get(decision)?.kind !== "too many")
599
+ return [];
600
+ const change = changeOf(decision, wayLimit);
601
+ return change === undefined ? [] : [change];
602
+ });
603
+ }
542
604
  export function generate(target, implementation, options = {}) {
543
605
  const combinations = positiveLimit("feasibility.combinations", options.feasibility?.combinations, FEASIBILITY_COMBINATION_LIMIT);
544
606
  const definition = target.kind === "behavior" ? target : target.behavior;
545
607
  const wayLimit = positiveLimit("feasibility.ways", options.feasibility?.ways, WAY_LIMIT);
608
+ options.progress?.(`${definition.name}: 行を組み立て中`);
546
609
  const rows = target.kind === "behavior" ? [] : target.rows.filter(row => definition.input.parse(row.given).success);
547
610
  const existing = new Set(rows
548
611
  .map(row => tagOf(definition.input, row.given))
549
612
  .filter((tag) => tag !== undefined));
550
613
  const answeredRows = rows.filter(row => !isTodo(row.expect));
551
614
  const origins = answeredRows.map(row => row.given);
552
- const standIns = Object.fromEntries(Object.entries(definition.requires)
615
+ const standIns = Object.fromEntries(Object.entries(definition.dependencies)
553
616
  .filter(([, declared]) => declared.takes === "nothing")
554
- .map(([name, declared]) => [name, declared.output.placeholder(name)]));
617
+ .map(([name, declared]) => [name, placeholderOf(declared.output, name)]));
618
+ // Stand-ins a search ran a row it found with, which the row is offered with.
619
+ const searchedStandIns = new Map();
555
620
  const withFrom = (origin) => {
621
+ const searchedWith = searchedStandIns.get(origin);
622
+ if (searchedWith !== undefined)
623
+ return { with: searchedWith };
556
624
  const written = answeredRows.find(row => row.given === origin)?.with;
557
625
  const standing = { ...standIns, ...written };
558
626
  return Object.keys(standing).length === 0 && written === undefined ? {} : { with: standing };
559
627
  };
560
628
  const originFor = (position) => origins.find(given => position.valuesIn(given).length > 0) ??
561
- definition.input.placeholder();
629
+ placeholderOf(definition.input);
630
+ const fakeTables = new Map((options.fakes ?? [])
631
+ .filter(table => table.behavior === definition.name)
632
+ .filter(table => !fakeIssuesOf(definition.dependencies, definition.name, options.fakes ?? []).some(item => item.table.dependency === table.dependency))
633
+ .map(table => [table.dependency, table]));
634
+ const usableFakes = [...fakeTables.values()];
635
+ const answering = Object.fromEntries([...fakeTables].map(([name, table]) => [name, answerFrom(table)]));
636
+ const tracedWith = (stand) => ({ ...answering, ...stand });
637
+ // A row asking each dependency what one of its fake rows asks: the call's
638
+ // argument written into the input where the argument reads the input.
639
+ const askingFakes = (tag, decision, origins, reaches) => {
640
+ const expression = decision.expression;
641
+ if (expression === undefined)
642
+ return undefined;
643
+ for (const call of callsIn(expression)) {
644
+ const table = fakeTables.get(call.dependency);
645
+ for (const [asked] of table?.rows ?? []) {
646
+ for (const origin of origins) {
647
+ const given = writtenArgument(origin, call.input, asked);
648
+ if (given !== undefined && tagOf(definition.input, given) === tag && definition.input.parse(given).success && reaches(given)) {
649
+ return given;
650
+ }
651
+ }
652
+ }
653
+ }
654
+ const calls = callsIn(expression);
655
+ for (const origin of origins) {
656
+ for (const given of askingTogether(origin, calls, dependency => (fakeTables.get(dependency)?.rows ?? []).map(([asked]) => asked))) {
657
+ if (tagOf(definition.input, given) === tag && definition.input.parse(given).success && reaches(given))
658
+ return given;
659
+ }
660
+ }
661
+ return undefined;
662
+ };
663
+ // What a point or a way that turns on a dependency's answer still needs: a
664
+ // fake row answering there, asked by an input the row can write.
665
+ const askedOf = (locals) => {
666
+ const called = [...new Set(locals.map(localLabel).filter(label => label.endsWith("()")))];
667
+ return called.length === 0 ? "" : ` — ${called.join("・")}がそう答えるfakeの行がない`;
668
+ };
562
669
  const generated = [];
563
670
  const notComposed = [];
564
671
  // A row moved from `from` that breaks an invariant relating finite positions
@@ -586,7 +693,7 @@ export function generate(target, implementation, options = {}) {
586
693
  const guardRead = guardReadSegmentsOf(implementation);
587
694
  const refused = excludedCases(definition.input);
588
695
  for (const tag of definition.input.variantTags.filter(tag => !existing.has(tag) && !refused.includes(tag))) {
589
- const given = definition.input.placeholderFor(tag);
696
+ const given = placeholderForOf(definition.input, tag);
590
697
  offer({ name: `${definition.name}: ${tag}`, given, reason: `${tag}の期待結果を人間が決める必要があります`, ...withFrom(given) }, given);
591
698
  }
592
699
  for (const position of measuredPositionsOf(definition, guardDivided, guardRead, combinations)) {
@@ -618,9 +725,14 @@ export function generate(target, implementation, options = {}) {
618
725
  const standsAt = [...rows, ...generated].some(row => coordinatesIn(position, border.measure, row.given).some(value => point.contains(value)));
619
726
  if (!standsAt) {
620
727
  const origin = originFor(position);
728
+ const given = writeExactly(position, origin, border.measure, point.witness);
729
+ if (given === undefined) {
730
+ notComposed.push(`${position.path} ${point.role} (${point.relation})`);
731
+ continue;
732
+ }
621
733
  offer({
622
734
  name: `${definition.name}: ${position.path} ${point.role} (${point.relation})`,
623
- given: position.write(origin, border.measure, point.witness),
735
+ given,
624
736
  reason: `${position.path}の${point.role}点(${point.relation})の期待結果を人間が決める必要があります`,
625
737
  ...withFrom(origin),
626
738
  }, origin);
@@ -628,7 +740,7 @@ export function generate(target, implementation, options = {}) {
628
740
  }
629
741
  }
630
742
  }
631
- const positionsByPath = new Map(positionsOf(definition.input).map(position => [trailKey(position.segments), position]));
743
+ const positionsByPath = new Map(positionsOf(definition.input, { containers: true }).map(position => [trailKey(position.segments), position]));
632
744
  for (const drawn of implementation === undefined ? [] : guardPartitionsOf(implementation)) {
633
745
  const position = positionsByPath.get(trailKey(drawn.segments));
634
746
  if (position === undefined) {
@@ -636,7 +748,11 @@ export function generate(target, implementation, options = {}) {
636
748
  }
637
749
  for (const item of drawn.classes) {
638
750
  const standsIn = [...rows, ...generated].some(row => position.valuesIn(row.given).some(value => value !== undefined && item.contains(value)));
639
- if (!standsIn) {
751
+ if (!standsIn && item.witness === undefined) {
752
+ // Owed all the same: no law refutes it, though no value was found (ADR-0130).
753
+ notComposed.push(`${drawn.path} = ${item.name}: スキーマが受け付ける値が見つからない`);
754
+ }
755
+ else if (!standsIn) {
640
756
  const origin = originFor(position);
641
757
  offer({
642
758
  name: `${definition.name}: ${drawn.path} = ${item.name}`,
@@ -647,38 +763,72 @@ export function generate(target, implementation, options = {}) {
647
763
  }
648
764
  }
649
765
  }
766
+ const toldComputations = new Set();
767
+ const untold = [];
650
768
  for (const drawn of implementation === undefined ? [] : guardBordersOf(implementation)) {
651
769
  const reachedBy = (given, deps) => tagOf(definition.input, given) === drawn.origin?.tag
652
- ? comparisonsReached(implementation, given, deps).filter(item => item.rule === drawn.comparison)
770
+ ? comparisonsReached(implementation, given, tracedWith(deps)).filter(item => item.rule === drawn.comparison)
653
771
  : [];
772
+ const searchNotes = new Map();
654
773
  for (const point of drawn.border.points) {
655
774
  if (point.status !== "owed" || point.witness === undefined) {
656
775
  continue;
657
776
  }
658
777
  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") {
778
+ if (standsAt || unmetStatus(pointFeasibility(drawn, point, implementation, combinations, wayLimit, usableFakes)).status === "no row owed") {
660
779
  continue;
661
780
  }
662
781
  const origin = origins.find(given => reachedBy(given, withFrom(given).with).length > 0) ??
663
- definition.input.placeholder();
782
+ placeholderOf(definition.input);
664
783
  const candidates = sidesOf(drawn)
665
784
  .map(side => drawn.compose(origin, point.witness, withFrom(origin).with, side))
666
785
  .filter(candidate => candidate !== undefined);
667
786
  // A row the input takes stands at the point only once the guards before
668
787
  // the comparison let it through, which moving another part may not.
669
788
  const reaches = (candidate) => reachedBy(candidate, withFrom(origin).with).some(item => point.contains(drawn.coordinateOf(item)));
789
+ // A comparison on a value the model computes cannot be written, but an input the search ran may reach it at the point.
790
+ const searchedPoint = () => {
791
+ if (drawn.origin === undefined || drawn.origin.decision.expression === undefined)
792
+ return undefined;
793
+ const hit = searchedWays(implementation, drawn.origin.tag, drawn.origin.decision, combinations, usableFakes).witnessed
794
+ .find(item => item.comparison.rule === drawn.comparison && point.contains(drawn.coordinateOf(item.comparison)) && definition.input.parse(item.given).success);
795
+ if (hit !== undefined) {
796
+ if (hit.with !== undefined)
797
+ searchedStandIns.set(hit.given, hit.with);
798
+ return hit.given;
799
+ }
800
+ // None reached the point: step from the runs nearest to it, one
801
+ // numeric field at a time, toward it (Souther 0.5.0's rows beside the
802
+ // nearest ones), and say what was tried where that reaches it neither.
803
+ const tried = searchedWays(implementation, drawn.origin.tag, drawn.origin.decision, combinations, usableFakes).witnessed
804
+ .filter(item => item.comparison.rule === drawn.comparison && definition.input.parse(item.given).success);
805
+ const stepped = besideTheNearest(definition, drawn, point, tried, (given, deps) => reachedBy(given, deps).map(item => drawn.coordinateOf(item)));
806
+ if (stepped.given !== undefined) {
807
+ if (stepped.with !== undefined)
808
+ searchedStandIns.set(stepped.given, stepped.with);
809
+ return stepped.given;
810
+ }
811
+ searchNotes.set(point, stepped.tried);
812
+ return undefined;
813
+ };
670
814
  const given = candidates.find(candidate => definition.input.parse(candidate).success && reaches(candidate)) ??
815
+ askingFakes(drawn.origin?.tag ?? "", drawn.origin?.decision, [
816
+ ...origins.filter(candidate => tagOf(definition.input, candidate) === drawn.origin?.tag),
817
+ ...(drawn.origin === undefined ? [] : [placeholderForOf(definition.input, drawn.origin.tag)]),
818
+ ], reaches) ??
819
+ searchedPoint() ??
671
820
  candidates.find(candidate => !definition.input.parse(candidate).success) ??
672
821
  candidates.find(candidate => definition.input.parse(candidate).success);
673
822
  if (given === undefined) {
674
- notComposed.push(`${drawn.path} ${point.role} (${point.relation})`);
823
+ const note = searchNotes.get(point);
824
+ notComposed.push(`${drawn.path} ${point.role} (${point.relation})${askedOf(drawn.segments.flatMap(segment => segment.startsWith(".#local:") ? [segment.slice(1)] : []))}${note === undefined ? "" : ` — ${note}`}`);
675
825
  }
676
826
  else {
677
827
  offer({
678
828
  name: `${definition.name}: ${drawn.path} ${point.role} (${point.relation})`,
679
829
  given,
680
830
  reason: `${drawn.path}の${point.role}点(${point.relation})の期待結果を人間が決める必要があります`,
681
- ...withFrom(origin),
831
+ ...withFrom(searchedStandIns.has(given) ? given : origin),
682
832
  }, origin);
683
833
  }
684
834
  }
@@ -689,11 +839,21 @@ export function generate(target, implementation, options = {}) {
689
839
  const owed = drawn.border.points.filter(point => point.status === "owed");
690
840
  const standsAt = (point) => items.some(item => point.contains(drawn.coordinateOf(item.comparison)));
691
841
  const due = owed.some(standsAt) &&
692
- owed.every(point => standsAt(point) || unmetStatus(reachOf(drawn, point, combinations, wayLimit)).status === "no row owed");
842
+ owed.every(point => standsAt(point) || unmetStatus(pointFeasibility(drawn, point, implementation, combinations, wayLimit, usableFakes)).status === "no row owed");
693
843
  const found = due ? besideOf(definition, implementation, drawn, items) : undefined;
844
+ const computation = computationOf(drawn.origin?.tag, drawn.form.parts);
845
+ if (found?.beside.status === "told")
846
+ toldComputations.add(computation);
694
847
  if (found?.beside.status !== "not told") {
695
848
  continue;
696
849
  }
850
+ untold.push({ computation, drawn, found: found });
851
+ }
852
+ // A computation cut at several places owes its weights once (ADR-0124): no
853
+ // row is offered beside a border whose computation another border tells.
854
+ for (const { computation, drawn, found } of untold) {
855
+ if (toldComputations.has(computation))
856
+ continue;
697
857
  const label = `${drawn.path} 隣の線 (${found.beside.another})`;
698
858
  if (found.given === undefined) {
699
859
  notComposed.push(label);
@@ -717,7 +877,7 @@ export function generate(target, implementation, options = {}) {
717
877
  if (standsAt) {
718
878
  continue;
719
879
  }
720
- const origin = origins.find(under) ?? definition.input.placeholderFor(drawn.segments[0].slice(1));
880
+ const origin = origins.find(under) ?? placeholderForOf(definition.input, drawn.segments[0].slice(1));
721
881
  const candidates = sidesOf(drawn)
722
882
  .map(side => drawn.compose(origin, point.witness, withFrom(origin).with, side))
723
883
  .filter(candidate => candidate !== undefined);
@@ -740,8 +900,11 @@ export function generate(target, implementation, options = {}) {
740
900
  if (decision.kind !== "rules") {
741
901
  continue;
742
902
  }
743
- const wayOf = (given, deps) => traceSync(implementation, given, deps).way;
903
+ const wayOf = (given, deps) => traceSync(implementation, given, tracedWith(deps)).way;
744
904
  const takes = (given, deps, way) => {
905
+ if (way.within !== undefined) {
906
+ return traceSync(implementation, given, tracedWith(deps)).iterations.some(taken => taken.within === way.within && sameSteps(taken.steps, way.steps));
907
+ }
745
908
  const taken = wayOf(given, deps);
746
909
  return taken !== undefined && sameSteps(taken.steps, way.steps);
747
910
  };
@@ -771,13 +934,9 @@ export function generate(target, implementation, options = {}) {
771
934
  };
772
935
  const origins_ = [
773
936
  ...origins.filter(given => tagOf(definition.input, given) === tag),
774
- definition.input.placeholderFor(tag),
937
+ placeholderForOf(definition.input, tag),
775
938
  ];
776
939
  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
940
  if (plan?.kind === "too many") {
782
941
  notComposed.push(`${decision.id}: ${tooManyWays(wayLimit)}ため組み立てない`);
783
942
  continue;
@@ -790,13 +949,17 @@ export function generate(target, implementation, options = {}) {
790
949
  continue;
791
950
  }
792
951
  if (witness === undefined &&
793
- feasibilityOf(way, scopeOf(implementation, tag), undefined, combinations).kind === "infeasible") {
952
+ wayFeasibility(way, implementation, tag, decision, combinations, usableFakes).kind === "infeasible") {
794
953
  continue;
795
954
  }
796
955
  const taken = (candidate) => candidate !== undefined && takes(candidate.given, withFrom(candidate.origin).with, way)
797
956
  ? candidate
798
957
  : undefined;
799
- const composed = taken(composeForWay(way, tag)) ??
958
+ const throughFakes = askingFakes(tag, decision, origins_, given => takes(given, withFrom(given).with, way));
959
+ const composed = (throughFakes === undefined ? undefined : { given: throughFakes, origin: throughFakes }) ??
960
+ (way.within === undefined ? undefined : composeElement(way)) ??
961
+ taken(searched(way)) ??
962
+ taken(composeForWay(way, tag)) ??
800
963
  (options.ways !== true
801
964
  ? undefined
802
965
  : witness === undefined
@@ -811,8 +974,49 @@ export function generate(target, implementation, options = {}) {
811
974
  });
812
975
  }
813
976
  else {
814
- notComposed.push(`${decision.id}: ${describeWay(way)}`);
977
+ notComposed.push(`${decision.id}: ${describeWay(way)}${askedOf(way.steps.flatMap(step => localRoots(step.distinction)))}`);
978
+ }
979
+ }
980
+ // A way one element takes through an iteration's body: a row whose array
981
+ // holds that one element, taken from what the rows hold or moved into each
982
+ // class of the element's positions.
983
+ function composeElement(way) {
984
+ const values = isIteration(way.within) ? way.within.values : undefined;
985
+ const position = isTerm(values) ? positionData(values) : undefined;
986
+ if (position === undefined || position.measure !== "value" || position.path.some(key => key.startsWith("#")))
987
+ return undefined;
988
+ const read = (given) => position.path.reduce((at, key) => (at !== null && typeof at === "object" ? at[key] : undefined), given);
989
+ const held = [...rows, ...generated].flatMap(row => {
990
+ const array = read(row.given);
991
+ return Array.isArray(array) ? array : [];
992
+ });
993
+ const trail = [`@${tag}`, ...position.path.map(key => `.${key}`), "[]"];
994
+ const moved = [...positionsByPath.values()].filter(at => at.kind === "divided" && trailKey(at.segments.slice(0, trail.length)) === trailKey(trail));
995
+ for (const origin of origins_) {
996
+ const candidates = [
997
+ ...held.map(element => writtenArgument(origin, values, [element])),
998
+ ...moved.flatMap(at => at.kind === "divided" ? at.classes.map(name => at.place(writtenArgument(origin, values, held.slice(0, 1)) ?? origin, name)) : []),
999
+ ];
1000
+ for (const given of candidates) {
1001
+ if (given !== undefined && definition.input.parse(given).success && takes(given, withFrom(origin).with, way))
1002
+ return { given, origin };
1003
+ }
815
1004
  }
1005
+ return undefined;
1006
+ }
1007
+ // A way through a value the model computes, from an input the search found
1008
+ // taking it.
1009
+ function searched(way) {
1010
+ if (opaqueRead(way, decision).length === 0)
1011
+ return undefined;
1012
+ const factored = factoredWitness(way, implementation, tag, decision, combinations)?.given;
1013
+ const found = searchedWitness(way, implementation, tag, decision, combinations, usableFakes)
1014
+ ?? (factored === undefined ? undefined : { given: factored });
1015
+ if (found === undefined)
1016
+ return undefined;
1017
+ if (found.with !== undefined)
1018
+ searchedStandIns.set(found.given, found.with);
1019
+ return { given: found.given, origin: found.given };
816
1020
  }
817
1021
  function composeFromReach(way, witness) {
818
1022
  const witnessed = [...witness].map(([key, value]) => ({ path: JSON.parse(key), value }));
@@ -826,7 +1030,7 @@ export function generate(target, implementation, options = {}) {
826
1030
  }
827
1031
  function composeFromWitnesses(way) {
828
1032
  for (const origin of origins_) {
829
- const witnesses = witnessesOf(way, scopeOf(implementation, tag), { discriminant, tag }, combinations);
1033
+ const witnesses = witnessesOf(way, scopeOf(implementation, tag, decision), { discriminant, tag }, combinations);
830
1034
  if (witnesses === undefined) {
831
1035
  break;
832
1036
  }
@@ -863,14 +1067,169 @@ export function generate(target, implementation, options = {}) {
863
1067
  }
864
1068
  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
1069
  for (const { obligation, given } of pairs.witnesses) {
866
- if (generated.some(row => isDeepStrictEqual(row.given, given)))
1070
+ if (generated.some(row => deepEqual(row.given, given)))
867
1071
  continue;
868
1072
  offer({ name: `${definition.name}: ${obligation.positions[0]} = ${obligation.classes[0]} × ${obligation.positions[1]} = ${obligation.classes[1]}`, given,
869
1073
  reason: "組み合わせの期待結果を人間が決める必要があります", ...withFrom(given) });
870
1074
  }
871
1075
  notComposed.push(...pairs.measure.notRead, ...pairs.measure.obligations.filter(pair => pair.status === "undecided").map(pair => `${pair.positions.join(" × ")}: ${pair.classes.join(" × ")} (${pair.reason})`));
1076
+ if (implementation !== undefined) {
1077
+ const walked = walkRowsFor(definition, implementation, answeredRows, row => tracedWith(withFrom(row.given).with), rows, generated);
1078
+ for (const { origin, ...row } of walked.rows)
1079
+ offer({ ...row, ...withFrom(origin) });
1080
+ notComposed.push(...walked.notComposed);
1081
+ for (const { origin, ...row } of suggestedRowsFor(definition, implementation, rows, [...rows.map(row => row.given), ...generated.map(row => row.given)])) {
1082
+ generated.push({ ...row, ...withFrom(origin) });
1083
+ }
1084
+ }
872
1085
  return { rows: generated, notComposed };
873
1086
  }
1087
+ // The inputs a called behavior's recorded rows were written with, asked in
1088
+ // its caller: each call of a dependency declared with its examples
1089
+ // (`dependency(checkStockExamples)`) has the argument a recorded row asks
1090
+ // written into a row of the case that makes the call. Such a row owes nothing
1091
+ // and is marked so; it is offered where no row asks it yet.
1092
+ function suggestedRowsFor(definition, implementation, rows, taken) {
1093
+ const suggested = [];
1094
+ const seen = [...taken];
1095
+ for (const [decision, tags] of decisionsWithCases(implementation)) {
1096
+ const expression = decision.kind === "rules" ? decision.expression : undefined;
1097
+ if (expression === undefined)
1098
+ continue;
1099
+ const origins = rows.filter(row => tags.includes(tagOf(definition.input, row.given) ?? ""));
1100
+ for (const call of callsIn(expression)) {
1101
+ const declared = definition.dependencies[call.dependency];
1102
+ for (const recorded of declared?.injected?.rows ?? []) {
1103
+ for (const origin of origins) {
1104
+ const given = writtenArgument(origin.given, call.input, recorded.given);
1105
+ if (given === undefined || !definition.input.parse(given).success || seen.some(other => deepEqual(other, given)))
1106
+ continue;
1107
+ seen.push(given);
1108
+ suggested.push({
1109
+ name: `${definition.name}: ${call.dependency}()の記録行「${recorded.name}」の入力を${describeArgument(call.input)}で尋ねる`,
1110
+ given,
1111
+ reason: "提案する入力(満たしていない義務はない)",
1112
+ suggested: true,
1113
+ origin: origin.given,
1114
+ });
1115
+ break;
1116
+ }
1117
+ }
1118
+ }
1119
+ }
1120
+ return suggested;
1121
+ }
1122
+ // A row of two or more elements for each fold whose rewrites (ADR-0126) no
1123
+ // answered row tells apart: the list a fold walks, where it is an input field,
1124
+ // grown by an element the rows hold, put last and then first, and the row kept
1125
+ // that tells the most rewrites apart from what the model answers on it.
1126
+ function walkRowsFor(definition, implementation, answeredRows, depsOf, rows, generated) {
1127
+ const offered = [];
1128
+ const notComposed = [];
1129
+ const tagOfGiven = (given) => tagOf(definition.input, given);
1130
+ for (const fold of foldsOf(implementation)) {
1131
+ if (fold.single)
1132
+ continue;
1133
+ const ofCase = answeredRows.filter(row => fold.tags.includes(tagOfGiven(row.given) ?? ""));
1134
+ const open = walkRewrites.filter(walk => !ofCase.some(row => {
1135
+ const deps = depsOf(row);
1136
+ const plain = runWalk(implementation, row.given, deps);
1137
+ if (plain.pending || plain.error !== undefined || !answers(definition, row.expect, plain.actual) || !tookSecond(plain, fold.node))
1138
+ return false;
1139
+ return tells(implementation, fold, walk, row.given, deps, actual => answers(definition, row.expect, actual)) === true;
1140
+ }));
1141
+ if (open.length === 0)
1142
+ continue;
1143
+ const label = `${fold.decision.id}: ${fold.label}`;
1144
+ if (fold.over === undefined) {
1145
+ notComposed.push(`${label}: 歩くリストが入力の欄ではないため、二つ以上の要素を歩く行を組み立てない`);
1146
+ continue;
1147
+ }
1148
+ const path = fold.over;
1149
+ const read = (given) => path.reduce((value, key) => (value !== null && typeof value === "object" ? value[key] : undefined), given);
1150
+ const origins = [...ofCase, ...rows.filter(row => isTodo(row.expect) && fold.tags.includes(tagOfGiven(row.given) ?? ""))];
1151
+ const pool = [];
1152
+ for (const row of rows) {
1153
+ const list = read(row.given);
1154
+ if (Array.isArray(list))
1155
+ for (const element of list)
1156
+ if (!pool.some(other => deepEqual(other, element)))
1157
+ pool.push(element);
1158
+ }
1159
+ let best;
1160
+ search: for (const origin of origins) {
1161
+ const held = read(origin.given);
1162
+ if (!Array.isArray(held))
1163
+ continue;
1164
+ const list = held;
1165
+ // Made one at a time, in the order a list of two is reached, and no more
1166
+ // than 64 from each origin: a long list grows into long candidates.
1167
+ function* grown() {
1168
+ if (list.length === 0) {
1169
+ for (const first of pool)
1170
+ for (const second of pool)
1171
+ yield [first, second];
1172
+ return;
1173
+ }
1174
+ for (const element of pool) {
1175
+ yield [...list, element];
1176
+ yield [element, ...list];
1177
+ }
1178
+ }
1179
+ let made = 0;
1180
+ for (const candidate of grown()) {
1181
+ if (++made > 64)
1182
+ break;
1183
+ const given = writtenAt(origin.given, path, candidate);
1184
+ if (!definition.input.parse(given).success)
1185
+ continue;
1186
+ const deps = depsOf(origin);
1187
+ const plain = runWalk(implementation, given, deps);
1188
+ if (plain.pending || plain.error !== undefined || !tookSecond(plain, fold.node))
1189
+ continue;
1190
+ const told = open.filter(walk => tells(implementation, fold, walk, given, deps, actual => answers(definition, plain.actual, actual)) === true).length;
1191
+ if (told > (best?.told ?? 0))
1192
+ best = { given, origin, told };
1193
+ if (told === open.length)
1194
+ break search;
1195
+ }
1196
+ }
1197
+ if (best === undefined) {
1198
+ notComposed.push(`${label}: 書き換え(${open.join("・")})を見分ける二つ以上の要素の行が見つからない`);
1199
+ continue;
1200
+ }
1201
+ if ([...generated, ...offered].some(row => deepEqual(row.given, best.given)))
1202
+ continue;
1203
+ offered.push({
1204
+ name: `${label} を二つ以上の要素で歩く`,
1205
+ given: best.given,
1206
+ reason: "foldの各段階が前の段階の答えを読むことを確かめる行の期待結果を人間が決める必要があります",
1207
+ origin: best.origin.given,
1208
+ });
1209
+ }
1210
+ return { rows: offered, notComposed };
1211
+ }
1212
+ // The input a call's argument reads, as the report writes it, so two calls
1213
+ // of one dependency asking one recorded row are named apart.
1214
+ function describeArgument(argument) {
1215
+ const read = [];
1216
+ const walk = (value) => {
1217
+ if (isTerm(value))
1218
+ read.push(describeTerm(value));
1219
+ else if (value !== null && typeof value === "object")
1220
+ for (const child of Object.values(value))
1221
+ walk(child);
1222
+ };
1223
+ walk(argument);
1224
+ return read.length === 0 ? "定数" : read.join("・");
1225
+ }
1226
+ function writtenAt(given, path, value) {
1227
+ if (path.length === 0)
1228
+ return value;
1229
+ const [key, ...rest] = path;
1230
+ const record = (given ?? {});
1231
+ return { ...record, [key]: writtenAt(record[key], rest, value) };
1232
+ }
874
1233
  export async function evaluate(exampleSet, name, subject) {
875
1234
  const row = exampleSet.rows.find(row => row.name === name);
876
1235
  if (row === undefined) {
@@ -963,7 +1322,7 @@ function pairablesOf(positions, guardPartitions) {
963
1322
  },
964
1323
  ];
965
1324
  }
966
- const drawn = guardPartitions.find(partition => isDeepStrictEqual(partition.segments, position.segments));
1325
+ const drawn = guardPartitions.find(partition => deepEqual(partition.segments, position.segments));
967
1326
  if (drawn === undefined) {
968
1327
  return [];
969
1328
  }
@@ -1010,7 +1369,7 @@ function combine(left, right) {
1010
1369
  const rightNarrowings = narrowings(right);
1011
1370
  return narrowings(left).every(narrowing => rightNarrowings.every(other => other.before !== narrowing.before || other.tag === narrowing.tag));
1012
1371
  }
1013
- function measureRules(implementation, met, owed, combinations, plans) {
1372
+ function measureRules(implementation, met, owed, combinations, plans, fakes) {
1014
1373
  if (implementation === undefined || implementation.pipeline !== undefined) {
1015
1374
  return { status: "unavailable", reason: "not applicable" };
1016
1375
  }
@@ -1018,29 +1377,29 @@ function measureRules(implementation, met, owed, combinations, plans) {
1018
1377
  return { status: "unavailable", reason: "not measured", notRead: [implementation.behavior.name] };
1019
1378
  }
1020
1379
  const decided = decisionsWithCases(implementation);
1021
- const notRead = decided.flatMap(([decision]) => decision.kind === "decision" || (decision.kind === "rules" && ["too many", "scoped"].includes(plans.get(decision)?.kind ?? ""))
1380
+ const notRead = decided.flatMap(([decision]) => decision.kind === "decision" || (decision.kind === "rules" && plans.get(decision)?.kind === "too many")
1022
1381
  ? [decision.id]
1023
1382
  : []);
1024
- const took = (taken, decision, steps) => taken.some(item => item.decision === decision && sameSteps(item.steps, steps));
1383
+ const took = (taken, decision, way) => taken.some(item => item.decision === decision && item.within === way.within && sameSteps(item.steps, way.steps));
1025
1384
  const rules = decided.flatMap(([decision, tags]) => {
1026
1385
  const plan = plans.get(decision);
1027
- if (decision.kind !== "rules" || plan === undefined || (plan.kind === "too many" || plan.kind === "scoped")) {
1386
+ if (decision.kind !== "rules" || plan === undefined || plan.kind === "too many") {
1028
1387
  return [];
1029
1388
  }
1030
1389
  const ways = plan.kind === "finite" ? plan.reached.map(item => item.way) : plan.ways;
1031
1390
  return ways.map((way) => {
1032
1391
  const base = { decision: decision.id, way: describeWay(way) };
1033
- if (took(met, decision.id, way.steps)) {
1392
+ if (took(met, decision.id, way)) {
1034
1393
  return { ...base, status: "met" };
1035
1394
  }
1036
- if (took(owed, decision.id, way.steps)) {
1395
+ if (took(owed, decision.id, way)) {
1037
1396
  return { ...base, status: "answer owed" };
1038
1397
  }
1039
1398
  return plan.kind === "finite"
1040
1399
  ? { ...base, status: "gap" }
1041
1400
  : {
1042
1401
  ...base,
1043
- ...unmetStatus(tags.map(tag => feasibilityOf(way, scopeOf(implementation, tag), undefined, combinations))),
1402
+ ...unmetStatus(tags.map(tag => wayFeasibility(way, implementation, tag, decision, combinations, fakes))),
1044
1403
  };
1045
1404
  });
1046
1405
  });
@@ -1051,7 +1410,7 @@ function measureRules(implementation, met, owed, combinations, plans) {
1051
1410
  ? { status: "unavailable", reason: "not measured", notRead }
1052
1411
  : { status: "partial", rules, notRead };
1053
1412
  }
1054
- function measureArms(implementation, met, owed, combinations, plans) {
1413
+ function measureArms(implementation, met, owed, combinations, plans, fakes) {
1055
1414
  if (implementation === undefined || implementation.pipeline !== undefined) {
1056
1415
  return { status: "unavailable", reason: "not applicable" };
1057
1416
  }
@@ -1059,20 +1418,20 @@ function measureArms(implementation, met, owed, combinations, plans) {
1059
1418
  return { status: "unavailable", reason: "not measured", notRead: [implementation.behavior.name] };
1060
1419
  }
1061
1420
  const decided = decisionsWithCases(implementation);
1062
- const notRead = decided.flatMap(([decision]) => decision.kind === "decision" || (decision.kind === "rules" && ["too many", "scoped"].includes(plans.get(decision)?.kind ?? ""))
1421
+ const notRead = decided.flatMap(([decision]) => decision.kind === "decision" || (decision.kind === "rules" && plans.get(decision)?.kind === "too many")
1063
1422
  ? [decision.id]
1064
1423
  : []);
1065
1424
  const took = (taken, decision, guard, arm) => taken.some(item => item.decision === decision && item.guard === guard && item.arm === arm);
1066
1425
  const arms = decided.flatMap(([decision, tags]) => {
1067
1426
  const plan = plans.get(decision);
1068
- if (decision.kind !== "rules" || plan === undefined || (plan.kind === "too many" || plan.kind === "scoped")) {
1427
+ if (decision.kind !== "rules" || plan === undefined || plan.kind === "too many") {
1069
1428
  return [];
1070
1429
  }
1071
1430
  const ways = plan.kind === "finite"
1072
1431
  ? plan.reached.map(({ way }) => ({ way, feasibility: { kind: "feasible" } }))
1073
1432
  : tags.flatMap(tag => plan.ways.map(way => ({
1074
1433
  way,
1075
- feasibility: feasibilityOf(way, scopeOf(implementation, tag), undefined, combinations),
1434
+ feasibility: wayFeasibility(way, implementation, tag, decision, combinations, fakes),
1076
1435
  })));
1077
1436
  const through = (index, arm) => ways.filter(({ way }) => decision.expression !== undefined
1078
1437
  ? way.choices?.some(choice => choice.condition === decision.guards[index]?.condition && choice.outcome === (arm === "holds"))
@@ -1143,7 +1502,7 @@ function openDecisionIn(implementation, error) {
1143
1502
  ? error.variant
1144
1503
  : `${error.behavior}: ${error.variant}`;
1145
1504
  }
1146
- function externalsIn(implementation) {
1505
+ export function externalsIn(implementation) {
1147
1506
  if (implementation === undefined) {
1148
1507
  return [];
1149
1508
  }
@@ -1154,6 +1513,373 @@ function externalsIn(implementation) {
1154
1513
  ? []
1155
1514
  : implementation.pipeline.flatMap(stage => externalsIn(stage));
1156
1515
  }
1516
+ const searches = new WeakMap();
1517
+ const tableIds = new WeakMap();
1518
+ let tableCount = 0;
1519
+ const IMPOSSIBLE = Symbol("an answer the dependency's contract refuses");
1520
+ function searchedWays(implementation, tag, decision, combinations, fakes = []) {
1521
+ const definition = implementation.behavior;
1522
+ // Keyed by the tables themselves, not the array holding them, which every check builds anew.
1523
+ if (!tableIds.has(definition))
1524
+ tableIds.set(definition, ++tableCount);
1525
+ const key = `${tableIds.get(definition)}\u0000${tag}\u0000${combinations}\u0000${fakes.map(table => {
1526
+ if (!tableIds.has(table))
1527
+ tableIds.set(table, ++tableCount);
1528
+ return tableIds.get(table);
1529
+ }).join(",")}`;
1530
+ const cached = searches.get(decision)?.get(key);
1531
+ if (cached !== undefined)
1532
+ return cached;
1533
+ const answering = Object.fromEntries(fakes.map(table => [table.dependency, answerFrom(table)]));
1534
+ const rules = Object.values(implementation.cases).flatMap(item => item.kind === "rules" ? item.guards.map(guard => guard.condition) : []);
1535
+ const values = Object.entries(definition.dependencies).filter(([, declared]) => declared.takes === "nothing");
1536
+ const expression = decision.expression;
1537
+ // Only the fields the ways turn on are tried, the rest held at a placeholder,
1538
+ // where no invariant of the case relates the two.
1539
+ const variant = definition.input.variants[tag];
1540
+ const turned = expression === undefined ? undefined : fieldsTurnedOn(expression, argumentMatters(definition, variant.shape));
1541
+ const caseRules = [...variant.invariants, ...definition.input.invariants];
1542
+ const projected = turned !== undefined && caseRules.every(rule => pathsRead(rule).every(path => path.length > 0 && turned.has(path[0])))
1543
+ ? object(Object.fromEntries(Object.entries(variant.shape).filter(([key]) => turned.has(key))))
1544
+ : undefined;
1545
+ const placeholder = placeholderForOf(definition.input, tag);
1546
+ const inputSchema = projected ?? definition.input;
1547
+ const schema = values.length === 0
1548
+ ? inputSchema
1549
+ : object({ input: inputSchema, deps: object(Object.fromEntries(values.map(([name, declared]) => [name, declared.output]))) });
1550
+ const raw = domainOf(schema, combinations, constantsOf(rules));
1551
+ const filled = (input) => (projected === undefined ? input : { ...placeholder, ...input, [definition.input.discriminant]: tag });
1552
+ const domain = {
1553
+ exhaustive: raw.exhaustive,
1554
+ values: raw.values.map(value => (values.length === 0 ? filled(value) : { ...value, input: filled(value.input) })),
1555
+ };
1556
+ const calls = expression === undefined ? [] : callsIn(expression);
1557
+ const inputOf = (candidate) => (values.length === 0 ? candidate : candidate.input);
1558
+ const standOf = (candidate) => (values.length === 0 ? undefined : candidate.deps);
1559
+ // Each input also asks every call what a fake row asks, where the argument
1560
+ // reads the input, so an answer a fake gives is reached.
1561
+ const asking = (candidate) => calls.flatMap(call => (fakes.find(table => table.dependency === call.dependency)?.rows ?? []).flatMap(([asked]) => {
1562
+ const written = writtenArgument(inputOf(candidate), call.input, asked);
1563
+ return written === undefined ? [] : [values.length === 0 ? written : { ...candidate, input: written }];
1564
+ }));
1565
+ const askingMore = (candidate) => askingTogether(inputOf(candidate), calls, dependency => (fakes.find(table => table.dependency === dependency)?.rows ?? []).map(([asked]) => asked))
1566
+ .map(written => (values.length === 0 ? written : { ...candidate, input: written }));
1567
+ const candidates = [...domain.values, ...domain.values.flatMap(asking), ...(calls.length < 2 ? [] : domain.values.flatMap(askingMore))].filter(candidate => tagOf(definition.input, inputOf(candidate)) === tag);
1568
+ const taken = [];
1569
+ const witnessed = [];
1570
+ const possible = [];
1571
+ const reached = [];
1572
+ const note = (ways, way) => {
1573
+ if (!ways.some(item => item.within === way.within && sameSteps(item.steps, way.steps)))
1574
+ ways.push(way);
1575
+ };
1576
+ for (const candidate of candidates) {
1577
+ const traced = traceSync(implementation, inputOf(candidate), { ...answering, ...standOf(candidate) });
1578
+ // A run that fails took the way it failed on: a row there shows the failure.
1579
+ if (traced.ended !== true && traced.error === undefined)
1580
+ continue;
1581
+ for (const comparison of traced.comparisons) {
1582
+ witnessed.push({ comparison, given: inputOf(candidate), ...(standOf(candidate) === undefined ? {} : { with: standOf(candidate) }) });
1583
+ }
1584
+ for (const way of [...(traced.way === undefined ? [] : [traced.way]), ...traced.iterations]) {
1585
+ if (!taken.some(item => item.way.within === way.within && sameSteps(item.way.steps, way.steps))) {
1586
+ taken.push({ way, given: inputOf(candidate), ...(standOf(candidate) === undefined ? {} : { with: standOf(candidate) }) });
1587
+ }
1588
+ }
1589
+ }
1590
+ // Every answer the contract allows: one answer for each dependency called, so
1591
+ // the runs are every answer only where each is called at one place, not in an
1592
+ // iteration.
1593
+ const called = [...new Set(calls.map(call => call.dependency))];
1594
+ const answers = called.map(name => {
1595
+ const declared = Object.hasOwn(definition.dependencies, name) ? definition.dependencies[name] : undefined;
1596
+ const bound = expression === undefined ? undefined : answersOf(expression).find(answer => answer.dependency === name)?.schema;
1597
+ if (declared?.takes !== "input")
1598
+ return { values: [], exhaustive: false };
1599
+ return domainOf(bound === undefined ? declared.output : answerSchema(declared.output, bound), combinations);
1600
+ });
1601
+ const once = called.every(name => calls.filter(call => call.dependency === name).length === 1) &&
1602
+ (expression === undefined || iterationsOf(expression).every(iteration => callsIn(iteration.body).length === 0));
1603
+ let exhaustive = domain.exhaustive && answers.every(answer => answer.exhaustive) && once;
1604
+ let budget = combinations;
1605
+ const assignments = function* (index, chosen) {
1606
+ if (index === answers.length) {
1607
+ yield chosen;
1608
+ return;
1609
+ }
1610
+ for (const value of answers[index].values)
1611
+ yield* assignments(index + 1, [...chosen, value]);
1612
+ };
1613
+ search: for (const candidate of domain.values.filter(value => tagOf(definition.input, inputOf(value)) === tag)) {
1614
+ for (const assignment of assignments(0, [])) {
1615
+ if (--budget < 0) {
1616
+ exhaustive = false;
1617
+ break search;
1618
+ }
1619
+ const answer = Object.fromEntries(called.map((name, index) => [name, (argument) => {
1620
+ const declared = definition.dependencies[name];
1621
+ const injected = declared.takes === "input" ? declared.injected?.behavior : undefined;
1622
+ if (injected !== undefined && brokenEnsures(injected, argument, assignment[index]) !== undefined)
1623
+ throw IMPOSSIBLE;
1624
+ return assignment[index];
1625
+ }]));
1626
+ const traced = traceSync(implementation, inputOf(candidate), { ...answer, ...standOf(candidate) });
1627
+ if (traced.error === IMPOSSIBLE)
1628
+ continue;
1629
+ // A run answering a promise was not followed to its end.
1630
+ if (traced.ended !== true && traced.error === undefined) {
1631
+ exhaustive = false;
1632
+ continue;
1633
+ }
1634
+ for (const way of [...(traced.way === undefined ? [] : [traced.way]), ...traced.iterations])
1635
+ note(possible, way);
1636
+ reached.push(...traced.comparisons);
1637
+ }
1638
+ }
1639
+ for (const item of taken)
1640
+ note(possible, item.way);
1641
+ const searched = { taken, possible, reached, witnessed, exhaustive };
1642
+ const byTag = searches.get(decision) ?? new Map();
1643
+ byTag.set(key, searched);
1644
+ searches.set(decision, byTag);
1645
+ return searched;
1646
+ }
1647
+ function searchedWitness(way, implementation, tag, decision, combinations, fakes) {
1648
+ return searchedWays(implementation, tag, decision, combinations, fakes).taken
1649
+ .find(item => item.way.within === way.within && sameSteps(item.way.steps, way.steps));
1650
+ }
1651
+ // Inputs written so two or more calls are each asked what one of their fake
1652
+ // rows asks, the later written over the earlier where they share a field, so a
1653
+ // way that turns on several dependencies' answers is reached. Asking one call
1654
+ // is left to the callers; the rows stop at ASKED_TOGETHER_LIMIT.
1655
+ const ASKED_TOGETHER_LIMIT = 256;
1656
+ function askingTogether(input, calls, askedBy) {
1657
+ const found = [];
1658
+ let level = [{ value: input, after: -1 }];
1659
+ for (let size = 1; size <= calls.length && found.length < ASKED_TOGETHER_LIMIT; size++) {
1660
+ const next = [];
1661
+ grow: for (const { value, after } of level) {
1662
+ for (let index = after + 1; index < calls.length; index++) {
1663
+ for (const asked of askedBy(calls[index].dependency)) {
1664
+ if (next.length >= ASKED_TOGETHER_LIMIT)
1665
+ break grow;
1666
+ const written = writtenArgument(value, calls[index].input, asked);
1667
+ if (written !== undefined)
1668
+ next.push({ value: written, after: index });
1669
+ }
1670
+ }
1671
+ }
1672
+ if (size >= 2)
1673
+ for (const item of next)
1674
+ if (found.length < ASKED_TOGETHER_LIMIT)
1675
+ found.push(item.value);
1676
+ level = next;
1677
+ }
1678
+ return found;
1679
+ }
1680
+ // A way through the body of an iteration over a field is taken only by an input
1681
+ // whose array holds an element, so the way also asks for one.
1682
+ function withEntry(way, entered = []) {
1683
+ const values = isIteration(way.within) ? way.within.values : undefined;
1684
+ const position = isTerm(values) ? positionData(values) : undefined;
1685
+ if (position === undefined || position.measure !== "value")
1686
+ return entered.length === 0 ? way : { ...way, steps: [...way.steps, ...entered] };
1687
+ const holdsOne = { kind: "compare", operator: ">=", left: positionTerm(position.path, "length"), right: 1 };
1688
+ return { ...way, steps: [...way.steps, ...entered, { distinction: holdsOne, outcome: true }] };
1689
+ }
1690
+ // Whether some row could take a way: a way reading a value the model computes
1691
+ // (`localsOf`'s opaque locals) is settled by running the case's inputs through
1692
+ // the decision, as far as they are few enough to try.
1693
+ function wayFeasibility(way, implementation, tag, decision, combinations, fakes) {
1694
+ const settled = way.steps.find(step => step.distinction.kind !== "match" && termPaths(step.distinction).length === 0 && holds(step.distinction, {}) !== step.outcome);
1695
+ if (settled !== undefined)
1696
+ return { kind: "infeasible", reason: "値を読まない条件で、この結果にならない" };
1697
+ // An iteration entered several ways is reachable where any of them is.
1698
+ const entries = (way.entered ?? [[]]).map(entered => {
1699
+ const entering = withEntry(way, entered);
1700
+ return feasibilityOf(entering, scopeOf(implementation, tag, decision, entering), undefined, combinations);
1701
+ });
1702
+ const found = entries.find(item => item.kind === "feasible") ?? entries.find(item => item.kind === "undecided") ?? entries[0];
1703
+ if (found.kind === "feasible" && way.entryUnlisted === true)
1704
+ return { kind: "undecided", reason: "反復に入る道筋が多すぎて、すべては調べきれない" };
1705
+ const expression = decision.expression;
1706
+ if (found.kind !== "feasible" || expression === undefined)
1707
+ return found;
1708
+ const read = opaqueRead(way, decision);
1709
+ if (read.length === 0)
1710
+ return found;
1711
+ const outside = outsideRange(way, implementation, tag, decision);
1712
+ if (outside !== undefined)
1713
+ return { kind: "infeasible", reason: outside };
1714
+ const searched = searchedWays(implementation, tag, decision, combinations, fakes);
1715
+ if (searched.possible.some(item => item.within === way.within && sameSteps(item.steps, way.steps)))
1716
+ return found;
1717
+ if (searched.exhaustive) {
1718
+ return { kind: "infeasible", reason: "入力の全値を試し、この道筋を通る値がない" };
1719
+ }
1720
+ const factored = factoredSearch(way, implementation, tag, decision, combinations);
1721
+ if (factored === "found")
1722
+ return found;
1723
+ if (factored === "none")
1724
+ return { kind: "infeasible", reason: "積が定数になる因数の組をすべて試し、この道筋を通るものがない" };
1725
+ return { kind: "undecided", reason: `${[...new Set(read.map(localLabel))].join("・")}はモデルが計算する値で、試した入力ではこの道筋を通らない` };
1726
+ }
1727
+ // Whether what a dependency is asked may change what a way takes: unless its
1728
+ // ensures say nothing of the argument and it takes every value the input field
1729
+ // asked of it may hold.
1730
+ function argumentMatters(definition, shape) {
1731
+ const plain = new Set(["string", "boolean", "number", "integer"]);
1732
+ return (name, argument) => {
1733
+ const declared = Object.hasOwn(definition.dependencies, name) ? definition.dependencies[name] : undefined;
1734
+ if (declared?.takes !== "input" || (declared.injected?.behavior.ensures.length ?? 0) > 0)
1735
+ return true;
1736
+ const position = isTerm(argument) ? positionData(argument) : undefined;
1737
+ if (position === undefined || position.measure !== "value" || position.path.length !== 1 || !Object.hasOwn(shape, position.path[0]))
1738
+ return true;
1739
+ const field = shape[position.path[0]], taken = declared.input;
1740
+ return !(plain.has(field.kind) && field.kind === taken.kind && field.invariants.length === 0 && taken.invariants.length === 0);
1741
+ };
1742
+ }
1743
+ // What a bind holds, by its local's name.
1744
+ function boundValueOf(template, name) {
1745
+ const node = nodeOf(template);
1746
+ if (node?.kind === "bind" && node.name === name)
1747
+ return node.value;
1748
+ for (const child of childrenOf(template)) {
1749
+ const found = boundValueOf(child, name);
1750
+ if (found !== undefined)
1751
+ return found;
1752
+ }
1753
+ return undefined;
1754
+ }
1755
+ // A step comparing a computed sum, difference or product with a constant, where
1756
+ // the bounds of what it reads leave it no value that takes the step's outcome
1757
+ // (two inputs of at least 2 never multiply to less than 4): why, or undefined.
1758
+ function outsideRange(way, implementation, tag, decision) {
1759
+ const expression = decision.expression;
1760
+ if (expression === undefined)
1761
+ return undefined;
1762
+ const scope = scopeOf(implementation, tag, decision, way);
1763
+ for (const step of way.steps) {
1764
+ const rule = step.distinction;
1765
+ if (rule.kind !== "compare" || typeof step.outcome !== "boolean")
1766
+ continue;
1767
+ const [term, constant, operator] = isTerm(rule.left) && !isTerm(rule.right)
1768
+ ? [rule.left, rule.right, rule.operator]
1769
+ : isTerm(rule.right) && !isTerm(rule.left) ? [rule.right, rule.left, mirroredOperator(rule.operator)] : [undefined, undefined, rule.operator];
1770
+ const position = term === undefined ? undefined : positionData(term);
1771
+ if (position === undefined || position.measure !== "value" || position.path.length !== 1)
1772
+ continue;
1773
+ const value = boundValueOf(expression, position.path[0]);
1774
+ if (value === undefined)
1775
+ continue;
1776
+ const range = rangeOf(value, scope, way.steps.filter(other => other !== step));
1777
+ let bound;
1778
+ try {
1779
+ bound = fractionOf(constant);
1780
+ }
1781
+ catch {
1782
+ continue;
1783
+ }
1784
+ if (range === undefined)
1785
+ continue;
1786
+ const meets = (holdsIt) => {
1787
+ const wanted = holdsIt ? operator : negated[operator];
1788
+ const { low, high } = range;
1789
+ switch (wanted) {
1790
+ case "<": return low.comparedTo(bound) < 0;
1791
+ case "<=": return low.comparedTo(bound) <= 0;
1792
+ case ">": return high.comparedTo(bound) > 0;
1793
+ case ">=": return high.comparedTo(bound) >= 0;
1794
+ case "==": return low.comparedTo(bound) <= 0 && high.comparedTo(bound) >= 0;
1795
+ case "!=": return !(low.comparedTo(bound) === 0 && high.comparedTo(bound) === 0);
1796
+ }
1797
+ };
1798
+ if (!meets(step.outcome)) {
1799
+ return `${localLabel(position.path[0])}が取りうる範囲(${String(range.low)}〜${String(range.high)})では、この結果にならない`;
1800
+ }
1801
+ }
1802
+ return undefined;
1803
+ }
1804
+ const negated = { "<": ">=", "<=": ">", ">": "<=", ">=": "<", "==": "!=", "!=": "==" };
1805
+ function mirroredOperator(operator) {
1806
+ return { "<": ">", "<=": ">=", ">": "<", ">=": "<=", "==": "==", "!=": "!=" }[operator];
1807
+ }
1808
+ // A way whose step holds that a product of two integer inputs equals a whole
1809
+ // number N other than 0 is taken only by inputs whose two factors are a
1810
+ // divisor pair of N. Those pairs, with every value of the other fields the ways
1811
+ // turn on, are every input that could take it: "found" where one does, "none"
1812
+ // where none does and the rest were all tried, undefined where it cannot tell.
1813
+ const FACTOR_LIMIT = 10 ** 12;
1814
+ function factoredSearch(way, implementation, tag, decision, combinations) {
1815
+ const found = factoredWitness(way, implementation, tag, decision, combinations);
1816
+ return found === undefined ? undefined : found.given !== undefined ? "found" : found.exhaustive ? "none" : undefined;
1817
+ }
1818
+ function factoredWitness(way, implementation, tag, decision, combinations) {
1819
+ const expression = decision.expression;
1820
+ const definition = implementation.behavior;
1821
+ if (expression === undefined || Object.keys(definition.dependencies).length > 0)
1822
+ return undefined;
1823
+ for (const step of way.steps) {
1824
+ const rule = step.distinction;
1825
+ if (rule.kind !== "compare" || step.outcome !== (rule.operator === "==") || (rule.operator !== "==" && rule.operator !== "!="))
1826
+ continue;
1827
+ const [term, constant] = isTerm(rule.left) ? [rule.left, rule.right] : [rule.right, rule.left];
1828
+ const position = isTerm(term) ? positionData(term) : undefined;
1829
+ if (position === undefined || position.measure !== "value" || position.path.length !== 1 || typeof constant !== "number" || !Number.isSafeInteger(constant) || constant === 0 || Math.abs(constant) > FACTOR_LIMIT)
1830
+ continue;
1831
+ const product = nodeOf(boundValueOf(expression, position.path[0]));
1832
+ if (product?.kind !== "operation" || product.operator !== "multiply")
1833
+ continue;
1834
+ const [first, second] = [product.left, product.right].map(side => (isTerm(side) ? positionData(side) : undefined));
1835
+ const variant = definition.input.variants[tag];
1836
+ if (first === undefined || second === undefined || first.path.length !== 1 || second.path.length !== 1 || first.path[0] === second.path[0])
1837
+ continue;
1838
+ if ([first, second].some(side => side.measure !== "value" || variant.shape[side.path[0]]?.kind !== "integer"))
1839
+ continue;
1840
+ const divisors = [];
1841
+ for (let d = 1; d * d <= Math.abs(constant); d++) {
1842
+ if (constant % d === 0)
1843
+ divisors.push(d, -d, constant / d, -constant / d);
1844
+ }
1845
+ const pairs = [...new Set(divisors)].map(d => [d, constant / d]);
1846
+ const turned = fieldsTurnedOn(expression, argumentMatters(definition, variant.shape));
1847
+ const others = Object.fromEntries(Object.entries(variant.shape).filter(([key]) => (turned === undefined || turned.has(key)) && key !== first.path[0] && key !== second.path[0]));
1848
+ const caseRules = [...variant.invariants, ...definition.input.invariants];
1849
+ const separate = turned !== undefined && caseRules.every(rule => pathsRead(rule).every(path => path.length > 0 && turned.has(path[0])));
1850
+ const rest = domainOf(object(others), combinations);
1851
+ const placeholder = placeholderForOf(definition.input, tag);
1852
+ let tried = 0;
1853
+ let refused = false;
1854
+ for (const [a, b] of pairs) {
1855
+ for (const other of rest.values) {
1856
+ if (++tried > combinations)
1857
+ return { exhaustive: false };
1858
+ const given = { ...placeholder, ...other, [first.path[0]]: a, [second.path[0]]: b, [definition.input.discriminant]: tag };
1859
+ if (!definition.input.parse(given).success) {
1860
+ // 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.
1861
+ if (variant.shape[first.path[0]].parse(a).success && variant.shape[second.path[0]].parse(b).success)
1862
+ refused = true;
1863
+ continue;
1864
+ }
1865
+ const traced = traceSync(implementation, given);
1866
+ if ([...(traced.way === undefined ? [] : [traced.way]), ...traced.iterations].some(taken => taken.within === way.within && sameSteps(taken.steps, way.steps)))
1867
+ return { given, exhaustive: true };
1868
+ }
1869
+ }
1870
+ return { exhaustive: rest.exhaustive && separate && !refused };
1871
+ }
1872
+ return undefined;
1873
+ }
1874
+ // The values a way reads that the model computes and no expression of the input
1875
+ // stands for.
1876
+ function opaqueRead(way, decision) {
1877
+ const expression = decision.expression;
1878
+ if (expression === undefined)
1879
+ return [];
1880
+ const opaque = new Set(localsOf(expression).filter(local => local.opaque).map(local => local.name));
1881
+ return way.steps.flatMap(step => step.distinction.kind === "match" ? [] : localRoots(step.distinction)).filter(name => opaque.has(name));
1882
+ }
1157
1883
  function unmetStatus(feasibilities) {
1158
1884
  if (feasibilities.length === 0 || feasibilities.some(item => item.kind === "feasible")) {
1159
1885
  return { status: "gap" };
@@ -1164,9 +1890,104 @@ function unmetStatus(feasibilities) {
1164
1890
  }
1165
1891
  return { status: "no row owed", reason: feasibilities[0].reason };
1166
1892
  }
1893
+ // The rows beside the runs nearest to a point on a computed value: from each
1894
+ // of the three runs whose value came nearest, one numeric field of the input
1895
+ // is moved by one, two, ten or a hundred either way, and the move that brings
1896
+ // the value nearest is kept, until the point is reached or no move brings it
1897
+ // nearer. Where none reaches it, what was tried is said: that is no proof the
1898
+ // point is unreachable.
1899
+ function besideTheNearest(definition, drawn, point, runs, coordinates) {
1900
+ const target = numeric(point.witness);
1901
+ if (target === undefined || runs.length === 0)
1902
+ return { tried: `${runs.length}件の実行を試したが、点に届く行は見つからない` };
1903
+ const distance = (given, deps) => {
1904
+ const values = coordinates(given, deps).map(numeric).filter((value) => value !== undefined);
1905
+ return values.length === 0 ? undefined : Math.min(...values.map(value => Math.abs(value - target)));
1906
+ };
1907
+ const variant = definition.input.variants[drawn.origin?.tag ?? ""];
1908
+ // Every integer, number and int64 leaf of the case, nested objects included.
1909
+ const fields = [];
1910
+ const numericLeaves = (schema, path) => {
1911
+ if (schema === undefined)
1912
+ return;
1913
+ if (schema.kind === "integer" || schema.kind === "number" || schema.kind === "int64")
1914
+ fields.push(path);
1915
+ else if (schema.kind === "object")
1916
+ for (const [key, field] of Object.entries(schema.shape))
1917
+ numericLeaves(field, [...path, key]);
1918
+ };
1919
+ numericLeaves(variant, []);
1920
+ const readAt = (given, path) => path.reduce((value, key) => (value !== null && typeof value === "object" ? value[key] : undefined), given);
1921
+ const scored = runs
1922
+ .map(run => ({ ...run, distance: distance(run.given, run.with) }))
1923
+ .filter((run) => run.distance !== undefined)
1924
+ .sort((a, b) => a.distance - b.distance);
1925
+ let nearest = scored[0]?.distance;
1926
+ let steps = 0;
1927
+ for (const start of scored.slice(0, 3)) {
1928
+ let current = start;
1929
+ for (let round = 0; round < 64 && current.distance > 0; round++) {
1930
+ let best;
1931
+ for (const field of fields) {
1932
+ for (const by of [1, -1, 2, -2, 10, -10, 100, -100]) {
1933
+ const value = readAt(current.given, field);
1934
+ if (typeof value !== "number" && typeof value !== "bigint")
1935
+ continue;
1936
+ const given = writtenAt(current.given, field, typeof value === "bigint" ? value + BigInt(by) : value + by);
1937
+ if (!definition.input.parse(given).success)
1938
+ continue;
1939
+ steps++;
1940
+ if (coordinates(given, current.with).some(reached => point.contains(reached))) {
1941
+ return { given, ...(current.with === undefined ? {} : { with: current.with }), tried: "" };
1942
+ }
1943
+ const moved = distance(given, current.with);
1944
+ if (moved !== undefined && moved < (best?.distance ?? current.distance))
1945
+ best = { ...current, given, distance: moved };
1946
+ }
1947
+ }
1948
+ if (best === undefined)
1949
+ break;
1950
+ current = best;
1951
+ nearest = Math.min(nearest ?? current.distance, current.distance);
1952
+ }
1953
+ if (current.distance === 0 && coordinates(current.given, current.with).some(value => point.contains(value))) {
1954
+ return { given: current.given, ...(current.with === undefined ? {} : { with: current.with }), tried: "" };
1955
+ }
1956
+ }
1957
+ return { tried: `${runs.length}件の実行と、近いものから${steps}件の隣の行を試したが、点に届く行は見つからない${nearest === undefined ? "" : `(最も近い差は${nearest})`}` };
1958
+ }
1959
+ function numeric(value) {
1960
+ if (typeof value === "number")
1961
+ return value;
1962
+ if (typeof value === "bigint")
1963
+ return Number(value);
1964
+ if (isDecimal(value))
1965
+ return value.toNumber();
1966
+ return undefined;
1967
+ }
1968
+ // A computation cut at several places owes its weights once (ADR-0124): a
1969
+ // border of it the rows tell from the lines beside it tells the computation's
1970
+ // weights, so another border of the same computation is told through it.
1971
+ function toldOnce(borders, drawn) {
1972
+ const keyOf = (index) => {
1973
+ const form = drawn[index].form;
1974
+ return form === undefined ? undefined : computationOf(drawn[index].origin?.tag, form.parts);
1975
+ };
1976
+ const told = new Map();
1977
+ borders.forEach((border, index) => {
1978
+ const key = keyOf(index);
1979
+ if (key !== undefined && border.beside?.status === "told" && border.beside.through === undefined && !told.has(key))
1980
+ told.set(key, border.rule);
1981
+ });
1982
+ return borders.map((border, index) => {
1983
+ const key = keyOf(index);
1984
+ const through = key === undefined ? undefined : told.get(key);
1985
+ return through !== undefined && border.beside?.status === "not told" ? { ...border, beside: { status: "told", through } } : border;
1986
+ });
1987
+ }
1167
1988
  function besideOf(definition, implementation, drawn, reachedIt) {
1168
1989
  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 => {
1990
+ const rows = reachedIt.filter(item => drawn.coordinateOf(item.comparison) !== undefined).flatMap(item => {
1170
1991
  const values = parts.map(part => part.valueOf(item.comparison.scope));
1171
1992
  return values.every(value => value !== undefined)
1172
1993
  ? [{ values, kept: holds(drawn.comparison, item.comparison.scope), given: item.given, deps: item.deps }]
@@ -1186,9 +2007,14 @@ function besideOf(definition, implementation, drawn, reachedIt) {
1186
2007
  .flatMap(parting => {
1187
2008
  const given = parts.reduce((written, part, index) => (written === undefined ? undefined : part.write(written, parting.values[index])), rows[parting.from].given);
1188
2009
  const deps = rows[parting.from].deps;
2010
+ // Writing one part can move another that reads the same field, as
2011
+ // `length($.code)` and `length(trim($.code))` both read $.code, so the
2012
+ // row is kept only where it reaches the comparison at the parting itself.
1189
2013
  const reaches = given !== undefined &&
1190
2014
  definition.input.parse(given).success &&
1191
- comparisonsReached(implementation, given, deps).some(item => item.rule === drawn.comparison);
2015
+ comparisonsReached(implementation, given, deps).some(item => item.rule === drawn.comparison &&
2016
+ drawn.coordinateOf(item) !== undefined &&
2017
+ parts.every((part, index) => part.valueOf(item.scope) === parting.values[index]));
1192
2018
  if (!reaches) {
1193
2019
  return [];
1194
2020
  }
@@ -1233,6 +2059,26 @@ function mentions(rule, target) {
1233
2059
  return false;
1234
2060
  }
1235
2061
  }
2062
+ // Whether some row could stand at a guard border point. A comparison reading a
2063
+ // value the model computes is settled by the search's runs: one reaching it at
2064
+ // the point makes it feasible, and runs of every input and answer none of which
2065
+ // do make it infeasible.
2066
+ function pointFeasibility(drawn, point, implementation, combinations, wayLimit, fakes) {
2067
+ const origin = drawn.origin;
2068
+ const expression = origin?.decision?.expression;
2069
+ if (origin === undefined || expression === undefined)
2070
+ return reachOf(drawn, point, combinations, wayLimit);
2071
+ const opaque = new Set(localsOf(expression).filter(local => local.opaque).map(local => local.name));
2072
+ const read = localRoots(drawn.comparison).filter(name => opaque.has(name));
2073
+ if (read.length === 0)
2074
+ return reachOf(drawn, point, combinations, wayLimit);
2075
+ const searched = searchedWays(implementation, origin.tag, origin.decision, combinations, fakes);
2076
+ if ([...searched.reached, ...searched.witnessed.map(item => item.comparison)].some(item => item.rule === drawn.comparison && point.contains(drawn.coordinateOf(item))))
2077
+ return [{ kind: "feasible" }];
2078
+ if (searched.exhaustive)
2079
+ return [{ kind: "infeasible", reason: "入力と依存の答えの全値を試し、この点に届く値がない" }];
2080
+ return [{ kind: "undecided", reason: `${[...new Set(read.map(localLabel))].join("・")}はモデルが計算する値で、試した入力ではこの点に届かない` }];
2081
+ }
1236
2082
  function reachOf(drawn, point, combinations, wayLimit) {
1237
2083
  const normalized = normalize(drawn.comparison);
1238
2084
  const { left, right } = drawn.comparison;
@@ -1259,6 +2105,7 @@ function reachOf(drawn, point, combinations, wayLimit) {
1259
2105
  return [{ kind: "feasible" }];
1260
2106
  }
1261
2107
  const prefixes = [];
2108
+ let unlisted = false;
1262
2109
  let followed = 0;
1263
2110
  for (const way of eachWayOf(decision)) {
1264
2111
  followed += 1;
@@ -1267,15 +2114,44 @@ function reachOf(drawn, point, combinations, wayLimit) {
1267
2114
  }
1268
2115
  const index = way.steps.findIndex(step => step.distinction === drawn.comparison);
1269
2116
  if (index !== -1) {
1270
- prefixes.push(way.steps.slice(0, index));
2117
+ // A comparison in an iteration's body is reached only through the iteration, entered and over an array that holds an element.
2118
+ for (const entered of way.entered ?? [[]]) {
2119
+ prefixes.push([...way.steps.slice(0, index), ...withEntry(way, entered).steps.slice(way.steps.length)]);
2120
+ if (way.entryUnlisted === true)
2121
+ unlisted = true;
2122
+ }
1271
2123
  }
1272
2124
  }
2125
+ // A row at the border is of the case it is drawn under.
2126
+ const inCases = (drawn.cases ?? []).map(item => ({
2127
+ distinction: { kind: "compare", operator: "==", left: positionTerm([...item.at, item.discriminant], "value"), right: item.tag },
2128
+ outcome: true,
2129
+ }));
1273
2130
  return prefixes.length === 0
1274
2131
  ? [{ kind: "feasible" }]
1275
- : prefixes.map(steps => feasibilityOf({ steps }, scope, placement, combinations));
2132
+ : prefixes.map(steps => feasibilityOf({ steps: [...steps, ...inCases] }, scope, placement, combinations))
2133
+ .map((found) => unlisted && found.kind === "feasible" ? { kind: "undecided", reason: "反復に入る道筋が多すぎて、すべては調べきれない" } : found);
2134
+ }
2135
+ function scopeOf(implementation, tag, decision, way) {
2136
+ const scope = feasibilityScope(implementation.behavior, tag, decision, way?.steps ?? []);
2137
+ return way === undefined ? scope : settledBy(scope, way.steps);
1276
2138
  }
1277
- function scopeOf(implementation, tag) {
1278
- return feasibilityScope(implementation.behavior, tag);
2139
+ // The scope with each sum field the way settles to one case read as that case,
2140
+ // so a field of the case is read with the kind it has there.
2141
+ function settledBy(scope, steps, path = []) {
2142
+ if (scope.kind !== "object")
2143
+ return scope;
2144
+ const { shape } = scope;
2145
+ let changed = false;
2146
+ const settled = Object.fromEntries(Object.entries(shape).map(([key, field]) => {
2147
+ const at = [...path, key];
2148
+ const tag = isVariantsSchema(field) ? selectedTag(field, at, steps) : undefined;
2149
+ const next = tag === undefined ? settledBy(field, steps, at) : settledBy(taggedCase(field, tag), steps, at);
2150
+ if (next !== field)
2151
+ changed = true;
2152
+ return [key, next];
2153
+ }));
2154
+ return changed ? { ...scope, shape: settled } : scope;
1279
2155
  }
1280
2156
  function coverage(all, covered, excluded = []) {
1281
2157
  const counted = all.filter(value => !excluded.includes(value));
@@ -1327,6 +2203,8 @@ function segmentsRead(rule, root, elements) {
1327
2203
  switch (rule.kind) {
1328
2204
  case "compare":
1329
2205
  return [rule.left, rule.right].flatMap(trailsOf);
2206
+ case "relation":
2207
+ return [rule.subject, rule.other].flatMap(trailsOf);
1330
2208
  case "all":
1331
2209
  case "any": {
1332
2210
  const of = trailOf(rule.of);
@@ -1362,7 +2240,7 @@ function namedSegments(position) {
1362
2240
  // A disregarded position a guard reads is kept rather than dropped, since the
1363
2241
  // guard's classes are attached to it; only what its type and invariants owe goes.
1364
2242
  function measuredPositionsOf(definition, guardDivided = new Set(), guardRead = [], combinations = FEASIBILITY_COMBINATION_LIMIT) {
1365
- return positionsOf(definition.input).map(position => withJointExclusions(definition, position, combinations)).flatMap((position) => {
2243
+ return withDividedContainers(definition.input, guardDivided).map(position => withJointExclusions(definition, position, combinations)).flatMap((position) => {
1366
2244
  if (!isDisregarded(definition, position)) {
1367
2245
  return [position];
1368
2246
  }
@@ -1380,11 +2258,19 @@ function measuredPositionsOf(definition, guardDivided = new Set(), guardRead = [
1380
2258
  ];
1381
2259
  });
1382
2260
  }
2261
+ // The positions of an input, with a record or an array a guard's relation
2262
+ // divides as a container (ADR-0129), which is no position otherwise.
2263
+ function withDividedContainers(input, guardDivided) {
2264
+ const plain = positionsOf(input);
2265
+ const known = new Set(plain.map(position => trailKey(position.segments)));
2266
+ const containers = positionsOf(input, { containers: true }).filter(position => !known.has(trailKey(position.segments)) && guardDivided.has(trailKey(position.segments)));
2267
+ return [...plain, ...containers];
2268
+ }
1383
2269
  const DISREGARD_COMBINATION_LIMIT = 255;
1384
2270
  // Not the combinations alone: moves are tried before a combination is known to
1385
2271
  // be one the input can hold, so the candidates tried that way are bounded too.
1386
2272
  const DISREGARD_CANDIDATE_LIMIT = 4096;
1387
- function positiveLimit(name, given, fallback) {
2273
+ export function positiveLimit(name, given, fallback) {
1388
2274
  if (given === undefined) {
1389
2275
  return fallback;
1390
2276
  }
@@ -1440,8 +2326,8 @@ async function disregardBroken(implementation, row, answered, standIns, limits)
1440
2326
  {
1441
2327
  path: instance.path,
1442
2328
  moves,
1443
- unmoved: (varied) => (isDeepStrictEqual(classified(varied), taken) &&
1444
- isDeepStrictEqual(coordinates(varied), original)) ||
2329
+ unmoved: (varied) => (deepEqual(classified(varied), taken) &&
2330
+ deepEqual(coordinates(varied), original)) ||
1445
2331
  (classified(varied).length === 0 && coordinates(varied).every(values => values.length === 0)),
1446
2332
  },
1447
2333
  ];
@@ -1468,7 +2354,7 @@ async function disregardBroken(implementation, row, answered, standIns, limits)
1468
2354
  return move === undefined ? axis.unmoved(varied) : move.reached(varied);
1469
2355
  });
1470
2356
  return holds &&
1471
- isDeepStrictEqual(readKept(varied), keptOriginally) &&
2357
+ deepEqual(readKept(varied), keptOriginally) &&
1472
2358
  definition.input.parse(varied).success
1473
2359
  ? [{ choice, varied }]
1474
2360
  : [];
@@ -1490,7 +2376,7 @@ async function disregardBroken(implementation, row, answered, standIns, limits)
1490
2376
  };
1491
2377
  }
1492
2378
  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) }));
2379
+ 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) }));
1494
2380
  if (outcome !== undefined) {
1495
2381
  const moved = axes.flatMap((axis, index) => {
1496
2382
  const move = choice[index];
@@ -1513,45 +2399,64 @@ async function disregardBroken(implementation, row, answered, standIns, limits)
1513
2399
  // the invariants relating finite positions keep can take is excluded, like
1514
2400
  // one a rule on the position alone refuses.
1515
2401
  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("."))) {
2402
+ if (position.kind !== "divided") {
1518
2403
  return position;
1519
2404
  }
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
2405
  const refused = position.classes.filter(className => {
1537
2406
  if (position.excluded.includes(className)) {
1538
2407
  return true;
1539
2408
  }
1540
- const at = coordinate(className);
1541
- return at !== undefined && refusedJointly(scope, at.path, at.value, combinations);
2409
+ const at = finiteCoordinateOf(definition, position, className);
2410
+ return at !== undefined && refusedJointly(at.scope, at.path, at.value, combinations);
1542
2411
  });
1543
2412
  return refused.length === position.excluded.length ? position : { ...position, excluded: refused };
1544
2413
  }
2414
+ // Where a class of a boolean, an enum or a sum field directly under an input
2415
+ // case sits for the joint invariant search: the case's scope, the field's keys
2416
+ // in it and the value the class stands for.
2417
+ export function finiteCoordinateOf(definition, position, className) {
2418
+ const [head, ...rest] = position.segments;
2419
+ if (head === undefined || rest.length === 0 || !rest.every(step => step.startsWith("."))) {
2420
+ return undefined;
2421
+ }
2422
+ const tag = head.slice(1);
2423
+ const scope = feasibilityScope(definition, tag);
2424
+ const keys = rest.map(step => step.slice(1));
2425
+ const field = schemaAtPath(scope, keys);
2426
+ switch (field?.kind) {
2427
+ case "boolean":
2428
+ return { tag, scope, path: keys, value: className === "true" };
2429
+ case "enum":
2430
+ return { tag, scope, path: keys, value: className };
2431
+ case "variants":
2432
+ return { tag, scope, path: [...keys, field.discriminant], value: className };
2433
+ default:
2434
+ return undefined;
2435
+ }
2436
+ }
2437
+ // Planned once per implementation and limits: what to change is read off the
2438
+ // plans before the measurement and the measurement reads the same plans, so
2439
+ // `modelChanges` followed by `check` plans each decision once.
2440
+ const planned = new WeakMap();
1545
2441
  function plansOf(implementation, combinations, wayLimit) {
2442
+ if (implementation === undefined)
2443
+ return new Map();
2444
+ const key = `${combinations}:${wayLimit}`;
2445
+ const cached = planned.get(implementation)?.get(key);
2446
+ if (cached !== undefined)
2447
+ return cached;
2448
+ const made = planFor(implementation, combinations, wayLimit);
2449
+ const byLimits = planned.get(implementation) ?? new Map();
2450
+ byLimits.set(key, made);
2451
+ planned.set(implementation, byLimits);
2452
+ return made;
2453
+ }
2454
+ function planFor(implementation, combinations, wayLimit) {
1546
2455
  const plans = new Map();
1547
2456
  for (const [decision, tags] of implementation === undefined ? [] : decisionsWithCases(implementation)) {
1548
2457
  if (decision.kind !== "rules") {
1549
2458
  continue;
1550
2459
  }
1551
- if (hasScopedChoices(decision.expression)) {
1552
- plans.set(decision, { kind: "scoped" });
1553
- continue;
1554
- }
1555
2460
  const reaches = tags.map(tag => ({
1556
2461
  tag,
1557
2462
  reached: decision.expression !== undefined ? undefined : finiteReach(decision, scopeOf(implementation, tag), combinations, [[implementation.behavior.input.discriminant]]),