tla-ts 0.0.1 → 0.0.3-dev.19c763f

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 (74) hide show
  1. package/README.md +98 -39
  2. package/dist/index.cjs +1 -1
  3. package/dist/index.d.cts +225 -30
  4. package/dist/index.d.ts +225 -30
  5. package/dist/index.js +1 -1
  6. package/dist/parallel-worker.cjs +2 -2
  7. package/dist/parallel-worker.js +2 -2
  8. package/dist/parallel.cjs +1 -1
  9. package/dist/parallel.js +2 -2
  10. package/dist/run-cli.cjs +21 -1
  11. package/dist/run-cli.js +21 -1
  12. package/dist/transfer.cjs +400 -39
  13. package/dist/transfer.js +400 -39
  14. package/package.json +6 -2
  15. package/src/ast.ts +213 -6
  16. package/src/bags.ts +161 -71
  17. package/src/builtins.ts +203 -23
  18. package/src/bundled-modules.ts +63 -32
  19. package/src/check.ts +1086 -244
  20. package/src/cli-options.ts +64 -0
  21. package/src/codegen.ts +58 -34
  22. package/src/config.ts +39 -11
  23. package/src/dependencies.ts +2 -2
  24. package/src/environment.ts +557 -153
  25. package/src/errors.ts +66 -1
  26. package/src/evaluate.ts +547 -255
  27. package/src/exit-codes.ts +53 -0
  28. package/src/fingerprints.ts +48 -13
  29. package/src/index.ts +9 -4
  30. package/src/instances.ts +235 -79
  31. package/src/java-overrides.ts +241 -0
  32. package/src/json.ts +153 -72
  33. package/src/levels.ts +850 -0
  34. package/src/lexer.ts +108 -29
  35. package/src/live-check.ts +710 -0
  36. package/src/liveness.ts +37 -599
  37. package/src/obligation-action.ts +384 -0
  38. package/src/obligation-anon.ts +575 -0
  39. package/src/obligation-deref.ts +637 -0
  40. package/src/obligation-expression.ts +1060 -0
  41. package/src/obligation-format.ts +406 -0
  42. package/src/obligation-generate.ts +1074 -0
  43. package/src/obligation-levels.ts +329 -0
  44. package/src/obligation-module.ts +1042 -0
  45. package/src/obligation-printer.ts +889 -0
  46. package/src/obligation-proof.ts +76 -0
  47. package/src/obligation-source.ts +1084 -0
  48. package/src/obligation-tuples.ts +184 -0
  49. package/src/obligations.ts +316 -0
  50. package/src/parallel-worker.ts +186 -201
  51. package/src/parallel.ts +179 -84
  52. package/src/parser.ts +970 -206
  53. package/src/pretty-print.ts +259 -0
  54. package/src/randomization.ts +24 -113
  55. package/src/resolve.ts +483 -51
  56. package/src/run-cli.ts +473 -62
  57. package/src/runtime.ts +65 -28
  58. package/src/spec-description.ts +521 -0
  59. package/src/standard-levels.ts +105 -0
  60. package/src/standard-modules.ts +223 -92
  61. package/src/state-graph.ts +157 -0
  62. package/src/subexpressions.ts +31 -45
  63. package/src/substitution-levels.ts +184 -0
  64. package/src/successors.ts +276 -53
  65. package/src/symmetry.ts +79 -23
  66. package/src/tableau.ts +43 -37
  67. package/src/tlc-ext.ts +148 -44
  68. package/src/tlc-module.ts +71 -66
  69. package/src/tlc-modules.ts +1022 -0
  70. package/src/tlc-order.ts +511 -0
  71. package/src/tlc-random.ts +411 -0
  72. package/src/tlc-summary.ts +109 -0
  73. package/src/transfer.ts +26 -5
  74. package/src/values.ts +1245 -176
