tla-ts 0.0.2 → 0.0.3-dev.1a99ab7

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 (60) hide show
  1. package/README.md +78 -12
  2. package/dist/index.cjs +1 -1
  3. package/dist/index.d.cts +60 -1
  4. package/dist/index.d.ts +60 -1
  5. package/dist/index.js +1 -1
  6. package/dist/parallel-worker.cjs +2 -2
  7. package/dist/parallel-worker.js +2 -2
  8. package/dist/parallel.cjs +1 -1
  9. package/dist/parallel.js +2 -2
  10. package/dist/run-cli.cjs +21 -2
  11. package/dist/run-cli.js +21 -2
  12. package/dist/transfer.cjs +27 -15
  13. package/dist/transfer.js +27 -15
  14. package/package.json +3 -1
  15. package/src/ast.ts +134 -4
  16. package/src/check.ts +274 -76
  17. package/src/cli-options.ts +64 -0
  18. package/src/codegen.ts +9 -19
  19. package/src/dependencies.ts +2 -2
  20. package/src/environment.ts +75 -16
  21. package/src/errors.ts +46 -3
  22. package/src/evaluate.ts +88 -143
  23. package/src/exit-codes.ts +21 -43
  24. package/src/fingerprints.ts +46 -11
  25. package/src/instances.ts +15 -14
  26. package/src/levels.ts +8 -8
  27. package/src/lexer.ts +11 -2
  28. package/src/live-check.ts +711 -0
  29. package/src/liveness.ts +54 -535
  30. package/src/obligation-action.ts +384 -0
  31. package/src/obligation-anon.ts +575 -0
  32. package/src/obligation-deref.ts +637 -0
  33. package/src/obligation-expression.ts +1060 -0
  34. package/src/obligation-format.ts +406 -0
  35. package/src/obligation-generate.ts +1074 -0
  36. package/src/obligation-levels.ts +329 -0
  37. package/src/obligation-module.ts +1042 -0
  38. package/src/obligation-printer.ts +889 -0
  39. package/src/obligation-proof.ts +76 -0
  40. package/src/obligation-source.ts +1084 -0
  41. package/src/obligation-tuples.ts +184 -0
  42. package/src/obligations.ts +316 -0
  43. package/src/parallel-worker.ts +166 -210
  44. package/src/parallel.ts +76 -35
  45. package/src/parser.ts +297 -53
  46. package/src/resolve.ts +16 -15
  47. package/src/run-cli.ts +353 -40
  48. package/src/runtime.ts +3 -1
  49. package/src/spec-description.ts +18 -6
  50. package/src/standard-levels.ts +3 -3
  51. package/src/standard-modules.ts +2 -7
  52. package/src/state-graph.ts +157 -0
  53. package/src/subexpressions.ts +10 -10
  54. package/src/successors.ts +77 -13
  55. package/src/symmetry.ts +14 -2
  56. package/src/tlc-ext.ts +29 -12
  57. package/src/tlc-module.ts +9 -28
  58. package/src/tlc-order.ts +17 -3
  59. package/src/transfer.ts +22 -1
  60. package/src/values.ts +118 -34
package/src/check.ts CHANGED
@@ -1,15 +1,27 @@
1
- import type { Assumption, Definition, Expression, SourceLocation } from "./ast";
1
+ import {
2
+ getChildren,
3
+ isLocallyResolved,
4
+ type Assumption,
5
+ type Definition,
6
+ type Expression,
7
+ type SourceLocation,
8
+ } from "./ast";
2
9
  import { parseConfig, type ConfigValue, type ModelConfig } from "./config";
3
10
  import { getReadVariables } from "./dependencies";
4
11
  import { createEnvironment } from "./environment";
