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
@@ -27,11 +27,16 @@ export interface LiveSuccessor {
27
27
  export interface Lasso {
28
28
  prefix: number[];
29
29
  cycle: number[];
30
+ // TLC warns that a stuttering counterexample to a liveness property may come from a missing
31
+ // fairness constraint.
30
32
  isCycleConstrained: boolean;
31
33
  }
32
34
 
33
35
  export interface LivenessChecker {
36
+ // How many solutions of the negated properties TLC checks, which it calls branches.
34
37
  branches: number;
38
+ // With a tracing environment, the checks record their call stack as TLC's replay of a failed
39
+ // check does.
35
40
  addInitialState: (index: number, state: Value[], tracing?: Environment) => void;
36
41
  addState: (
37
42
  index: number,
@@ -48,6 +53,8 @@ interface SearchGraph {
48
53
  getSuccessors: (index: number, state: Value[]) => LiveSuccessor[];
49
54
  }
50
55
 
56
+ // Numbers in a typed array that doubles as it fills, so a graph of millions of nodes takes a few
57
+ // bytes for each.
51
58
  interface Pool<Data extends Int32Array | Uint8Array> {
52
59
  data: Data;
53
60
  length: number;
@@ -59,12 +66,17 @@ interface BehaviorGraph {
59
66
  actionIds: Int32Array;
60
67
  nodeStates: number[];
61
68
  nodeTableaux: number[];
69
+ // Where a node's edges start in edgeTargets, or UNWRITTEN until TLC writes the node with its
70
+ // successors, and how many it has.
62
71
  edgeStarts: number[];
63
72
  edgeCounts: number[];
64
73
  edgeTargets: Pool<Int32Array>;
74
+ // The results of the action checks on each edge, and of the state checks on each state, which
75
+ // are the same for every node of the state.
65
76
  edgeActions: Pool<Uint8Array>;
66
77
  stateResults: Pool<Uint8Array>;
67
78
  initial: number[];
79
+ // The nodes of each state in the order they are recorded, a list through nextSiblings.
68
80
  firstNodes: Pool<Int32Array>;
69
81
  lastNodes: Pool<Int32Array>;
70
82
  nextSiblings: number[];
@@ -125,7 +137,8 @@ const writeToPool = <Data extends Int32Array | Uint8Array>(
125
137
 
126
138
  const NO_NODE = -1;
127
139
 
128
- // A Map holds at most 2^24 entries, so an open-addressing table of (state plus one, tableau node, node) triples finds each node.
140
+ // A Map holds at most 2^24 entries, so each tableau node of a state finds its node in an
141
+ // open-addressing table of (state plus one, tableau node, node) triples.
129
142
  interface NodeTable {
130
143
  slots: Int32Array;
131
144
  size: number;
@@ -212,9 +225,9 @@ export const createLivenessChecker = (
212
225
  solution,
213
226
  actionIds: Int32Array.from(solution.actionChecks, (predicate) => {
214
227
  const key = getTermKey(predicate);
215
- const actionId = actionIds.get(key) ?? actionIds.size;
216
- actionIds.set(key, actionId);
217
- return actionId;
228
+ const id = actionIds.get(key) ?? actionIds.size;
229
+ actionIds.set(key, id);
230
+ return id;
218
231
  }),
219
232
  nodeStates: [],
220
233
  nodeTableaux: [],
@@ -231,17 +244,23 @@ export const createLivenessChecker = (
231
244
  isDone: [],
232
245
  errorNode: undefined,
233
246
  }));
234
- let capacityMultiplier = 1;
247
+ const capacity = { multiplier: 1 };
235
248
 
249
+ // TLC evaluates every check on its own. Without side effects the order can't show, so the
250
+ // checks of one state share their results.
236
251
  const isShared = !hasRepeatedEffects(environment);
237
- let evaluationEnvironment = environment;
238
- const sharedStates = new Map<Value[], Map<LiveExpression, boolean>>();
239
- const sharedActions = new Map<Value[], Map<Value[], Int8Array>>();
252
+ const evaluation = { environment };
253
+ const shared = {
254
+ states: new Map<Value[], Map<LiveExpression, boolean>>(),
255
+ actions: new Map<Value[], Map<Value[], Int8Array>>(),
256
+ };
240
257
  const getStateCache = (state: Value[]) => {
241
- const cache = sharedStates.get(state) ?? new Map<LiveExpression, boolean>();
242
- sharedStates.set(state, cache);
258
+ const cache = shared.states.get(state) ?? new Map<LiveExpression, boolean>();
259
+ shared.states.set(state, cache);
243
260
  return cache;
244
261
  };
262
+ // TLCGet("level") reads the level of the state whose successors the checks run on.
263
+ // A check that fails leaves no source, so the failure's trace reads the levels of the search.
245
264
  const evaluateFrom = <Result>(source: number | undefined, evaluate: () => Result) => {
246
265
  environment.runtime.setLivenessSource(source);
247
266
  try {
@@ -255,7 +274,7 @@ export const createLivenessChecker = (
255
274
  predicate,
256
275
  state,
257
276
  undefined,
258
- evaluationEnvironment,
277
+ evaluation.environment,
259
278
  isShared ? getStateCache(state) : new Map(),
260
279
  );
261
280
  const checkState = (behavior: BehaviorGraph, source: number, state: Value[]) =>
@@ -274,27 +293,27 @@ export const createLivenessChecker = (
274
293
  const predicates = behavior.solution.actionChecks;
275
294
  if (!isShared) {
276
295
  return Uint8Array.from(predicates, (predicate) =>
277
- evaluateLive(predicate, state, successor, evaluationEnvironment, new Map()) ? 1 : 0,
296
+ evaluateLive(predicate, state, successor, evaluation.environment, new Map()) ? 1 : 0,
278
297
  );
279
298
  }
280
299
  const stateCache = getStateCache(state);
281
- const results = sharedActions.get(state) ?? new Map<Value[], Int8Array>();
282
- sharedActions.set(state, results);
300
+ const results = shared.actions.get(state) ?? new Map<Value[], Int8Array>();
301
+ shared.actions.set(state, results);
283
302
  const known = results.get(successor) ?? new Int8Array(actionIds.size).fill(-1);
284
303
  results.set(successor, known);
285
- return Uint8Array.from(behavior.actionIds, (actionId, position) => {
286
- if (known[actionId] === -1) {
287
- known[actionId] = evaluateLive(
304
+ return Uint8Array.from(behavior.actionIds, (id, position) => {
305
+ if (known[id] === -1) {
306
+ known[id] = evaluateLive(
288
307
  predicates[position],
289
308
  state,
290
309
  successor,
291
- evaluationEnvironment,
310
+ evaluation.environment,
292
311
  stateCache,
293
312
  )
294
313
  ? 1
295
314
  : 0;
296
315
  }
297
- return known[actionId];
316
+ return known[id];
298
317
  });
299
318
  });
300
319
  const isConsistent = (
@@ -306,6 +325,8 @@ export const createLivenessChecker = (
306
325
  evaluateFrom(source, () =>
307
326
  tableau.nodes[node].statePredicates.every((predicate) => evaluateState(predicate, state)),
308
327
  );
328
+ // TLC 1.7.4 doesn't stop at a tableau node that accepts every behavior, so it finds a violation
329
+ // of a property like a safety property only in its liveness checks.
309
330
  const isAccepting = (tableau: Tableau, node: number) => {
310
331
  if (environment.runtime.version === "1.7.4") return false;
311
332
  const tableauNode = tableau.nodes[node];
@@ -374,12 +395,16 @@ export const createLivenessChecker = (
374
395
  behavior.edgeCounts[node] = targets.length;
375
396
  };
376
397
 
377
- // TLC iterates a state's successors and the state itself in the slot order of a SetOfStates, a hash set whose capacity grows with every set that outgrows it.
398
+ // TLC collects a state's successors and the state itself in a SetOfStates, a hash set it
399
+ // iterates in slot order. Its capacity starts at 16 times a factor that grows with every set
400
+ // that outgrows it.
378
401
  const getSuccessorSet = (index: number, state: Value[], successors: LiveSuccessor[]) => {
379
- let successorSlots = Array.from<LiveSuccessor | undefined>({
380
- length: SUCCESSOR_CAPACITY * capacityMultiplier,
381
- });
382
- let successorCount = 0;
402
+ const table = {
403
+ slots: Array.from<LiveSuccessor | undefined>({
404
+ length: SUCCESSOR_CAPACITY * capacity.multiplier,
405
+ }),
406
+ count: 0,
407
+ };
383
408
  const insertSuccessor = (slots: (LiveSuccessor | undefined)[], successor: LiveSuccessor) => {
384
409
  for (
385
410
  let slot = (search.getFingerprint(successor) & 0x7fffffff) % slots.length;
@@ -396,17 +421,17 @@ export const createLivenessChecker = (
396
421
  }
397
422
  };
398
423
  const addSuccessor = (successor: LiveSuccessor) => {
399
- if (successorCount >= successorSlots.length >> 1) {
400
- const old = successorSlots;
401
- successorSlots = Array.from<LiveSuccessor | undefined>({ length: 2 * old.length + 1 });
402
- for (const entry of old) if (entry) insertSuccessor(successorSlots, entry);
424
+ if (table.count >= table.slots.length >> 1) {
425
+ const old = table.slots;
426
+ table.slots = Array.from<LiveSuccessor | undefined>({ length: 2 * old.length + 1 });
427
+ for (const entry of old) if (entry) insertSuccessor(table.slots, entry);
403
428
  }
404
- if (insertSuccessor(successorSlots, successor)) successorCount++;
429
+ if (insertSuccessor(table.slots, successor)) table.count++;
405
430
  };
406
431
  successors.forEach(addSuccessor);
407
432
  addSuccessor({ index, state });
408
- if (successorSlots.length > SUCCESSOR_CAPACITY * capacityMultiplier) capacityMultiplier++;
409
- return successorSlots.filter((entry): entry is LiveSuccessor => entry !== undefined);
433
+ if (table.slots.length > SUCCESSOR_CAPACITY * capacity.multiplier) capacity.multiplier++;
434
+ return table.slots.filter((entry): entry is LiveSuccessor => entry !== undefined);
410
435
  };
411
436
 
412
437
  const expandLate = (
@@ -446,7 +471,8 @@ export const createLivenessChecker = (
446
471
  const isDone = behavior.isDone[successor.index] === true;
447
472
  for (const next of tableauNode.successors) {
448
473
  if (!isConsistent(tableau, next, index, successor.state)) continue;
449
- // Deviation from TLC: TLC records the node of a successor the search never stored, which it never expands.
474
+ // A successor the search never stored follows a violation or an error, after which nothing
475
+ // checks the graph. TLC records its node, which it never expands.
450
476
  if (successor.index === -1) continue;
451
477
  const existing = getNodeId(behavior, successor.index, next);
452
478
  if (existing !== undefined && successors.includes(existing)) continue;
@@ -469,7 +495,7 @@ export const createLivenessChecker = (
469
495
  stateResults: Uint8Array,
470
496
  index: number,
471
497
  ) => {
472
- const consistency = tableau.nodes.map((_tableauNode, node) =>
498
+ const consistency = tableau.nodes.map((_, node) =>
473
499
  set.map((successor) => isConsistent(tableau, node, index, successor.state)),
474
500
  );
475
501
  behavior.isDone[index] = true;
@@ -545,6 +571,7 @@ export const createLivenessChecker = (
545
571
  throw new TlaEvaluationError(`Couldn't re-create liveness trace (path) starting at: ${target}`);
546
572
  };
547
573
 
574
+ // TLC's LiveWorker#checkSccs, a Tarjan search that pushes every successor of a node at once.
548
575
  const findLassoInModel = (
549
576
  behavior: BehaviorGraph,
550
577
  model: Solution["models"][number],
@@ -601,6 +628,8 @@ export const createLivenessChecker = (
601
628
  return getLasso(root, members, membersByState);
602
629
  };
603
630
 
631
+ // TLC's LiveWorker#printTrace: a prefix to the root, a greedy walk through the component until it
632
+ // satisfies every check, and a breadth-first path back to the root.
604
633
  const getLasso = (
605
634
  root: number,
606
635
  members: Set<number>,
@@ -616,75 +645,74 @@ export const createLivenessChecker = (
616
645
  const stateDone = model.infinitelyOftenStates.map(() => false);
617
646
  const actionDone = model.infinitelyOftenActions.map(() => false);
618
647
  const promiseDone = solution.promises.map(() => false);
619
- let remainingCount = stateDone.length + actionDone.length + promiseDone.length;
620
- let currentNode = root;
648
+ const remaining = { count: stateDone.length + actionDone.length + promiseDone.length };
649
+ const current = { node: root };
621
650
  const isMember = (node: number) => members.has(node);
622
651
  const moveTo = (next: number) => {
623
- cycleStack.push(currentNode);
624
- currentNode = next;
652
+ cycleStack.push(current.node);
653
+ current.node = next;
625
654
  };
626
- while (remainingCount > 0) {
627
- const countAtStart = remainingCount;
655
+ while (remaining.count > 0) {
656
+ const countAtStart = remaining.count;
628
657
  while (true) {
629
658
  model.infinitelyOftenStates.forEach((position, slot) => {
630
- if (!stateDone[slot] && getStateResult(behavior, currentNode, position)) {
659
+ if (!stateDone[slot] && getStateResult(behavior, current.node, position)) {
631
660
  stateDone[slot] = true;
632
- remainingCount--;
661
+ remaining.count--;
633
662
  }
634
663
  });
635
664
  solution.promises.forEach((promise, position) => {
636
- if (!promiseDone[position] && isFulfilled(currentNode, promise)) {
665
+ if (!promiseDone[position] && isFulfilled(current.node, promise)) {
637
666
  promiseDone[position] = true;
638
- remainingCount--;
667
+ remaining.count--;
639
668
  }
640
669
  });
641
- if (remainingCount <= 0) break;
642
- let lastNext = -1;
643
- let unvisitedNext = -1;
644
- const countBeforeActions = remainingCount;
645
- const isTaken = getNodeSuccessors(behavior, currentNode).some((next, edge) => {
670
+ if (remaining.count <= 0) break;
671
+ const step = { last: -1, unvisited: -1 };
672
+ const countBeforeActions = remaining.count;
673
+ const taken = getNodeSuccessors(behavior, current.node).some((next, edge) => {
646
674
  if (membersByState.has(behavior.nodeStates[next])) {
647
- if (!isMember(next) || !isAllowed(currentNode, edge)) return false;
648
- lastNext = next;
675
+ if (!isMember(next) || !isAllowed(current.node, edge)) return false;
676
+ step.last = next;
649
677
  model.infinitelyOftenActions.forEach((position, slot) => {
650
- if (!actionDone[slot] && getAction(currentNode, edge, position)) {
678
+ if (!actionDone[slot] && getAction(current.node, edge, position)) {
651
679
  actionDone[slot] = true;
652
- remainingCount--;
680
+ remaining.count--;
653
681
  }
654
682
  });
655
683
  }
656
- if (remainingCount < countBeforeActions) {
684
+ if (remaining.count < countBeforeActions) {
657
685
  moveTo(next);
658
686
  seen.clear();
659
687
  return true;
660
688
  }
661
- if (isMember(next) && !seen.has(next)) unvisitedNext = next;
689
+ if (isMember(next) && !seen.has(next)) step.unvisited = next;
662
690
  return false;
663
691
  });
664
- if (isTaken) break;
665
- if (remainingCount < countAtStart) {
666
- moveTo(lastNext);
692
+ if (taken) break;
693
+ if (remaining.count < countAtStart) {
694
+ moveTo(step.last);
667
695
  seen.clear();
668
696
  break;
669
697
  }
670
- while (unvisitedNext === -1) {
698
+ while (step.unvisited === -1) {
671
699
  const previous = cycleStack.pop();
672
700
  if (previous === undefined) {
673
701
  throw new TlaEvaluationError(
674
702
  "TLC failed to build the counterexample of a liveness property",
675
703
  );
676
704
  }
677
- currentNode = previous;
678
- unvisitedNext =
705
+ current.node = previous;
706
+ step.unvisited =
679
707
  getNodeSuccessors(behavior, previous).find(
680
708
  (next) => isMember(next) && !seen.has(next),
681
709
  ) ?? -1;
682
710
  }
683
- moveTo(unvisitedNext);
684
- seen.add(unvisitedNext);
711
+ moveTo(step.unvisited);
712
+ seen.add(step.unvisited);
685
713
  }
686
714
  }
687
- const postfix = getClosingPath(root, currentNode, membersByState, isAllowed);
715
+ const postfix = getClosingPath(root, current.node, membersByState, isAllowed);
688
716
  for (let position = cycleStack.length - 1; position >= 0; position--) {
689
717
  const state = behavior.nodeStates[cycleStack[position]];
690
718
  if (postfix[postfix.length - 1] !== state) postfix.push(state);
@@ -743,7 +771,7 @@ export const createLivenessChecker = (
743
771
 
744
772
  for (let position = 0; position < queue.length; position++) {
745
773
  const stack = [queue[position], UNVISITED, 0];
746
- let nextLink = 0;
774
+ const counter = { link: 0 };
747
775
  while (stack.length >= 3) {
748
776
  const lowLink = stack.pop() ?? 0;
749
777
  const location = stack.pop();
@@ -760,10 +788,10 @@ export const createLivenessChecker = (
760
788
  stack.push(Math.min(lowLink, links[node]));
761
789
  continue;
762
790
  }
763
- links[node] = nextLink;
791
+ links[node] = counter.link;
764
792
  stack.push(lowLink, node, SCC_MARKER);
765
793
  components.push(node);
766
- let nextLowLink = nextLink++;
794
+ const nextLowLink = { value: counter.link++ };
767
795
  getNodeSuccessors(behavior, node).forEach((next, edge) => {
768
796
  if (!isWritten(behavior, next)) return;
769
797
  if (!isAllowed(node, edge)) {
@@ -771,9 +799,9 @@ export const createLivenessChecker = (
771
799
  return;
772
800
  }
773
801
  if (links[next] === UNVISITED) stack.push(next, UNVISITED);
774
- else nextLowLink = Math.min(nextLowLink, links[next]);
802
+ else nextLowLink.value = Math.min(nextLowLink.value, links[next]);
775
803
  });
776
- stack.push(nextLowLink);
804
+ stack.push(nextLowLink.value);
777
805
  }
778
806
  }
779
807
  return undefined;
@@ -782,9 +810,9 @@ export const createLivenessChecker = (
782
810
  return {
783
811
  branches: behaviors.length,
784
812
  addInitialState: (index, state, tracing) => {
785
- evaluationEnvironment = tracing ?? environment;
786
- sharedStates.clear();
787
- sharedActions.clear();
813
+ evaluation.environment = tracing ?? environment;
814
+ shared.states.clear();
815
+ shared.actions.clear();
788
816
  try {
789
817
  for (const behavior of behaviors) {
790
818
  const tableau = behavior.solution.tableau;
@@ -800,13 +828,13 @@ export const createLivenessChecker = (
800
828
  }
801
829
  }
802
830
  } finally {
803
- evaluationEnvironment = environment;
831
+ evaluation.environment = environment;
804
832
  }
805
833
  },
806
834
  addState: (index, state, successors, tracing) => {
807
- evaluationEnvironment = tracing ?? environment;
808
- sharedStates.clear();
809
- sharedActions.clear();
835
+ evaluation.environment = tracing ?? environment;
836
+ shared.states.clear();
837
+ shared.actions.clear();
810
838
  try {
811
839
  const set = getSuccessorSet(index, state, successors);
812
840
  for (const behavior of behaviors) {
@@ -831,7 +859,7 @@ export const createLivenessChecker = (
831
859
  }
832
860
  return undefined;
833
861
  } finally {
834
- evaluationEnvironment = environment;
862
+ evaluation.environment = environment;
835
863
  }
836
864
  },
837
865
  findViolation: () => {
@@ -843,11 +871,12 @@ export const createLivenessChecker = (
843
871
  }
844
872
  return undefined;
845
873
  },
874
+ // TLC names every property that the counterexample violates, once each.
846
875
  getViolatedProperties: (path, cycleStart) => [
847
876
  ...new Set(
848
877
  properties
849
878
  .filter(
850
- (_property, position) =>
879
+ (_, position) =>
851
880
  !evaluateOnLasso(negations[position].body, path, cycleStart, 0, environment),
852
881
  )
853
882
  .map((property) => property.name),
package/src/liveness.ts CHANGED
@@ -47,6 +47,7 @@ export interface ScopedExpression {
47
47
  scope: Scope | undefined;
48
48
  }
49
49
 
50
+ // The name TLC gives a part of a property: a conjunct's location or the enclosing definition.
50
51
  interface ExpandedExpression extends ScopedExpression {
51
52
  name: string | undefined;
52
53
  path: string[];
@@ -80,6 +81,7 @@ const getConstantContext = (environment: Environment, scope: Scope | undefined):
80
81
  next: undefined,
81
82
  });
82
83
 
84
+ // TLC adds the message of the error that stopped it, when it has one.
83
85
  const createCannotHandleError = (expression: Expression, inner?: string) =>
84
86
  new TlaEvaluationError(
85
87
  `TLC cannot handle the temporal formula ${describeRange(expression)}${inner === undefined ? "" : `:\n${inner}`}`,
@@ -93,6 +95,7 @@ export const getLevel = (
93
95
  visiting = new Set<object>(),
94
96
  ): number => {
95
97
  const getBodyLevel = (binding: object, body: Expression, bodyScope: Scope | undefined) => {
98
+ // A recursive call adds nothing, as SANY's level never decreases while it iterates.
96
99
  if (visiting.has(binding)) return CONSTANT_LEVEL;
97
100
  visiting.add(binding);
98
101
  const level = getLevel(body, bodyScope, environment, new Set(), visiting);
@@ -131,10 +134,10 @@ export const getLevel = (
131
134
  return getGlobalLevel(name) ?? getBindingLevel(name) ?? CONSTANT_LEVEL;
132
135
  };
133
136
  const getChildrenLevel = (node: Expression) => {
134
- let level = CONSTANT_LEVEL;
137
+ const level = { value: CONSTANT_LEVEL };
135
138
  mapChildren(node, (child, bound) => {
136
- level = Math.max(
137
- level,
139
+ level.value = Math.max(
140
+ level.value,
138
141
  getLevel(
139
142
  child,
140
143
  scope,
@@ -145,7 +148,7 @@ export const getLevel = (
145
148
  );
146
149
  return child;
147
150
  });
148
- return level;
151
+ return level.value;
149
152
  };
150
153
  switch (expression.kind) {
151
154
  case "Prime":
@@ -181,6 +184,8 @@ export const getLevel = (
181
184
  ) {
182
185
  return level;
183
186
  }
187
+ // SANY counts an argument only where the definition's level depends on its parameter, so
188
+ // ENABLED of an operator argument stays a state predicate.
184
189
  return getBodyLevel(
185
190
  operator,
186
191
  operator.body,
@@ -192,6 +197,7 @@ export const getLevel = (
192
197
  }
193
198
  };
194
199
 
200
+ // TLC leaves a formula whose sets it fails to enumerate, and doesn't expect an EvalException.
195
201
  const getUnrolledElements = (bounds: Bound[], context: Context) => {
196
202
  try {
197
203
  return getBoundElements(bounds, context);
@@ -209,8 +215,10 @@ export const expandTemporal = (
209
215
  expression: Expression,
210
216
  scope: Scope | undefined,
211
217
  environment: Environment,
218
+ // Whether TLC expands the formula as a property, which unrolls each \A over a constant set.
212
219
  isProperty: boolean,
213
220
  expanding = new Set<Definition>(),
221
+ // Whether the expansion entered an instance's definition, after which TLC expands no call.
214
222
  isSubstituted = false,
215
223
  name?: string,
216
224
  path: string[] = [],
@@ -254,6 +262,7 @@ export const expandTemporal = (
254
262
  const definition = environment.constants.has(expression.name)
255
263
  ? undefined
256
264
  : getDefinition(expression.name, environment);
265
+ // TLC expands a definition it didn't compute at startup, even a constant one.
257
266
  if (
258
267
  !binding &&
259
268
  definition?.kind === "Operator" &&
@@ -264,6 +273,7 @@ export const expandTemporal = (
264
273
  if (expanding.has(definition)) {
265
274
  throw createStackOverflowError();
266
275
  }
276
+ // TLC names a part after the operator as the spec writes it, as I!Op outside the instance.
267
277
  return expand(
268
278
  definition.body,
269
279
  undefined,
@@ -274,6 +284,7 @@ export const expandTemporal = (
274
284
  }
275
285
  }
276
286
  const context = getConstantContext(environment, scope);
287
+ // TLC 1.7.4 expands no call, a property every one, and a specification only temporal ones.
277
288
  if (
278
289
  expression.kind === "Apply" &&
279
290
  environment.runtime.version !== "1.7.4" &&
@@ -283,6 +294,8 @@ export const expandTemporal = (
283
294
  const definition = isLocallyResolved(expression)
284
295
  ? undefined
285
296
  : getDefinition(expression.operator, environment);
297
+ // An instance's definition that takes only the instance's parameters takes no arguments in
298
+ // TLC, which expands it even within the instance.
286
299
  const isOwnArgumentFree =
287
300
  operator?.kind === "Closure" &&
288
301
  operator.params.every((param) => environment.instanceParams.has(param));
@@ -341,6 +354,7 @@ export const toLiveExpression = (
341
354
  scope: Scope | undefined,
342
355
  level: number,
343
356
  ): LiveExpression => {
357
+ // TLC after 1.7.4 bounds the level of a formula whose parts are constant by the formula's own.
344
358
  const atomLevel =
345
359
  level === CONSTANT_LEVEL && !is174 ? getLevel(expression, scope, environment) : level;
346
360
  if (atomLevel === CONSTANT_LEVEL) {
@@ -353,6 +367,7 @@ export const toLiveExpression = (
353
367
  return createBoolean(value);
354
368
  }
355
369
  if (atomLevel === VARIABLE_LEVEL) return { kind: "State", expression, scope };
370
+ // TLC checks <<A>>_v's subscript before it evaluates A.
356
371
  if (expression.kind === "AngleAction") {
357
372
  return {
358
373
  kind: "Action",
@@ -364,7 +379,7 @@ export const toLiveExpression = (
364
379
  return { kind: "Action", expression, subscript: undefined, scope };
365
380
  };
366
381
 
367
- let expansionDepth = 0;
382
+ const expansion = { depth: 0 };
368
383
 
369
384
  const expand = (
370
385
  body: Expression,
@@ -372,14 +387,15 @@ export const toLiveExpression = (
372
387
  expression: Expression,
373
388
  scope: Scope | undefined,
374
389
  ) => {
375
- if (expansionDepth >= MAXIMUM_EXPANSION_DEPTH) {
390
+ if (expansion.depth >= MAXIMUM_EXPANSION_DEPTH) {
376
391
  throw createStackOverflowError();
377
392
  }
378
- expansionDepth++;
393
+ expansion.depth++;
379
394
  const result = convert(body, bodyScope);
380
- expansionDepth--;
395
+ expansion.depth--;
381
396
  const level = getLiveLevel(result);
382
- // Deviation from TLC: Liveness#astToLive takes a temporal call with a constant body for an action, which classifyExpr rejects.
397
+ // For a constant body, Liveness#astToLive bounds the level of a temporal call by its own and
398
+ // takes the call for an action, which classifyExpr rejects. tla-ts keeps the constant.
383
399
  const isConstantTemporal =
384
400
  level === CONSTANT_LEVEL && getLevel(expression, scope, environment) > ACTION_LEVEL;
385
401
  return level > ACTION_LEVEL || isConstantTemporal ? result : toAtom(expression, scope, level);
@@ -409,6 +425,8 @@ export const toLiveExpression = (
409
425
  ? resolveOperator(name, context)
410
426
  : resolveGlobalOperator(name, environment);
411
427
  const args = expression.kind === "Apply" ? expression.args : [];
428
+ // An operator constant can be substituted by a conjunction or disjunction, whose arguments
429
+ // TLC translates as it translates its operands.
412
430
  const junction =
413
431
  operator?.kind === "Builtin" && args.length === 2 ? JUNCTIONS.get(operator.name) : undefined;
414
432
  if (junction) {
@@ -438,6 +456,8 @@ export const toLiveExpression = (
438
456
  );
439
457
  };
440
458
 
459
+ // TLC can't handle a call whose expansion fails, except that after 1.7.4 it fails as a
460
+ // recursive operator's expansion does.
441
461
  const expandCall = (
442
462
  expression: Expression,
443
463
  expandBody: () => LiveExpression,
@@ -459,6 +479,7 @@ export const toLiveExpression = (
459
479
  const level = getLevel(expression, scope, environment);
460
480
  const operands: LiveExpression[] = [];
461
481
  const isForall = expression.kind === "Forall";
482
+ // TLC can't handle a quantifier whose body fails, and under \A adds another failure's message.
462
483
  try {
463
484
  forEachBinding(expression.bounds, getConstantContext(environment, scope), (boundScope) => {
464
485
  operands.push(convert(expression.body, boundScope));
@@ -478,11 +499,13 @@ export const toLiveExpression = (
478
499
  return toWhole(expression, scope, createJunction(isForall ? "And" : "Or", operands));
479
500
  };
480
501
 
502
+ // TLC takes a formula whose translated parts are below temporal level whole, at their level.
481
503
  const toWhole = (expression: Expression, scope: Scope | undefined, parts: LiveExpression) => {
482
504
  const level = getLiveLevel(parts);
483
505
  return level > ACTION_LEVEL ? parts : toAtom(expression, scope, level);
484
506
  };
485
507
 
508
+ // A constant translated part, such as a quantifier over {}, can make the whole formula constant.
486
509
  const isTranslatedWhole = (expression: Expression) =>
487
510
  expression.kind === "Label" ||
488
511
  expression.kind === "Let" ||
@@ -545,6 +568,7 @@ export const toLiveExpression = (
545
568
  case "Exists":
546
569
  return convertQuantifier(expression, scope);
547
570
  case "If": {
571
+ // TLC 1.7.4 translates both branches whatever the guard.
548
572
  if (!is174 && getLevel(expression.condition, scope, environment) === CONSTANT_LEVEL) {
549
573
  const condition = evaluate(expression.condition, getConstantContext(environment, scope));
550
574
  if (typeof condition === "boolean") {
@@ -674,7 +698,7 @@ export const evaluateOnLasso = (
674
698
  ): boolean => {
675
699
  const getNext = (index: number) => (index + 1 < path.length ? index + 1 : cycleStart);
676
700
  const getFuture = (index: number) =>
677
- path.map((_state, offset) => offset).filter((offset) => offset >= Math.min(index, cycleStart));
701
+ path.map((_, offset) => offset).filter((offset) => offset >= Math.min(index, cycleStart));
678
702
  const recurse = (operand: LiveExpression, index = position) =>
679
703
  evaluateOnLasso(operand, path, cycleStart, index, environment);
680
704
  switch (expression.kind) {