tla-ts 0.0.8 → 0.0.9-dev.331c500

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 (63) hide show
  1. package/README.md +23 -0
  2. package/dist/compile.cjs +23 -0
  3. package/dist/compile.js +23 -0
  4. package/dist/deciders.cjs +15 -15
  5. package/dist/deciders.js +48 -48
  6. package/dist/index.cjs +1 -1
  7. package/dist/index.d.cts +27 -9
  8. package/dist/index.d.ts +27 -9
  9. package/dist/index.js +1 -1
  10. package/dist/parallel-worker.cjs +1 -1
  11. package/dist/parallel-worker.js +1 -1
  12. package/dist/prove.cjs +30 -30
  13. package/dist/prove.js +32 -32
  14. package/dist/run.cjs +28 -28
  15. package/dist/run.js +31 -31
  16. package/dist/tlapm.cjs +2 -2
  17. package/dist/tlapm.js +1 -1
  18. package/dist/transfer.cjs +30 -33
  19. package/dist/transfer.js +30 -33
  20. package/dist/worker.cjs +4 -4
  21. package/dist/worker.js +4 -4
  22. package/package.json +3 -1
  23. package/src/check.ts +77 -46
  24. package/src/cli/options.ts +2 -1
  25. package/src/cli/tlc.ts +26 -8
  26. package/src/cli/typescript.ts +26 -0
  27. package/src/codegen.ts +0 -5
  28. package/src/dependencies.ts +348 -24
  29. package/src/environment.ts +27 -11
  30. package/src/errors.ts +15 -0
  31. package/src/evaluate.ts +188 -712
  32. package/src/instances.ts +67 -6
  33. package/src/lexer.ts +140 -51
  34. package/src/liveness-checker.ts +6 -3
  35. package/src/liveness.ts +8 -18
  36. package/src/parallel-worker.ts +7 -5
  37. package/src/parallel.ts +18 -9
  38. package/src/prover/smt/solver/solver.ts +31 -27
  39. package/src/sany/generator.ts +9 -7
  40. package/src/sany/linter.ts +30 -21
  41. package/src/search.ts +48 -32
  42. package/src/spec-description.ts +1 -1
  43. package/src/successors.ts +6 -12
  44. package/src/symmetry.ts +32 -143
  45. package/src/tlc/fingerprint.ts +69 -116
  46. package/src/tlc/order.ts +27 -48
  47. package/src/tlc/replay.ts +1 -1
  48. package/src/typescript/actions.ts +494 -0
  49. package/src/typescript/collections.ts +615 -0
  50. package/src/typescript/compile.ts +70 -0
  51. package/src/typescript/context.ts +106 -0
  52. package/src/typescript/emit.ts +122 -0
  53. package/src/typescript/expressions.ts +508 -0
  54. package/src/typescript/formula.ts +160 -0
  55. package/src/typescript/functions.ts +295 -0
  56. package/src/typescript/model.ts +164 -0
  57. package/src/typescript/names.ts +116 -0
  58. package/src/typescript/program.ts +51 -0
  59. package/src/typescript/properties.ts +142 -0
  60. package/src/typescript/scope.ts +117 -0
  61. package/src/typescript/steps.ts +175 -0
  62. package/src/typescript/types.ts +178 -0
  63. package/src/values.ts +151 -85