5
- import { getErrorExitCode, TlaConfigError, TlaEvaluationError, TlaModuleError } from "./errors";
6
- import { EXIT_STATUS, setExitCode, setNextStatePhase, withLivenessExitCode } from "./exit-codes";
12
+ import {
13
+ getErrorExitCode,
14
+ TlaConfigError,
15
+ TlaEvaluationError,
16
+ TlaModuleError,
17
+ UNEXPECTED_EXCEPTION,
18
+ } from "./errors";
19
+ import { EXIT_STATUS, setExitCode, withLivenessExitCode } from "./exit-codes";
7
20
  import {
8
21
  describeRange,
9
22
  evaluate,
10
23
  expectBoolean,
11
24
  formatRange,
12
- getChildren,
13
25
  getDefinition,
14
26
  isConstantLevel,
15
27
  isImpure,
@@ -19,13 +31,11 @@ import {
19
31
  } from "./evaluate";
20
32
  import {
21
33
  createLivenessChecker,
22
- expandTemporal,
23
- getLevel,
24
34
  type Lasso,
35
+ type LivenessChecker,
25
36
  type LiveSuccessor,
26
- type ScopedExpression,
27
- type TemporalProperty,
28
- } from "./liveness";
37
+ } from "./live-check";
38
+ import { expandTemporal, getLevel, type ScopedExpression, type TemporalProperty } from "./liveness";
29
39
  import { ACTION_LEVEL, createLevelAnalyzer, TEMPORAL_LEVEL } from "./levels";
30
40
  import { prettyPrint } from "./pretty-print";
