tla-ts 0.0.10-dev.28c823e4b → 0.0.10-dev.b4a856304

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 (68) hide show
  1. package/dist/index.cjs +1 -1
  2. package/dist/index.d.cts +0 -34
  3. package/dist/index.d.ts +0 -34
  4. package/dist/index.js +1 -1
  5. package/dist/parallel-worker.cjs +1 -1
  6. package/dist/parallel-worker.js +1 -1
  7. package/dist/prove.cjs +43 -43
  8. package/dist/prove.js +47 -47
  9. package/dist/run.cjs +30 -30
  10. package/dist/run.js +33 -33
  11. package/dist/transfer.cjs +38 -38
  12. package/dist/transfer.js +39 -39
  13. package/package.json +1 -1
  14. package/src/ast.ts +5 -0
  15. package/src/bags.ts +5 -2
  16. package/src/builtins.ts +8 -1
  17. package/src/check.ts +193 -128
  18. package/src/cli/run.ts +2 -0
  19. package/src/cli/runtime-invariants.ts +7 -8
  20. package/src/cli/shared.ts +4 -0
  21. package/src/cli/tlc-arguments.ts +30 -24
  22. package/src/cli/tlc-usage.ts +3 -2
  23. package/src/evaluate.ts +102 -26
  24. package/src/java-overrides.ts +9 -4
  25. package/src/json-reader.ts +2 -1
  26. package/src/json.ts +11 -4
  27. package/src/levels.ts +15 -7
  28. package/src/lexer.ts +83 -72
  29. package/src/liveness-checker.ts +106 -77
  30. package/src/liveness.ts +34 -10
  31. package/src/parallel.ts +33 -26
  32. package/src/parser.ts +226 -163
  33. package/src/pcal/ast.ts +65 -53
  34. package/src/pcal/parse.ts +191 -144
  35. package/src/pcal/tokenize.ts +115 -91
  36. package/src/pcal/translate.ts +98 -83
  37. package/src/pcal/validate.ts +50 -48
  38. package/src/pretty-print.ts +6 -6
  39. package/src/randomization.ts +4 -1
  40. package/src/resolve.ts +70 -12
  41. package/src/runtime.ts +18 -11
  42. package/src/sany/builtins.ts +3 -1
  43. package/src/sany/generator.ts +127 -74
  44. package/src/sany/levels.ts +9 -5
  45. package/src/sany/lexer.ts +44 -40
  46. package/src/sany/linter.ts +1 -0
  47. package/src/search.ts +1 -1
  48. package/src/simulate.ts +59 -50
  49. package/src/spec-description.ts +34 -23
  50. package/src/standard-definitions.ts +3 -0
  51. package/src/standard-modules.ts +12 -1
  52. package/src/state-graph.ts +8 -1
  53. package/src/subexpressions.ts +47 -38
  54. package/src/successors.ts +35 -14
  55. package/src/symmetry.ts +19 -4
  56. package/src/tlc/fingerprint.ts +21 -15
  57. package/src/tlc/jar-data.ts +1 -0
  58. package/src/tlc/messages.ts +21 -2
  59. package/src/tlc/order.ts +38 -20
  60. package/src/tlc/random.ts +30 -18
  61. package/src/tlc/replay.ts +33 -13
  62. package/src/tlc/summary.ts +45 -36
  63. package/src/tlc/tlc-operators.ts +14 -4
  64. package/src/tlc/tlcext-operators.ts +15 -11
  65. package/src/tlc/trace-spec.ts +4 -0
  66. package/src/tlc/value-stream.ts +13 -9
  67. package/src/tlc/version.ts +1 -0
  68. package/src/values.ts +181 -74
package/src/tlc/random.ts CHANGED
@@ -24,14 +24,14 @@ const SEED_MASK = (1n << 48n) - 1n;
24
24
  const MAXIMUM_INT = 2147483647;
25
25
 