package/src/successors.ts CHANGED
@@ -1,6 +1,16 @@
1
- import type { Bound, Definition, Expression } from "./ast";
2
- import { TlaEvaluationError } from "./errors";
3
1
  import {
2
+ getChildren,
3
+ isLocallyResolved,
4
+ type Bound,
5
+ type Definition,
6
+ type Expression,
7
+ } from "./ast";
8
+ import { getReadVariables } from "./dependencies";
9
+ import { TlaEvaluationError, UNEXPECTED_EXCEPTION } from "./errors";
10
+ import { EXIT_STATUS, setExitCode } from "./exit-codes";
11
+ import {
12
+ describeLocation,
13
+ describeRange,
4
14
  bindArgument,
5
15
  bindDefinitions,
6
16
  bindOperatorArguments,
@@ -11,21 +21,23 @@ import {
11
21
  forEachBinding,
12
22
  getBoundsDomain,
13
23
  getDefinition,
24
+ getEnumeratedElements,
25
+ getReevaluatedDefinitions,
14
26
  lookupScope,
15
27
  resolveApplyOperator,
16
28
  resolveGlobalOperator,
17
- isLocallyResolved,
18
29
  type Context,
19
30
  type Environment,
20
31
  type Scope,
21
32
  type State,
22
33
  } from "./evaluate";
34
+ import { mapChildren } from "./instances";
23
35
  import {
24
36
  createTuple,
25
37
  formatValue,
38
+ getStreamedElements,
26
39
  isElementOf,
27
40
  isEnumerable,
28
- toFiniteSet,
29
41
  valuesEqual,
30
42
  type Value,
31
43
  } from "./values";
@@ -39,6 +51,7 @@ interface Run {
39
51
  environment: Environment;
40
52
  isInit: boolean;
41
53
  current: Value[] | undefined;
54
+ isStopped: boolean;
42
55
  }
43
56
 
44
57
  type Continuation = (partial: State, action: string | undefined) => void;
@@ -62,10 +75,7 @@ type Conjunct = { expression: Expression } & (
62
75
  const initRunners = new WeakMap<Expression, Runner>();
63
76
  const nextRunners = new WeakMap<Expression, Runner>();
64
77
 
65
- const describeLocation = (expression: Expression) =>
66
- `line ${expression.location.line}, column ${expression.location.column}`;
67
-
68
- const getContext = (run: Run, scope: Scope | undefined, partial: State): Context =>
78
+ const getContext = (run: Run, scope: Scope | undefined, partial: State) =>
69
79
  run.isInit
70
80
  ? { environment: run.environment, scope, state: partial, next: undefined }
71
81
  : { environment: run.environment, scope, state: run.current, next: partial };
@@ -79,7 +89,12 @@ const assign = (partial: State, index: number, value: Value) => {
79
89
  const holds = (expression: Expression, context: Context) => {
80
90
  const value = evaluate(expression, context);
81
91
  if (typeof value === "boolean") return value;
82
- return expectBoolean(value, `the action at ${describeLocation(expression)}`);
92
+ try {
93
+ return expectBoolean(value, `the action at ${describeLocation(expression)}`);
94
+ } catch (error) {
95
+ // TLC fails with an unexpected exception when the next-state relation isn't a boolean.
96
+ throw context.next === undefined ? error : setExitCode(error, EXIT_STATUS.error);
97
+ }
83
98
  };
84
99
 
85
100
  const isAssignmentOperator = (operator: string) =>
@@ -188,16 +203,12 @@ const ACTION_KINDS = new Set([
188
203
  "FunctionApplication",
189
204
  ]);
190
205
 
191
- const isGuard = (expression: Expression, environment: Environment, isInit: boolean): boolean => {
206
+ const isGuard = (expression: Expression, environment: Environment, isInit: boolean) => {
192
207
  if (ACTION_KINDS.has(expression.kind)) return false;
193
208
  if (expression.kind === "Identifier") {
194
- if (
195
- environment.variableIndex.has(expression.name) ||
196
- environment.constants.has(expression.name)
197
- ) {
198
- return true;
199
- }
200
- return false;
209
+ return (
210
+ environment.variableIndex.has(expression.name) || environment.constants.has(expression.name)
211
+ );
201
212
  }
202
213
  if (expression.kind !== "Apply") return true;
203
214
  if (expression.operator === "=>") return false;
@@ -212,6 +223,56 @@ const isGuard = (expression: Expression, environment: Environment, isInit: boole
212
223
  return definition === undefined && environment.builtins.has(expression.operator);
213
224
  };
214
225
 
226
+ const NO_NAMES: ReadonlySet<string> = new Set();
227
+
228
+ // The local names an expression reads from enclosing scopes, or undefined when it applies a local
229
+ // operator, whose body may assign variables.
230
+ const getReadLocals = (
231
+ expression: Expression,
232
+ bound: ReadonlySet<string>,
233
+ ): string[] | undefined => {
234
+ if (isLocallyResolved(expression)) {
235
+ if (expression.kind !== "Identifier") return undefined;
236
+ return bound.has(expression.name) ? [] : [expression.name];
237
+ }
238
+ const names: string[] = [];
239
+ const result = { isReadOnly: true };
240
+ mapChildren(expression, (child, childNames) => {
241
+ const childLocals = result.isReadOnly
242
+ ? getReadLocals(child, childNames.length === 0 ? bound : new Set([...bound, ...childNames]))
243
+ : [];
244
+ if (childLocals) names.push(...childLocals);
245
+ else result.isReadOnly = false;
246
+ return child;
247
+ });
248
+ return result.isReadOnly ? names : undefined;
249
+ };
250
+
251
+ // TLC generates a successor for every disjunct and witness that holds, so an expression only
252
+ // checks like a guard when it has neither.
253
+ const hasBranches = (
254
+ expression: Expression,
255
+ environment: Environment,
256
+ visited: Set<Definition>,
257
+ ): boolean => {
258
+ if (expression.kind === "Or" || expression.kind === "Exists") return true;
259
+ const name =
260
+ expression.kind === "Identifier"
261
+ ? expression.name
262
+ : expression.kind === "Apply"
263
+ ? expression.operator
264
+ : undefined;
265
+ const definition =
266
+ name === undefined || isLocallyResolved(expression)
267
+ ? undefined
268
+ : getDefinition(name, environment);
269
+ if (definition && !visited.has(definition)) {
270
+ visited.add(definition);
271
+ if (hasBranches(definition.body, environment, visited)) return true;
272
+ }
273
+ return getChildren(expression).some((child) => hasBranches(child, environment, visited));
274
+ };
275
+
215
276
  const toConjunct = (
216
277
  expression: Expression,
217
278
  environment: Environment,
@@ -332,8 +393,8 @@ const compileMembership = (
332
393
  `In computing next states, the right side of \\in is not enumerable: ${formatValue(value)} at ${describeLocation(expression)}`,
333
394
  );
334
395
  }
335
- const elements = toFiniteSet(value).elements;
336
- for (let position = 0; position < elements.length; position++) {
396
+ const elements = getStreamedElements(value);
397
+ for (let position = 0; position < elements.length && !run.isStopped; position++) {
337
398
  onComplete(assign(partial, index, elements[position]), action);
338
399
  }
339
400
  };
@@ -542,6 +603,104 @@ const compileIdentifier = (
542
603
  };
543
604
  };
544
605
 
606
+ // A PlusCal action starts with a guard such as pc[self] = "L1", and a process is a disjunction of
607
+ // its actions. The labels an expression requires of one variable at one bound name let a
608
+ // disjunction skip the operands whose guard is false without evaluating them.
609
+ interface LabelGuard {
610
+ variable: number;
611
+ argument: string;
612
+ labels: Set<string>;
613
+ }
614
+
615
+ const getLabelGuard = (
616
+ expression: Expression,
617
+ environment: Environment,
618
+ visited: Set<Expression>,
619
+ ): LabelGuard | undefined => {
620
+ if (visited.has(expression)) return undefined;
621
+ visited.add(expression);
622
+ if (expression.kind === "And") {
623
+ const first = expression.operands[0];
624
+ if (first.kind !== "Apply" || first.operator !== "=" || isLocallyResolved(first)) {
625
+ return undefined;
626
+ }
627
+ const target = first.args[0];
628
+ const label = first.args[1];
629
+ if (target.kind !== "FunctionApplication" || label.kind !== "String") return undefined;
630
+ const argument = target.args.length === 1 ? target.args[0] : undefined;
631
+ if (argument?.kind !== "Identifier" || !isLocallyResolved(argument)) return undefined;
632
+ const variable = getStaticVariableIndex(target.function, environment, false);
633
+ if (variable === undefined) return undefined;
634
+ return { variable, argument: argument.name, labels: new Set([label.value]) };
635
+ }
636
+ if (expression.kind === "Or") {
637
+ const guards = expression.operands.map((operand) =>
638
+ getLabelGuard(operand, environment, visited),
639
+ );
640
+ const first = guards[0];
641
+ const isShared = guards.every(
642
+ (guard) =>
643
+ guard !== undefined &&
644
+ guard.variable === first?.variable &&
645
+ guard.argument === first.argument,
646
+ );
647
+ if (!first || !isShared) return undefined;
648
+ const labels = new Set(guards.flatMap((guard) => [...(guard?.labels ?? [])]));
649
+ return { variable: first.variable, argument: first.argument, labels };
650
+ }
651
+ if (expression.kind !== "Apply" || isLocallyResolved(expression)) return undefined;
652
+ const closure = resolveGlobalOperator(expression.operator, environment);
653
+ if (closure?.kind !== "Closure" || closure.scope !== undefined) return undefined;
654
+ const guard = getLabelGuard(closure.body, environment, visited);
655
+ const position = closure.params.findIndex(
656
+ (param) => param.arity === 0 && param.name === guard?.argument,
657
+ );
658
+ const argument = expression.args[position];
659
+ if (!guard || argument?.kind !== "Identifier" || !isLocallyResolved(argument)) {
660
+ return undefined;
661
+ }
662
+ return { variable: guard.variable, argument: argument.name, labels: guard.labels };
663
+ };
664
+
665
+ const getLabel = (run: Run, scope: Scope | undefined, guard: LabelGuard) => {
666
+ const binding = lookupScope(scope, guard.argument);
667
+ const functionValue = run.current?.[guard.variable];
668
+ if (
669
+ binding?.kind !== "Value" ||
670
+ typeof functionValue !== "object" ||
671
+ functionValue.kind !== "Function"
672
+ ) {
673
+ return undefined;
674
+ }
675
+ const position = functionValue.domain.indexOf(binding.value);
676
+ const label = position === -1 ? undefined : functionValue.range[position];
677
+ return typeof label === "string" ? label : undefined;
678
+ };
679
+
680
+ const compileDisjunction = (
681
+ operands: Expression[],
682
+ environment: Environment,
683
+ isInit: boolean,
684
+ ): Runner => {
685
+ const runners = operands.map((operand) => getRunner(operand, environment, isInit));
686
+ const guards = isInit
687
+ ? []
688
+ : operands.map((operand) => getLabelGuard(operand, environment, new Set()));
689
+ const dispatch = guards.find((guard) => guard !== undefined);
690
+ const labels = guards.map((guard) =>
691
+ guard?.variable === dispatch?.variable && guard?.argument === dispatch?.argument
692
+ ? guard?.labels
693
+ : undefined,
694
+ );
695
+ return (run, scope, partial, action, isFixed, onComplete) => {
696
+ const label = dispatch && getLabel(run, scope, dispatch);
697
+ for (let index = 0; index < runners.length && !run.isStopped; index++) {
698
+ if (label !== undefined && labels[index]?.has(label) === false) continue;
699
+ runners[index](run, scope, partial, action, isFixed, onComplete);
700
+ }
701
+ };
702
+ };
703
+
545
704
  const compileAction = (
546
705
  expression: Expression,
547
706
  environment: Environment,
@@ -551,26 +710,19 @@ const compileAction = (
551
710
  switch (expression.kind) {
552
711
  case "And":
553
712
  return compileConjunction(expression.operands, environment, isInit);
554
- case "Or": {
555
- const operands = expression.operands.map(child);
556
- return (run, scope, partial, action, isFixed, onComplete) => {
557
- for (const operand of operands) operand(run, scope, partial, action, isFixed, onComplete);
558
- };
559
- }
713
+ case "Or":
714
+ return compileDisjunction(expression.operands, environment, isInit);
560
715
  case "Exists": {
561
716
  const body = child(expression.body);
562
717
  const bound = expression.bounds[0];
563
718
  if (expression.bounds.length === 1 && bound.pattern.kind === "Name") {
564
719
  const name = bound.pattern.name;
565
720
  return (run, scope, partial, action, isFixed, onComplete) => {
566
- const set = evaluate(bound.set, getContext(run, scope, partial));
567
- if (!isEnumerable(set)) {
568
- throw new TlaEvaluationError(
569
- `TLC encountered a non-enumerable quantifier bound ${formatValue(set)} at ${describeLocation(bound.set)}`,
570
- );
571
- }
572
- const elements = toFiniteSet(set).elements;
573
- for (let index = 0; index < elements.length; index++) {
721
+ const elements = getEnumeratedElements(
722
+ evaluate(bound.set, getContext(run, scope, partial)),
723
+ bound.set,
724
+ );
725
+ for (let index = 0; index < elements.length && !run.isStopped; index++) {
574
726
  body(
575
727
  run,
576
728
  bindValue(scope, name, elements[index]),
@@ -585,12 +737,18 @@ const compileAction = (
585
737
  return (run, scope, partial, action, isFixed, onComplete) => {
586
738
  forEachBinding(expression.bounds, getContext(run, scope, partial), (boundScope) => {
587
739
  body(run, boundScope, partial, action, isFixed, onComplete);
588
- return false;
740
+ return run.isStopped;
589
741
  });
590
742
  };
591
743
  }
592
744
  case "Forall": {
593
745
  const body = child(expression.body);
746
+ const readLocals =
747
+ !isInit &&
748
+ getReadVariables(expression, environment) !== undefined &&
749
+ !hasBranches(expression.body, environment, new Set())
750
+ ? getReadLocals(expression, NO_NAMES)
751
+ : undefined;
594
752
  return (run, scope, partial, action, _isFixed, onComplete) => {
595
753
  const boundScopes: (Scope | undefined)[] = [];
596
754
  forEachBinding(expression.bounds, getContext(run, scope, partial), (boundScope) => {
@@ -598,6 +756,16 @@ const compileAction = (
598
756
  return false;
599
757
  });
600
758
  const scopes = [...boundScopes.slice(0, 1), ...boundScopes.slice(1).reverse()];
759
+ const isBoundToValues = readLocals?.every(
760
+ (name) => lookupScope(scope, name)?.kind === "Value",
761
+ );
762
+ if (isBoundToValues) {
763
+ const isSatisfied = scopes.every((boundScope) =>
764
+ holds(expression.body, getContext(run, boundScope, partial)),
765
+ );
766
+ if (isSatisfied) onComplete(partial, action);
767
+ return;
768
+ }
601
769
  const visit = (index: number, nextPartial: State, nextAction: string | undefined): void => {
602
770
  if (index === scopes.length) {
603
771
  onComplete(nextPartial, nextAction);
@@ -641,16 +809,19 @@ const compileAction = (
641
809
  );
642
810
  const body = arm?.body ?? other;
643
811
  if (!body)
644
- throw new TlaEvaluationError(`No CASE guard is true at ${describeLocation(expression)}`);
812
+ throw new TlaEvaluationError(
813
+ `${UNEXPECTED_EXCEPTION}In computing next states, TLC encountered a CASE with no conditions true.\n${describeRange(expression)}`,
814
+ );
645
815
  body(run, scope, partial, action, isFixed, onComplete);
646
816
  };
647
817
  }
648
818
  case "Let": {
649
819
  const body = child(expression.body);
820
+ const reevaluated = getReevaluatedDefinitions(expression.definitions, environment);
650
821
  return (run, scope, partial, action, isFixed, onComplete) =>
651
822
  body(
652
823
  run,
653
- bindDefinitions(expression.definitions, getContext(run, scope, partial)),
824
+ bindDefinitions(expression.definitions, getContext(run, scope, partial), reevaluated),
654
825
  partial,
655
826
  action,
656
827
  isFixed,
@@ -749,62 +920,114 @@ export const isEnabled = (expression: Expression, context: Context): boolean =>
749
920
  );
750
921
  }
751
922
  const environment = context.environment;
752
- const found = { value: false };
923
+ const run: Run = { environment, isInit: false, current: state, isStopped: false };
924
+ // TLC stops computing ENABLED at the first successor, so it skips the rest of the action.
753
925
  getRunner(expression, environment, false)(
754
- { environment, isInit: false, current: state },
926
+ run,
755
927
  context.scope,
756
928
  getEmptyState(environment),
757
929
  undefined,
758
930
  false,
759
931
  () => {
760
- found.value = true;
932
+ run.isStopped = true;
761
933
  },
762
934
  );
763
- return found.value;
935
+ return run.isStopped;
764
936
  };
765
937
 
766
- export const getInitialStates = (expression: Expression, environment: Environment): Value[][] => {
767
- const states: Value[][] = [];
768
- const run: Run = { environment, isInit: true, current: undefined };
938
+ export const forEachInitialState = (
939
+ expression: Expression,
940
+ environment: Environment,
941
+ onState: (state: Value[]) => boolean,
942
+ scope?: Scope,
943
+ ) => {
944
+ const run: Run = { environment, isInit: true, current: undefined, isStopped: false };
769
945
  getRunner(expression, environment, true)(
770
946
  run,
771
- undefined,
947
+ scope,
772
948
  getEmptyState(environment),
773
949
  undefined,
774
950
  false,
775
951
  (partial) => {
952
+ if (run.isStopped) return;
776
953
  if (!isComplete(partial)) {
777
- throw new TlaEvaluationError(
778
- `The initial predicate does not assign ${getMissingVariables(partial, environment).join(", ")}`,
954
+ // TLC reports an initial state that isn't completely specified as an illegal state, not as
955
+ // an evaluation failure.
956
+ throw setExitCode(
957
+ new TlaEvaluationError(
958
+ `The initial predicate does not assign ${getMissingVariables(partial, environment).join(", ")}`,
959
+ ),
960
+ EXIT_STATUS.error,
779
961
  );
780
962
  }
781
- states.push(partial);
963
+ run.isStopped = onState(partial);
782
964
  },
783
965
  );
966
+ };
967
+
968
+ export const getInitialStates = (
969
+ expression: Expression,
970
+ environment: Environment,
971
+ scope?: Scope,
972
+ ): Value[][] => {
973
+ const states: Value[][] = [];
974
+ forEachInitialState(
975
+ expression,
976
+ environment,
977
+ (state) => {
978
+ states.push(state);
979
+ return false;
980
+ },
981
+ scope,
982
+ );
784
983
  return states;
785
984
  };
786
985
 
787
- export const getSuccessors = (
986
+ export const forEachSuccessor = (
788
987
  expression: Expression,
789
988
  state: Value[],
790
989
  environment: Environment,
791
- ): Successor[] => {
792
- const successors: Successor[] = [];
793
- const run: Run = { environment, isInit: false, current: state };
990
+ onSuccessor: (successor: Successor) => boolean,
991
+ scope?: Scope,
992
+ ) => {
993
+ const run: Run = { environment, isInit: false, current: state, isStopped: false };
994
+ const counter = { successors: 0 };
794
995
  getRunner(expression, environment, false)(
795
996
  run,
796
- undefined,
997
+ scope,
797
998
  getEmptyState(environment),
798
999
  undefined,
799
1000
  false,
800
1001
  (partial, action) => {
1002
+ if (run.isStopped) return;
801
1003
  if (!isComplete(partial)) {
802
1004
  throw new TlaEvaluationError(
803
1005
  `Successor state is not completely specified by action ${action ?? "Next"}. The following variables are not assigned: ${getMissingVariables(partial, environment).join(", ")}`,
804
1006
  );
805
1007
  }
806
- successors.push({ state: partial, action });
1008
+ counter.successors++;
1009
+ run.isStopped = onSuccessor({ state: partial, action });
1010
+ },
1011
+ );
1012
+ return counter.successors;
1013
+ };
1014
+
1015
+ export const getSuccessors = (
1016
+ expression: Expression,
1017
+ state: Value[],
1018
+ environment: Environment,
1019
+ scope?: Scope,
1020
+ ): Successor[] => {
1021
+ const successors: Successor[] = [];
1022
+ forEachSuccessor(
1023
+ expression,
1024
+ state,
1025
+ environment,
1026
+ (successor) => {
1027
+ successors.push(successor);
1028
+ return false;
807
1029
  },
1030
+ scope,
808
1031
  );
809
1032
  return successors;
810
1033
  };
package/src/symmetry.ts CHANGED
@@ -5,9 +5,11 @@ import {
5
5
  createFunction,
6
6
  createSet,
7
7
  createSortedFunction,
8
+ createSortedSet,
8
9
  isEnumerable,
9
10
  isFunctionValue,
10
11
  isModelValue,
12
+ isSameValue,
11
13
  isSetValue,
12
14
  toFiniteFunction,
13
15
  toFiniteSet,
@@ -18,6 +20,9 @@ import {
18
20
 
19
21
  type Images = Map<string, ModelValue>;
20
22
 
23
+ const CACHE_LIMIT = 1 << 22;
24
+ const CACHED_SIZE_LIMIT = 64;
25
+
21
26
  interface Permutation {
22
27
  images: Images;
23
28
  cache: WeakMap<ObjectValue, Value>;
@@ -31,7 +36,7 @@ const getPermutationKey = (permutation: Images) =>
31
36
  .sort()
32
37
  .join(",");
33
38
 
34
- const composePermutations = (first: Images, second: Images): Images => {
39
+ const composePermutations = (first: Images, second: Images) => {
35
40
  const composed: Images = new Map();
36
41
  const names = new Set([...first.keys(), ...second.keys()]);
37
42
  names.forEach((name) => {
@@ -42,14 +47,14 @@ const composePermutations = (first: Images, second: Images): Images => {
42
47
  return composed;
43
48
  };
44
49
 
45
- const toImages = (value: Value, name: string): Images => {
50
+ const toImages = (value: Value, name: string) => {
46
51
  if (!isFunctionValue(value)) {
47
52
  throw new TlaConfigError(`The symmetry values of ${name} must be functions`);
48
53
  }
49
- const fn = toFiniteFunction(value);
54
+ const functionValue = toFiniteFunction(value);
50
55
  const permutation: Images = new Map();
51
- fn.domain.forEach((key, index) => {
52
- const image = fn.range[index];
56
+ functionValue.domain.forEach((key, index) => {
57
+ const image = functionValue.range[index];
53
58
  if (!isModelValue(key) || !isModelValue(image)) {
54
59
  throw new TlaConfigError("Symmetry function must have model values as domain and range");
55
60
  }
@@ -103,7 +108,7 @@ export const getSymmetryGroup = (name: string, environment: Environment): Permut
103
108
  }));
104
109
  };
105
110
 
106
- const permuteElements = (elements: Value[], permutation: Permutation): Value[] | undefined => {
111
+ const permuteElements = (elements: Value[], permutation: Permutation) => {
107
112
  for (let index = 0; index < elements.length; index++) {
108
113
  const element = elements[index];
109
114
  const permuted = permuteValue(element, permutation);
@@ -118,8 +123,32 @@ const permuteElements = (elements: Value[], permutation: Permutation): Value[] |
118
123
  return undefined;
119
124
  };
120
125
 
121
- const CACHE_LIMIT = 1 << 22;
122
- const CACHED_SIZE_LIMIT = 16;
126
+ // A permutation maps distinct elements to distinct elements and keeps the elements it doesn't move
127
+ // in order, so it sorts only the moved ones and merges them back.
128
+ const permuteSortedElements = (elements: Value[], permutation: Permutation) => {
129
+ const kept: Value[] = [];
130
+ const moved: Value[] = [];
131
+ for (const element of elements) {
132
+ const permuted = permuteValue(element, permutation);
133
+ if (permuted === element) kept.push(element);
134
+ else moved.push(permuted);
135
+ }
136
+ if (moved.length === 0) return undefined;
137
+ moved.sort(compareValues);
138
+ const merged: Value[] = [];
139
+ let keptIndex = 0;
140
+ let movedIndex = 0;
141
+ while (keptIndex < kept.length && movedIndex < moved.length) {
142
+ merged.push(
143
+ compareValues(kept[keptIndex], moved[movedIndex]) < 0
144
+ ? kept[keptIndex++]
145
+ : moved[movedIndex++],
146
+ );
147
+ }
148
+ while (keptIndex < kept.length) merged.push(kept[keptIndex++]);
149
+ while (movedIndex < moved.length) merged.push(moved[movedIndex++]);
150
+ return merged;
151
+ };
123
152
 
124
153
  const getSize = (value: ObjectValue) =>
125
154
  value.kind === "Set"
@@ -135,7 +164,10 @@ const permuteValue = (value: Value, permutation: Permutation): Value => {
135
164
  if (size === 0 || size > CACHED_SIZE_LIMIT) return computePermutedValue(value, permutation);
136
165
  const cached = permutation.cache.get(value);
137
166
  if (cached !== undefined) return cached;
138
- const permuted = computePermutedValue(value, permutation);
167
+ const computed = computePermutedValue(value, permutation);
168
+ // A permutation often maps a value to an equal one. Keeping the original lets the comparison
169
+ // with the smallest state so far stop at identity.
170
+ const permuted = computed !== value && isSameValue(computed, value) ? value : computed;
139
171
  if (permutation.cacheSize >= permutation.cacheLimit) {
140
172
  permutation.cache = new WeakMap();
141
173
  permutation.cacheSize = 0;
@@ -145,20 +177,30 @@ const permuteValue = (value: Value, permutation: Permutation): Value => {
145
177
  return permuted;
146
178
  };
147
179
 
148
- const computePermutedValue = (value: ObjectValue, permutation: Permutation): Value => {
180
+ const computePermutedValue = (value: ObjectValue, permutation: Permutation) => {
149
181
  const kind = value.kind;
150
182
  if (kind === "Set") {
151
- const elements = permuteElements(value.elements, permutation);
152
- return elements ? createSet(elements) : value;
183
+ const elements = permuteSortedElements(value.elements, permutation);
184
+ return elements ? createSortedSet(elements) : value;
153
185
  }
154
186
  if (kind === "Function" || (kind === "LazyFunction" && isEnumerable(value.domain))) {
155
- const fn = toFiniteFunction(value);
156
- const domain = permuteElements(fn.domain, permutation);
157
- const range = permuteElements(fn.range, permutation) ?? fn.range;
187
+ const functionValue = toFiniteFunction(value);
188
+ const domain = permuteElements(functionValue.domain, permutation);
189
+ const range = permuteElements(functionValue.range, permutation) ?? functionValue.range;
158
190
  if (domain) {
159
- return createFunction(domain.map((key, index): [Value, Value] => [key, range[index]]));
191
+ const permuted = createFunction(
192
+ domain.map((key, index): [Value, Value] => [key, range[index]]),
193
+ );
194
+ // A permutation often maps the domain to itself, such as a function over the symmetric set.
195
+ // Sharing the original domain array lets comparisons with other images skip the domain.
196
+ const isSameDomain = permuted.domain.every(
197
+ (key, index) => key === functionValue.domain[index],
198
+ );
199
+ return isSameDomain ? createSortedFunction(functionValue.domain, permuted.range) : permuted;
160
200
  }
161
- return range === fn.range ? fn : createSortedFunction(fn.domain, range);
201
+ return range === functionValue.range
202
+ ? functionValue
203
+ : createSortedFunction(functionValue.domain, range);
162
204
  }
163
205
  if (kind === "Interval" || !isSetValue(value) || !isEnumerable(value)) return value;
164
206
  const set = toFiniteSet(value);
@@ -173,20 +215,34 @@ const permuteRemaining = (state: Value[], permuted: Value[], permutation: Permut
173
215
  return permuted;
174
216
  };
175
217
 
176
- const getSmallerPermutation = (state: Value[], minimum: Value[], permutation: Permutation) => {
218
+ const getSmallerPermutation = (
219
+ state: Value[],
220
+ minimum: Value[],
221
+ permutation: Permutation,
222
+ order: number[] | undefined,
223
+ ) => {
177
224
  const permuted: Value[] = [];
178
- for (let index = 0; index < state.length; index++) {
225
+ for (let position = 0; position < state.length; position++) {
226
+ const index = order ? order[position] : position;
179
227
  const value = permuteValue(state[index], permutation);
180
228
  const comparison = compareValues(value, minimum[index]);
181
229
  if (comparison > 0) return undefined;
182
- permuted.push(value);
183
- if (comparison < 0) return permuteRemaining(state, permuted, permutation);
230
+ if (!order) permuted.push(value);
231
+ if (comparison < 0) {
232
+ return order
233
+ ? state.map((item) => permuteValue(item, permutation))
234
+ : permuteRemaining(state, permuted, permutation);
235
+ }
184
236
  }
185
237
  return undefined;
186
238
  };
187
239
 
188
- export const getRepresentative = (state: Value[], group: Permutation[]): Value[] =>
240
+ export const getRepresentative = (
241
+ state: Value[],
242
+ group: Permutation[],
243
+ order?: number[],
244
+ ): Value[] =>
189
245
  group.reduce(
190
- (minimum, permutation) => getSmallerPermutation(state, minimum, permutation) ?? minimum,
246
+ (minimum, permutation) => getSmallerPermutation(state, minimum, permutation, order) ?? minimum,
191
247
  state,
192
248
  );