@@ -21,36 +21,40 @@ export const checkSmt = (text: string, options: DecideOptions): SmtCheck => {
21
21
  const manager = new AstManager(
22
22
  new ResourceLimit(Date.now() + options.timeLimitMs, options.signal),
23
23
  );
24
- // combined_solver gives each assertion to the incremental smt kernel as well, which rewrites it
25
- // when it is asserted and keeps it, though check-sat then runs the tactic on the assertions. The
26
- // kernel's model finder counts a step of the resource limit when it is made, and
27
- // solver::assert_expr counts one for each assertion.
28
- const incremental = new AssertedFormulas(manager);
29
- manager.limit.inc();
30
- const problem = parseSmtlib(text, manager, (assertion) => {
24
+ // The limit stops watching the collector however the check ends, as an unsupported input or a
25
+ // problem without check-sat ends it early.
26
+ try {
27
+ // combined_solver gives each assertion to the incremental smt kernel as well, which rewrites it
28
+ // when it is asserted and keeps it, though check-sat then runs the tactic on the assertions. The
29
+ // kernel's model finder counts a step of the resource limit when it is made, and
30
+ // solver::assert_expr counts one for each assertion.
31
+ const incremental = new AssertedFormulas(manager);
31
32
  manager.limit.inc();
32
- incremental.assertExpr(assertion);
33
- });
34
- if (!problem.hasCheckSat) return { verdict: "unknown", numInstances: 0 };
35
- const goal = applyUfniaTactic(manager, problem.assertions);
36
- // and_then runs smt_tactic only on a goal that the preprocessing left undecided.
37
- if (goal.isInconsistent || goal.forms.size === 0) {
33
+ const problem = parseSmtlib(text, manager, (assertion) => {
34
+ manager.limit.inc();
35
+ incremental.assertExpr(assertion);
36
+ });
37
+ if (!problem.hasCheckSat) return { verdict: "unknown", numInstances: 0 };
38
+ const goal = applyUfniaTactic(manager, problem.assertions);
39
+ // and_then runs smt_tactic only on a goal that the preprocessing left undecided.
40
+ if (goal.isInconsistent || goal.forms.size === 0) {
41
+ return { verdict: goal.isInconsistent ? "unsat" : "sat", numInstances: 0 };
42
+ }
43
+ // smt_tactic makes the context, which makes its asserted formulas first, and asserts the goal.
44
+ // setup_context then makes the theories, before the formulas are reduced.
45
+ const asserted = new AssertedFormulas(manager);
46
+ const context = new Context(manager, { isMbqi: true, relevancyLevel: 2 });
47
+ for (const assertion of goal.forms.items) asserted.assertExpr(assertion);
48
+ context.setupContext();
49
+ context.internalizeAssertions(asserted);
50
+ const result = context.search();
51
+ return {
52
+ verdict: result === L_FALSE ? "unsat" : result === L_TRUE ? "sat" : "unknown",
53
+ numInstances: context.qmanager.getNumInstances(),
54
+ };
55
+ } finally {
38
56
  manager.limit.release();
39
- return { verdict: goal.isInconsistent ? "unsat" : "sat", numInstances: 0 };
40
57
  }
41
- // smt_tactic makes the context, which makes its asserted formulas first, and asserts the goal.
42
- // setup_context then makes the theories, before the formulas are reduced.
43
- const asserted = new AssertedFormulas(manager);
44
- const context = new Context(manager, { isMbqi: true, relevancyLevel: 2 });
45
- for (const assertion of goal.forms.items) asserted.assertExpr(assertion);
46
- context.setupContext();
47
- context.internalizeAssertions(asserted);
48
- const result = context.search();
49
- manager.limit.release();
50
- return {
51
- verdict: result === L_FALSE ? "unsat" : result === L_TRUE ? "sat" : "unknown",
52
- numInstances: context.qmanager.getNumInstances(),
53
- };
54
58
  };
55
59
 
56
60
  // Throws SmtParseError on malformed input. Input outside the subset the solver supports is unknown,
@@ -1783,11 +1783,15 @@ export const generateSanySpecification = (
1783
1783
  (params.length === 0 || params[params.length - 1].arity === 0);
1784
1784
  if (existing.letInLevel !== state.curLevel) {
1785
1785
  addError(location, `Recursive operator ${name} defined at wrong LET/IN level.`);
1786
- } else if (!isMatching) {
1787
- addError(
1788
- location,
1789
- `Definition of ${existing.name} has different arity than its RECURSIVE declaration.`,
1790
- );
1786
+ } else {
1787
+ if (!isMatching) {
1788
+ addError(
1789
+ location,
1790
+ `Definition of ${existing.name} has different arity than its RECURSIVE declaration.`,
1791
+ );
1792
+ }
1793
+ // SANY sets the parameters before it analyzes the body.
1794
+ existing.params = params;
1791
1795
  }
1792
1796
  } else if (existing !== undefined) {
1793
1797
  addError(location, `Operator ${name} already defined or declared.`);
@@ -1805,8 +1809,6 @@ export const generateSanySpecification = (
1805
1809
  !existing.isDefined &&
1806
1810
  existing.letInLevel === state.curLevel
1807
1811
  ) {
1808
- // OpDefNode.setParams keeps the arity of the RECURSIVE declaration.
1809
- existing.params = params;
1810
1812
  existing.weights = params.map(() => 0);
1811
1813
  existing.maxLevels = params.map(() => TEMPORAL_LEVEL);
1812
1814
  existing.isLeibnizArg = params.map(() => true);
@@ -74,13 +74,14 @@ const getFieldName = (pair: OpApplNode) => {
74
74
  return name?.kind === "String" ? name : undefined;
75
75
  };
76
76
 
77
- // Records.sameDomain.
78
- const isSameDomain = (record: OpApplNode, other: OpApplNode) => {
79
- if (record === other) return true;
80
- if (record.operands.length !== other.operands.length) return false;
81
- const names = new Set(getFieldPairs(other).map((pair) => getFieldName(pair)?.value));
82
- return getFieldPairs(record).every((pair) => names.has(getFieldName(pair)?.value));
83
- };
77
+ // Records.sameDomain, given that SANY rejects a record with two fields of the same name.
78
+ const getDomain = (record: OpApplNode) =>
79
+ JSON.stringify([
80
+ record.operands.length,
81
+ ...getFieldPairs(record)
82
+ .map((pair) => getFieldName(pair)?.value)
83
+ .sort(),
84
+ ]);
84
85
 
85
86
  // ModuleNode.getExtendedModuleSet(true).
86
87
  const getExtendedModules = (module: ModuleNode, found = new Set<ModuleNode>()) => {
@@ -94,19 +95,9 @@ const getExtendedModules = (module: ModuleNode, found = new Set<ModuleNode>()) =
94
95
 
95
96
  // Linter.lintRecords: the warnings for the records of a module.
96
97
  export const lintSanyModule = (module: ModuleNode): SanyMessage[] => {
97
- const allRecords = [
98
- ...[...getExtendedModules(module)].flatMap((extended) => extended.records),
99
- ...module.records,
100
- ];
101
- return module.records.flatMap((record) => {
102
- // Linter checks the field's value, the record's fields and the fields of every record with the
103
- // same domain, which includes the record itself.
104
- const isExempt = allRecords
105
- .filter((other) => isSameDomain(other, record))
106
- .flatMap(getFieldPairs)
107
- .some(isBuiltFromDeclarations);
108
- if (isExempt) return [];
109
- return getFieldPairs(record).flatMap((pair) => {
98
+ const linted = module.records.map((record) => ({
99
+ domain: getDomain(record),
100
+ warnings: getFieldPairs(record).flatMap((pair): SanyMessage[] => {
110
101
  const name = getFieldName(pair);
111
102
  const symbol = name && getContextSymbol(module.context, name.value);
112
103
  if (name === undefined || symbol === undefined) return [];
@@ -117,6 +108,24 @@ export const lintSanyModule = (module: ModuleNode): SanyMessage[] => {
117
108
  isWarning: true,
118
109
  },
119
110
  ];
120
- });
111
+ }),
112
+ }));
113
+ const warnedDomains = new Set(
114
+ linted.flatMap((item) => (item.warnings.length > 0 ? [item.domain] : [])),
115
+ );
116
+ const exemptDomains = new Set<string>();
117
+ [
118
+ ...[...getExtendedModules(module)].flatMap((extended) => extended.records),
119
+ ...module.records,
120
+ ].forEach((record) => {
121
+ const domain = getDomain(record);
122
+ if (
123
+ warnedDomains.has(domain) &&
124
+ !exemptDomains.has(domain) &&
125
+ getFieldPairs(record).some(isBuiltFromDeclarations)
126
+ ) {
127
+ exemptDomains.add(domain);
128
+ }
121
129
  });
130
+ return linted.flatMap((item) => (exemptDomains.has(item.domain) ? [] : item.warnings));
122
131
  };
package/src/search.ts CHANGED
@@ -14,7 +14,7 @@ import type {
14
14
  Violation,
15
15
  } from "./check";
16
16
  import type { ConfigValue, ModelConfig } from "./config";
17
- import { getReadVariables } from "./dependencies";
17
+ import { getReadVariables, isConstantLevel } from "./dependencies";
18
18
  import {
19
19
  isStackOverflow,
20
20
  TlaConfigError,
@@ -27,10 +27,10 @@ import {
27
27
  describeRange,
28
28
  evaluate,
29
29
  evaluateStartupDefinitions,
30
+ getStartupValue,
30
31
  expectBoolean,
31
32
  formatRange,
32
33
  getDefinition,
33
- isConstantLevel,
34
34
  type Context,
35
35
  type Environment,
36
36
  type Scope,
@@ -49,7 +49,7 @@ import { prettyPrint } from "./pretty-print";
49
49
  import { getPossibleCounts, type CheckerRuntime } from "./runtime";
50
50
  import { getRepresentative, getSymmetryGroup } from "./symmetry";
51
51
  import { MESSAGE_CODE, MISSING_INIT_174, withHeadline } from "./tlc/messages";
52
- import { createTlcFingerprinter, getTlcFingerprint } from "./tlc/fingerprint";
52
+ import { getTlcFingerprint, getTlcFingerprints } from "./tlc/fingerprint";
53
53
  import { formatValue, isUpdatedElementOf, type Value } from "./values";
54
54
 
55
55
  interface NamedExpression {
@@ -563,6 +563,8 @@ interface Search {
563
563
  // TLC drops a constraint that is a true constant formula.
564
564
  isConstrained: boolean;
565
565
  findViolatedInvariant: (state: Value[], parent?: Value[]) => StateCheck | undefined;
566
+ // Every invariant an initial state violates, which TLC reports with -continue.
567
+ getViolatedInvariants: (state: Value[]) => StateCheck[];
566
568
  // The checks of a state that TLC evaluates when it replays the computation of the initial states
567
569
  // or of the successors of a state, with an environment that records the call stack. The first
568
570
  // returns the check that stops the replay, and the second false where TLC stops it.
@@ -760,9 +762,33 @@ export const createSearch = (
760
762
  : [getViewValue(view.expression, representative)],
761
763
  );
762
764
  };
765
+ // With -continue, TLC goes on to the successors of a state that violates an invariant.
766
+ const violatingStates = new WeakSet<Value[]>();
767
+ const isViolated = (invariant: StateCheck, state: Value[], parent: Value[] | undefined) => {
768
+ // A parent that satisfies every invariant leaves only what the step changed to fail.
769
+ const checkedParent = parent && !violatingStates.has(parent) ? parent : undefined;
770
+ if (isUnchangedFor(invariant, state, checkedParent)) return false;
771
+ try {
772
+ const context = getContext(environment, state, undefined, invariant.scope);
773
+ const membership = invariant.membership;
774
+ return checkedParent && membership
775
+ ? !isUpdatedElementOf(
776
+ state[membership.variable],
777
+ checkedParent[membership.variable],
778
+ evaluate(membership.set, context),
779
+ )
780
+ : !holdsAsConjunct(invariant, context);
781
+ } catch (error) {
782
+ // TLC reports a failure only on a state after the initial states as an invariant failure.
783
+ if (!parent) throw error;
784
+ throw withHeadline(
785
+ setExitCode(error, EXIT_STATUS.safetyEvaluationFailure),
786
+ MESSAGE_CODE.invariantEvaluationFailed,
787
+ `Evaluating invariant ${invariant.name} failed.`,
788
+ );
789
+ }
790
+ };
763
791
  const isFingerprintedLikeTlc = hasWideString(config, environment);
764
- // One fingerprinter for every level keeps the values it cached for the states of earlier levels.
765
- let storedFingerprinter: ReturnType<typeof createTlcFingerprinter> | undefined;
766
792
  runtime.getFingerprint = getTlcStateFingerprint;
767
793
  const findUnwitnessedPossible = () => {
768
794
  const unwitnessed = possible.find((item) => !runtime.possibleCounts.get(item.name));
@@ -786,8 +812,7 @@ export const createSearch = (
786
812
  if (view !== undefined || isFingerprintedLikeTlc) {
787
813
  return BigInt64Array.from(states, getTlcStateFingerprint);
788
814
  }
789
- storedFingerprinter ??= createTlcFingerprinter(getTlcOrder());
790
- return storedFingerprinter(fingerprintStates);
815
+ return getTlcFingerprints(fingerprintStates, getTlcOrder());
791
816
  },
792
817
  getFingerprintState: (state) => {
793
818
  if (isFingerprintedLikeTlc) return [String(getTlcStateFingerprint(state))];
@@ -798,30 +823,21 @@ export const createSearch = (
798
823
  : getRepresentative(state, symmetryGroup, getTlcOrder());
799
824
  return view === undefined ? representative : [getViewValue(view.expression, representative)];
800
825
  },
801
- findViolatedInvariant: (state, parent) =>
802
- invariants.find((invariant) => {
803
- if (isUnchangedFor(invariant, state, parent)) return false;
804
- try {
805
- const context = getContext(environment, state, undefined, invariant.scope);
806
- const membership = invariant.membership;
807
- // The parent satisfies every invariant, so only the entries the step changed can fail.
808
- return parent && membership
809
- ? !isUpdatedElementOf(
810
- state[membership.variable],
811
- parent[membership.variable],
812
- evaluate(membership.set, context),
813
- )
814
- : !holdsAsConjunct(invariant, context);
815
- } catch (error) {
816
- // TLC reports a failure only on a state after the initial states as an invariant failure.
817
- if (!parent) throw error;
818
- throw withHeadline(
819
- setExitCode(error, EXIT_STATUS.safetyEvaluationFailure),
820
- MESSAGE_CODE.invariantEvaluationFailed,
821
- `Evaluating invariant ${invariant.name} failed.`,
822
- );
823
- }
824
- }),
826
+ findViolatedInvariant: (state, parent) => {
827
+ const violated = invariants.find((invariant) => isViolated(invariant, state, parent));
828
+ if (violated) violatingStates.add(state);
829
+ return violated;
830
+ },
831
+ getViolatedInvariants: (state) => {
832
+ const violated = invariantPredicates.filter((predicate) =>
833
+ invariants.some(
834
+ (invariant) =>
835
+ invariant.predicate === predicate.predicate && isViolated(invariant, state, undefined),
836
+ ),
837
+ );
838
+ if (violated.length > 0) violatingStates.add(state);
839
+ return violated;
840
+ },
825
841
  checkReplayedInitialState: (state, tracing, addFingerprint) => {
826
842
  const holdsIn = (expression: Expression, scope: Scope | undefined) =>
827
843
  holdsLikeTlc(expression, getContext(tracing, state, undefined, scope));
@@ -925,7 +941,7 @@ export const createSearch = (
925
941
  // a postcondition before it checks any of them.
926
942
  const constant = config.postconditions.find((name) => {
927
943
  const definition = getDefinition(name, environment);
928
- return definition !== undefined && environment.definitionValues.has(definition);
944
+ return definition !== undefined && getStartupValue(definition, environment) !== undefined;
929
945
  });
930
946
  if (constant !== undefined) {
931
947
  if (isAfterViolation) return undefined;
@@ -1,3 +1,4 @@
1
+ import { isConstantLevel } from "./dependencies";
1
2
  import {
2
3
  isLocallyResolved,
3
4
  type Definition,
@@ -14,7 +15,6 @@ import {
14
15
  evaluate,
15
16
  forEachBinding,
16
17
  getDefinition,
17
- isConstantLevel,
18
18
  lookupScope,
19
19
  resolveGlobalOperator,
20
20
  type Closure,
package/src/successors.ts CHANGED
@@ -204,7 +204,7 @@ const getRuntimeVariableIndex = (
204
204
  }
205
205
  if (expression.kind !== "Identifier") return undefined;
206
206
  const binding = lookupScope(scope, expression.name);
207
- if (binding?.kind === "Thunk") {
207
+ if (binding?.kind === "Thunk" && !binding.isReleased) {
208
208
  return getRuntimeVariableIndex(binding.expression, binding.scope, partial, run, isPrimed);
209
209
  }
210
210
  if (binding) return undefined;
@@ -569,7 +569,7 @@ const compileUnchanged = (expression: Expression, environment: Environment): Run
569
569
  return (run, scope, partial, action, isFixed, onComplete) => {
570
570
  const binding =
571
571
  expression.kind === "Identifier" ? lookupScope(scope, expression.name) : undefined;
572
- if (binding?.kind === "Thunk") {
572
+ if (binding?.kind === "Thunk" && !binding.isReleased) {
573
573
  getRunner(getUnchangedWrapper(binding.expression), environment, false)(
574
574
  run,
575
575
  binding.scope,
@@ -640,7 +640,7 @@ const compileIdentifier = (
640
640
  const compiled = { body: undefined as Runner | undefined };
641
641
  return (run, scope, partial, action, isFixed, onComplete) => {
642
642
  const binding = lookupScope(scope, expression.name);
643
- if (binding?.kind === "Thunk") {
643
+ if (binding?.kind === "Thunk" && !binding.isReleased) {
644
644
  getRunner(binding.expression, environment, isInit)(
645
645
  run,
646
646
  binding.scope,
@@ -1056,15 +1056,9 @@ const compileAction = (
1056
1056
  }
1057
1057
  };
1058
1058
 
1059
- const emptyStates = new WeakMap<Environment, State>();
1060
-
1061
- const getEmptyState = (environment: Environment) => {
1062
- const cached = emptyStates.get(environment);
1063
- if (cached) return cached;
1064
- const state = environment.variables.map((): Value | undefined => undefined);
1065
- emptyStates.set(environment, state);
1066
- return state;
1067
- };
1059
+ // A partial state that assigns no variable, which a run fills in as it assigns them.
1060
+ const getEmptyState = (environment: Environment): State =>
1061
+ environment.variables.map((): Value | undefined => undefined);
1068
1062
 
1069
1063
  const isComplete = (partial: State): partial is Value[] => {
1070
1064
  for (let index = 0; index < partial.length; index++) {
package/src/symmetry.ts CHANGED
@@ -13,41 +13,16 @@ import {
13
13
  isEnumerable,
14
14
  isFunctionValue,
15
15
  isModelValue,
16
- isSameValue,
17
16
  isSetValue,
18
17
  toFiniteFunction,
19
18
  toFiniteSet,
20
19
  type ModelValue,
21
- type ObjectValue,
22
20
  type Value,
23
21
  } from "./values";
24
22
 
23
+ // The image of each model value a permutation moves, by name.
25
24
  type Images = Map<string, ModelValue>;
26
25
 
27
- const CACHE_LIMIT = 1 << 22;
28
- const CACHED_SIZE_LIMIT = 64;
29
-
30
- interface Permutation {
31
- images: Images;
32
- cache: WeakMap<ObjectValue, Value>;
33
- cacheSize: number;
34
- cacheLimit: number;
35
- }
36
-
37
- // The images of one value under every permutation, the identity first, and how each image compares
38
- // with the image of each permutation the search has held as the smallest.
39
- interface Orbit {
40
- images: Value[];
41
- comparisons: (Int8Array | undefined)[];
42
- }
43
-
44
- interface SymmetryGroup {
45
- permutations: Permutation[];
46
- orbits: WeakMap<ObjectValue, Orbit>;
47
- orbitCount: number;
48
- orbitLimit: number;
49
- }
50
-
51
26
  const getPermutationKey = (permutation: Images) =>
52
27
  [...permutation]
53
28
  .map(([name, image]) => `${name}>${image.name}`)
@@ -104,7 +79,7 @@ export const getSymmetryGroup = (
104
79
  name: string,
105
80
  environment: Environment,
106
81
  substitutions: Substitution[],
107
- ): SymmetryGroup | undefined => {
82
+ ): Images[] | undefined => {
108
83
  const definition = environment.definitions.get(name);
109
84
  if (definition === undefined && !environment.constants.has(name)) {
110
85
  throw new TlaConfigError(
@@ -187,29 +162,18 @@ export const getSymmetryGroup = (
187
162
  }),
188
163
  );
189
164
  if (group.size === 0) return undefined;
190
- const cacheLimit = Math.max(256, Math.floor(CACHE_LIMIT / group.size));
191
- return {
192
- permutations: [...group.values()].map((images) => ({
193
- images,
194
- cache: new WeakMap<ObjectValue, Value>(),
195
- cacheSize: 0,
196
- cacheLimit,
197
- })),
198
- orbits: new WeakMap(),
199
- orbitCount: 0,
200
- orbitLimit: cacheLimit,
201
- };
165
+ return [...group.values()];
202
166
  };
203
167
 
204
- const permuteElements = (elements: Value[], permutation: Permutation) => {
168
+ const permuteElements = (elements: Value[], images: Images) => {
205
169
  for (let index = 0; index < elements.length; index++) {
206
170
  const element = elements[index];
207
- const permuted = permuteValue(element, permutation);
171
+ const permuted = permuteValue(element, images);
208
172
  if (permuted === element) continue;
209
173
  const result = elements.slice(0, index);
210
174
  result.push(permuted);
211
175
  for (let rest = index + 1; rest < elements.length; rest++) {
212
- result.push(permuteValue(elements[rest], permutation));
176
+ result.push(permuteValue(elements[rest], images));
213
177
  }
214
178
  return result;
215
179
  }
@@ -218,11 +182,11 @@ const permuteElements = (elements: Value[], permutation: Permutation) => {
218
182
 
219
183
  // A permutation maps distinct elements to distinct elements and keeps the elements it doesn't move
220
184
  // in order, so it sorts only the moved ones and merges them back.
221
- const permuteSortedElements = (elements: Value[], permutation: Permutation) => {
185
+ const permuteSortedElements = (elements: Value[], images: Images) => {
222
186
  const kept: Value[] = [];
223
187
  const moved: Value[] = [];
224
188
  for (const element of elements) {
225
- const permuted = permuteValue(element, permutation);
189
+ const permuted = permuteValue(element, images);
226
190
  if (permuted === element) kept.push(element);
227
191
  else moved.push(permuted);
228
192
  }
@@ -243,43 +207,20 @@ const permuteSortedElements = (elements: Value[], permutation: Permutation) => {
243
207
  return merged;
244
208
  };
245
209
 
246
- const getSize = (value: ObjectValue) =>
247
- value.kind === "Set"
248
- ? value.elements.length
249
- : value.kind === "Function"
250
- ? value.domain.length
251
- : 0;
252
-
253
- const permuteValue = (value: Value, permutation: Permutation): Value => {
210
+ // Value#permute: the value with each model value replaced by its image. A value the permutation
211
+ // doesn't move is returned itself, so that comparing it with itself stops at identity.
212
+ const permuteValue = (value: Value, images: Images): Value => {
254
213
  if (typeof value !== "object") return value;
255
- if (value.kind === "ModelValue") return permutation.images.get(value.name) ?? value;
256
- const size = getSize(value);
257
- if (size === 0 || size > CACHED_SIZE_LIMIT) return computePermutedValue(value, permutation);
258
- const cached = permutation.cache.get(value);
259
- if (cached !== undefined) return cached;
260
- const computed = computePermutedValue(value, permutation);
261
- // A permutation often maps a value to an equal one. Keeping the original lets the comparison
262
- // with the smallest state so far stop at identity.
263
- const permuted = computed !== value && isSameValue(computed, value) ? value : computed;
264
- if (permutation.cacheSize >= permutation.cacheLimit) {
265
- permutation.cache = new WeakMap();
266
- permutation.cacheSize = 0;
267
- }
268
- permutation.cache.set(value, permuted);
269
- permutation.cacheSize++;
270
- return permuted;
271
- };
272
-
273
- const computePermutedValue = (value: ObjectValue, permutation: Permutation) => {
274
214
  const kind = value.kind;
215
+ if (kind === "ModelValue") return images.get(value.name) ?? value;
275
216
  if (kind === "Set") {
276
- const elements = permuteSortedElements(value.elements, permutation);
217
+ const elements = permuteSortedElements(value.elements, images);
277
218
  return elements ? createSortedSet(elements) : value;
278
219
  }
279
220
  if (kind === "Function" || (kind === "LazyFunction" && isEnumerable(value.domain))) {
280
221
  const functionValue = toFiniteFunction(value);
281
- const domain = permuteElements(functionValue.domain, permutation);
282
- const range = permuteElements(functionValue.range, permutation) ?? functionValue.range;
222
+ const domain = permuteElements(functionValue.domain, images);
223
+ const range = permuteElements(functionValue.range, images) ?? functionValue.range;
283
224
  if (domain) {
284
225
  const permuted = createFunction(
285
226
  domain.map((key, index): [Value, Value] => [key, range[index]]),
@@ -297,80 +238,28 @@ const computePermutedValue = (value: ObjectValue, permutation: Permutation) => {
297
238
  }
298
239
  if (kind === "Interval" || !isSetValue(value) || !isEnumerable(value)) return value;
299
240
  const set = toFiniteSet(value);
300
- const elements = permuteElements(set.elements, permutation);
241
+ const elements = permuteElements(set.elements, images);
301
242
  return elements ? createSet(elements) : set;
302
243
  };
303
244
 
304
- const getOrbit = (value: ObjectValue, group: SymmetryGroup) => {
305
- const cached = group.orbits.get(value);
306
- if (cached !== undefined) return cached;
307
- if (group.orbitCount >= group.orbitLimit) {
308
- group.orbits = new WeakMap();
309
- group.orbitCount = 0;
310
- }
311
- const orbit: Orbit = { images: [value], comparisons: [] };
312
- group.orbits.set(value, orbit);
313
- group.orbitCount++;
314
- return orbit;
315
- };
316
-
317
- const getImage = (orbit: Orbit, permutation: number, group: SymmetryGroup) =>
318
- (orbit.images[permutation] ??= permuteValue(
319
- orbit.images[0],
320
- group.permutations[permutation - 1],
321
- ));
322
-
323
- // Two images of a value compare the same way every time, and comparing them again changes nothing,
324
- // so an orbit compares each pair once.
325
- const compareImages = (
326
- value: ObjectValue,
327
- permutation: number,
328
- minimum: number,
329
- group: SymmetryGroup,
330
- ) => {
331
- const orbit = getOrbit(value, group);
332
- const comparisons = (orbit.comparisons[minimum] ??= new Int8Array(group.permutations.length + 1));
333
- if (comparisons[permutation] === 0) {
334
- const comparison = compareValues(
335
- getImage(orbit, permutation, group),
336
- getImage(orbit, minimum, group),
337
- );
338
- comparisons[permutation] = Math.sign(comparison) + 2;
339
- }
340
- return comparisons[permutation] - 2;
341
- };
342
-
343
- const isSmallerImage = (
344
- state: Value[],
345
- permutation: number,
346
- minimum: number,
347
- group: SymmetryGroup,
348
- order: number[],
349
- ) => {
350
- for (const index of order) {
351
- const value = state[index];
352
- const comparison =
353
- typeof value === "object" ? compareImages(value, permutation, minimum, group) : 0;
354
- if (comparison !== 0) return comparison < 0;
355
- }
356
- return false;
357
- };
358
-
359
- // TLC keeps the smallest image of the state in its variable order, replacing it only with a
360
- // strictly smaller one.
245
+ // TLCStateMut#fingerPrint: the smallest image of the state under the group in TLC's variable
246
+ // order. TLC permutes the state under each permutation, variable by variable, and moves on to the
247
+ // next permutation as soon as a variable's image is larger than the smallest state's.
361
248
  export const getRepresentative = (
362
249
  state: Value[],
363
- group: SymmetryGroup,
250
+ permutations: Images[],
364
251
  order: number[],
365
252
  ): Value[] => {
366
- const minimum = group.permutations.reduce(
367
- (smallest, _, index) =>
368
- isSmallerImage(state, index + 1, smallest, group, order) ? index + 1 : smallest,
369
- 0,
370
- );
371
- return minimum === 0
372
- ? state
373
- : state.map((value) =>
374
- typeof value === "object" ? getImage(getOrbit(value, group), minimum, group) : value,
375
- );
253
+ let smallest = state;
254
+ for (const images of permutations) {
255
+ const permuted = state.slice();
256
+ let comparison = 0;
257
+ for (const index of order) {
258
+ permuted[index] = permuteValue(state[index], images);
259
+ if (comparison === 0) comparison = compareValues(permuted[index], smallest[index]);
260
+ if (comparison > 0) break;
261
+ }
262
+ if (comparison < 0) smallest = permuted;
263
+ }
264
+ return smallest;
376
265
  };