26
26
  export const createJavaRandom = (seed: bigint): JavaRandom => {
27
- let state = (BigInt.asUintN(64, seed) ^ MULTIPLIER) & SEED_MASK;
27
+ const state = { value: (BigInt.asUintN(64, seed) ^ MULTIPLIER) & SEED_MASK };
28
28
  const next = (bits: number) => {
29
- state = (state * MULTIPLIER + 0xbn) & SEED_MASK;
30
- return Number(BigInt.asIntN(32, state >> BigInt(48 - bits)));
29
+ state.value = (state.value * MULTIPLIER + 0xbn) & SEED_MASK;
30
+ return Number(BigInt.asIntN(32, state.value >> BigInt(48 - bits)));
31
31
  };
32
32
  return {
33
33
  setSeed: (value) => {
34
- state = (BigInt.asUintN(64, value) ^ MULTIPLIER) & SEED_MASK;
34
+ state.value = (BigInt.asUintN(64, value) ^ MULTIPLIER) & SEED_MASK;
35
35
  },
36
36
  nextInt: (bound) => {
37
37
  const first = next(31);
@@ -47,6 +47,7 @@ export const createJavaRandom = (seed: bigint): JavaRandom => {
47
47
  };
48
48
  };
49
49
 
50
+ // RandomGenerator.primes holds the 1341 consecutive primes from 1277011 to 1295953.
50
51
  const PRIMES: number[] = [];
51
52
 
52
53
  const isPrime = (candidate: number) => {
@@ -65,24 +66,29 @@ const getPrimes = () => {
65
66
 
66
67
  export const nextPrime = (random: JavaRandom) => {
67
68
  const primes = getPrimes();
68
- let index = primes.length;
69
- while (index === primes.length) index = Math.floor(random.nextDouble() * primes.length);
70
- return primes[index];
69
+ const choice = { index: primes.length };
70
+ while (choice.index === primes.length) {
71
+ choice.index = Math.floor(random.nextDouble() * primes.length);
72
+ }
73
+ return primes[choice.index];
71
74
  };
72
75
 
73
76
  const getPrimeFactors = (value: number) => {
74
77
  const factors: number[] = [];
75
- let remaining = value;
76
- for (let divisor = 2; divisor * divisor <= remaining; divisor++) {
77
- while (remaining % divisor === 0) {
78
+ const remaining = { value };
79
+ for (let divisor = 2; divisor * divisor <= remaining.value; divisor++) {
80
+ while (remaining.value % divisor === 0) {
78
81
  factors.push(divisor);
79
- remaining /= divisor;
82
+ remaining.value /= divisor;
80
83
  }
81
84
  }
82
- if (remaining > 1) factors.push(remaining);
85
+ if (remaining.value > 1) factors.push(remaining.value);
83
86
  return factors;
84
87
  };
85
88
 
89
+ // EnumerableValue.computeOptimalMandA: the smallest modulus m >= max(size, 9) that isn't a
90
+ // multiple of 4 and has a repeated prime factor, and the multiplier 1 + the product of its
91
+ // distinct prime factors.
86
92
  const getModulusAndMultiplier = (size: number) => {
87
93
  for (let modulus = Math.max(size, 9); ; modulus++) {
88
94
  const factors = getPrimeFactors(modulus);
@@ -99,32 +105,35 @@ const getModulusAndMultiplier = (size: number) => {
99
105
  const getSubsetIndicesMaster = (count: number, size: number, random: JavaRandom) => {
100
106
  if (size <= 0) return [];
101
107
  const generator = getModulusAndMultiplier(size);
102
- let index = BigInt(random.nextInt(size));
108
+ const state = { index: BigInt(random.nextInt(size)) };
103
109
  const increment = BigInt(nextPrime(random));
104
110
  return Array.from({ length: count }, () => {
105
111
  do {
106
- index = (generator.multiplier * index + increment) % generator.modulus;
107
- } while (index >= size);
108
- return index;
112
+ state.index = (generator.multiplier * state.index + increment) % generator.modulus;
113
+ } while (state.index >= size);
114
+ return state.index;
109
115
  });
110
116
  };
111
117
 
118
+ // TLC 1.7.4's EnumerableValue.SubsetEnumerator: the i-th index is (x * i + a) mod size, for a
119
+ // prime x above size and a = random.nextInt(size), so the first size indices are distinct.
112
120
  const getSubsetIndices174 = (count: number, size: number, random: JavaRandom) => {
113
121
  if (size <= 0) return [];
114
122
  const stride = BigInt(size < 191 ? 191 : MAXIMUM_INT);
115
123
  const offset = BigInt(random.nextInt(size));
116
124
  return Array.from(
117
125
  { length: Math.min(count, size) },
118
- (_value, index) => (stride * BigInt(index) + offset) % BigInt(size),
126
+ (_, index) => (stride * BigInt(index) + offset) % BigInt(size),
119
127
  );
120
128
  };
121
129
 
122
130
  const LARGE_STRIDE = (1n << 63n) - 1n - 24n;
123
131
 
132
+ // For products with more than 2^31 - 1 elements.
124
133
  const getLargeSubsetIndices = (count: number, size: bigint, random: JavaRandom) => {
125
134
  const signed = random.nextLong();
126
135
  const offset = BigInt.asIntN(64, signed < 0n ? -signed : signed);
127
- return Array.from({ length: count }, (_value, index) => {
136
+ return Array.from({ length: count }, (_, index) => {
128
137
  const value = (LARGE_STRIDE * BigInt(index) + offset) % size;
129
138
  return value < 0n ? value + size : value;
130
139
  });
@@ -170,6 +179,7 @@ const getProduct = (set: Value): Product | undefined => {
170
179
  return undefined;
171
180
  };
172
181
 
182
+ // TLC 1.7.4 enumerates a set of tuples to draw from it.
173
183
  export const getEnumeratedFactors = (set: Value, version: TlcVersion) =>
174
184
  version === "1.7.4" && typeof set === "object" && set.kind === "ProductSet"
175
185
  ? set.factors
@@ -201,6 +211,8 @@ export const getRandomSubset = (
201
211
  return getSubsetIndices(count, elements.length, random).map((index) => elements[Number(index)]);
202
212
  };
203
213
 
214
+ // TLC!RandomElement chooses each component of a set of functions, records, or tuples
215
+ // separately, and otherwise indexes the enumerated set with nextDouble.
204
216
  export const getRandomElement = (set: Value, random: JavaRandom): Value => {
205
217
  if (typeof set === "object" && set.kind === "FunctionSet") {
206
218
  // TLC builds the chosen function without the interval its domain came from.
package/src/tlc/replay.ts CHANGED
@@ -40,11 +40,16 @@ import {
40
40
  import { substitutionFrames } from "../instances";
41
41
  import { MESSAGE_CODE } from "./messages";
42
42
 
43
+ // Replays a failed computation as TLC's CallStackTool does, walking the predicates in the order
44
+ // and nesting of Tool.getInitStates and getNextStates, so it records the nodes TLC records, and
45
+ // counts the coverage TLC counts.
46
+
43
47
  interface ReplayAction {
44
48
  expression: Expression;
45
49
  scope: Scope | undefined;
46
50
  }
47
51
 
52
+ // TLC's ActionItemList: the conjuncts left to process, the first at the head.
48
53
  interface ActionItem {
49
54
  kind: "Predicate" | "Unchanged" | "Changed";
50
55
  expression: Expression;
@@ -77,6 +82,7 @@ const withFrame = <Result>(replay: Replay, expression: Expression, run: () => Re
77
82
  try {
78
83
  return run();
79
84
  } catch (error) {
85
+ // A quantifier enumerates its bounds outside any evaluation.
80
86
  freezeCallStack(callStack, sets.slice(depth), error);
81
87
  throw error;
82
88
  } finally {
@@ -95,6 +101,8 @@ const runAt = <Result>(replay: Replay, node: number, run: () => Result) =>
95
101
  const evaluateAt = (replay: Replay, node: number, expression: Expression, context: Context) =>
96
102
  runAt(replay, node, () => evaluate(expression, context));
97
103
 
104
+ // TLC evaluates a user-defined or overridden operator's arguments under its node, but doesn't
105
+ // count the node itself.
98
106
  const evaluateOperatorAt = (
99
107
  replay: Replay,
100
108
  node: number,
@@ -124,6 +132,7 @@ const assign = (partial: State, index: number, value: Value) => {
124
132
  return copy;
125
133
  };
126
134
 
135
+ // SANY parses A /\ B /\ C as (A /\ B) /\ C, so the replay recreates the node of each prefix.
127
136
  const getPrefix = (expression: Expression & { kind: "And" | "Or" }, count: number): Expression => {
128
137
  const first = expression.operands[0].location;
129
138
  const range = expression.location.range;
@@ -184,9 +193,13 @@ const isTrue = (value: Value) => {
184
193
  return value;
185
194
  };
186
195
 
196
+ // Once every variable has a value, TLC evaluates the conjuncts left instead of walking them,
197
+ // though not under ENABLED, and the next states take this shortcut only with warnings on.
187
198
  export const isAssignedShortcut = (replay: Pick<Replay, "environment" | "isInit" | "isEnabled">) =>
188
199
  !replay.isEnabled && (replay.isInit || replay.environment.runtime.isWarningEnabled);
189
200
 
201
+ // TLC counts the node that goes on to the conjuncts left for each next state they produce, but
202
+ // counts an initial state only as it adds it.
190
203
  const proceed = (
191
204
  replay: Replay,
192
205
  items: ActionItem | undefined,
@@ -256,6 +269,7 @@ const isChanged = (replay: Replay, item: ActionItem, partial: State) => {
256
269
  try {
257
270
  return !isEqualLikeTlc(before, after);
258
271
  } catch (error) {
272
+ // TLC's v0.equals(v1) raises a FingerprintException when v0 has a source.
259
273
  if (replay.callStack) freezeCallStack(replay.callStack, [before], error);
260
274
  throw error;
261
275
  }
@@ -308,6 +322,7 @@ const visitAt = (
308
322
  switch (expression.kind) {
309
323
  case "Let": {
310
324
  const context = getContext(replay, scope, partial);
325
+ // TLC walks a LET definition's body again at each reference, under the reference.
311
326
  const definitions = expression.definitions;
312
327
  const bound = replay.coverage
313
328
  ? bindDefinitions(definitions, context, {
@@ -328,6 +343,7 @@ const visitAt = (
328
343
  }
329
344
  });
330
345
 
346
+ // The value of a user-defined operator TLC evaluates instead of walking its body.
331
347
  const visitValue = (
332
348
  replay: Replay,
333
349
  value: Value,
@@ -413,6 +429,7 @@ const visitDefined = (
413
429
  return visitValue(replay, value, items, partial, node);
414
430
  };
415
431
 
432
+ // A variable takes the value when it has none yet, and otherwise must already have it.
416
433
  const proceedWithValue = (
417
434
  replay: Replay,
418
435
  items: ActionItem | undefined,
@@ -434,6 +451,7 @@ const createItem = (
434
451
  rest: ActionItem | undefined,
435
452
  ): ActionItem => ({ kind, expression, scope, node, rest });
436
453
 
454
+ // TLC costs a set it enumerates for each element, and for the end of the enumeration.
437
455
  const getEnumerated = (replay: Replay, set: Value, elements: Value[]) => {
438
456
  if (replay.coverage) costCoverage(replay.coverage, set, elements.length + 1);
439
457
  return elements;
@@ -464,6 +482,7 @@ const visitAssignment = (
464
482
  return proceedWithValue(replay, items, partial, index, value, node);
465
483
  }
466
484
  const set: Value = expression.operator === "\\subseteq" ? { kind: "Subset", base: value } : value;
485
+ // TLC gives the power set the source of its base, so a failure to enumerate it names both.
467
486
  if (typeof set === "object" && set !== value) replay.callStack?.sources.set(set, source);
468
487
  if (assigned !== undefined) {
469
488
  return (
@@ -491,6 +510,7 @@ const ENABLED_TEMPORAL_FORMS: Partial<Record<Expression["kind"], string>> = {
491
510
  StrongFairness: "SF",
492
511
  };
493
512
 
513
+ // TLC rejects a temporal formula, and a quantifier or CHOOSE without a bound, under ENABLED.
494
514
  export const getEnabledFailure = (expression: Expression) => {
495
515
  const form =
496
516
  expression.kind === "Apply" && (expression.operator === "~>" || expression.operator === "-+->")
@@ -616,6 +636,7 @@ const visitApplication = (
616
636
  case "Forall": {
617
637
  const bounds = getBindings(replay, expression, context, node);
618
638
  if (bounds.length === 0) return proceed(replay, items, partial, node);
639
+ // TLC adds each binding after the first to the front of the conjuncts left.
619
640
  const rest = bounds
620
641
  .slice(1)
621
642
  .reduce<ActionItem | undefined>(
@@ -743,7 +764,9 @@ const visitUnchanged = (
743
764
  return visitUnchanged(replay, operator.body, items, operator.scope, partial, node);
744
765
  }
745
766
  }
746
- // Deviation from TLC: Tool#enabledUnchanged evaluates the application in the partial next state and fails on an unassigned variable.
767
+ // Tool#enabledUnchanged evaluates an operator application in the partial next state, which
768
+ // fails on a variable it hasn't assigned, as its comment says. tla-ts walks the operator's
769
+ // body as it walks a definition without parameters.
747
770
  if (replay.isEnabled && expression.kind === "Apply") {
748
771
  const context = getContext(replay, scope, partial);
749
772
  const operator = resolveApplyOperator(expression, context);
@@ -812,6 +835,7 @@ export const replayEnabled = (
812
835
  const callStack = replay.callStack;
813
836
  const depth = callStack?.expressions.length ?? 0;
814
837
  try {
838
+ // liveness.ts builds the <<A>>_v of WF_v(A) at the location of A.
815
839
  if (expression.kind === "AngleAction" && expression.location === expression.action.location) {
816
840
  const changed = createItem("Changed", expression.subscript, scope, -1, undefined);
817
841
  visit(replay, expression.action, changed, scope, getEmptyState(environment), -1);
@@ -821,6 +845,7 @@ export const replayEnabled = (
821
845
  return false;
822
846
  } catch (error) {
823
847
  if (error !== ENABLED_FOUND) throw error;
848
+ // The frames the walk left are those of the successor, not of a failure.
824
849
  if (callStack) {
825
850
  callStack.expressions.length = depth;
826
851
  callStack.isFrozen = false;
@@ -845,12 +870,14 @@ export const replayInitialStates = (
845
870
  visit(replay, first.expression, rest, first.scope, getEmptyState(environment), first.node ?? -1);
846
871
  };
847
872
 
873
+ // TLC checks the successors of an action once it has computed them all.
848
874
  export const replaySuccessors = <Action extends ReplayAction>(
849
875
  actions: Action[],
850
876
  state: Value[],
851
877
  environment: Environment,
852
878
  onState: (state: Value[], action: Action) => void,
853
879
  ) => {
880
+ // TLC fails to split a next-state relation that isn't an operator application, so replays none.
854
881
  if (actions.some((action) => LITERAL_KINDS.has(action.expression.kind))) return;
855
882
  actions.forEach((action) => {
856
883
  const successors: Value[][] = [];
@@ -871,9 +898,10 @@ export const walkSuccessors = (
871
898
  visit(replay, action.expression, undefined, action.scope, getEmptyState(environment), node);
872
899
  };
873
900
 
901
+ // TLC's Spec.getPrimedLocs, whose nodes TLC reports even when they never produce a state.
874
902
  export const getPrimedRanges = (actions: ReplayAction[], environment: Environment) => {
875
903
  const ranges: Expression[] = [];
876
- const createContext = (scope: Scope | undefined): Context => ({
904
+ const context = (scope: Scope | undefined): Context => ({
877
905
  environment,
878
906
  scope,
879
907
  state: undefined,
@@ -905,11 +933,7 @@ export const getPrimedRanges = (actions: ReplayAction[], environment: Environmen
905
933
  ): void => {
906
934
  switch (expression.kind) {
907
935
  case "Let":
908
- collect(
909
- expression.body,
910
- bindDefinitions(expression.definitions, createContext(scope)),
911
- visited,
912
- );
936
+ collect(expression.body, bindDefinitions(expression.definitions, context(scope)), visited);
913
937
  return;
914
938
  case "Label":
915
939
  collect(expression.body, scope, visited);
@@ -965,7 +989,7 @@ export const getPrimedRanges = (actions: ReplayAction[], environment: Environmen
965
989
  }
966
990
  const operator =
967
991
  expression.kind === "Apply"
968
- ? resolveApplyOperator(expression, createContext(scope))
992
+ ? resolveApplyOperator(expression, context(scope))
969
993
  : binding?.kind === "Operator"
970
994
  ? binding.operator
971
995
  : binding
@@ -977,11 +1001,7 @@ export const getPrimedRanges = (actions: ReplayAction[], environment: Environmen
977
1001
  const args = expression.kind === "Apply" ? expression.args : [];
978
1002
  if (operator.params.length !== args.length) return;
979
1003
  visited.add(operator.body);
980
- collect(
981
- operator.body,
982
- bindOperatorArguments(operator, args, createContext(scope)),
983
- visited,
984
- );
1004
+ collect(operator.body, bindOperatorArguments(operator, args, context(scope)), visited);
985
1005
  visited.delete(operator.body);
986
1006
  }
987
1007
  }
@@ -1,12 +1,16 @@
1
+ // TLC counts how many new states each expanded state yields in 32 buckets, the last of which
2
+ // holds every count from 31 up.
1
3
  export const OUT_DEGREE_BUCKETS = 32;
2
4
 
3
5
  export const getOptimisticProbability = (distinctStates: number, generatedStates: number) =>
4
6
  distinctStates * ((generatedStates - distinctStates) / 2 ** 64);
5
7
 
8
+ // TLC computes the estimate from the actual fingerprints only when the optimistic one is this high.
6
9
  const ACTUAL_PROBABILITY_THRESHOLD = 1e-10;
7
10
 
8
11
  const withDecimalPoint = (text: string) => (text.includes(".") ? text : `${text}.0`);
9
12
 
13
+ // Java's Double.toString, which prints a number below 1E-3 or from 1E7 up in scientific notation.
10
14
  const toJavaString = (value: number) => {
11
15
  const magnitude = Math.abs(value);
12
16
  if (magnitude >= 1e-3 && magnitude < 1e7) return withDecimalPoint(String(value));
@@ -17,36 +21,37 @@ const toJavaString = (value: number) => {
17
21
  const isDigit = (character: string | undefined) =>
18
22
  character !== undefined && character >= "0" && character <= "9";
19
23
 
24
+ // TLC's ProbabilityToString, which keeps two significant digits and drops a leading zero.
20
25
  export const formatProbability = (value: number) => {
21
26
  if (value === 0) return "0.0";
22
27
  const text = toJavaString(value);
23
- let next = 0;
24
- let digits = 0;
25
- let result = "";
26
- while (text[next] === "0") next++;
27
- while (isDigit(text[next])) {
28
- result += text[next++];
29
- digits++;
28
+ const cursor = { next: 0, digits: 0, result: "" };
29
+ while (text[cursor.next] === "0") cursor.next++;
30
+ while (isDigit(text[cursor.next])) {
31
+ cursor.result += text[cursor.next++];
32
+ cursor.digits++;
30
33
  }
31
- if (next === text.length) return result;
32
- if (text[next] !== ".") return text;
33
- next++;
34
- if (digits >= 2) {
35
- while (isDigit(text[next])) next++;
34
+ if (cursor.next === text.length) return cursor.result;
35
+ if (text[cursor.next] !== ".") return text;
36
+ cursor.next++;
37
+ if (cursor.digits >= 2) {
38
+ while (isDigit(text[cursor.next])) cursor.next++;
36
39
  } else {
37
- result += ".";
38
- if (digits === 0) {
39
- while (text[next] === "0") result += text[next++];
40
+ cursor.result += ".";
41
+ if (cursor.digits === 0) {
42
+ while (text[cursor.next] === "0") cursor.result += text[cursor.next++];
40
43
  }
41
- while (isDigit(text[next]) && digits < 2) {
42
- result += text[next++];
43
- digits++;
44
+ while (isDigit(text[cursor.next]) && cursor.digits < 2) {
45
+ cursor.result += text[cursor.next++];
46
+ cursor.digits++;
44
47
  }
45
- if (isDigit(text[next]) && Number(text[next]) >= 5) result = roundUp(result);
46
- while (isDigit(text[next])) next++;
48
+ if (isDigit(text[cursor.next]) && Number(text[cursor.next]) >= 5) {
49
+ cursor.result = roundUp(cursor.result);
50
+ }
51
+ while (isDigit(text[cursor.next])) cursor.next++;
47
52
  }
48
- if (next >= text.length) return result;
49
- if (text[next] === "E") return `${result}${text.slice(next)}`;
53
+ if (cursor.next >= text.length) return cursor.result;
54
+ if (text[cursor.next] === "E") return `${cursor.result}${text.slice(cursor.next)}`;
50
55
  return text;
51
56
  };
52
57
 
@@ -60,15 +65,18 @@ const roundUp = (digits: string): string => {
60
65
  return `${front}${Number(last) + 1}`;
61
66
  };
62
67
 
68
+ // 1 divided by the distance, rounded half up to two significant digits like Java's BigDecimal.
63
69
  export const getActualProbability = (distance: bigint) => {
64
- let exponent = 0;
65
- while (10n ** BigInt(exponent + 1) < distance * 10n) exponent++;
66
- const scale = 10n ** BigInt(exponent + 1);
70
+ const exponent = { value: 0 };
71
+ while (10n ** BigInt(exponent.value + 1) < distance * 10n) exponent.value++;
72
+ const scale = 10n ** BigInt(exponent.value + 1);
67
73
  const quotient = scale / distance;
68
74
  const isRoundedUp = (scale % distance) * 2n >= distance;
69
- return Number(`${quotient + (isRoundedUp ? 1n : 0n)}e-${exponent + 1}`);
75
+ return Number(`${quotient + (isRoundedUp ? 1n : 0n)}e-${exponent.value + 1}`);
70
76
  };
71
77
 
78
+ // TLC splits its fingerprints into two sets by their top bit and reports the smallest distance
79
+ // between two fingerprints in the same set. Sorted as signed integers, each set is contiguous.
72
80
  export const getFingerprintDistance = (
73
81
  distinctStates: number,
74
82
  generatedStates: number,
@@ -77,9 +85,10 @@ export const getFingerprintDistance = (
77
85
  const probability = getOptimisticProbability(distinctStates, generatedStates);
78
86
  if (probability < ACTUAL_PROBABILITY_THRESHOLD) return undefined;
79
87
  const fingerprints = getFingerprints().sort();
88
+ // A gap whose high words differ by at most 2^20 is below 2^53, so a number holds it exactly and
89
+ // only wider gaps need a BigInt.
80
90
  const words = new Int32Array(fingerprints.buffer);
81
- let narrowest = Number.POSITIVE_INFINITY;
82
- let widest = 0x7fff_ffff_ffff_ffffn;
91
+ const nearest = { narrow: Number.POSITIVE_INFINITY, wide: 0x7fff_ffff_ffff_ffffn };
83
92
  for (let index = 1; index < fingerprints.length; index++) {
84
93
  const high = words[2 * index + 1];
85
94
  const previousHigh = words[2 * index - 1];
@@ -87,15 +96,15 @@ export const getFingerprintDistance = (
87
96
  const highGap = high - previousHigh;
88
97
  if (highGap <= 0x10_0000) {
89
98
  const gap = highGap * 0x1_0000_0000 + (words[2 * index] >>> 0) - (words[2 * index - 2] >>> 0);
90
- narrowest = Math.min(narrowest, gap);
99
+ nearest.narrow = Math.min(nearest.narrow, gap);
91
100
  } else {
92
101
  const gap = fingerprints[index] - fingerprints[index - 1];
93
- if (gap < widest) widest = gap;
102
+ if (gap < nearest.wide) nearest.wide = gap;
94
103
  }
95
104
  }
96
- if (narrowest === Number.POSITIVE_INFINITY) return widest;
97
- const narrow = BigInt(narrowest);
98
- return narrow < widest ? narrow : widest;
105
+ if (nearest.narrow === Number.POSITIVE_INFINITY) return nearest.wide;
106
+ const narrow = BigInt(nearest.narrow);
107
+ return narrow < nearest.wide ? narrow : nearest.wide;
99
108
  };
100
109
 
101
110
  export const getOutDegreeSummary = (buckets: number[]) => {
@@ -104,10 +113,10 @@ export const getOutDegreeSummary = (buckets: number[]) => {
104
113
  const degrees = buckets.flatMap((count, degree) => (count > 0 ? [degree] : []));
105
114
  const total = buckets.reduce((sum, count, degree) => sum + count * degree, 0);
106
115
  const position = Math.floor(observations * 0.95);
107
- let cumulativeCount = 0;
116
+ const cumulative = { count: 0 };
108
117
  const percentile = degrees.find((degree) => {
109
- cumulativeCount += buckets[degree];
110
- return cumulativeCount > position;
118
+ cumulative.count += buckets[degree];
119
+ return cumulative.count > position;
111
120
  });
112
121
  return `The average outdegree of the complete state graph is ${Math.round(total / observations)} (minimum is ${degrees[0]}, the maximum ${degrees[degrees.length - 1]} and the 95th percentile is ${percentile}).`;
113
122
  };
@@ -46,9 +46,12 @@ const formatCalendarVersion = (date: Date) =>
46
46
  const getRegisterFunction = <Key extends Value>(registers: Map<Key, Value>) =>
47
47
  createFunction([...registers].map(([key, value]): [Value, Value] => [key, createTuple([value])]));
48
48
 
49
+ // TLC doesn't normalize the records it builds, so they keep their written order.
49
50
  const createTlcRecord = (fields: [string, Value][]) =>
50
51
  setFunctionClass(createWrittenFunction(fields), "record");
51
52
 
53
+ // TLC creates its model checker after it processes the spec, so these are undefined before then.
54
+
52
55
  const CHECKER_KEYS = new Set(["diameter", "generated", "distinct", "queue", "stats", "config"]);
53
56
  const TLC_174_KEYS = new Set(["diameter", "distinct", "queue", "duration", "level"]);
54
57
  const CHECKER_KEYS_174 = new Set(["diameter", "distinct", "queue", "level"]);
@@ -150,6 +153,7 @@ const getPermutations = (elements: Value[]): Value[][] =>
150
153
  ]),
151
154
  );
152
155
 
156
+ // TLC sorts the value of a TLCEval argument that it caches, with every value inside it.
153
157
  const normalizeDeeply = (value: Value): void => {
154
158
  if (typeof value !== "object") return;
155
159
  if (value.kind === "Set" || value.kind === "MixedSet") {
@@ -203,6 +207,7 @@ export const createTlcOperators = (
203
207
  defineOperator(":>", 2, (args) =>
204
208
  createFunction([[getValue(args, 0, ":>"), getValue(args, 1, ":>")]]),
205
209
  ),
210
+ // CombineFcn converts both arguments before it checks either.
206
211
  defineOperator("@@", 2, (args) => {
207
212
  const leftValue = getValue(args, 0, "@@");
208
213
  const rightValue = getValue(args, 1, "@@");
@@ -219,6 +224,7 @@ export const createTlcOperators = (
219
224
  defineOperator("ToString", 1, (args) =>
220
225
  rankString(formatValue(getValue(args, 0, "ToString"), true)),
221
226
  ),
227
+ // The checker passes no context where TLC caches the value, which it then sorts.
222
228
  {
223
229
  ...defineLazyOperator("TLCEval", 1, (args, context) => {
224
230
  const value = convertLikeTlcEval(getThunk(args, 0, "TLCEval")());
@@ -247,20 +253,23 @@ export const createTlcOperators = (
247
253
  if (typeof result === "boolean") return result;
248
254
  throw createModuleArgumentError("second", "SortSeq", "boolean function", result);
249
255
  };
256
+ // TLC's insertion sort moves each element back past the ones it precedes.
250
257
  const sorted = elements.slice(0, 1);
251
258
  elements.slice(1).forEach((element) => {
252
- let position = sorted.length;
253
- while (position > 0 && precedes(element, sorted[position - 1])) position--;
254
- sorted.splice(position, 0, element);
259
+ const position = { index: sorted.length };
260
+ while (position.index > 0 && precedes(element, sorted[position.index - 1])) position.index--;
261
+ sorted.splice(position.index, 0, element);
255
262
  });
256
263
  return createTuple(sorted);
257
264
  }),
265
+ // TLC reports a failure of TLCGet, its argument's too, as one of TLCGetSet.TLCGetEval.
258
266
  runtime.version === "1.7.4"
259
267
  ? overrideWithJava(
260
268
  {
261
269
  ...defineStateOperator("TLCGet", 1, (args, context) =>
262
270
  getTlcValue(runtime, getValue(args, 0, "TLCGet"), context),
263
271
  ),
272
+ // Unlike TLCGetSet.TLCGetEval, TLC.TLCGet declares no minimum level.
264
273
  isLevelConstant: true,
265
274
  },
266
275
  "public static tlc2.value.impl.Value tlc2.module.TLC.TLCGet(tlc2.value.impl.Value)",
@@ -272,7 +281,8 @@ export const createTlcOperators = (
272
281
  "public static tlc2.value.impl.Value tlc2.module.TLCGetSet.TLCGetEval(tlc2.tool.impl.Tool,tla2sany.semantic.ExprOrOpArgNode[],tlc2.util.Context,tlc2.tool.TLCState,tlc2.tool.TLCState,int,tlc2.tool.coverage.CostModel)",
273
282
  ),
274
283
  defineStateOperator("TLCSet", 2, (args) => {
275
- setTlcValue(runtime, print, getValue(args, 0, "TLCSet"), getValue(args, 1, "TLCSet"));
284
+ const key = getValue(args, 0, "TLCSet");
285
+ setTlcValue(runtime, print, key, getValue(args, 1, "TLCSet"));
276
286
  return true;
277
287
  }),
278
288
  defineConstant("Any", ANY_SET),
@@ -54,6 +54,7 @@ export const createActionRecord = (action: string | undefined) =>
54
54
  ],
55
55
  ]);
56
56
 
57
+ // TLC's CounterExample is its own class, so ToTrace refuses a record that only looks like one.
57
58
  const counterExamples = new WeakSet<Value & object>();
58
59
 
59
60
  const createCounterExampleRecord = (action: Value[], states: Value[]) => {
@@ -188,18 +189,16 @@ export const createTlcExtOperators = (
188
189
  }
189
190
  return false;
190
191
  }),
191
- defineStateOperator(
192
- "TLCGetOrDefault",
193
- 2,
194
- (args) =>
195
- getRegister(runtime, getValue(args, 0, "TLCGetOrDefault")) ??
196
- getValue(args, 1, "TLCGetOrDefault"),
197
- ),
198
- defineStateOperator("Trace", 0, (_args, context) => {
192
+ defineStateOperator("TLCGetOrDefault", 2, (args) => {
193
+ const key = getValue(args, 0, "TLCGetOrDefault");
194
+ return getRegister(runtime, key) ?? getValue(args, 1, "TLCGetOrDefault");
195
+ }),
196
+ defineStateOperator("Trace", 0, (_, context) => {
199
197
  const variables = context?.environment.variables ?? [];
198
+ // TLC evaluates an assumption in an empty state, which assigns none of the variables.
200
199
  const state = context?.state ?? variables.map(() => undefined);
201
200
  if (!context || !isCompleteState(state)) {
202
- const unassigned = variables.filter((_name, index) => state[index] === undefined);
201
+ const unassigned = variables.filter((_, index) => state[index] === undefined);
203
202
  throw new TlaEvaluationError(
204
203
  `In evaluating TLCExt!Trace, the state is not completely specified yet (variable${unassigned.length > 1 ? "s" : ""} ${unassigned.join(", ")} undefined).`,
205
204
  );
@@ -211,6 +210,7 @@ export const createTlcExtOperators = (
211
210
  name,
212
211
  step[index],
213
212
  ]);
213
+ // A simulated behavior's states also record their actions.
214
214
  const action = runtime.getSimulationValue?.("action", step);
215
215
  return createRecord(action === undefined ? fields : [["_action", action], ...fields]);
216
216
  }),
@@ -244,6 +244,7 @@ export const createTlcExtOperators = (
244
244
  }
245
245
  return createModelValue(name);
246
246
  }),
247
+ // Only simulation runs the deferred expression, for the successor it chooses.
247
248
  defineLazyOperator("TLCDefer", 1, (args, context) => {
248
249
  const expression = getOperator(args, 0, "TLCDefer").expression;
249
250
  if (context && expression) {
@@ -256,7 +257,9 @@ export const createTlcExtOperators = (
256
257
  defineOperator("TLCNoOp", 1, (args) => getValue(args, 0, "TLCNoOp")),
257
258
  {
258
259
  ...defineLazyOperator("PickSuccessor", 1, (args, context) => {
259
- // Deviation from TLC: TLCExt#pickSuccessor fingerprints a partial successor and fails, where TLCExt.tla promises TRUE.
260
+ // Outside an action, TLC's successor is an empty state, which assigns none of the variables.
261
+ // TLCExt.tla promises TRUE for a successor not fully determined, where TLCExt#pickSuccessor
262
+ // fingerprints it first and fails.
260
263
  const next = context?.next ?? (context?.environment.variables ?? []).map(() => undefined);
261
264
  if (!isCompleteState(next)) return true;
262
265
  if (context?.next && runtime.isSeen(next)) return true;
@@ -279,7 +282,7 @@ export const createTlcExtOperators = (
279
282
  `Extend behavior of length ${runtime.getLevel(context.state)} with a "${action?.name}" step [<Action ${action?.location.range && formatRange(action.location.range)}>]? (Yes/no/explored/states/diff):`,
280
283
  ),
281
284
  );
282
- // Deviation from TLC: PickSuccessor has no standard input to read an answer from.
285
+ // tla-ts gives PickSuccessor no standard input to read an answer from.
283
286
  throw new TlaEndOfInputError();
284
287
  }),
285
288
  isActionLevel: true,
@@ -320,6 +323,7 @@ export const createTlcExtOperators = (
320
323
  );
321
324
  }
322
325
  const definition = context ? getDefinition(name, context.environment) : undefined;
326
+ // A definition that TLC overrides with Java has the Java method's value, not its body's.
323
327
  const builtin = definition ? undefined : context?.environment.builtins.get(name);
324
328
  if (builtin?.arity === 0) return builtin.evaluate([], context);
325
329
  if (!definition || !context) {
@@ -30,6 +30,7 @@ const getJavaHash = (text: string) => {
30
30
  return hash ^ (hash >>> 16);
31
31
  };
32
32
 
33
+ // TLC lists the modules and the variables in the order a Java HashSet or HashMap iterates them.
33
34
  const getHashOrder = (names: string[]) => {
34
35
  const unique = [...new Set(names)];
35
36
  const capacity = 2 ** Math.max(4, Math.ceil(Math.log2(unique.length / 0.75)));
@@ -47,6 +48,7 @@ const formatJavaDate = (date: Date) => {
47
48
  return `${getPart({ weekday: "short" }, "weekday")} ${getPart({ month: "short" }, "month")} ${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())} ${getPart({ timeZoneName: "short" }, "timeZoneName")} ${date.getFullYear()}`;
48
49
  };
49
50
 
51
+ // Java's String#split drops the empty strings at the end.
50
52
  const splitLines = (text: string) => {
51
53
  const lines = text.split("\n");
52
54
  while (lines.length > 1 && lines[lines.length - 1] === "") lines.pop();
@@ -197,6 +199,8 @@ ${lassoStep}${variables
197
199
 
198
200
  `;
199
201
  const statesWithoutLasso = trace.filter((state) => !state.isBackToState && !state.isStuttering);
202
+ // TLC adds a view when a state appears twice before the lasso closes, so that TLCGet("level")
203
+ // tells the copies apart.
200
204
  const isViewed =
201
205
  isLasso &&
202
206
  new Set(statesWithoutLasso.map((state) => JSON.stringify(state.values))).size <