31
41
  import {
@@ -37,10 +47,17 @@ import {
37
47
  } from "./successors";
38
48
  import {
39
49
  getActionLabel,
50
+ getActionSignature,
40
51
  getNextActions,
41
52
  getSpecificationValue,
42
53
  type SpecAction,
43
54
  } from "./spec-description";
55
+ import {
56
+ createStateWriter,
57
+ type GraphState,
58
+ type StateDump,
59
+ type StateWriter,
60
+ } from "./state-graph";
44
61
  import { getRepresentative, getSymmetryGroup } from "./symmetry";
45
62
  import { getTlcStringOrder, getTlcVariableOrder } from "./tlc-order";
46
63
  import { createTlcFingerprinter, getTlcFingerprint } from "./tlc-random";
@@ -50,10 +67,12 @@ import { createCounterExample } from "./tlc-ext";
50
67
  import { getFingerprintDistance, OUT_DEGREE_BUCKETS } from "./tlc-summary";
51
68
  import {
52
69
  combineHash,
70
+ formatState,
53
71
  formatValue,
54
72
  getValueHash,
55
73
  isFunctionValue,
56
74
  isSameValue,
75
+ isUpdatedElementOf,
57
76
  setStringOrder,
58
77
  toFiniteFunction,
59
78
  type Value,
@@ -72,6 +91,8 @@ export interface CheckOptions {
72
91
  workers?: number;
73
92
  // TLC's -lncheck: "final" checks liveness only on the complete state graph.
74
93
  livenessCheck?: "default" | "final";
94
+ // TLC's -dump: writes the reachable states, or with `dot` the state graph, through writeFile.
95
+ dump?: StateDump;
75
96
  }
76
97
 
77
98
  export type CheckStatus =
@@ -93,6 +114,8 @@ export interface TraceStep {
93
114
 
94
115
  export interface Violation {
95
116
  name: string;
117
+ // Every temporal property that a liveness counterexample violates, in the configuration's order.
118
+ properties?: string[];
96
119
  trace: TraceStep[];
97
120
  loopStart: number | undefined;
98
121
  loopLabel?: string;
@@ -139,6 +162,13 @@ interface NamedExpression {
139
162
 
140
163
  interface StateCheck extends NamedExpression {
141
164
  variables: number[] | undefined;
165
+ membership: Membership | undefined;
166
+ }
167
+
168
+ // A conjunct `x \in S` whose S reads no variables.
169
+ interface Membership {
170
+ variable: number;
171
+ set: Expression;
142
172
  }
143
173
 
144
174
  interface ActionProperty {
@@ -416,12 +446,12 @@ const getProperties = (config: ModelConfig, environment: Environment): Propertie
416
446
  config.properties.forEach((name) => {
417
447
  const definition = getConfigPredicate("property", name, environment);
418
448
  if (!definition) return;
419
- expandTemporal(definition.body, undefined, environment, true).forEach((item) => {
449
+ expandTemporal(definition.body, undefined, environment, true, name).forEach((item) => {
420
450
  const conjunct = item.expression;
421
451
  if (isConstantTrue(item, environment, "property")) return;
422
452
  if (conjunct.kind === "Always" && conjunct.expression.kind === "BoxAction") {
423
453
  properties.actionProperties.push({
424
- name,
454
+ name: item.name,
425
455
  box: conjunct.expression,
426
456
  action: conjunct.expression.action,
427
457
  subscript: conjunct.expression.subscript,
@@ -433,12 +463,22 @@ const getProperties = (config: ModelConfig, environment: Environment): Propertie
433
463
  conjunct.kind === "Always" &&
434
464
  getLevel(conjunct.expression, item.scope, environment) <= 1
435
465
  ) {
436
- properties.invariants.push({ name, expression: conjunct.expression, scope: item.scope });
466
+ // TLC names the invariant []P after P when P is an operator name.
467
+ const expression = conjunct.expression;
468
+ properties.invariants.push({
469
+ name: expression.kind === "Identifier" ? expression.name : item.name,
470
+ expression,
471
+ scope: item.scope,
472
+ });
437
473
  return;
438
474
  }
439
475
  const level = getLevel(conjunct, item.scope, environment);
440
476
  if (level < ACTION_LEVEL) {
441
- properties.initialPredicates.push({ name, expression: conjunct, scope: item.scope });
477
+ properties.initialPredicates.push({
478
+ name: item.name,
479
+ expression: conjunct,
480
+ scope: item.scope,
481
+ });
442
482
  return;
443
483
  }
444
484
  if (level === ACTION_LEVEL) {
@@ -481,14 +521,34 @@ const getPossiblePredicates = (names: string[], environment: Environment) =>
481
521
  return { name, expression, scope: undefined };
482
522
  });
483
523
 
524
+ const getMembership = (
525
+ expression: Expression,
526
+ variables: number[] | undefined,
527
+ environment: Environment,
528
+ ): Membership | undefined => {
529
+ if (expression.kind !== "Apply" || expression.operator !== "\\in" || variables?.length !== 1)
530
+ return undefined;
531
+ const element = expression.args[0];
532
+ if (element.kind !== "Identifier" || isLocallyResolved(element)) return undefined;
533
+ return environment.variableIndex.get(element.name) === variables[0]
534
+ ? { variable: variables[0], set: expression.args[1] }
535
+ : undefined;
536
+ };
537
+
484
538
  const getStateChecks = (named: NamedExpression[], environment: Environment): StateCheck[] =>
485
539
  named.flatMap((item) =>
486
- getConjuncts(item.expression, environment).map((expression) => ({
487
- name: item.name,
488
- expression,
489
- scope: item.scope,
490
- variables: getReadVariables(expression, environment),
491
- })),
540
+ getConjuncts(item.expression, environment).map((expression) => {
541
+ // A LET or an argument in the scope can read variables the expression doesn't name.
542
+ const variables =
543
+ item.scope === undefined ? getReadVariables(expression, environment) : undefined;
544
+ return {
545
+ name: item.name,
546
+ expression,
547
+ scope: item.scope,
548
+ variables,
549
+ membership: getMembership(expression, variables, environment),
550
+ };
551
+ }),
492
552
  );
493
553
 
494
554
  const isUnchangedFor = (stateCheck: StateCheck, state: Value[], parent: Value[] | undefined) => {
@@ -743,10 +803,16 @@ export const createSearch = (
743
803
  invariants.find((invariant) => {
744
804
  if (isUnchangedFor(invariant, state, parent)) return false;
745
805
  try {
746
- return !holdsLikeTlc(
747
- invariant.expression,
748
- getContext(environment, state, undefined, invariant.scope),
749
- );
806
+ const context = getContext(environment, state, undefined, invariant.scope);
807
+ const membership = invariant.membership;
808
+ // The parent satisfies every invariant, so only the entries the step changed can fail.
809
+ return parent && membership
810
+ ? !isUpdatedElementOf(
811
+ state[membership.variable],
812
+ parent[membership.variable],
813
+ evaluate(membership.set, context),
814
+ )
815
+ : !holdsLikeTlc(invariant.expression, context);
750
816
  } catch (error) {
751
817
  // TLC reports a failure only on a state after the initial states as an invariant failure.
752
818
  if (!parent) throw error;
@@ -787,7 +853,10 @@ export const createSearch = (
787
853
  )
788
854
  );
789
855
  } catch (error) {
790
- throw withHeadline(error, `Evaluating action property ${property.name} failed.`);
856
+ throw withHeadline(
857
+ withNextStateExitCode(error),
858
+ `Evaluating action property ${property.name} failed.`,
859
+ );
791
860
  }
792
861
  }),
793
862
  satisfiesActionConstraints: (state, next) =>
@@ -795,8 +864,7 @@ export const createSearch = (
795
864
  holdsLikeTlc(
796
865
  constraint.expression,
797
866
  getContext(environment, state, next),
798
- (expression) =>
799
- `TLC threw an unexpected exception.\nThis was probably caused by an error in the spec or model.\nSee the User Output or TLC Console for clues to what happened.\nThe exception was a java.lang.RuntimeException\n: ${getExpectedBoolean(expression, environment)}`,
867
+ (expression) => `${UNEXPECTED_EXCEPTION}${getExpectedBoolean(expression, environment)}`,
800
868
  ),
801
869
  ),
802
870
  trackStatePossible:
@@ -824,6 +892,11 @@ export const createSearch = (
824
892
  };
825
893
  };
826
894
 
895
+ // TLC exits with the code of a standard module's failure only when the failure escapes the
896
+ // computation of next states. In every other phase, the phase decides the code.
897
+ const withNextStateExitCode = (error: unknown) =>
898
+ error instanceof TlaModuleError ? setExitCode(error, error.exitCode) : error;
899
+
827
900
  const withHeadline = (error: unknown, headline: string) =>
828
901
  error instanceof TlaEvaluationError
829
902
  ? setExitCode(
@@ -832,8 +905,15 @@ const withHeadline = (error: unknown, headline: string) =>
832
905
  )
833
906
  : error;
834
907
 
908
+ // TLC finishes the -dump file whether or not the search finds a violation.
835
909
  export const checkSequentially = (options: CheckOptions): CheckResult => {
836
- setNextStatePhase(false);
910
+ const stateWriter = options.dump && createStateWriter(options.dump, options.writeFile);
911
+ const result = searchStates(options, stateWriter);
912
+ stateWriter?.close();
913
+ return result;
914
+ };
915
+
916
+ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefined): CheckResult => {
837
917
  const config = typeof options.config === "string" ? parseConfig(options.config) : options.config;
838
918
  const onPrint = options.onPrint ?? console.log;
839
919
  // TLC prints again while it rebuilds a trace, between the states it prints. Printing those lines
@@ -929,8 +1009,36 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
929
1009
  const getFingerprintState = search.getFingerprintState;
930
1010
  const nextActions = { value: undefined as SpecAction[] | undefined };
931
1011
  const isReducing = config.view !== undefined || config.symmetry !== undefined;
1012
+ const tlcFingerprints: number[] = [];
932
1013
  const liveness = withLivenessExitCode(() =>
933
- createLivenessChecker(search.properties.liveness, spec.temporals, environment),
1014
+ createLivenessChecker(search.properties.liveness, spec.temporals, environment, {
1015
+ getFingerprint: (index) =>
1016
+ (tlcFingerprints[index] ??= Number(
1017
+ BigInt.asIntN(32, runtime.getFingerprint(states[index])),
1018
+ )),
1019
+ getSuccessors: (state) => {
1020
+ const successors: LiveSuccessor[] = [];
1021
+ if (spec.next === undefined) return successors;
1022
+ forEachSuccessor(
1023
+ spec.next,
1024
+ state,
1025
+ environment,
1026
+ (successor) => {
1027
+ canonicalizeState(successor.state);
1028
+ const isInModel =
1029
+ search.satisfiesConstraints(successor.state, state) &&
1030
+ search.satisfiesActionConstraints(state, successor.state);
1031
+ if (!isInModel) return false;
1032
+ const fingerprintState = getFingerprintState(successor.state);
1033
+ const index = findStateIndex(getStateHash(fingerprintState), fingerprintState);
1034
+ successors.push({ index, state: successor.state });
1035
+ return false;
1036
+ },
1037
+ spec.scope,
1038
+ );
1039
+ return successors;
1040
+ },
1041
+ }),
934
1042
  );
935
1043
  const isCanonicalizedFirst = search.isSymmetric || liveness !== undefined;
936
1044
 
@@ -939,7 +1047,9 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
939
1047
  const parents: number[] = [];
940
1048
  const actions: (string | undefined)[] = [];
941
1049
  const depths: number[] = [];
942
- const buckets = new Map<number, number | number[]>();
1050
+ // A Map holds at most 2^24 entries, so an open-addressing table keeps each seen state's hash
1051
+ // and its index plus one side by side, probed by the hash.
1052
+ const seen = { slots: new Int32Array(1 << 17), size: 0, shift: 16 };
943
1053
  const canonicalizeState = createCanonicalizer();
944
1054
 
945
1055
  const toRecord = (state: Value[]): Record<string, Value> =>
@@ -952,11 +1062,16 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
952
1062
  position: number,
953
1063
  loopStart: number | undefined,
954
1064
  ) => {
955
- const state = steps[position].state;
956
- const next = (steps[position + 1] ?? steps[loopStart ?? position]).state;
957
1065
  // TLC evaluates TLCGet("level") and Trace in an alias at the state's position in the trace.
958
1066
  runtime.getLevel = () => position + 1;
959
1067
  runtime.getBehavior = () => steps.slice(0, position + 1).map((step) => step.state);
1068
+ return evaluateAlias(
1069
+ alias,
1070
+ steps[position].state,
1071
+ (steps[position + 1] ?? steps[loopStart ?? position]).state,
1072
+ );
1073
+ };
1074
+ const evaluateAlias = (alias: string, state: Value[], next: Value[] | undefined) => {
960
1075
  try {
961
1076
  const body = getConfigDefinition("alias", alias, environment).body;
962
1077
  const value = evaluate(createIdentifier(alias), getContext(environment, state, next));
@@ -1071,7 +1186,7 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1071
1186
  outDegrees: failureOutDegrees,
1072
1187
  };
1073
1188
  };
1074
- const getPathTrace = (path: number[], loopStart?: number) => {
1189
+ const getPathSteps = (path: number[], loopStart?: number) => {
1075
1190
  const steps = getPathStates(path, NEXT_RECOVERY_FAILURE);
1076
1191
  const last = steps[steps.length - 1].state;
1077
1192
  const isClosed =
@@ -1080,7 +1195,7 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1080
1195
  loopStart === path.length - 1 ||
1081
1196
  findSuccessorWithFingerprint(last, path[loopStart]) !== undefined;
1082
1197
  if (!isClosed) throw new TlaEvaluationError(NEXT_RECOVERY_FAILURE);
1083
- return toTrace(steps, path, loopStart);
1198
+ return steps;
1084
1199
  };
1085
1200
  const getStateHash = (state: Value[]) => {
1086
1201
  let hash = 0x811c9dc5;
@@ -1094,19 +1209,35 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1094
1209
  }
1095
1210
  return true;
1096
1211
  };
1212
+ const getSlot = (hash: number) => (Math.imul(hash, 0x9e3779b1) >>> seen.shift) << 1;
1097
1213
  const findStateIndex = (hash: number, state: Value[]) => {
1098
- const bucket = buckets.get(hash);
1099
- if (bucket === undefined) return -1;
1100
- if (typeof bucket === "number") {
1101
- return isSameState(fingerprintStates[bucket], state) ? bucket : -1;
1214
+ const mask = seen.slots.length - 1;
1215
+ for (let slot = getSlot(hash); ; slot = (slot + 2) & mask) {
1216
+ const entry = seen.slots[slot + 1];
1217
+ if (entry === 0) return -1;
1218
+ if (seen.slots[slot] === hash && isSameState(fingerprintStates[entry - 1], state)) {
1219
+ return entry - 1;
1220
+ }
1102
1221
  }
1103
- return bucket.find((index) => isSameState(fingerprintStates[index], state)) ?? -1;
1222
+ };
1223
+ const insertSeen = (hash: number, entry: number) => {
1224
+ const mask = seen.slots.length - 1;
1225
+ let slot = getSlot(hash);
1226
+ while (seen.slots[slot + 1] !== 0) slot = (slot + 2) & mask;
1227
+ seen.slots[slot] = hash;
1228
+ seen.slots[slot + 1] = entry;
1104
1229
  };
1105
1230
  const markSeen = (hash: number, index: number) => {
1106
- const bucket = buckets.get(hash);
1107
- if (bucket === undefined) buckets.set(hash, index);
1108
- else if (typeof bucket === "number") buckets.set(hash, [bucket, index]);
1109
- else bucket.push(index);
1231
+ seen.size++;
1232
+ if (seen.size * 4 > seen.slots.length) {
1233
+ const slots = seen.slots;
1234
+ seen.slots = new Int32Array(slots.length * 2);
1235
+ seen.shift--;
1236
+ for (let slot = 0; slot < slots.length; slot += 2) {
1237
+ if (slots[slot + 1] !== 0) insertSeen(slots[slot], slots[slot + 1]);
1238
+ }
1239
+ }
1240
+ insertSeen(hash, index + 1);
1110
1241
  };
1111
1242
  const countDistinctState = (depth: number) => {
1112
1243
  runtime.distinctStates = states.length + 1;
@@ -1146,7 +1277,7 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1146
1277
  };
1147
1278
  runtime.getCurrentState = () => (current.index === -1 ? undefined : states[current.index]);
1148
1279
  runtime.setLivenessSource = (index) => {
1149
- current.livenessSource = index;
1280
+ current.livenessSource = index ?? -1;
1150
1281
  };
1151
1282
  runtime.getLevel = (state) => {
1152
1283
  const source = current.livenessSource;
@@ -1157,6 +1288,18 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1157
1288
  return current.isExpanding ? depths[current.index] + 1 : 0;
1158
1289
  };
1159
1290
 
1291
+ const getGraphState = (state: Value[], level: number): GraphState => ({
1292
+ fingerprint: BigInt.asIntN(64, runtime.getFingerprint(state)),
1293
+ level,
1294
+ getLabel: () =>
1295
+ formatState(
1296
+ config.alias === undefined
1297
+ ? toRecord(state)
1298
+ : evaluateAlias(config.alias, state, undefined),
1299
+ ),
1300
+ getText: () => formatState(toRecord(state)),
1301
+ });
1302
+
1160
1303
  const visitInitialState = (state: Value[]) => {
1161
1304
  canonicalizeState(state);
1162
1305
  runtime.generatedStates++;
@@ -1173,6 +1316,7 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1173
1316
  countDistinctState(1);
1174
1317
  runtime.queueSize++;
1175
1318
  liveness?.addInitialState(states.length, state);
1319
+ stateWriter?.writeInitialState(getGraphState(state, 1));
1176
1320
  }
1177
1321
  const violated = search.findViolatedInvariant(state);
1178
1322
  if (violated) {
@@ -1193,7 +1337,13 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1193
1337
  addState(state, fingerprintState, -1, undefined);
1194
1338
  return undefined;
1195
1339
  };
1196
- const visitSuccessor = (index: number, successor: Successor, liveSuccessors: LiveSuccessor[]) => {
1340
+ const visitSuccessor = (
1341
+ index: number,
1342
+ successor: Successor,
1343
+ liveSuccessors: LiveSuccessor[],
1344
+ source: GraphState | undefined,
1345
+ action: SpecAction | undefined,
1346
+ ) => {
1197
1347
  const state = states[index];
1198
1348
  runtime.generatedStates++;
1199
1349
  current.candidate = successor.state;
@@ -1207,6 +1357,14 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1207
1357
  const isInModel = isStateInModel && search.satisfiesActionConstraints(state, successor.state);
1208
1358
  if (isInModel) search.trackActionPossible(state, successor.state);
1209
1359
  const existing = isInModel ? found : -1;
1360
+ if (source && isInModel) {
1361
+ stateWriter?.writeSuccessor(
1362
+ source,
1363
+ getGraphState(successor.state, depths[index] + 1),
1364
+ existing !== -1,
1365
+ action && { name: action.name, signature: getActionSignature(action) },
1366
+ );
1367
+ }
1210
1368
  if (existing !== -1 && liveness) {
1211
1369
  const stored = states[existing];
1212
1370
  const isStored = stored.every((value, position) => value === successor.state[position]);
@@ -1278,23 +1436,55 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1278
1436
  }
1279
1437
  return createSuccess();
1280
1438
  }
1439
+ // TLC labels and colors an edge of the -dump state graph by the action that generated it. When
1440
+ // the graph names its edges, the search generates successors action by action, as TLC does.
1441
+ const isNamingEdges = Boolean(
1442
+ options.dump?.dot && (options.dump.actionLabels || options.dump.colorize),
1443
+ );
1444
+ const forEachActionSuccessor = (
1445
+ state: Value[],
1446
+ onSuccessor: (successor: Successor, action: SpecAction | undefined) => boolean,
1447
+ ) => {
1448
+ if (!isNamingEdges) {
1449
+ return forEachSuccessor(
1450
+ next,
1451
+ state,
1452
+ environment,
1453
+ (successor) => onSuccessor(successor, undefined),
1454
+ spec.scope,
1455
+ );
1456
+ }
1457
+ nextActions.value ??= getNextActions(config, environment, specification.instanceActions);
1458
+ const progress = { isStopped: false };
1459
+ return nextActions.value.reduce((count, action) => {
1460
+ if (progress.isStopped) return count;
1461
+ return (
1462
+ count +
1463
+ forEachSuccessor(
1464
+ action.expression,
1465
+ state,
1466
+ environment,
1467
+ (successor) => {
1468
+ progress.isStopped = onSuccessor(successor, action);
1469
+ return progress.isStopped;
1470
+ },
1471
+ action.scope,
1472
+ )
1473
+ );
1474
+ }, 0);
1475
+ };
1281
1476
  const expandState = (index: number) => {
1282
1477
  const state = states[index];
1283
1478
  const liveSuccessors: LiveSuccessor[] = [];
1284
- const successorCount = forEachSuccessor(
1285
- next,
1286
- state,
1287
- environment,
1288
- (successor) => {
1289
- try {
1290
- outcome.result = visitSuccessor(index, successor, liveSuccessors);
1291
- } catch (error) {
1292
- outcome.result = toFailure(error, getTrace(index, successor));
1293
- }
1294
- return outcome.result !== undefined;
1295
- },
1296
- spec.scope,
1297
- );
1479
+ const source = stateWriter && getGraphState(state, depths[index]);
1480
+ const successorCount = forEachActionSuccessor(state, (successor, action) => {
1481
+ try {
1482
+ outcome.result = visitSuccessor(index, successor, liveSuccessors, source, action);
1483
+ } catch (error) {
1484
+ outcome.result = toFailure(error, getTrace(index, successor));
1485
+ }
1486
+ return outcome.result !== undefined;
1487
+ });
1298
1488
  current.isExpanding = false;
1299
1489
  if (outcome.result) return outcome.result;
1300
1490
  if (successorCount === 0 && config.checkDeadlock) {
@@ -1302,32 +1492,43 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1302
1492
  }
1303
1493
  try {
1304
1494
  const accepted = liveness?.addState(index, state, liveSuccessors);
1305
- current.livenessSource = -1;
1306
- if (!accepted) return undefined;
1495
+ if (!liveness || !accepted) return undefined;
1496
+ const steps = getPathSteps(accepted);
1497
+ const properties = liveness.getViolatedProperties(
1498
+ steps.map((step) => step.state),
1499
+ steps.length - 1,
1500
+ );
1307
1501
  return reportViolation("property-violation", {
1308
- name: accepted.name,
1309
- trace: getPathTrace(accepted.path),
1502
+ name: properties[0],
1503
+ properties,
1504
+ trace: toTrace(steps, accepted),
1310
1505
  });
1311
1506
  } catch (error) {
1312
1507
  return toFailure(error, getStateTrace(index), undefined, getPartialOutDegrees());
1313
1508
  }
1314
1509
  };
1315
- const reportLasso = (lasso: Lasso) => {
1510
+ // TLC names the properties and the step back into the cycle from the states it prints.
1511
+ const reportLasso = (checker: LivenessChecker, lasso: Lasso) => {
1316
1512
  const path = [...lasso.prefix, ...lasso.cycle];
1317
- const trace = getPathTrace(path, lasso.prefix.length);
1318
- const back = path[lasso.prefix.length];
1513
+ const loopStart = lasso.prefix.length;
1514
+ const steps = getPathSteps(path, loopStart);
1515
+ const trace = toTrace(steps, path, loopStart);
1516
+ const properties = checker.getViolatedProperties(
1517
+ steps.map((step) => step.state),
1518
+ loopStart,
1519
+ );
1520
+ const back = path[loopStart];
1319
1521
  const last = path[path.length - 1];
1522
+ const lastState = steps[steps.length - 1].state;
1320
1523
  const loopLabel =
1321
- back === last ? undefined : withoutOutput(() => getLabel(last, states[last], states[back]));
1524
+ back === last ? undefined : withoutOutput(() => getLabel(last, lastState, states[back]));
1322
1525
  return reportViolation(
1323
1526
  "liveness-violation",
1324
- { name: lasso.name, trace, loopStart: lasso.prefix.length, loopLabel },
1527
+ { name: properties[0], properties, trace, loopStart, loopLabel },
1325
1528
  () =>
1326
1529
  back === last
1327
1530
  ? trace[trace.length - 1].action
1328
- : getTraceSuccessors(states[last]).find((successor) =>
1329
- isSameState(successor.state, states[back]),
1330
- )?.action,
1531
+ : findSuccessorWithFingerprint(lastState, back)?.action,
1331
1532
  );
1332
1533
  };
1333
1534
  const isPeriodic = liveness !== undefined && options.livenessCheck !== "final";
@@ -1340,11 +1541,9 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1340
1541
  if (!isGrown || periodic.time > (now - startedAt) * LIVENESS_RATIO) return undefined;
1341
1542
  periodic.size = expanded;
1342
1543
  const lasso = liveness?.findViolation();
1343
- current.livenessSource = -1;
1344
1544
  periodic.time += performance.now() - now;
1345
1545
  return lasso;
1346
1546
  };
1347
- setNextStatePhase(true);
1348
1547
  for (let index = 0; index < states.length && !runtime.isStopped; index++) {
1349
1548
  current.index = index;
1350
1549
  current.candidate = undefined;
@@ -1353,22 +1552,21 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1353
1552
  try {
1354
1553
  outcome.result = expandState(index);
1355
1554
  } catch (error) {
1356
- outcome.result = toFailure(error, getStateTrace(index));
1555
+ outcome.result = toFailure(withNextStateExitCode(error), getStateTrace(index));
1357
1556
  }
1358
1557
  if (outcome.result) return outcome.result;
1359
1558
  outDegrees[getOutDegreeBucket()]++;
1360
1559
  expansion.newStates = 0;
1361
1560
  if (isPeriodic && performance.now() >= periodic.at) {
1362
1561
  const lasso = findPeriodicViolation(index + 1);
1363
- if (lasso) return reportLasso(lasso);
1562
+ if (liveness && lasso) return reportLasso(liveness, lasso);
1364
1563
  }
1365
1564
  }
1366
1565
 
1367
1566
  current.index = -1;
1368
1567
  current.candidate = undefined;
1369
1568
  const lasso = liveness?.findViolation();
1370
- current.livenessSource = -1;
1371
- if (lasso) return reportLasso(lasso);
1569
+ if (liveness && lasso) return reportLasso(liveness, lasso);
1372
1570
 
1373
1571
  const postconditionViolation = search.findPostconditionViolation();
1374
1572
  if (postconditionViolation) {
@@ -0,0 +1,64 @@
1
+ export interface OptionSpec {
2
+ flag: string;
3
+ isRequired?: boolean;
4
+ isRepeatable?: boolean;
5
+ // How many of the arguments after the flag the option takes, when that depends on them.
6
+ getArity?: (rest: string[]) => number;
7
+ }
8
+
9
+ export interface ParsedOption {
10
+ name: string;
11
+ values: string[];
12
+ }
13
+
14
+ export interface ParsedArgs {
15
+ options: ParsedOption[];
16
+ positionals: string[];
17
+ unknown: string[];
18
+ incomplete: ParsedOption | undefined;
19
+ has: (name: string) => boolean;
20
+ get: (name: string) => string[] | undefined;
21
+ }
22
+
23
+ const formatOption = (spec: OptionSpec) => {
24
+ const text = spec.isRequired ? spec.flag : `[${spec.flag}]`;
25
+ return spec.isRepeatable ? `${text}...` : text;
26
+ };
27
+
28
+ // Each <name> in a flag such as "--toolbox <start> <end>" is one value the option takes, and
29
+ // {options} in the usage stands for the options.
30
+ export const defineCommand = (usage: string, specs: OptionSpec[]) => {
31
+ const arities = new Map(
32
+ specs.map((spec) => {
33
+ const [name, ...values] = spec.flag.split(" ");
34
+ return [name, spec.getArity ?? (() => values.length)];
35
+ }),
36
+ );
37
+ const parse = (args: string[]): ParsedArgs => {
38
+ const options: ParsedOption[] = [];
39
+ const positionals: string[] = [];
40
+ const unknown: string[] = [];
41
+ const incomplete: ParsedOption[] = [];
42
+ for (let index = 0; index < args.length; index++) {
43
+ const getArity = arities.get(args[index]);
44
+ if (getArity === undefined) {
45
+ (args[index].startsWith("-") ? unknown : positionals).push(args[index]);
46
+ continue;
47
+ }
48
+ const arity = getArity(args.slice(index + 1));
49
+ const option = { name: args[index], values: args.slice(index + 1, index + 1 + arity) };
50
+ options.push(option);
51
+ if (option.values.length < arity) incomplete.push(option);
52
+ index += arity;
53
+ }
54
+ return {
55
+ options,
56
+ positionals,
57
+ unknown,
58
+ incomplete: incomplete[0],
59
+ has: (name) => options.some((option) => option.name === name),
60
+ get: (name) => options.findLast((option) => option.name === name)?.values,
61
+ };
62
+ };
63
+ return { usage: usage.replace("{options}", specs.map(formatOption).join(" ")), parse };
64
+ };