@toiroakr/chisel 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/README.md +249 -20
  2. package/dist/absence.d.ts +27 -0
  3. package/dist/absence.js +228 -0
  4. package/dist/absence.js.map +1 -0
  5. package/dist/behavior.d.ts +21 -9
  6. package/dist/behavior.js +219 -52
  7. package/dist/behavior.js.map +1 -1
  8. package/dist/border.d.ts +4 -7
  9. package/dist/border.js +43 -35
  10. package/dist/border.js.map +1 -1
  11. package/dist/bounds.d.ts +1 -0
  12. package/dist/bounds.js +26 -0
  13. package/dist/bounds.js.map +1 -0
  14. package/dist/cli.d.ts +2 -0
  15. package/dist/cli.js +272 -4
  16. package/dist/cli.js.map +1 -1
  17. package/dist/codec.js +7 -4
  18. package/dist/codec.js.map +1 -1
  19. package/dist/codegen.js +4 -8
  20. package/dist/codegen.js.map +1 -1
  21. package/dist/composition.d.ts +3 -3
  22. package/dist/composition.js +4 -4
  23. package/dist/composition.js.map +1 -1
  24. package/dist/data.d.ts +1 -0
  25. package/dist/data.js +2 -0
  26. package/dist/data.js.map +1 -1
  27. package/dist/dependency.d.ts +9 -6
  28. package/dist/dependency.js +23 -17
  29. package/dist/dependency.js.map +1 -1
  30. package/dist/domain.d.ts +5 -1
  31. package/dist/domain.js +6 -6
  32. package/dist/domain.js.map +1 -1
  33. package/dist/ensures.js +2 -2
  34. package/dist/ensures.js.map +1 -1
  35. package/dist/equal.d.ts +1 -0
  36. package/dist/equal.js +135 -0
  37. package/dist/equal.js.map +1 -0
  38. package/dist/feasibility.d.ts +5 -3
  39. package/dist/feasibility.js +106 -37
  40. package/dist/feasibility.js.map +1 -1
  41. package/dist/guard-borders.d.ts +12 -5
  42. package/dist/guard-borders.js +122 -171
  43. package/dist/guard-borders.js.map +1 -1
  44. package/dist/guard-scope.d.ts +61 -0
  45. package/dist/guard-scope.js +364 -0
  46. package/dist/guard-scope.js.map +1 -0
  47. package/dist/index.d.ts +17 -6
  48. package/dist/index.js +8 -3
  49. package/dist/index.js.map +1 -1
  50. package/dist/interleave.d.ts +31 -0
  51. package/dist/interleave.js +202 -0
  52. package/dist/interleave.js.map +1 -0
  53. package/dist/interval.d.ts +7 -0
  54. package/dist/interval.js +171 -21
  55. package/dist/interval.js.map +1 -1
  56. package/dist/isolated.js.map +1 -1
  57. package/dist/machine-check.d.ts +73 -0
  58. package/dist/machine-check.js +215 -0
  59. package/dist/machine-check.js.map +1 -0
  60. package/dist/machine.d.ts +97 -0
  61. package/dist/machine.js +200 -0
  62. package/dist/machine.js.map +1 -0
  63. package/dist/model.d.ts +74 -9
  64. package/dist/model.js +469 -34
  65. package/dist/model.js.map +1 -1
  66. package/dist/outcomes.d.ts +7 -0
  67. package/dist/outcomes.js +38 -0
  68. package/dist/outcomes.js.map +1 -0
  69. package/dist/pairs.js +12 -4
  70. package/dist/pairs.js.map +1 -1
  71. package/dist/partition.d.ts +1 -0
  72. package/dist/partition.js +90 -11
  73. package/dist/partition.js.map +1 -1
  74. package/dist/proof.d.ts +6 -0
  75. package/dist/proof.js +96 -22
  76. package/dist/proof.js.map +1 -1
  77. package/dist/replay.d.ts +45 -0
  78. package/dist/replay.js +157 -0
  79. package/dist/replay.js.map +1 -0
  80. package/dist/rule.d.ts +47 -7
  81. package/dist/rule.js +284 -17
  82. package/dist/rule.js.map +1 -1
  83. package/dist/runtime.d.ts +12 -0
  84. package/dist/runtime.js +8 -0
  85. package/dist/runtime.js.map +1 -0
  86. package/dist/schema.js +16 -12
  87. package/dist/schema.js.map +1 -1
  88. package/dist/specification.d.ts +12 -2
  89. package/dist/specification.js +622 -82
  90. package/dist/specification.js.map +1 -1
  91. package/dist/temporal-global.d.ts +4 -0
  92. package/dist/temporal-global.js +11 -0
  93. package/dist/temporal-global.js.map +1 -0
  94. package/dist/temporal.d.ts +22 -0
  95. package/dist/temporal.js +113 -0
  96. package/dist/temporal.js.map +1 -0
  97. package/dist/tla.d.ts +54 -0
  98. package/dist/tla.js +579 -0
  99. package/dist/tla.js.map +1 -0
  100. package/dist/verification.d.ts +7 -0
  101. package/dist/verification.js +5 -0
  102. package/dist/verification.js.map +1 -0
  103. package/dist/ways.d.ts +8 -5
  104. package/dist/ways.js +30 -39
  105. package/dist/ways.js.map +1 -1
  106. package/dist/world.d.ts +98 -0
  107. package/dist/world.js +467 -0
  108. package/dist/world.js.map +1 -0
  109. package/package.json +32 -9
@@ -1,19 +1,22 @@
1
- import { hasScopedChoices } from "./model.js";
2
- import { verify } from "./proof.js";
1
+ import { answersOf, callsIn, childrenOf, fieldsTurnedOn, iterationsOf, nodeOf, localRoots, localsOf, writtenArgument } from "./model.js";
2
+ import { rangeOf } from "./interval.js";
3
+ import { fractionOf } from "./exact.js";
4
+ import { selectedTag, taggedCase, verify } from "./proof.js";
3
5
  import { constantsOf, domainOf } from "./domain.js";
4
6
  import { pairCoverage, PAIR_LIMIT } from "./pairs.js";
5
- import { isDeepStrictEqual } from "node:util";
7
+ import { deepEqual } from "./equal.js";
6
8
  import { WAY_LIMIT, describeWay, eachWayOf, sameSteps } from "./ways.js";
7
9
  import { answerFrom, fakeIssuesOf, fakeWarningsOf } from "./dependency.js";
10
+ import { answerSchema } from "./guard-scope.js";
8
11
  import { comparisonsNotReadOf, ensuresBordersOf, invariantContradictionsOf, mayBeLeftOut, invariantPairBordersOf, guardBordersOf, guardPartitionsOf, feasibilityScope, } from "./guard-borders.js";
9
12
  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";
13
+ import { DEPS, localLabel, describeRule, describeTerm, differenceOf, holds, withDeps, isTerm, positionData, positionOf, positionTerm, termData, termPaths, pathsRead } from "./rule.js";
11
14
  import { emptiedBy, normalize } from "./border.js";
12
15
  import { FEASIBILITY_COMBINATION_LIMIT, feasibilityOf, finiteReach, keepingInvariants, keepingOrderings, refusedJointly, tooManyWays, unreached, witnessesOf } from "./feasibility.js";
13
16
  import { readEnsures } from "./ensures.js";
14
17
  import { allOnOneSide, lineTheRowsAllow, partingsOf, spelled } from "./beside.js";
15
- import { coordinatesIn, excludedCases, positionsOf } from "./partition.js";
16
- import { isVariantsSchema, schemaAtPath, tagOf } from "./schema.js";
18
+ import { coordinatesIn, excludedCases, positionsOf, writeExactly } from "./partition.js";
19
+ import { isVariantsSchema, object, schemaAtPath, tagOf } from "./schema.js";
17
20
  async function runAndCompare(definition, name, given, expected, subject) {
18
21
  try {
19
22
  const actual = await subject(given);
@@ -43,12 +46,12 @@ function answers(definition, expected, actual) {
43
46
  const received = actual;
44
47
  if (isCaseOnly(expected.result)) {
45
48
  return isVariantsSchema(definition.result) && tagOf(definition.result, received.result) === expected.result.case &&
46
- isDeepStrictEqual(canonicalEffects(received.effects), canonicalEffects(expected.effects));
49
+ deepEqual(canonicalEffects(received.effects), canonicalEffects(expected.effects));
47
50
  }
48
51
  const result = definition.result.parse(received.result);
49
52
  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));
53
+ return result.success && answer.success && deepEqual(result.value, answer.value) &&
54
+ deepEqual(canonicalEffects(received.effects), canonicalEffects(expected.effects));
52
55
  }
