tla-ts 0.0.10-dev.b4a856304 → 0.0.10-dev.f16792fed

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 (72) hide show
  1. package/dist/index.cjs +1 -1
  2. package/dist/index.d.cts +34 -0
  3. package/dist/index.d.ts +34 -0
  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 +48 -48
  8. package/dist/prove.js +29 -29
  9. package/dist/run.cjs +40 -40
  10. package/dist/run.js +31 -31
  11. package/dist/transfer.cjs +36 -36
  12. package/dist/transfer.js +40 -40
  13. package/package.json +1 -1
  14. package/src/ast.ts +0 -5
  15. package/src/bags.ts +2 -5
  16. package/src/builtins.ts +1 -8
  17. package/src/check.ts +128 -193
  18. package/src/cli/options.ts +1 -1
  19. package/src/cli/run.ts +0 -2
  20. package/src/cli/runtime-invariants.ts +8 -7
  21. package/src/cli/shared.ts +0 -4
  22. package/src/cli/tlc-arguments.ts +24 -30
  23. package/src/cli/tlc-usage.ts +2 -3
  24. package/src/coverage.ts +3 -8
  25. package/src/evaluate.ts +26 -102
  26. package/src/java-hash.ts +7 -0
  27. package/src/java-overrides.ts +4 -9
  28. package/src/json-reader.ts +1 -2
  29. package/src/json.ts +4 -11
  30. package/src/levels.ts +7 -15
  31. package/src/lexer.ts +72 -83
  32. package/src/liveness-checker.ts +77 -106
  33. package/src/liveness.ts +10 -34
  34. package/src/parallel.ts +26 -33
  35. package/src/parser.ts +163 -226
  36. package/src/pcal/ast.ts +53 -65
  37. package/src/pcal/parse.ts +144 -191
  38. package/src/pcal/tokenize.ts +91 -115
  39. package/src/pcal/translate.ts +83 -98
  40. package/src/pcal/validate.ts +48 -50
  41. package/src/pretty-print.ts +6 -6
  42. package/src/randomization.ts +1 -4
  43. package/src/resolve.ts +12 -70
  44. package/src/runtime.ts +11 -18
  45. package/src/sany/builtins.ts +1 -3
  46. package/src/sany/generator.ts +74 -127
  47. package/src/sany/levels.ts +5 -9
  48. package/src/sany/lexer.ts +40 -44
  49. package/src/sany/linter.ts +0 -1
  50. package/src/sany/nodes.ts +4 -10
  51. package/src/search.ts +1 -1
  52. package/src/simulate.ts +50 -59
  53. package/src/spec-description.ts +23 -34
  54. package/src/standard-definitions.ts +0 -3
  55. package/src/standard-modules.ts +1 -12
  56. package/src/state-graph.ts +3 -15
  57. package/src/subexpressions.ts +38 -47
  58. package/src/successors.ts +14 -35
  59. package/src/symmetry.ts +4 -19
  60. package/src/tlc/fingerprint.ts +15 -21
  61. package/src/tlc/jar-data.ts +0 -1
  62. package/src/tlc/messages.ts +2 -21
  63. package/src/tlc/order.ts +22 -47
  64. package/src/tlc/random.ts +18 -30
  65. package/src/tlc/replay.ts +13 -33
  66. package/src/tlc/summary.ts +36 -45
  67. package/src/tlc/tlc-operators.ts +4 -14
  68. package/src/tlc/tlcext-operators.ts +11 -15
  69. package/src/tlc/trace-spec.ts +4 -9
  70. package/src/tlc/value-stream.ts +9 -13
  71. package/src/tlc/version.ts +0 -1
  72. package/src/values.ts +74 -186
package/src/tlc/order.ts CHANGED
@@ -1,7 +1,7 @@
1
- // Reproduces TLC's string order, by first interning, and its variable order, from SANY's context.
2
1
  import type { Module, SourceLocation } from "../ast";
3
2
  import type { ConfigValue, ModelConfig } from "../config";
4
3
  import { createMissingModuleError } from "../errors";
4
+ import { getJavaHashCode } from "../java-hash";
5
5
  import { tokenize, type Token } from "../lexer";
6
6
  import { extractModule, parseModule, parseModuleTokens } from "../parser";
7
7
  import { isBefore } from "../resolve";