53
56
  export function example(_definition, row) {
54
57
  return row;
@@ -104,10 +107,11 @@ export async function check(specification, options = {}) {
104
107
  const reached = [];
105
108
  const waysMet = [];
106
109
  const waysOwed = [];
107
- const fakeIssues = fakeIssuesOf(definition.requires, definition.name, specification.fakes);
110
+ const fakeIssues = fakeIssuesOf(definition.dependencies, definition.name, specification.fakes);
108
111
  const tables = new Map(specification.fakes
109
112
  .filter(table => !fakeIssues.some(item => item.table.dependency === table.dependency))
110
113
  .map(table => [table.dependency, answerFrom(table)]));
114
+ const usableFakes = specification.fakes.filter(table => tables.has(table.dependency));
111
115
  const standIns = (row) => ({
112
116
  ...Object.fromEntries(tables),
113
117
  ...(row.with ?? {}),
@@ -128,7 +132,7 @@ export async function check(specification, options = {}) {
128
132
  const unstoodFor = (row) => {
129
133
  const written = (row.with ?? {});
130
134
  for (const [name, value] of Object.entries(written)) {
131
- const declared = definition.requires[name];
135
+ const declared = definition.dependencies[name];
132
136
  if (declared === undefined) {
133
137
  return `with ${name} names no dependency of ${definition.name}`;
134
138
  }
@@ -137,7 +141,7 @@ export async function check(specification, options = {}) {
137
141
  return `with ${name} is not a value the dependency answers: ${parsed.issues[0].message}`;
138
142
  }
139
143
  }
140
- const missing = Object.keys(definition.requires).find(name => !(name in written) && !tables.has(name));
144
+ const missing = Object.keys(definition.dependencies).find(name => !(name in written) && !tables.has(name));
141
145
  return missing === undefined ? undefined : `No stand-in for dependency ${missing}`;
142
146
  };
143
147
  const observe = (inputTag, actual) => {
@@ -192,6 +196,7 @@ export async function check(specification, options = {}) {
192
196
  if (traced.way !== undefined) {
193
197
  waysOwed.push(traced.way);
194
198
  }
199
+ waysOwed.push(...traced.iterations);
195
200
  }
196
201
  catch (error) {
197
202
  const open = openDecisionIn(implementation, error);
@@ -267,6 +272,7 @@ export async function check(specification, options = {}) {
267
272
  if (traced.way !== undefined) {
268
273
  waysMet.push(traced.way);
269
274
  }
275
+ waysMet.push(...traced.iterations);
270
276
  return traced.execution;
271
277
  });
272
278
  if (actual !== undefined && inputTag !== undefined) {
@@ -352,7 +358,7 @@ export async function check(specification, options = {}) {
352
358
  : [`${path}: 不変条件を満たす値がありません (${emptied.map(border => border.rule).join(", ")})`];
353
359
  }).concat(invariantContradictionsOf(definition));
354
360
  const partitions = positions.map((position, index) => {
355
- const drawn = guardPartitions.find(partition => isDeepStrictEqual(partition.segments, position.segments));
361
+ const drawn = guardPartitions.find(partition => deepEqual(partition.segments, position.segments));
356
362
  if (drawn !== undefined && position.kind !== "divided") {
357
363
  const values = answeredGivens.flatMap(given => position.valuesIn(given));
358
364
  const names = drawn.classes.map(item => item.name);
@@ -407,7 +413,7 @@ export async function check(specification, options = {}) {
407
413
  if (coordinates.some(value => point.contains(value))) {
408
414
  return { ...base, status: "met" };
409
415
  }
410
- return { ...base, ...unmetStatus(reachOf(drawn, point, combinations, wayLimit)) };
416
+ return { ...base, ...unmetStatus(pointFeasibility(drawn, point, specification.implementation, combinations, wayLimit, usableFakes)) };
411
417
  });
412
418
  const owed = drawn.border.points.flatMap((point, index) => (point.status === "owed" ? [points[index]] : []));
413
419
  const due = drawn.form !== undefined &&
@@ -465,8 +471,8 @@ export async function check(specification, options = {}) {
465
471
  borders.every(border => border.points.every(point => point.status !== "gap")) &&
466
472
  borders.every(border => border.beside?.status !== "not told");
467
473
  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);
474
+ const arms = measureArms(specification.implementation, armsMet, armsOwed, combinations, plans, usableFakes);
475
+ const rulesMeasure = measureRules(specification.implementation, waysMet, waysOwed, combinations, plans, usableFakes);
470
476
  const lines = [
471
477
  ...(arms.status === "unavailable" ? [] : arms.arms),
472
478
  ...(rulesMeasure.status === "unavailable" ? [] : rulesMeasure.rules),
@@ -511,7 +517,7 @@ export async function check(specification, options = {}) {
511
517
  borders,
512
518
  pairs: countPairs(pairablesOf(positions, guardPartitions), answeredGivens),
513
519
  fakeIssues: fakeIssues.map(item => item.issue),
514
- fakeWarnings: fakeWarningsOf(definition.requires, specification.fakes),
520
+ fakeWarnings: fakeWarningsOf(definition.dependencies, specification.fakes),
515
521
  evidence: {
516
522
  input: definition.input.variantTags.filter(tag => !refusedInputs.includes(tag)).map(tag => ({
517
523
  case: tag,
@@ -549,16 +555,60 @@ export function generate(target, implementation, options = {}) {
549
555
  .filter((tag) => tag !== undefined));
550
556
  const answeredRows = rows.filter(row => !isTodo(row.expect));
551
557
  const origins = answeredRows.map(row => row.given);
552
- const standIns = Object.fromEntries(Object.entries(definition.requires)
558
+ const standIns = Object.fromEntries(Object.entries(definition.dependencies)
553
559
  .filter(([, declared]) => declared.takes === "nothing")
554
560
  .map(([name, declared]) => [name, declared.output.placeholder(name)]));
561
+ // Stand-ins a search ran a row it found with, which the row is offered with.
562
+ const searchedStandIns = new Map();
555
563
  const withFrom = (origin) => {
564
+ const searchedWith = searchedStandIns.get(origin);
565
+ if (searchedWith !== undefined)
566
+ return { with: searchedWith };
556
567
  const written = answeredRows.find(row => row.given === origin)?.with;
557
568
  const standing = { ...standIns, ...written };
558
569
  return Object.keys(standing).length === 0 && written === undefined ? {} : { with: standing };
559
570
  };
560
571
  const originFor = (position) => origins.find(given => position.valuesIn(given).length > 0) ??
561
572
  definition.input.placeholder();
573
+ const fakeTables = new Map((options.fakes ?? [])
574
+ .filter(table => table.behavior === definition.name)
575
+ .filter(table => !fakeIssuesOf(definition.dependencies, definition.name, options.fakes ?? []).some(item => item.table.dependency === table.dependency))
576
+ .map(table => [table.dependency, table]));
577
+ const usableFakes = [...fakeTables.values()];
578
+ const answering = Object.fromEntries([...fakeTables].map(([name, table]) => [name, answerFrom(table)]));
579
+ const tracedWith = (stand) => ({ ...answering, ...stand });
580
+ // A row asking each dependency what one of its fake rows asks: the call's
581
+ // argument written into the input where the argument reads the input.
582
+ const askingFakes = (tag, decision, origins, reaches) => {
583
+ const expression = decision.expression;
584
+ if (expression === undefined)
585
+ return undefined;
586
+ for (const call of callsIn(expression)) {
587
+ const table = fakeTables.get(call.dependency);
588
+ for (const [asked] of table?.rows ?? []) {
589
+ for (const origin of origins) {
590
+ const given = writtenArgument(origin, call.input, asked);
591
+ if (given !== undefined && tagOf(definition.input, given) === tag && definition.input.parse(given).success && reaches(given)) {
592
+ return given;
593
+ }
594
+ }
595
+ }
596
+ }
597
+ const calls = callsIn(expression);
598
+ for (const origin of origins) {
599
+ for (const given of askingTogether(origin, calls, dependency => (fakeTables.get(dependency)?.rows ?? []).map(([asked]) => asked))) {
600
+ if (tagOf(definition.input, given) === tag && definition.input.parse(given).success && reaches(given))
601
+ return given;
602
+ }
603
+ }
604
+ return undefined;
605
+ };
606
+ // What a point or a way that turns on a dependency's answer still needs: a
607
+ // fake row answering there, asked by an input the row can write.
608
+ const askedOf = (locals) => {
609
+ const called = [...new Set(locals.map(localLabel).filter(label => label.endsWith("()")))];
610
+ return called.length === 0 ? "" : ` — ${called.join("・")}がそう答えるfakeの行がない`;
611
+ };
562
612
  const generated = [];
563
613
  const notComposed = [];
564
614
  // A row moved from `from` that breaks an invariant relating finite positions
@@ -618,9 +668,14 @@ export function generate(target, implementation, options = {}) {
618
668
  const standsAt = [...rows, ...generated].some(row => coordinatesIn(position, border.measure, row.given).some(value => point.contains(value)));
619
669
  if (!standsAt) {
620
670
  const origin = originFor(position);
671
+ const given = writeExactly(position, origin, border.measure, point.witness);
672
+ if (given === undefined) {
673
+ notComposed.push(`${position.path} ${point.role} (${point.relation})`);
674
+ continue;
675
+ }
621
676
  offer({
622
677
  name: `${definition.name}: ${position.path} ${point.role} (${point.relation})`,
623
- given: position.write(origin, border.measure, point.witness),
678
+ given,
624
679
  reason: `${position.path}の${point.role}点(${point.relation})の期待結果を人間が決める必要があります`,
625
680
  ...withFrom(origin),
626
681
  }, origin);
@@ -649,14 +704,14 @@ export function generate(target, implementation, options = {}) {
649
704
  }
650
705
  for (const drawn of implementation === undefined ? [] : guardBordersOf(implementation)) {
651
706
  const reachedBy = (given, deps) => tagOf(definition.input, given) === drawn.origin?.tag
652
- ? comparisonsReached(implementation, given, deps).filter(item => item.rule === drawn.comparison)
707
+ ? comparisonsReached(implementation, given, tracedWith(deps)).filter(item => item.rule === drawn.comparison)
653
708
  : [];
654
709
  for (const point of drawn.border.points) {
655
710
  if (point.status !== "owed" || point.witness === undefined) {
656
711
  continue;
657
712
  }
658
713
  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") {
714
+ if (standsAt || unmetStatus(pointFeasibility(drawn, point, implementation, combinations, wayLimit, usableFakes)).status === "no row owed") {
660
715
  continue;
661
716
  }
662
717
  const origin = origins.find(given => reachedBy(given, withFrom(given).with).length > 0) ??
@@ -667,18 +722,35 @@ export function generate(target, implementation, options = {}) {
667
722
  // A row the input takes stands at the point only once the guards before
668
723
  // the comparison let it through, which moving another part may not.
669
724
  const reaches = (candidate) => reachedBy(candidate, withFrom(origin).with).some(item => point.contains(drawn.coordinateOf(item)));
725
+ // A comparison on a value the model computes cannot be written, but an input the search ran may reach it at the point.
726
+ const searchedPoint = () => {
727
+ if (drawn.origin === undefined || drawn.origin.decision.expression === undefined)
728
+ return undefined;
729
+ const hit = searchedWays(implementation, drawn.origin.tag, drawn.origin.decision, combinations, usableFakes).witnessed
730
+ .find(item => item.comparison.rule === drawn.comparison && point.contains(drawn.coordinateOf(item.comparison)) && definition.input.parse(item.given).success);
731
+ if (hit === undefined)
732
+ return undefined;
733
+ if (hit.with !== undefined)
734
+ searchedStandIns.set(hit.given, hit.with);
735
+ return hit.given;
736
+ };
670
737
  const given = candidates.find(candidate => definition.input.parse(candidate).success && reaches(candidate)) ??
738
+ askingFakes(drawn.origin?.tag ?? "", drawn.origin?.decision, [
739
+ ...origins.filter(candidate => tagOf(definition.input, candidate) === drawn.origin?.tag),
740
+ ...(drawn.origin === undefined ? [] : [definition.input.placeholderFor(drawn.origin.tag)]),
741
+ ], reaches) ??
742
+ searchedPoint() ??
671
743
  candidates.find(candidate => !definition.input.parse(candidate).success) ??
672
744
  candidates.find(candidate => definition.input.parse(candidate).success);
673
745
  if (given === undefined) {
674
- notComposed.push(`${drawn.path} ${point.role} (${point.relation})`);
746
+ notComposed.push(`${drawn.path} ${point.role} (${point.relation})${askedOf(drawn.segments.flatMap(segment => segment.startsWith(".#local:") ? [segment.slice(1)] : []))}`);
675
747
  }
676
748
  else {
677
749
  offer({
678
750
  name: `${definition.name}: ${drawn.path} ${point.role} (${point.relation})`,
679
751
  given,
680
752
  reason: `${drawn.path}の${point.role}点(${point.relation})の期待結果を人間が決める必要があります`,
681
- ...withFrom(origin),
753
+ ...withFrom(searchedStandIns.has(given) ? given : origin),
682
754
  }, origin);
683
755
  }
684
756
  }
@@ -689,7 +761,7 @@ export function generate(target, implementation, options = {}) {
689
761
  const owed = drawn.border.points.filter(point => point.status === "owed");
690
762
  const standsAt = (point) => items.some(item => point.contains(drawn.coordinateOf(item.comparison)));
691
763
  const due = owed.some(standsAt) &&
692
- owed.every(point => standsAt(point) || unmetStatus(reachOf(drawn, point, combinations, wayLimit)).status === "no row owed");
764
+ owed.every(point => standsAt(point) || unmetStatus(pointFeasibility(drawn, point, implementation, combinations, wayLimit, usableFakes)).status === "no row owed");
693
765
  const found = due ? besideOf(definition, implementation, drawn, items) : undefined;
694
766
  if (found?.beside.status !== "not told") {
695
767
  continue;
@@ -740,8 +812,11 @@ export function generate(target, implementation, options = {}) {
740
812
  if (decision.kind !== "rules") {
741
813
  continue;
742
814
  }
743
- const wayOf = (given, deps) => traceSync(implementation, given, deps).way;
815
+ const wayOf = (given, deps) => traceSync(implementation, given, tracedWith(deps)).way;
744
816
  const takes = (given, deps, way) => {
817
+ if (way.within !== undefined) {
818
+ return traceSync(implementation, given, tracedWith(deps)).iterations.some(taken => taken.within === way.within && sameSteps(taken.steps, way.steps));
819
+ }
745
820
  const taken = wayOf(given, deps);
746
821
  return taken !== undefined && sameSteps(taken.steps, way.steps);
747
822
  };
@@ -774,10 +849,6 @@ export function generate(target, implementation, options = {}) {
774
849
  definition.input.placeholderFor(tag),
775
850
  ];
776
851
  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
852
  if (plan?.kind === "too many") {
782
853
  notComposed.push(`${decision.id}: ${tooManyWays(wayLimit)}ため組み立てない`);
783
854
  continue;
@@ -790,13 +861,17 @@ export function generate(target, implementation, options = {}) {
790
861
  continue;
791
862
  }
792
863
  if (witness === undefined &&
793
- feasibilityOf(way, scopeOf(implementation, tag), undefined, combinations).kind === "infeasible") {
864
+ wayFeasibility(way, implementation, tag, decision, combinations, usableFakes).kind === "infeasible") {
794
865
  continue;
795
866
  }
796
867
  const taken = (candidate) => candidate !== undefined && takes(candidate.given, withFrom(candidate.origin).with, way)
797
868
  ? candidate
798
869
  : undefined;
799
- const composed = taken(composeForWay(way, tag)) ??
870
+ const throughFakes = askingFakes(tag, decision, origins_, given => takes(given, withFrom(given).with, way));
871
+ const composed = (throughFakes === undefined ? undefined : { given: throughFakes, origin: throughFakes }) ??
872
+ (way.within === undefined ? undefined : composeElement(way)) ??
873
+ taken(searched(way)) ??
874
+ taken(composeForWay(way, tag)) ??
800
875
  (options.ways !== true
801
876
  ? undefined
802
877
  : witness === undefined
@@ -811,8 +886,49 @@ export function generate(target, implementation, options = {}) {
811
886
  });
812
887
  }
813
888
  else {
814
- notComposed.push(`${decision.id}: ${describeWay(way)}`);
889
+ notComposed.push(`${decision.id}: ${describeWay(way)}${askedOf(way.steps.flatMap(step => localRoots(step.distinction)))}`);
890
+ }
891
+ }
892
+ // A way one element takes through an iteration's body: a row whose array
893
+ // holds that one element, taken from what the rows hold or moved into each
894
+ // class of the element's positions.
895
+ function composeElement(way) {
896
+ const values = way.within?.values;
897
+ const position = isTerm(values) ? positionData(values) : undefined;
898
+ if (position === undefined || position.measure !== "value" || position.path.some(key => key.startsWith("#")))
899
+ return undefined;
900
+ const read = (given) => position.path.reduce((at, key) => (at !== null && typeof at === "object" ? at[key] : undefined), given);
901
+ const held = [...rows, ...generated].flatMap(row => {
902
+ const array = read(row.given);
903
+ return Array.isArray(array) ? array : [];
904
+ });
905
+ const trail = [`@${tag}`, ...position.path.map(key => `.${key}`), "[]"];
906
+ const moved = [...positionsByPath.values()].filter(at => at.kind === "divided" && trailKey(at.segments.slice(0, trail.length)) === trailKey(trail));
907
+ for (const origin of origins_) {
908
+ const candidates = [
909
+ ...held.map(element => writtenArgument(origin, values, [element])),
910
+ ...moved.flatMap(at => at.kind === "divided" ? at.classes.map(name => at.place(writtenArgument(origin, values, held.slice(0, 1)) ?? origin, name)) : []),
911
+ ];
912
+ for (const given of candidates) {
913
+ if (given !== undefined && definition.input.parse(given).success && takes(given, withFrom(origin).with, way))
914
+ return { given, origin };
915
+ }
815
916
  }
917
+ return undefined;
918
+ }
919
+ // A way through a value the model computes, from an input the search found
920
+ // taking it.
921
+ function searched(way) {
922
+ if (opaqueRead(way, decision).length === 0)
923
+ return undefined;
924
+ const factored = factoredWitness(way, implementation, tag, decision, combinations)?.given;
925
+ const found = searchedWitness(way, implementation, tag, decision, combinations, usableFakes)
926
+ ?? (factored === undefined ? undefined : { given: factored });
927
+ if (found === undefined)
928
+ return undefined;
929
+ if (found.with !== undefined)
930
+ searchedStandIns.set(found.given, found.with);
931
+ return { given: found.given, origin: found.given };
816
932
  }
817
933
  function composeFromReach(way, witness) {
818
934
  const witnessed = [...witness].map(([key, value]) => ({ path: JSON.parse(key), value }));
@@ -826,7 +942,7 @@ export function generate(target, implementation, options = {}) {
826
942
  }
827
943
  function composeFromWitnesses(way) {
828
944
  for (const origin of origins_) {
829
- const witnesses = witnessesOf(way, scopeOf(implementation, tag), { discriminant, tag }, combinations);
945
+ const witnesses = witnessesOf(way, scopeOf(implementation, tag, decision), { discriminant, tag }, combinations);
830
946
  if (witnesses === undefined) {
831
947
  break;
832
948
  }
@@ -863,7 +979,7 @@ export function generate(target, implementation, options = {}) {
863
979
  }
864
980
  const pairs = pairCoverage(definition, implementation, measuredPositionsOf(definition, guardDivided, guardRead, combinations), implementation === undefined ? [] : guardPartitionsOf(implementation), [...rows, ...generated.map(row => ({ ...row, kind: "example", expect: { kind: "todo", reason: row.reason } }))], { obligations: positiveLimit("pairs.obligations", options.pairs?.obligations, PAIR_LIMIT), candidates: positiveLimit("pairs.candidates", options.pairs?.candidates, combinations) });
865
981
  for (const { obligation, given } of pairs.witnesses) {
866
- if (generated.some(row => isDeepStrictEqual(row.given, given)))
982
+ if (generated.some(row => deepEqual(row.given, given)))
867
983
  continue;
868
984
  offer({ name: `${definition.name}: ${obligation.positions[0]} = ${obligation.classes[0]} × ${obligation.positions[1]} = ${obligation.classes[1]}`, given,
869
985
  reason: "組み合わせの期待結果を人間が決める必要があります", ...withFrom(given) });
@@ -963,7 +1079,7 @@ function pairablesOf(positions, guardPartitions) {
963
1079
  },
964
1080
  ];
965
1081
  }
966
- const drawn = guardPartitions.find(partition => isDeepStrictEqual(partition.segments, position.segments));
1082
+ const drawn = guardPartitions.find(partition => deepEqual(partition.segments, position.segments));
967
1083
  if (drawn === undefined) {
968
1084
  return [];
969
1085
  }
@@ -1010,7 +1126,7 @@ function combine(left, right) {
1010
1126
  const rightNarrowings = narrowings(right);
1011
1127
  return narrowings(left).every(narrowing => rightNarrowings.every(other => other.before !== narrowing.before || other.tag === narrowing.tag));
1012
1128
  }
1013
- function measureRules(implementation, met, owed, combinations, plans) {
1129
+ function measureRules(implementation, met, owed, combinations, plans, fakes) {
1014
1130
  if (implementation === undefined || implementation.pipeline !== undefined) {
1015
1131
  return { status: "unavailable", reason: "not applicable" };
1016
1132
  }
@@ -1018,29 +1134,29 @@ function measureRules(implementation, met, owed, combinations, plans) {
1018
1134
  return { status: "unavailable", reason: "not measured", notRead: [implementation.behavior.name] };
1019
1135
  }
1020
1136
  const decided = decisionsWithCases(implementation);
1021
- const notRead = decided.flatMap(([decision]) => decision.kind === "decision" || (decision.kind === "rules" && ["too many", "scoped"].includes(plans.get(decision)?.kind ?? ""))
1137
+ const notRead = decided.flatMap(([decision]) => decision.kind === "decision" || (decision.kind === "rules" && plans.get(decision)?.kind === "too many")
1022
1138
  ? [decision.id]
1023
1139
  : []);
1024
- const took = (taken, decision, steps) => taken.some(item => item.decision === decision && sameSteps(item.steps, steps));
1140
+ const took = (taken, decision, way) => taken.some(item => item.decision === decision && item.within === way.within && sameSteps(item.steps, way.steps));
1025
1141
  const rules = decided.flatMap(([decision, tags]) => {
1026
1142
  const plan = plans.get(decision);
1027
- if (decision.kind !== "rules" || plan === undefined || (plan.kind === "too many" || plan.kind === "scoped")) {
1143
+ if (decision.kind !== "rules" || plan === undefined || plan.kind === "too many") {
1028
1144
  return [];
1029
1145
  }
1030
1146
  const ways = plan.kind === "finite" ? plan.reached.map(item => item.way) : plan.ways;
1031
1147
  return ways.map((way) => {
1032
1148
  const base = { decision: decision.id, way: describeWay(way) };
1033
- if (took(met, decision.id, way.steps)) {
1149
+ if (took(met, decision.id, way)) {
1034
1150
  return { ...base, status: "met" };
1035
1151
  }
1036
- if (took(owed, decision.id, way.steps)) {
1152
+ if (took(owed, decision.id, way)) {
1037
1153
  return { ...base, status: "answer owed" };
1038
1154
  }
1039
1155
  return plan.kind === "finite"
1040
1156
  ? { ...base, status: "gap" }
1041
1157
  : {
1042
1158
  ...base,
1043
- ...unmetStatus(tags.map(tag => feasibilityOf(way, scopeOf(implementation, tag), undefined, combinations))),
1159
+ ...unmetStatus(tags.map(tag => wayFeasibility(way, implementation, tag, decision, combinations, fakes))),
1044
1160
  };
1045
1161
  });
1046
1162
  });
@@ -1051,7 +1167,7 @@ function measureRules(implementation, met, owed, combinations, plans) {
1051
1167
  ? { status: "unavailable", reason: "not measured", notRead }
1052
1168
  : { status: "partial", rules, notRead };
1053
1169
  }
1054
- function measureArms(implementation, met, owed, combinations, plans) {
1170
+ function measureArms(implementation, met, owed, combinations, plans, fakes) {
1055
1171
  if (implementation === undefined || implementation.pipeline !== undefined) {
1056
1172
  return { status: "unavailable", reason: "not applicable" };
1057
1173
  }
@@ -1059,20 +1175,20 @@ function measureArms(implementation, met, owed, combinations, plans) {
1059
1175
  return { status: "unavailable", reason: "not measured", notRead: [implementation.behavior.name] };
1060
1176
  }
1061
1177
  const decided = decisionsWithCases(implementation);
1062
- const notRead = decided.flatMap(([decision]) => decision.kind === "decision" || (decision.kind === "rules" && ["too many", "scoped"].includes(plans.get(decision)?.kind ?? ""))
1178
+ const notRead = decided.flatMap(([decision]) => decision.kind === "decision" || (decision.kind === "rules" && plans.get(decision)?.kind === "too many")
1063
1179
  ? [decision.id]
1064
1180
  : []);
1065
1181
  const took = (taken, decision, guard, arm) => taken.some(item => item.decision === decision && item.guard === guard && item.arm === arm);
1066
1182
  const arms = decided.flatMap(([decision, tags]) => {
1067
1183
  const plan = plans.get(decision);
1068
- if (decision.kind !== "rules" || plan === undefined || (plan.kind === "too many" || plan.kind === "scoped")) {
1184
+ if (decision.kind !== "rules" || plan === undefined || plan.kind === "too many") {
1069
1185
  return [];
1070
1186
  }
1071
1187
  const ways = plan.kind === "finite"
1072
1188
  ? plan.reached.map(({ way }) => ({ way, feasibility: { kind: "feasible" } }))
1073
1189
  : tags.flatMap(tag => plan.ways.map(way => ({
1074
1190
  way,
1075
- feasibility: feasibilityOf(way, scopeOf(implementation, tag), undefined, combinations),
1191
+ feasibility: wayFeasibility(way, implementation, tag, decision, combinations, fakes),
1076
1192
  })));
1077
1193
  const through = (index, arm) => ways.filter(({ way }) => decision.expression !== undefined
1078
1194
  ? way.choices?.some(choice => choice.condition === decision.guards[index]?.condition && choice.outcome === (arm === "holds"))
@@ -1143,7 +1259,7 @@ function openDecisionIn(implementation, error) {
1143
1259
  ? error.variant
1144
1260
  : `${error.behavior}: ${error.variant}`;
1145
1261
  }
1146
- function externalsIn(implementation) {
1262
+ export function externalsIn(implementation) {
1147
1263
  if (implementation === undefined) {
1148
1264
  return [];
1149
1265
  }
@@ -1154,6 +1270,373 @@ function externalsIn(implementation) {
1154
1270
  ? []
1155
1271
  : implementation.pipeline.flatMap(stage => externalsIn(stage));
1156
1272
  }
1273
+ const searches = new WeakMap();
1274
+ const tableIds = new WeakMap();
1275
+ let tableCount = 0;
1276
+ const IMPOSSIBLE = Symbol("an answer the dependency's contract refuses");
1277
+ function searchedWays(implementation, tag, decision, combinations, fakes = []) {
1278
+ const definition = implementation.behavior;
1279
+ // Keyed by the tables themselves, not the array holding them, which every check builds anew.
1280
+ if (!tableIds.has(definition))
1281
+ tableIds.set(definition, ++tableCount);
1282
+ const key = `${tableIds.get(definition)}\u0000${tag}\u0000${combinations}\u0000${fakes.map(table => {
1283
+ if (!tableIds.has(table))
1284
+ tableIds.set(table, ++tableCount);
1285
+ return tableIds.get(table);
1286
+ }).join(",")}`;
1287
+ const cached = searches.get(decision)?.get(key);
1288
+ if (cached !== undefined)
1289
+ return cached;
1290
+ const answering = Object.fromEntries(fakes.map(table => [table.dependency, answerFrom(table)]));
1291
+ const rules = Object.values(implementation.cases).flatMap(item => item.kind === "rules" ? item.guards.map(guard => guard.condition) : []);
1292
+ const values = Object.entries(definition.dependencies).filter(([, declared]) => declared.takes === "nothing");
1293
+ const expression = decision.expression;
1294
+ // Only the fields the ways turn on are tried, the rest held at a placeholder,
1295
+ // where no invariant of the case relates the two.
1296
+ const variant = definition.input.variants[tag];
1297
+ const turned = expression === undefined ? undefined : fieldsTurnedOn(expression, argumentMatters(definition, variant.shape));
1298
+ const caseRules = [...variant.invariants, ...definition.input.invariants];
1299
+ const projected = turned !== undefined && caseRules.every(rule => pathsRead(rule).every(path => path.length > 0 && turned.has(path[0])))
1300
+ ? object(Object.fromEntries(Object.entries(variant.shape).filter(([key]) => turned.has(key))))
1301
+ : undefined;
1302
+ const placeholder = definition.input.placeholderFor(tag);
1303
+ const inputSchema = projected ?? definition.input;
1304
+ const schema = values.length === 0
1305
+ ? inputSchema
1306
+ : object({ input: inputSchema, deps: object(Object.fromEntries(values.map(([name, declared]) => [name, declared.output]))) });
1307
+ const raw = domainOf(schema, combinations, constantsOf(rules));
1308
+ const filled = (input) => (projected === undefined ? input : { ...placeholder, ...input, [definition.input.discriminant]: tag });
1309
+ const domain = {
1310
+ exhaustive: raw.exhaustive,
1311
+ values: raw.values.map(value => (values.length === 0 ? filled(value) : { ...value, input: filled(value.input) })),
1312
+ };
1313
+ const calls = expression === undefined ? [] : callsIn(expression);
1314
+ const inputOf = (candidate) => (values.length === 0 ? candidate : candidate.input);
1315
+ const standOf = (candidate) => (values.length === 0 ? undefined : candidate.deps);
1316
+ // Each input also asks every call what a fake row asks, where the argument
1317
+ // reads the input, so an answer a fake gives is reached.
1318
+ const asking = (candidate) => calls.flatMap(call => (fakes.find(table => table.dependency === call.dependency)?.rows ?? []).flatMap(([asked]) => {
1319
+ const written = writtenArgument(inputOf(candidate), call.input, asked);
1320
+ return written === undefined ? [] : [values.length === 0 ? written : { ...candidate, input: written }];
1321
+ }));
1322
+ const askingMore = (candidate) => askingTogether(inputOf(candidate), calls, dependency => (fakes.find(table => table.dependency === dependency)?.rows ?? []).map(([asked]) => asked))
1323
+ .map(written => (values.length === 0 ? written : { ...candidate, input: written }));
1324
+ const candidates = [...domain.values, ...domain.values.flatMap(asking), ...(calls.length < 2 ? [] : domain.values.flatMap(askingMore))].filter(candidate => tagOf(definition.input, inputOf(candidate)) === tag);
1325
+ const taken = [];
1326
+ const witnessed = [];
1327
+ const possible = [];
1328
+ const reached = [];
1329
+ const note = (ways, way) => {
1330
+ if (!ways.some(item => item.within === way.within && sameSteps(item.steps, way.steps)))
1331
+ ways.push(way);
1332
+ };
1333
+ for (const candidate of candidates) {
1334
+ const traced = traceSync(implementation, inputOf(candidate), { ...answering, ...standOf(candidate) });
1335
+ // A run that fails took the way it failed on: a row there shows the failure.
1336
+ if (traced.ended !== true && traced.error === undefined)
1337
+ continue;
1338
+ for (const comparison of traced.comparisons) {
1339
+ witnessed.push({ comparison, given: inputOf(candidate), ...(standOf(candidate) === undefined ? {} : { with: standOf(candidate) }) });
1340
+ }
1341
+ for (const way of [...(traced.way === undefined ? [] : [traced.way]), ...traced.iterations]) {
1342
+ if (!taken.some(item => item.way.within === way.within && sameSteps(item.way.steps, way.steps))) {
1343
+ taken.push({ way, given: inputOf(candidate), ...(standOf(candidate) === undefined ? {} : { with: standOf(candidate) }) });
1344
+ }
1345
+ }
1346
+ }
1347
+ // Every answer the contract allows: one answer for each dependency called, so
1348
+ // the runs are every answer only where each is called at one place, not in an
1349
+ // iteration.
1350
+ const called = [...new Set(calls.map(call => call.dependency))];
1351
+ const answers = called.map(name => {
1352
+ const declared = Object.hasOwn(definition.dependencies, name) ? definition.dependencies[name] : undefined;
1353
+ const bound = expression === undefined ? undefined : answersOf(expression).find(answer => answer.dependency === name)?.schema;
1354
+ if (declared?.takes !== "input")
1355
+ return { values: [], exhaustive: false };
1356
+ return domainOf(bound === undefined ? declared.output : answerSchema(declared.output, bound), combinations);
1357
+ });
1358
+ const once = called.every(name => calls.filter(call => call.dependency === name).length === 1) &&
1359
+ (expression === undefined || iterationsOf(expression).every(iteration => callsIn(iteration.body).length === 0));
1360
+ let exhaustive = domain.exhaustive && answers.every(answer => answer.exhaustive) && once;
1361
+ let budget = combinations;
1362
+ const assignments = function* (index, chosen) {
1363
+ if (index === answers.length) {
1364
+ yield chosen;
1365
+ return;
1366
+ }
1367
+ for (const value of answers[index].values)
1368
+ yield* assignments(index + 1, [...chosen, value]);
1369
+ };
1370
+ search: for (const candidate of domain.values.filter(value => tagOf(definition.input, inputOf(value)) === tag)) {
1371
+ for (const assignment of assignments(0, [])) {
1372
+ if (--budget < 0) {
1373
+ exhaustive = false;
1374
+ break search;
1375
+ }
1376
+ const answer = Object.fromEntries(called.map((name, index) => [name, (argument) => {
1377
+ const declared = definition.dependencies[name];
1378
+ const injected = declared.takes === "input" ? declared.injected?.behavior : undefined;
1379
+ if (injected !== undefined && brokenEnsures(injected, argument, assignment[index]) !== undefined)
1380
+ throw IMPOSSIBLE;
1381
+ return assignment[index];
1382
+ }]));
1383
+ const traced = traceSync(implementation, inputOf(candidate), { ...answer, ...standOf(candidate) });
1384
+ if (traced.error === IMPOSSIBLE)
1385
+ continue;
1386
+ // A run answering a promise was not followed to its end.
1387
+ if (traced.ended !== true && traced.error === undefined) {
1388
+ exhaustive = false;
1389
+ continue;
1390
+ }
1391
+ for (const way of [...(traced.way === undefined ? [] : [traced.way]), ...traced.iterations])
1392
+ note(possible, way);
1393
+ reached.push(...traced.comparisons);
1394
+ }
1395
+ }
1396
+ for (const item of taken)
1397
+ note(possible, item.way);
1398
+ const searched = { taken, possible, reached, witnessed, exhaustive };
1399
+ const byTag = searches.get(decision) ?? new Map();
1400
+ byTag.set(key, searched);
1401
+ searches.set(decision, byTag);
1402
+ return searched;
1403
+ }
1404
+ function searchedWitness(way, implementation, tag, decision, combinations, fakes) {
1405
+ return searchedWays(implementation, tag, decision, combinations, fakes).taken
1406
+ .find(item => item.way.within === way.within && sameSteps(item.way.steps, way.steps));
1407
+ }
1408
+ // Inputs written so two or more calls are each asked what one of their fake
1409
+ // rows asks, the later written over the earlier where they share a field, so a
1410
+ // way that turns on several dependencies' answers is reached. Asking one call
1411
+ // is left to the callers; the rows stop at ASKED_TOGETHER_LIMIT.
1412
+ const ASKED_TOGETHER_LIMIT = 256;
1413
+ function askingTogether(input, calls, askedBy) {
1414
+ const found = [];
1415
+ let level = [{ value: input, after: -1 }];
1416
+ for (let size = 1; size <= calls.length && found.length < ASKED_TOGETHER_LIMIT; size++) {
1417
+ const next = [];
1418
+ grow: for (const { value, after } of level) {
1419
+ for (let index = after + 1; index < calls.length; index++) {
1420
+ for (const asked of askedBy(calls[index].dependency)) {
1421
+ if (next.length >= ASKED_TOGETHER_LIMIT)
1422
+ break grow;
1423
+ const written = writtenArgument(value, calls[index].input, asked);
1424
+ if (written !== undefined)
1425
+ next.push({ value: written, after: index });
1426
+ }
1427
+ }
1428
+ }
1429
+ if (size >= 2)
1430
+ for (const item of next)
1431
+ if (found.length < ASKED_TOGETHER_LIMIT)
1432
+ found.push(item.value);
1433
+ level = next;
1434
+ }
1435
+ return found;
1436
+ }
1437
+ // A way through the body of an iteration over a field is taken only by an input
1438
+ // whose array holds an element, so the way also asks for one.
1439
+ function withEntry(way, entered = []) {
1440
+ const values = way.within?.values;
1441
+ const position = isTerm(values) ? positionData(values) : undefined;
1442
+ if (position === undefined || position.measure !== "value")
1443
+ return entered.length === 0 ? way : { ...way, steps: [...way.steps, ...entered] };
1444
+ const holdsOne = { kind: "compare", operator: ">=", left: positionTerm(position.path, "length"), right: 1 };
1445
+ return { ...way, steps: [...way.steps, ...entered, { distinction: holdsOne, outcome: true }] };
1446
+ }
1447
+ // Whether some row could take a way: a way reading a value the model computes
1448
+ // (`localsOf`'s opaque locals) is settled by running the case's inputs through
1449
+ // the decision, as far as they are few enough to try.
1450
+ function wayFeasibility(way, implementation, tag, decision, combinations, fakes) {
1451
+ const settled = way.steps.find(step => step.distinction.kind !== "match" && termPaths(step.distinction).length === 0 && holds(step.distinction, {}) !== step.outcome);
1452
+ if (settled !== undefined)
1453
+ return { kind: "infeasible", reason: "値を読まない条件で、この結果にならない" };
1454
+ // An iteration entered several ways is reachable where any of them is.
1455
+ const entries = (way.entered ?? [[]]).map(entered => {
1456
+ const entering = withEntry(way, entered);
1457
+ return feasibilityOf(entering, scopeOf(implementation, tag, decision, entering), undefined, combinations);
1458
+ });
1459
+ const found = entries.find(item => item.kind === "feasible") ?? entries.find(item => item.kind === "undecided") ?? entries[0];
1460
+ if (found.kind === "feasible" && way.entryUnlisted === true)
1461
+ return { kind: "undecided", reason: "反復に入る道筋が多すぎて、すべては調べきれない" };
1462
+ const expression = decision.expression;
1463
+ if (found.kind !== "feasible" || expression === undefined)
1464
+ return found;
1465
+ const read = opaqueRead(way, decision);
1466
+ if (read.length === 0)
1467
+ return found;
1468
+ const outside = outsideRange(way, implementation, tag, decision);
1469
+ if (outside !== undefined)
1470
+ return { kind: "infeasible", reason: outside };
1471
+ const searched = searchedWays(implementation, tag, decision, combinations, fakes);
1472
+ if (searched.possible.some(item => item.within === way.within && sameSteps(item.steps, way.steps)))
1473
+ return found;
1474
+ if (searched.exhaustive) {
1475
+ return { kind: "infeasible", reason: "入力の全値を試し、この道筋を通る値がない" };
1476
+ }
1477
+ const factored = factoredSearch(way, implementation, tag, decision, combinations);
1478
+ if (factored === "found")
1479
+ return found;
1480
+ if (factored === "none")
1481
+ return { kind: "infeasible", reason: "積が定数になる因数の組をすべて試し、この道筋を通るものがない" };
1482
+ return { kind: "undecided", reason: `${[...new Set(read.map(localLabel))].join("・")}はモデルが計算する値で、試した入力ではこの道筋を通らない` };
1483
+ }
1484
+ // Whether what a dependency is asked may change what a way takes: unless its
1485
+ // ensures say nothing of the argument and it takes every value the input field
1486
+ // asked of it may hold.
1487
+ function argumentMatters(definition, shape) {
1488
+ const plain = new Set(["string", "boolean", "number", "integer"]);
1489
+ return (name, argument) => {
1490
+ const declared = Object.hasOwn(definition.dependencies, name) ? definition.dependencies[name] : undefined;
1491
+ if (declared?.takes !== "input" || (declared.injected?.behavior.ensures.length ?? 0) > 0)
1492
+ return true;
1493
+ const position = isTerm(argument) ? positionData(argument) : undefined;
1494
+ if (position === undefined || position.measure !== "value" || position.path.length !== 1 || !Object.hasOwn(shape, position.path[0]))
1495
+ return true;
1496
+ const field = shape[position.path[0]], taken = declared.input;
1497
+ return !(plain.has(field.kind) && field.kind === taken.kind && field.invariants.length === 0 && taken.invariants.length === 0);
1498
+ };
1499
+ }
1500
+ // What a bind holds, by its local's name.
1501
+ function boundValueOf(template, name) {
1502
+ const node = nodeOf(template);
1503
+ if (node?.kind === "bind" && node.name === name)
1504
+ return node.value;
1505
+ for (const child of childrenOf(template)) {
1506
+ const found = boundValueOf(child, name);
1507
+ if (found !== undefined)
1508
+ return found;
1509
+ }
1510
+ return undefined;
1511
+ }
1512
+ // A step comparing a computed sum, difference or product with a constant, where
1513
+ // the bounds of what it reads leave it no value that takes the step's outcome
1514
+ // (two inputs of at least 2 never multiply to less than 4): why, or undefined.
1515
+ function outsideRange(way, implementation, tag, decision) {
1516
+ const expression = decision.expression;
1517
+ if (expression === undefined)
1518
+ return undefined;
1519
+ const scope = scopeOf(implementation, tag, decision, way);
1520
+ for (const step of way.steps) {
1521
+ const rule = step.distinction;
1522
+ if (rule.kind !== "compare" || typeof step.outcome !== "boolean")
1523
+ continue;
1524
+ const [term, constant, operator] = isTerm(rule.left) && !isTerm(rule.right)
1525
+ ? [rule.left, rule.right, rule.operator]
1526
+ : isTerm(rule.right) && !isTerm(rule.left) ? [rule.right, rule.left, mirroredOperator(rule.operator)] : [undefined, undefined, rule.operator];
1527
+ const position = term === undefined ? undefined : positionData(term);
1528
+ if (position === undefined || position.measure !== "value" || position.path.length !== 1)
1529
+ continue;
1530
+ const value = boundValueOf(expression, position.path[0]);
1531
+ if (value === undefined)
1532
+ continue;
1533
+ const range = rangeOf(value, scope, way.steps.filter(other => other !== step));
1534
+ let bound;
1535
+ try {
1536
+ bound = fractionOf(constant);
1537
+ }
1538
+ catch {
1539
+ continue;
1540
+ }
1541
+ if (range === undefined)
1542
+ continue;
1543
+ const meets = (holdsIt) => {
1544
+ const wanted = holdsIt ? operator : negated[operator];
1545
+ const { low, high } = range;
1546
+ switch (wanted) {
1547
+ case "<": return low.comparedTo(bound) < 0;
1548
+ case "<=": return low.comparedTo(bound) <= 0;
1549
+ case ">": return high.comparedTo(bound) > 0;
1550
+ case ">=": return high.comparedTo(bound) >= 0;
1551
+ case "==": return low.comparedTo(bound) <= 0 && high.comparedTo(bound) >= 0;
1552
+ case "!=": return !(low.comparedTo(bound) === 0 && high.comparedTo(bound) === 0);
1553
+ }
1554
+ };
1555
+ if (!meets(step.outcome)) {
1556
+ return `${localLabel(position.path[0])}が取りうる範囲(${String(range.low)}〜${String(range.high)})では、この結果にならない`;
1557
+ }
1558
+ }
1559
+ return undefined;
1560
+ }
1561
+ const negated = { "<": ">=", "<=": ">", ">": "<=", ">=": "<", "==": "!=", "!=": "==" };
1562
+ function mirroredOperator(operator) {
1563
+ return { "<": ">", "<=": ">=", ">": "<", ">=": "<=", "==": "==", "!=": "!=" }[operator];
1564
+ }
1565
+ // A way whose step holds that a product of two integer inputs equals a whole
1566
+ // number N other than 0 is taken only by inputs whose two factors are a
1567
+ // divisor pair of N. Those pairs, with every value of the other fields the ways
1568
+ // turn on, are every input that could take it: "found" where one does, "none"
1569
+ // where none does and the rest were all tried, undefined where it cannot tell.
1570
+ const FACTOR_LIMIT = 10 ** 12;
1571
+ function factoredSearch(way, implementation, tag, decision, combinations) {
1572
+ const found = factoredWitness(way, implementation, tag, decision, combinations);
1573
+ return found === undefined ? undefined : found.given !== undefined ? "found" : found.exhaustive ? "none" : undefined;
1574
+ }
1575
+ function factoredWitness(way, implementation, tag, decision, combinations) {
1576
+ const expression = decision.expression;
1577
+ const definition = implementation.behavior;
1578
+ if (expression === undefined || Object.keys(definition.dependencies).length > 0)
1579
+ return undefined;
1580
+ for (const step of way.steps) {
1581
+ const rule = step.distinction;
1582
+ if (rule.kind !== "compare" || step.outcome !== (rule.operator === "==") || (rule.operator !== "==" && rule.operator !== "!="))
1583
+ continue;
1584
+ const [term, constant] = isTerm(rule.left) ? [rule.left, rule.right] : [rule.right, rule.left];
1585
+ const position = isTerm(term) ? positionData(term) : undefined;
1586
+ if (position === undefined || position.measure !== "value" || position.path.length !== 1 || typeof constant !== "number" || !Number.isSafeInteger(constant) || constant === 0 || Math.abs(constant) > FACTOR_LIMIT)
1587
+ continue;
1588
+ const product = nodeOf(boundValueOf(expression, position.path[0]));
1589
+ if (product?.kind !== "operation" || product.operator !== "multiply")
1590
+ continue;
1591
+ const [first, second] = [product.left, product.right].map(side => (isTerm(side) ? positionData(side) : undefined));
1592
+ const variant = definition.input.variants[tag];
1593
+ if (first === undefined || second === undefined || first.path.length !== 1 || second.path.length !== 1 || first.path[0] === second.path[0])
1594
+ continue;
1595
+ if ([first, second].some(side => side.measure !== "value" || variant.shape[side.path[0]]?.kind !== "integer"))
1596
+ continue;
1597
+ const divisors = [];
1598
+ for (let d = 1; d * d <= Math.abs(constant); d++) {
1599
+ if (constant % d === 0)
1600
+ divisors.push(d, -d, constant / d, -constant / d);
1601
+ }
1602
+ const pairs = [...new Set(divisors)].map(d => [d, constant / d]);
1603
+ const turned = fieldsTurnedOn(expression, argumentMatters(definition, variant.shape));
1604
+ const others = Object.fromEntries(Object.entries(variant.shape).filter(([key]) => (turned === undefined || turned.has(key)) && key !== first.path[0] && key !== second.path[0]));
1605
+ const caseRules = [...variant.invariants, ...definition.input.invariants];
1606
+ const separate = turned !== undefined && caseRules.every(rule => pathsRead(rule).every(path => path.length > 0 && turned.has(path[0])));
1607
+ const rest = domainOf(object(others), combinations);
1608
+ const placeholder = definition.input.placeholderFor(tag);
1609
+ let tried = 0;
1610
+ let refused = false;
1611
+ for (const [a, b] of pairs) {
1612
+ for (const other of rest.values) {
1613
+ if (++tried > combinations)
1614
+ return { exhaustive: false };
1615
+ const given = { ...placeholder, ...other, [first.path[0]]: a, [second.path[0]]: b, [definition.input.discriminant]: tag };
1616
+ if (!definition.input.parse(given).success) {
1617
+ // A pair a factor's own bounds refuse is no input. One they take, in an input refused for what else it holds, may be refused only by the placeholder: the search then proves nothing.
1618
+ if (variant.shape[first.path[0]].parse(a).success && variant.shape[second.path[0]].parse(b).success)
1619
+ refused = true;
1620
+ continue;
1621
+ }
1622
+ const traced = traceSync(implementation, given);
1623
+ if ([...(traced.way === undefined ? [] : [traced.way]), ...traced.iterations].some(taken => taken.within === way.within && sameSteps(taken.steps, way.steps)))
1624
+ return { given, exhaustive: true };
1625
+ }
1626
+ }
1627
+ return { exhaustive: rest.exhaustive && separate && !refused };
1628
+ }
1629
+ return undefined;
1630
+ }
1631
+ // The values a way reads that the model computes and no expression of the input
1632
+ // stands for.
1633
+ function opaqueRead(way, decision) {
1634
+ const expression = decision.expression;
1635
+ if (expression === undefined)
1636
+ return [];
1637
+ const opaque = new Set(localsOf(expression).filter(local => local.opaque).map(local => local.name));
1638
+ return way.steps.flatMap(step => step.distinction.kind === "match" ? [] : localRoots(step.distinction)).filter(name => opaque.has(name));
1639
+ }
1157
1640
  function unmetStatus(feasibilities) {
1158
1641
  if (feasibilities.length === 0 || feasibilities.some(item => item.kind === "feasible")) {
1159
1642
  return { status: "gap" };
@@ -1166,7 +1649,7 @@ function unmetStatus(feasibilities) {
1166
1649
  }
1167
1650
  function besideOf(definition, implementation, drawn, reachedIt) {
1168
1651
  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 => {
1652
+ const rows = reachedIt.filter(item => drawn.coordinateOf(item.comparison) !== undefined).flatMap(item => {
1170
1653
  const values = parts.map(part => part.valueOf(item.comparison.scope));
1171
1654
  return values.every(value => value !== undefined)
1172
1655
  ? [{ values, kept: holds(drawn.comparison, item.comparison.scope), given: item.given, deps: item.deps }]
@@ -1186,9 +1669,14 @@ function besideOf(definition, implementation, drawn, reachedIt) {
1186
1669
  .flatMap(parting => {
1187
1670
  const given = parts.reduce((written, part, index) => (written === undefined ? undefined : part.write(written, parting.values[index])), rows[parting.from].given);
1188
1671
  const deps = rows[parting.from].deps;
1672
+ // Writing one part can move another that reads the same field, as
1673
+ // `length($.code)` and `length(trim($.code))` both read $.code, so the
1674
+ // row is kept only where it reaches the comparison at the parting itself.
1189
1675
  const reaches = given !== undefined &&
1190
1676
  definition.input.parse(given).success &&
1191
- comparisonsReached(implementation, given, deps).some(item => item.rule === drawn.comparison);
1677
+ comparisonsReached(implementation, given, deps).some(item => item.rule === drawn.comparison &&
1678
+ drawn.coordinateOf(item) !== undefined &&
1679
+ parts.every((part, index) => part.valueOf(item.scope) === parting.values[index]));
1192
1680
  if (!reaches) {
1193
1681
  return [];
1194
1682
  }
@@ -1233,6 +1721,26 @@ function mentions(rule, target) {
1233
1721
  return false;
1234
1722
  }
1235
1723
  }
1724
+ // Whether some row could stand at a guard border point. A comparison reading a
1725
+ // value the model computes is settled by the search's runs: one reaching it at
1726
+ // the point makes it feasible, and runs of every input and answer none of which
1727
+ // do make it infeasible.
1728
+ function pointFeasibility(drawn, point, implementation, combinations, wayLimit, fakes) {
1729
+ const origin = drawn.origin;
1730
+ const expression = origin?.decision?.expression;
1731
+ if (origin === undefined || expression === undefined)
1732
+ return reachOf(drawn, point, combinations, wayLimit);
1733
+ const opaque = new Set(localsOf(expression).filter(local => local.opaque).map(local => local.name));
1734
+ const read = localRoots(drawn.comparison).filter(name => opaque.has(name));
1735
+ if (read.length === 0)
1736
+ return reachOf(drawn, point, combinations, wayLimit);
1737
+ const searched = searchedWays(implementation, origin.tag, origin.decision, combinations, fakes);
1738
+ if ([...searched.reached, ...searched.witnessed.map(item => item.comparison)].some(item => item.rule === drawn.comparison && point.contains(drawn.coordinateOf(item))))
1739
+ return [{ kind: "feasible" }];
1740
+ if (searched.exhaustive)
1741
+ return [{ kind: "infeasible", reason: "入力と依存の答えの全値を試し、この点に届く値がない" }];
1742
+ return [{ kind: "undecided", reason: `${[...new Set(read.map(localLabel))].join("・")}はモデルが計算する値で、試した入力ではこの点に届かない` }];
1743
+ }
1236
1744
  function reachOf(drawn, point, combinations, wayLimit) {
1237
1745
  const normalized = normalize(drawn.comparison);
1238
1746
  const { left, right } = drawn.comparison;
@@ -1259,6 +1767,7 @@ function reachOf(drawn, point, combinations, wayLimit) {
1259
1767
  return [{ kind: "feasible" }];
1260
1768
  }
1261
1769
  const prefixes = [];
1770
+ let unlisted = false;
1262
1771
  let followed = 0;
1263
1772
  for (const way of eachWayOf(decision)) {
1264
1773
  followed += 1;
@@ -1267,15 +1776,44 @@ function reachOf(drawn, point, combinations, wayLimit) {
1267
1776
  }
1268
1777
  const index = way.steps.findIndex(step => step.distinction === drawn.comparison);
1269
1778
  if (index !== -1) {
1270
- prefixes.push(way.steps.slice(0, index));
1779
+ // A comparison in an iteration's body is reached only through the iteration, entered and over an array that holds an element.
1780
+ for (const entered of way.entered ?? [[]]) {
1781
+ prefixes.push([...way.steps.slice(0, index), ...withEntry(way, entered).steps.slice(way.steps.length)]);
1782
+ if (way.entryUnlisted === true)
1783
+ unlisted = true;
1784
+ }
1271
1785
  }
1272
1786
  }
1787
+ // A row at the border is of the case it is drawn under.
1788
+ const inCases = (drawn.cases ?? []).map(item => ({
1789
+ distinction: { kind: "compare", operator: "==", left: positionTerm([...item.at, item.discriminant], "value"), right: item.tag },
1790
+ outcome: true,
1791
+ }));
1273
1792
  return prefixes.length === 0
1274
1793
  ? [{ kind: "feasible" }]
1275
- : prefixes.map(steps => feasibilityOf({ steps }, scope, placement, combinations));
1794
+ : prefixes.map(steps => feasibilityOf({ steps: [...steps, ...inCases] }, scope, placement, combinations))
1795
+ .map((found) => unlisted && found.kind === "feasible" ? { kind: "undecided", reason: "反復に入る道筋が多すぎて、すべては調べきれない" } : found);
1276
1796
  }
1277
- function scopeOf(implementation, tag) {
1278
- return feasibilityScope(implementation.behavior, tag);
1797
+ function scopeOf(implementation, tag, decision, way) {
1798
+ const scope = feasibilityScope(implementation.behavior, tag, decision, way?.steps ?? []);
1799
+ return way === undefined ? scope : settledBy(scope, way.steps);
1800
+ }
1801
+ // The scope with each sum field the way settles to one case read as that case,
1802
+ // so a field of the case is read with the kind it has there.
1803
+ function settledBy(scope, steps, path = []) {
1804
+ if (scope.kind !== "object")
1805
+ return scope;
1806
+ const { shape } = scope;
1807
+ let changed = false;
1808
+ const settled = Object.fromEntries(Object.entries(shape).map(([key, field]) => {
1809
+ const at = [...path, key];
1810
+ const tag = isVariantsSchema(field) ? selectedTag(field, at, steps) : undefined;
1811
+ const next = tag === undefined ? settledBy(field, steps, at) : settledBy(taggedCase(field, tag), steps, at);
1812
+ if (next !== field)
1813
+ changed = true;
1814
+ return [key, next];
1815
+ }));
1816
+ return changed ? { ...scope, shape: settled } : scope;
1279
1817
  }
1280
1818
  function coverage(all, covered, excluded = []) {
1281
1819
  const counted = all.filter(value => !excluded.includes(value));
@@ -1384,7 +1922,7 @@ const DISREGARD_COMBINATION_LIMIT = 255;
1384
1922
  // Not the combinations alone: moves are tried before a combination is known to
1385
1923
  // be one the input can hold, so the candidates tried that way are bounded too.
1386
1924
  const DISREGARD_CANDIDATE_LIMIT = 4096;
1387
- function positiveLimit(name, given, fallback) {
1925
+ export function positiveLimit(name, given, fallback) {
1388
1926
  if (given === undefined) {
1389
1927
  return fallback;
1390
1928
  }
@@ -1440,8 +1978,8 @@ async function disregardBroken(implementation, row, answered, standIns, limits)
1440
1978
  {
1441
1979
  path: instance.path,
1442
1980
  moves,
1443
- unmoved: (varied) => (isDeepStrictEqual(classified(varied), taken) &&
1444
- isDeepStrictEqual(coordinates(varied), original)) ||
1981
+ unmoved: (varied) => (deepEqual(classified(varied), taken) &&
1982
+ deepEqual(coordinates(varied), original)) ||
1445
1983
  (classified(varied).length === 0 && coordinates(varied).every(values => values.length === 0)),
1446
1984
  },
1447
1985
  ];
@@ -1468,7 +2006,7 @@ async function disregardBroken(implementation, row, answered, standIns, limits)
1468
2006
  return move === undefined ? axis.unmoved(varied) : move.reached(varied);
1469
2007
  });
1470
2008
  return holds &&
1471
- isDeepStrictEqual(readKept(varied), keptOriginally) &&
2009
+ deepEqual(readKept(varied), keptOriginally) &&
1472
2010
  definition.input.parse(varied).success
1473
2011
  ? [{ choice, varied }]
1474
2012
  : [];
@@ -1490,7 +2028,7 @@ async function disregardBroken(implementation, row, answered, standIns, limits)
1490
2028
  };
1491
2029
  }
1492
2030
  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) }));
2031
+ const outcome = await runTraced(implementation, varied, standIns).then((traced) => deepEqual(traced.execution, answered) ? undefined : { text: "its answer changed" }, (error) => ({ text: "it threw", error: error instanceof Error ? error.message : String(error) }));
1494
2032
  if (outcome !== undefined) {
1495
2033
  const moved = axes.flatMap((axis, index) => {
1496
2034
  const move = choice[index];
@@ -1513,45 +2051,47 @@ async function disregardBroken(implementation, row, answered, standIns, limits)
1513
2051
  // the invariants relating finite positions keep can take is excluded, like
1514
2052
  // one a rule on the position alone refuses.
1515
2053
  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("."))) {
2054
+ if (position.kind !== "divided") {
1518
2055
  return position;
1519
2056
  }
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
2057
  const refused = position.classes.filter(className => {
1537
2058
  if (position.excluded.includes(className)) {
1538
2059
  return true;
1539
2060
  }
1540
- const at = coordinate(className);
1541
- return at !== undefined && refusedJointly(scope, at.path, at.value, combinations);
2061
+ const at = finiteCoordinateOf(definition, position, className);
2062
+ return at !== undefined && refusedJointly(at.scope, at.path, at.value, combinations);
1542
2063
  });
1543
2064
  return refused.length === position.excluded.length ? position : { ...position, excluded: refused };
1544
2065
  }
2066
+ // Where a class of a boolean, an enum or a sum field directly under an input
2067
+ // case sits for the joint invariant search: the case's scope, the field's keys
2068
+ // in it and the value the class stands for.
2069
+ export function finiteCoordinateOf(definition, position, className) {
2070
+ const [head, ...rest] = position.segments;
2071
+ if (head === undefined || rest.length === 0 || !rest.every(step => step.startsWith("."))) {
2072
+ return undefined;
2073
+ }
2074
+ const tag = head.slice(1);
2075
+ const scope = feasibilityScope(definition, tag);
2076
+ const keys = rest.map(step => step.slice(1));
2077
+ const field = schemaAtPath(scope, keys);
2078
+ switch (field?.kind) {
2079
+ case "boolean":
2080
+ return { tag, scope, path: keys, value: className === "true" };
2081
+ case "enum":
2082
+ return { tag, scope, path: keys, value: className };
2083
+ case "variants":
2084
+ return { tag, scope, path: [...keys, field.discriminant], value: className };
2085
+ default:
2086
+ return undefined;
2087
+ }
2088
+ }
1545
2089
  function plansOf(implementation, combinations, wayLimit) {
1546
2090
  const plans = new Map();
1547
2091
  for (const [decision, tags] of implementation === undefined ? [] : decisionsWithCases(implementation)) {
1548
2092
  if (decision.kind !== "rules") {
1549
2093
  continue;
1550
2094
  }
1551
- if (hasScopedChoices(decision.expression)) {
1552
- plans.set(decision, { kind: "scoped" });
1553
- continue;
1554
- }
1555
2095
  const reaches = tags.map(tag => ({
1556
2096
  tag,
1557
2097
  reached: decision.expression !== undefined ? undefined : finiteReach(decision, scopeOf(implementation, tag), combinations, [[implementation.behavior.input.discriminant]]),