@@ -28,7 +28,6 @@ interface SymbolEntry {
28
28
  interface SymbolTable {
29
29
  put: (entry: SymbolEntry) => void;
30
30
  inserted: SymbolEntry[];
31
- // Where the entries the module adds itself start, after those of the modules it extends.
32
31
  ownStart: number;
33
32
  enumerate: () => SymbolEntry[];
34
33
  }
@@ -57,16 +56,6 @@ const CANONICAL_OPERATORS = new Map(
57
56
 
58
57
  const getCanonicalName = (name: string) => CANONICAL_OPERATORS.get(name) ?? name;
59
58
 
60
- const getJavaHash = (text: string) => {
61
- let hash = 0;
62
- for (let index = 0; index < text.length; index++) {
63
- hash = (Math.imul(hash, 31) + text.charCodeAt(index)) | 0;
64
- }
65
- return hash;
66
- };
67
-
68
- // java.util.Hashtable as SANY's Context uses it: capacity 11, load factor 0.75, new entries at
69
- // the head of their bucket, and enumeration from the last bucket, each from tail to head.
70
59
  const createSymbolTable = (): SymbolTable => {
71
60
  let buckets: SymbolEntry[][] = Array.from({ length: 11 }, () => []);
72
61
  let threshold = 8;
@@ -106,7 +95,7 @@ const createSymbolTable = (): SymbolTable => {
106
95
  const createEntry = (name: string, kind: SymbolKind, isLocal: boolean): SymbolEntry => ({
107
96
  key: kind === "module" ? `module ${name}` : name,
108
97
  name,
109
- hash: getJavaHash(name) & 0x7fffffff,
98
+ hash: getJavaHashCode(name) & 0x7fffffff,
110
99
  kind,
111
100
  isLocal,
112
101
  });
@@ -154,7 +143,6 @@ type ModuleSearch = (
154
143
  visited: Set<string>,
155
144
  ) => [ModuleReferences, string] | undefined;
156
145
 
157
- // In the order SANY's SpecObj walks them to decide which module to parse next.
158
146
  const getModuleReferences = (
159
147
  tokens: Token[],
160
148
  unit: string | undefined,
@@ -179,10 +167,10 @@ const getModuleReferences = (
179
167
  innerModules.set(name, inner.references);
180
168
  references.inner.push(inner.references);
181
169
  index = inner.end;
182
- } else if (tokens[index - 1]?.text === ".") {
183
- // A record field named EXTENDS or INSTANCE, as in r.EXTENDS or [r EXCEPT !.INSTANCE = 0].
184
170
  continue;
185
- } else if (token.text === "EXTENDS") {
171
+ }
172
+ if (tokens[index - 1]?.text === ".") continue;
173
+ if (token.text === "EXTENDS") {
186
174
  const names = getDeclarations(tokens, index + 1);
187
175
  references.extends.push(...names);
188
176
  names.forEach((name) => allExtends.add(name));
@@ -209,8 +197,6 @@ const STRING_ESCAPES: Record<string, string> = {
209
197
  "\f": "\\f",
210
198
  };
211
199
 
212
- // SANY reads <1>2 and ---- MODULE as one token each, and interns a string literal with its
213
- // quotes, its contents only during semantic analysis.
214
200
  const getParsedTexts = (tokens: Token[]) => {
215
201
  const texts: string[] = [];
216
202
  for (let index = 0; index < tokens.length; index++) {
@@ -236,7 +222,6 @@ const getParsedTexts = (tokens: Token[]) => {
236
222
  return texts;
237
223
  };
238
224
 
239
- // A module starts with ---- MODULE Name, so its third token is its name.
240
225
  const getModuleName = (tokens: Token[]) => tokens[2]?.text;
241
226
 
242
227
  const getRanges = (tokens: Token[]) => {
@@ -264,19 +249,17 @@ interface ModuleText {
264
249
  getModule: () => Module;
265
250
  }
266
251
 
267
- // Read and parsed once, for every order and for the environment that evaluates it.
268
252
  const readModuleText = (text: string | undefined): ModuleText => {
269
253
  const tokens = text === undefined ? [] : tokenize(text);
270
- const parsed = { module: undefined as Module | undefined };
254
+ let parsedModule: Module | undefined;
271
255
  return {
272
256
  tokens,
273
257
  ranges: getRanges(tokens),
274
258
  getModule: () =>
275
- (parsed.module ??= text === undefined ? parseModule("") : parseModuleTokens(text, tokens)),
259
+ (parsedModule ??= text === undefined ? parseModule("") : parseModuleTokens(text, tokens)),
276
260
  };
277
261
  };
278
262
 
279
- // A module without a source has no tokens.
280
263
  const createModuleSet = (source: string, loadModule: ModuleLoader) => {
281
264
  const files = new Map<string, ParsedModule>();
282
265
  const nestedModules = new Map<string, ParsedModule>();
@@ -298,11 +281,12 @@ const createModuleSet = (source: string, loadModule: ModuleLoader) => {
298
281
  TLC_MODULE_SOURCES.get(name) ??
299
282
  SANY_STANDARD_MODULES.get(name) ??
300
283
  extractModule(source, name));
301
- const { tokens, ranges, getModule } = readText(text);
302
- const range = ranges.get(getModuleName(tokens) ?? "") ?? { start: 0, end: 0 };
303
- const file = { tokens, ...range, getModule };
284
+ const moduleText = readText(text);
285
+ const tokens = moduleText.tokens;
286
+ const range = moduleText.ranges.get(getModuleName(tokens) ?? "") ?? { start: 0, end: 0 };
287
+ const file = { tokens, ...range, getModule: moduleText.getModule };
304
288
  files.set(name ?? "", file);
305
- ranges.forEach((nestedRange, nestedName) => {
289
+ moduleText.ranges.forEach((nestedRange, nestedName) => {
306
290
  if (nestedRange.start === range.start || nestedModules.has(nestedName)) return;
307
291
  nestedModules.set(nestedName, {
308
292
  tokens,
@@ -320,7 +304,6 @@ const createModuleSet = (source: string, loadModule: ModuleLoader) => {
320
304
  };
321
305
  };
322
306
 
323
- // The root module's context is under undefined.
324
307
  type ModuleSet = ReturnType<typeof createModuleSet>["getParsed"];
325
308
 
326
309
  const createContexts = (getParsed: ModuleSet) => {
@@ -346,13 +329,12 @@ const createContexts = (getParsed: ModuleSet) => {
346
329
  : [],
347
330
  ),
348
331
  );
349
- const depth = { value: 0 };
350
- tokens.slice(unit.start, unit.end).forEach((_, offset) => {
332
+ let depth = 0;
333
+ tokens.slice(unit.start, unit.end).forEach((token, offset) => {
351
334
  const index = unit.start + offset;
352
- const token = tokens[index];
353
335
  if (token.kind === "Separator" && tokens[index + 1]?.text === "MODULE") {
354
- depth.value++;
355
- if (depth.value === 2) {
336
+ depth++;
337
+ if (depth === 2) {
356
338
  const name = tokens[index + 2].text;
357
339
  units.push({
358
340
  location: getLocation(token),
@@ -361,8 +343,8 @@ const createContexts = (getParsed: ModuleSet) => {
361
343
  }
362
344
  return;
363
345
  }
364
- if (token.kind === "ModuleEnd") depth.value--;
365
- if (depth.value !== 1 || token.kind !== "Keyword") return;
346
+ if (token.kind === "ModuleEnd") depth--;
347
+ if (depth !== 1 || token.kind !== "Keyword") return;
366
348
  const isDeclaration = declarationKeywords.has(`${token.line}:${token.column}`);
367
349
  if (isDeclaration && (token.text === "CONSTANT" || token.text === "CONSTANTS")) {
368
350
  declare(index, "constant");
@@ -462,8 +444,6 @@ const createContexts = (getParsed: ModuleSet) => {
462
444
  };
463
445
  };
464
446
 
465
- // In order: config values, TLC's startup strings, each module's tokens as SpecObj.loadSpec
466
- // parses them, string literals in semantic analysis order, and TLCGet's names.
467
447
  const getStringOrder = (getParsed: ModuleSet, config: ModelConfig): string[] => {
468
448
  const order = new Set<string>();
469
449
  const intern = (text: string) => {
@@ -539,7 +519,6 @@ const getStringOrder = (getParsed: ModuleSet, config: ModelConfig): string[] =>
539
519
  dependencies.set(module.unit, [...(dependencies.get(module.unit) ?? []), name]);
540
520
  if (parsedUnits.has(name)) continue;
541
521
  parsedUnits.add(name);
542
- // SANY stops at the first module it can't find, in the order it reads them.
543
522
  if (getParsed(name).tokens.length === 0) {
544
523
  const importer = module.unit ?? getModuleName(getParsed(undefined).tokens);
545
524
  throw createMissingModuleError(name, importer);
@@ -568,11 +547,7 @@ const getStringOrder = (getParsed: ModuleSet, config: ModelConfig): string[] =>
568
547
 
569
548
  export interface TlcOrder {
570
549
  getStringOrder: (config: ModelConfig) => string[];
571
- // The reverse of the root module's context enumeration, in which TLC compares variables and
572
- // checks that the configuration assigns each constant.
573
550
  getDeclarationOrder: (kind: "variable" | "constant") => string[];
574
- // In the order TLC computes constant definitions at startup. An INSTANCE adds those of the
575
- // module it instantiates in the order that module's Hashtable enumerates them.
576
551
  createDefinitionOrder: () => (name: string | undefined) => string[];
577
552
  parseModule: (source: string) => Module;
578
553
  }
@@ -593,11 +568,11 @@ export const createTlcOrder = (source: string, loadModule: ModuleLoader): TlcOrd
593
568
  .reverse(),
594
569
  parseModule: modules.parseText,
595
570
  createDefinitionOrder: () => {
596
- const { getContext, getOwnEntries } = getContexts();
597
- // The root module's context finds the modules nested in the files it extends or instantiates.
598
- getContext(undefined);
571
+ const moduleContexts = getContexts();
572
+ moduleContexts.getContext(undefined);
599
573
  return (name) =>
600
- getOwnEntries(name)
574
+ moduleContexts
575
+ .getOwnEntries(name)
601
576
  .filter((entry) => entry.kind === "definition")
602
577
  .map((entry) => entry.name);
603
578
  },
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
- const state = { value: (BigInt.asUintN(64, seed) ^ MULTIPLIER) & SEED_MASK };
27
+ let state = (BigInt.asUintN(64, seed) ^ MULTIPLIER) & SEED_MASK;
28
28
  const next = (bits: number) => {
29
- state.value = (state.value * MULTIPLIER + 0xbn) & SEED_MASK;
30
- return Number(BigInt.asIntN(32, state.value >> BigInt(48 - bits)));
29
+ state = (state * MULTIPLIER + 0xbn) & SEED_MASK;
30
+ return Number(BigInt.asIntN(32, state >> BigInt(48 - bits)));
31
31
  };
32
32
  return {
33
33
  setSeed: (value) => {
34
- state.value = (BigInt.asUintN(64, value) ^ MULTIPLIER) & SEED_MASK;
34
+ state = (BigInt.asUintN(64, value) ^ MULTIPLIER) & SEED_MASK;
35
35
  },
36
36
  nextInt: (bound) => {
37
37
  const first = next(31);
@@ -47,7 +47,6 @@ export const createJavaRandom = (seed: bigint): JavaRandom => {
47
47
  };
48
48
  };
49
49
 
50
- // RandomGenerator.primes holds the 1341 consecutive primes from 1277011 to 1295953.
51
50
  const PRIMES: number[] = [];
52
51
 
53
52
  const isPrime = (candidate: number) => {
@@ -66,29 +65,24 @@ const getPrimes = () => {
66
65
 
67
66
  export const nextPrime = (random: JavaRandom) => {
68
67
  const primes = getPrimes();
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];
68
+ let index = primes.length;
69
+ while (index === primes.length) index = Math.floor(random.nextDouble() * primes.length);
70
+ return primes[index];
74
71
  };
75
72
 
76
73
  const getPrimeFactors = (value: number) => {
77
74
  const factors: number[] = [];
78
- const remaining = { value };
79
- for (let divisor = 2; divisor * divisor <= remaining.value; divisor++) {
80
- while (remaining.value % divisor === 0) {
75
+ let remaining = value;
76
+ for (let divisor = 2; divisor * divisor <= remaining; divisor++) {
77
+ while (remaining % divisor === 0) {
81
78
  factors.push(divisor);
82
- remaining.value /= divisor;
79
+ remaining /= divisor;
83
80
  }
84
81
  }
85
- if (remaining.value > 1) factors.push(remaining.value);
82
+ if (remaining > 1) factors.push(remaining);
86
83
  return factors;
87
84
  };
88
85
 
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.
92
86
  const getModulusAndMultiplier = (size: number) => {
93
87
  for (let modulus = Math.max(size, 9); ; modulus++) {
94
88
  const factors = getPrimeFactors(modulus);
@@ -105,35 +99,32 @@ const getModulusAndMultiplier = (size: number) => {
105
99
  const getSubsetIndicesMaster = (count: number, size: number, random: JavaRandom) => {
106
100
  if (size <= 0) return [];
107
101
  const generator = getModulusAndMultiplier(size);
108
- const state = { index: BigInt(random.nextInt(size)) };
102
+ let index = BigInt(random.nextInt(size));
109
103
  const increment = BigInt(nextPrime(random));
110
104
  return Array.from({ length: count }, () => {
111
105
  do {
112
- state.index = (generator.multiplier * state.index + increment) % generator.modulus;
113
- } while (state.index >= size);
114
- return state.index;
106
+ index = (generator.multiplier * index + increment) % generator.modulus;
107
+ } while (index >= size);
108
+ return index;
115
109
  });
116
110
  };
117
111
 
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.
120
112
  const getSubsetIndices174 = (count: number, size: number, random: JavaRandom) => {
121
113
  if (size <= 0) return [];
122
114
  const stride = BigInt(size < 191 ? 191 : MAXIMUM_INT);
123
115
  const offset = BigInt(random.nextInt(size));
124
116
  return Array.from(
125
117
  { length: Math.min(count, size) },
126
- (_, index) => (stride * BigInt(index) + offset) % BigInt(size),
118
+ (_value, index) => (stride * BigInt(index) + offset) % BigInt(size),
127
119
  );
128
120
  };
129
121
 
130
122
  const LARGE_STRIDE = (1n << 63n) - 1n - 24n;
131
123
 
132
- // For products with more than 2^31 - 1 elements.
133
124
  const getLargeSubsetIndices = (count: number, size: bigint, random: JavaRandom) => {
134
125
  const signed = random.nextLong();
135
126
  const offset = BigInt.asIntN(64, signed < 0n ? -signed : signed);
136
- return Array.from({ length: count }, (_, index) => {
127
+ return Array.from({ length: count }, (_value, index) => {
137
128
  const value = (LARGE_STRIDE * BigInt(index) + offset) % size;
138
129
  return value < 0n ? value + size : value;
139
130
  });
@@ -179,7 +170,6 @@ const getProduct = (set: Value): Product | undefined => {
179
170
  return undefined;
180
171
  };
181
172
 
182
- // TLC 1.7.4 enumerates a set of tuples to draw from it.
183
173
  export const getEnumeratedFactors = (set: Value, version: TlcVersion) =>
184
174
  version === "1.7.4" && typeof set === "object" && set.kind === "ProductSet"
185
175
  ? set.factors
@@ -211,8 +201,6 @@ export const getRandomSubset = (
211
201
  return getSubsetIndices(count, elements.length, random).map((index) => elements[Number(index)]);
212
202
  };
213
203
 
214
- // TLC!RandomElement chooses each component of a set of functions, records, or tuples
215
- // separately, and otherwise indexes the enumerated set with nextDouble.
216
204
  export const getRandomElement = (set: Value, random: JavaRandom): Value => {
217
205
  if (typeof set === "object" && set.kind === "FunctionSet") {
218
206
  // TLC builds the chosen function without the interval its domain came from.
package/src/tlc/replay.ts CHANGED
@@ -40,16 +40,11 @@ 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
-
47
43
  interface ReplayAction {
48
44
  expression: Expression;
49
45
  scope: Scope | undefined;
50
46
  }
51
47
 
52
- // TLC's ActionItemList: the conjuncts left to process, the first at the head.
53
48
  interface ActionItem {
54
49
  kind: "Predicate" | "Unchanged" | "Changed";
55
50
  expression: Expression;
@@ -82,7 +77,6 @@ const withFrame = <Result>(replay: Replay, expression: Expression, run: () => Re
82
77
  try {
83
78
  return run();
84
79
  } catch (error) {
85
- // A quantifier enumerates its bounds outside any evaluation.
86
80
  freezeCallStack(callStack, sets.slice(depth), error);
87
81
  throw error;
88
82
  } finally {
@@ -101,8 +95,6 @@ const runAt = <Result>(replay: Replay, node: number, run: () => Result) =>
101
95
  const evaluateAt = (replay: Replay, node: number, expression: Expression, context: Context) =>
102
96
  runAt(replay, node, () => evaluate(expression, context));
103
97
 
104
- // TLC evaluates a user-defined or overridden operator's arguments under its node, but doesn't
105
- // count the node itself.
106
98
  const evaluateOperatorAt = (
107
99
  replay: Replay,
108
100
  node: number,
@@ -132,7 +124,6 @@ const assign = (partial: State, index: number, value: Value) => {
132
124
  return copy;
133
125
  };
134
126
 
135
- // SANY parses A /\ B /\ C as (A /\ B) /\ C, so the replay recreates the node of each prefix.
136
127
  const getPrefix = (expression: Expression & { kind: "And" | "Or" }, count: number): Expression => {
137
128
  const first = expression.operands[0].location;
138
129
  const range = expression.location.range;
@@ -193,13 +184,9 @@ const isTrue = (value: Value) => {
193
184
  return value;
194
185
  };
195
186
 
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.
198
187
  export const isAssignedShortcut = (replay: Pick<Replay, "environment" | "isInit" | "isEnabled">) =>
199
188
  !replay.isEnabled && (replay.isInit || replay.environment.runtime.isWarningEnabled);
200
189
 
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.
203
190
  const proceed = (
204
191
  replay: Replay,
205
192
  items: ActionItem | undefined,
@@ -269,7 +256,6 @@ const isChanged = (replay: Replay, item: ActionItem, partial: State) => {
269
256
  try {
270
257
  return !isEqualLikeTlc(before, after);
271
258
  } catch (error) {
272
- // TLC's v0.equals(v1) raises a FingerprintException when v0 has a source.
273
259
  if (replay.callStack) freezeCallStack(replay.callStack, [before], error);
274
260
  throw error;
275
261
  }
@@ -322,7 +308,6 @@ const visitAt = (
322
308
  switch (expression.kind) {
323
309
  case "Let": {
324
310
  const context = getContext(replay, scope, partial);
325
- // TLC walks a LET definition's body again at each reference, under the reference.
326
311
  const definitions = expression.definitions;
327
312
  const bound = replay.coverage
328
313
  ? bindDefinitions(definitions, context, {
@@ -343,7 +328,6 @@ const visitAt = (
343
328
  }
344
329
  });
345
330
 
346
- // The value of a user-defined operator TLC evaluates instead of walking its body.
347
331
  const visitValue = (
348
332
  replay: Replay,
349
333
  value: Value,
@@ -429,7 +413,6 @@ const visitDefined = (
429
413
  return visitValue(replay, value, items, partial, node);
430
414
  };
431
415
 
432
- // A variable takes the value when it has none yet, and otherwise must already have it.
433
416
  const proceedWithValue = (
434
417
  replay: Replay,
435
418
  items: ActionItem | undefined,
@@ -451,7 +434,6 @@ const createItem = (
451
434
  rest: ActionItem | undefined,
452
435
  ): ActionItem => ({ kind, expression, scope, node, rest });
453
436
 
454
- // TLC costs a set it enumerates for each element, and for the end of the enumeration.
455
437
  const getEnumerated = (replay: Replay, set: Value, elements: Value[]) => {
456
438
  if (replay.coverage) costCoverage(replay.coverage, set, elements.length + 1);
457
439
  return elements;
@@ -482,7 +464,6 @@ const visitAssignment = (
482
464
  return proceedWithValue(replay, items, partial, index, value, node);
483
465
  }
484
466
  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.
486
467
  if (typeof set === "object" && set !== value) replay.callStack?.sources.set(set, source);
487
468
  if (assigned !== undefined) {
488
469
  return (
@@ -510,7 +491,6 @@ const ENABLED_TEMPORAL_FORMS: Partial<Record<Expression["kind"], string>> = {
510
491
  StrongFairness: "SF",
511
492
  };
512
493
 
513
- // TLC rejects a temporal formula, and a quantifier or CHOOSE without a bound, under ENABLED.
514
494
  export const getEnabledFailure = (expression: Expression) => {
515
495
  const form =
516
496
  expression.kind === "Apply" && (expression.operator === "~>" || expression.operator === "-+->")
@@ -636,7 +616,6 @@ const visitApplication = (
636
616
  case "Forall": {
637
617
  const bounds = getBindings(replay, expression, context, node);
638
618
  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.
640
619
  const rest = bounds
641
620
  .slice(1)
642
621
  .reduce<ActionItem | undefined>(
@@ -764,9 +743,7 @@ const visitUnchanged = (
764
743
  return visitUnchanged(replay, operator.body, items, operator.scope, partial, node);
765
744
  }
766
745
  }
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.
746
+ // Deviation from TLC: Tool#enabledUnchanged evaluates the application in the partial next state and fails on an unassigned variable.
770
747
  if (replay.isEnabled && expression.kind === "Apply") {
771
748
  const context = getContext(replay, scope, partial);
772
749
  const operator = resolveApplyOperator(expression, context);
@@ -835,7 +812,6 @@ export const replayEnabled = (
835
812
  const callStack = replay.callStack;
836
813
  const depth = callStack?.expressions.length ?? 0;
837
814
  try {
838
- // liveness.ts builds the <<A>>_v of WF_v(A) at the location of A.
839
815
  if (expression.kind === "AngleAction" && expression.location === expression.action.location) {
840
816
  const changed = createItem("Changed", expression.subscript, scope, -1, undefined);
841
817
  visit(replay, expression.action, changed, scope, getEmptyState(environment), -1);
@@ -845,7 +821,6 @@ export const replayEnabled = (
845
821
  return false;
846
822
  } catch (error) {
847
823
  if (error !== ENABLED_FOUND) throw error;
848
- // The frames the walk left are those of the successor, not of a failure.
849
824
  if (callStack) {
850
825
  callStack.expressions.length = depth;
851
826
  callStack.isFrozen = false;
@@ -870,14 +845,12 @@ export const replayInitialStates = (
870
845
  visit(replay, first.expression, rest, first.scope, getEmptyState(environment), first.node ?? -1);
871
846
  };
872
847
 
873
- // TLC checks the successors of an action once it has computed them all.
874
848
  export const replaySuccessors = <Action extends ReplayAction>(
875
849
  actions: Action[],
876
850
  state: Value[],
877
851
  environment: Environment,
878
852
  onState: (state: Value[], action: Action) => void,
879
853
  ) => {
880
- // TLC fails to split a next-state relation that isn't an operator application, so replays none.
881
854
  if (actions.some((action) => LITERAL_KINDS.has(action.expression.kind))) return;
882
855
  actions.forEach((action) => {
883
856
  const successors: Value[][] = [];
@@ -898,10 +871,9 @@ export const walkSuccessors = (
898
871
  visit(replay, action.expression, undefined, action.scope, getEmptyState(environment), node);
899
872
  };
900
873
 
901
- // TLC's Spec.getPrimedLocs, whose nodes TLC reports even when they never produce a state.
902
874
  export const getPrimedRanges = (actions: ReplayAction[], environment: Environment) => {
903
875
  const ranges: Expression[] = [];
904
- const context = (scope: Scope | undefined): Context => ({
876
+ const createContext = (scope: Scope | undefined): Context => ({
905
877
  environment,
906
878
  scope,
907
879
  state: undefined,
@@ -933,7 +905,11 @@ export const getPrimedRanges = (actions: ReplayAction[], environment: Environmen
933
905
  ): void => {
934
906
  switch (expression.kind) {
935
907
  case "Let":
936
- collect(expression.body, bindDefinitions(expression.definitions, context(scope)), visited);
908
+ collect(
909
+ expression.body,
910
+ bindDefinitions(expression.definitions, createContext(scope)),
911
+ visited,
912
+ );
937
913
  return;
938
914
  case "Label":
939
915
  collect(expression.body, scope, visited);
@@ -989,7 +965,7 @@ export const getPrimedRanges = (actions: ReplayAction[], environment: Environmen
989
965
  }
990
966
  const operator =
991
967
  expression.kind === "Apply"
992
- ? resolveApplyOperator(expression, context(scope))
968
+ ? resolveApplyOperator(expression, createContext(scope))
993
969
  : binding?.kind === "Operator"
994
970
  ? binding.operator
995
971
  : binding
@@ -1001,7 +977,11 @@ export const getPrimedRanges = (actions: ReplayAction[], environment: Environmen
1001
977
  const args = expression.kind === "Apply" ? expression.args : [];
1002
978
  if (operator.params.length !== args.length) return;
1003
979
  visited.add(operator.body);
1004
- collect(operator.body, bindOperatorArguments(operator, args, context(scope)), visited);
980
+ collect(
981
+ operator.body,
982
+ bindOperatorArguments(operator, args, createContext(scope)),
983
+ visited,
984
+ );
1005
985
  visited.delete(operator.body);
1006
986
  }
1007
987
  }
@@ -1,16 +1,12 @@
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.
3
1
  export const OUT_DEGREE_BUCKETS = 32;
4
2
 
5
3
  export const getOptimisticProbability = (distinctStates: number, generatedStates: number) =>
6
4
  distinctStates * ((generatedStates - distinctStates) / 2 ** 64);
7
5
 
8
- // TLC computes the estimate from the actual fingerprints only when the optimistic one is this high.
9
6
  const ACTUAL_PROBABILITY_THRESHOLD = 1e-10;
10
7
 
11
8
  const withDecimalPoint = (text: string) => (text.includes(".") ? text : `${text}.0`);
12
9
 
13
- // Java's Double.toString, which prints a number below 1E-3 or from 1E7 up in scientific notation.
14
10
  const toJavaString = (value: number) => {
15
11
  const magnitude = Math.abs(value);
16
12
  if (magnitude >= 1e-3 && magnitude < 1e7) return withDecimalPoint(String(value));
@@ -21,37 +17,36 @@ const toJavaString = (value: number) => {
21
17
  const isDigit = (character: string | undefined) =>
22
18
  character !== undefined && character >= "0" && character <= "9";
23
19
 
24
- // TLC's ProbabilityToString, which keeps two significant digits and drops a leading zero.
25
20
  export const formatProbability = (value: number) => {
26
21
  if (value === 0) return "0.0";
27
22
  const text = toJavaString(value);
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++;
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++;
33
30
  }
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++;
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++;
39
36
  } else {
40
- cursor.result += ".";
41
- if (cursor.digits === 0) {
42
- while (text[cursor.next] === "0") cursor.result += text[cursor.next++];
37
+ result += ".";
38
+ if (digits === 0) {
39
+ while (text[next] === "0") result += text[next++];
43
40
  }
44
- while (isDigit(text[cursor.next]) && cursor.digits < 2) {
45
- cursor.result += text[cursor.next++];
46
- cursor.digits++;
41
+ while (isDigit(text[next]) && digits < 2) {
42
+ result += text[next++];
43
+ digits++;
47
44
  }
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++;
45
+ if (isDigit(text[next]) && Number(text[next]) >= 5) result = roundUp(result);
46
+ while (isDigit(text[next])) next++;
52
47
  }
53
- if (cursor.next >= text.length) return cursor.result;
54
- if (text[cursor.next] === "E") return `${cursor.result}${text.slice(cursor.next)}`;
48
+ if (next >= text.length) return result;
49
+ if (text[next] === "E") return `${result}${text.slice(next)}`;
55
50
  return text;
56
51
  };
57
52
 
@@ -65,18 +60,15 @@ const roundUp = (digits: string): string => {
65
60
  return `${front}${Number(last) + 1}`;
66
61
  };
67
62
 
68
- // 1 divided by the distance, rounded half up to two significant digits like Java's BigDecimal.
69
63
  export const getActualProbability = (distance: bigint) => {
70
- const exponent = { value: 0 };
71
- while (10n ** BigInt(exponent.value + 1) < distance * 10n) exponent.value++;
72
- const scale = 10n ** BigInt(exponent.value + 1);
64
+ let exponent = 0;
65
+ while (10n ** BigInt(exponent + 1) < distance * 10n) exponent++;
66
+ const scale = 10n ** BigInt(exponent + 1);
73
67
  const quotient = scale / distance;
74
68
  const isRoundedUp = (scale % distance) * 2n >= distance;
75
- return Number(`${quotient + (isRoundedUp ? 1n : 0n)}e-${exponent.value + 1}`);
69
+ return Number(`${quotient + (isRoundedUp ? 1n : 0n)}e-${exponent + 1}`);
76
70
  };
77
71
 
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.
80
72
  export const getFingerprintDistance = (
81
73
  distinctStates: number,
82
74
  generatedStates: number,
@@ -85,10 +77,9 @@ export const getFingerprintDistance = (
85
77
  const probability = getOptimisticProbability(distinctStates, generatedStates);
86
78
  if (probability < ACTUAL_PROBABILITY_THRESHOLD) return undefined;
87
79
  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.
90
80
  const words = new Int32Array(fingerprints.buffer);
91
- const nearest = { narrow: Number.POSITIVE_INFINITY, wide: 0x7fff_ffff_ffff_ffffn };
81
+ let narrowest = Number.POSITIVE_INFINITY;
82
+ let widest = 0x7fff_ffff_ffff_ffffn;
92
83
  for (let index = 1; index < fingerprints.length; index++) {
93
84
  const high = words[2 * index + 1];
94
85
  const previousHigh = words[2 * index - 1];
@@ -96,15 +87,15 @@ export const getFingerprintDistance = (
96
87
  const highGap = high - previousHigh;
97
88
  if (highGap <= 0x10_0000) {
98
89
  const gap = highGap * 0x1_0000_0000 + (words[2 * index] >>> 0) - (words[2 * index - 2] >>> 0);
99
- nearest.narrow = Math.min(nearest.narrow, gap);
90
+ narrowest = Math.min(narrowest, gap);
100
91
  } else {
101
92
  const gap = fingerprints[index] - fingerprints[index - 1];
102
- if (gap < nearest.wide) nearest.wide = gap;
93
+ if (gap < widest) widest = gap;
103
94
  }
104
95
  }
105
- if (nearest.narrow === Number.POSITIVE_INFINITY) return nearest.wide;
106
- const narrow = BigInt(nearest.narrow);
107
- return narrow < nearest.wide ? narrow : nearest.wide;
96
+ if (narrowest === Number.POSITIVE_INFINITY) return widest;
97
+ const narrow = BigInt(narrowest);
98
+ return narrow < widest ? narrow : widest;
108
99
  };
109
100
 
110
101
  export const getOutDegreeSummary = (buckets: number[]) => {
@@ -113,10 +104,10 @@ export const getOutDegreeSummary = (buckets: number[]) => {
113
104
  const degrees = buckets.flatMap((count, degree) => (count > 0 ? [degree] : []));
114
105
  const total = buckets.reduce((sum, count, degree) => sum + count * degree, 0);
115
106
  const position = Math.floor(observations * 0.95);
116
- const cumulative = { count: 0 };
107
+ let cumulativeCount = 0;
117
108
  const percentile = degrees.find((degree) => {
118
- cumulative.count += buckets[degree];
119
- return cumulative.count > position;
109
+ cumulativeCount += buckets[degree];
110
+ return cumulativeCount > position;
120
111
  });
121
112
  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}).`;
122
113
  };