tla-ts 0.0.3-dev.3cf2ad0 → 0.0.3-dev.45d0f50

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 (48) hide show
  1. package/README.md +16 -2
  2. package/dist/index.cjs +1 -1
  3. package/dist/index.d.cts +9 -0
  4. package/dist/index.d.ts +9 -0
  5. package/dist/index.js +1 -1
  6. package/dist/parallel-worker.cjs +1 -1
  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 +17 -16
  11. package/dist/run-cli.js +6 -5
  12. package/dist/transfer.cjs +27 -15
  13. package/dist/transfer.js +27 -15
  14. package/package.json +1 -1
  15. package/src/ast.ts +90 -0
  16. package/src/check.ts +264 -78
  17. package/src/cli-options.ts +11 -5
  18. package/src/codegen.ts +15 -22
  19. package/src/dependencies.ts +2 -2
  20. package/src/environment.ts +94 -24
  21. package/src/errors.ts +18 -2
  22. package/src/evaluate.ts +122 -147
  23. package/src/exit-codes.ts +21 -43
  24. package/src/instances.ts +15 -14
  25. package/src/levels.ts +8 -8
  26. package/src/lexer.ts +5 -1
  27. package/src/live-check.ts +770 -0
  28. package/src/liveness.ts +54 -535
  29. package/src/parallel-worker.ts +7 -3
  30. package/src/parallel.ts +20 -4
  31. package/src/parser.ts +12 -1
  32. package/src/resolve.ts +16 -15
  33. package/src/run-cli.ts +58 -13
  34. package/src/runtime.ts +3 -1
  35. package/src/spec-description.ts +18 -6
  36. package/src/standard-modules.ts +2 -7
  37. package/src/state-graph.ts +157 -0
  38. package/src/subexpressions.ts +10 -10
  39. package/src/successors.ts +79 -15
  40. package/src/symmetry.ts +25 -7
  41. package/src/tableau.ts +51 -24
  42. package/src/tlc-ext.ts +29 -12
  43. package/src/tlc-module.ts +14 -33
  44. package/src/tlc-modules.ts +4 -0
  45. package/src/tlc-order.ts +25 -7
  46. package/src/tlc-random.ts +9 -6
  47. package/src/tlc-summary.ts +20 -5
  48. package/src/values.ts +121 -20
package/src/check.ts CHANGED
@@ -1,32 +1,42 @@
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
+ TlaIncompleteStateError,
17
+ TlaModuleError,
18
+ UNEXPECTED_EXCEPTION,
19
+ } from "./errors";
20
+ import { EXIT_STATUS, setExitCode, withLivenessExitCode } from "./exit-codes";
7
21
  import {
8
22
  describeRange,
9
23
  evaluate,
10
24
  expectBoolean,
11
25
  formatRange,
12
- getChildren,
13
26
  getDefinition,
14
27
  isConstantLevel,
15
28
  isImpure,
16
- isLocallyResolved,
17
29
  type Context,
18
30
  type Environment,
19
31
  type Scope,
20
32
  } from "./evaluate";
21
33
  import {
22
34
  createLivenessChecker,
23
- expandTemporal,
24
- getLevel,
25
35
  type Lasso,
36
+ type LivenessChecker,
26
37
  type LiveSuccessor,
27
- type ScopedExpression,
28
- type TemporalProperty,
29
- } from "./liveness";
38
+ } from "./live-check";
39
+ import { expandTemporal, getLevel, type ScopedExpression, type TemporalProperty } from "./liveness";
30
40
  import { ACTION_LEVEL, createLevelAnalyzer, TEMPORAL_LEVEL } from "./levels";
31
41
  import { prettyPrint } from "./pretty-print";
32
42
  import {
@@ -38,12 +48,19 @@ import {
38
48
  } from "./successors";
39
49
  import {
40
50
  getActionLabel,
51
+ getActionSignature,
41
52
  getNextActions,
42
53
  getSpecificationValue,
43
54
  type SpecAction,
44
55
  } from "./spec-description";
56
+ import {
57
+ createStateWriter,
58
+ type GraphState,
59
+ type StateDump,
60
+ type StateWriter,
61
+ } from "./state-graph";
45
62
  import { getRepresentative, getSymmetryGroup } from "./symmetry";
46
- import { getTlcStringOrder, getTlcVariableOrder } from "./tlc-order";
63
+ import { getTlcStringOrder, getTlcDeclarationOrder } from "./tlc-order";
47
64
  import { createTlcFingerprinter, getTlcFingerprint } from "./tlc-random";
48
65
  import { createCanonicalizer } from "./canonical";
49
66
  import { getPossibleCounts, type CheckerRuntime } from "./runtime";
@@ -51,6 +68,7 @@ import { createCounterExample } from "./tlc-ext";
51
68
  import { getFingerprintDistance, OUT_DEGREE_BUCKETS } from "./tlc-summary";
52
69
  import {
53
70
  combineHash,
71
+ formatState,
54
72
  formatValue,
55
73
  getValueHash,
56
74
  isFunctionValue,
@@ -74,6 +92,8 @@ export interface CheckOptions {
74
92
  workers?: number;
75
93
  // TLC's -lncheck: "final" checks liveness only on the complete state graph.
76
94
  livenessCheck?: "default" | "final";
95
+ // TLC's -dump: writes the reachable states, or with `dot` the state graph, through writeFile.
96
+ dump?: StateDump;
77
97
  }
78
98
 
79
99
  export type CheckStatus =
@@ -95,6 +115,8 @@ export interface TraceStep {
95
115
 
96
116
  export interface Violation {
97
117
  name: string;
118
+ // Every temporal property that a liveness counterexample violates, in the configuration's order.
119
+ properties?: string[];
98
120
  trace: TraceStep[];
99
121
  loopStart: number | undefined;
100
122
  loopLabel?: string;
@@ -255,8 +277,11 @@ const getInvariants = (names: string[], environment: Environment) => {
255
277
  levels.params.size === 0
256
278
  ? ""
257
279
  : "\nNote that a bug can cause TLC to incorrectly report this error.\nIf you believe your TLA+ or PlusCal specification to be correct,\nplease check if this bug described in LevelNode.java starting at line 590ff affects you.";
258
- throw new TlaConfigError(
259
- `The invariant ${name} is not a state predicate (one with no primes or temporal operators).${note}`,
280
+ throw setExitCode(
281
+ new TlaConfigError(
282
+ `The invariant ${name} is not a state predicate (one with no primes or temporal operators).${note}`,
283
+ ),
284
+ EXIT_STATUS.safetyEvaluationFailure,
260
285
  );
261
286
  }
262
287
  return [{ name, expression: createIdentifier(name), scope: undefined }];
@@ -354,8 +379,11 @@ const getSpecification = (config: ModelConfig, environment: Environment): Specif
354
379
  conjunct.kind === "Always" &&
355
380
  getLevel(conjunct.expression, item.scope, environment) < ACTION_LEVEL
356
381
  ) {
357
- throw new TlaConfigError(
358
- `TLC cannot handle []P in the specification ${config.specification} when P is a state predicate`,
382
+ throw setExitCode(
383
+ new TlaConfigError(
384
+ `TLC cannot handle the temporal formula ${describeRange(conjunct.expression)}`,
385
+ ),
386
+ EXIT_STATUS.error,
359
387
  );
360
388
  }
361
389
  const level = getLevel(conjunct, item.scope, environment);
@@ -425,12 +453,12 @@ const getProperties = (config: ModelConfig, environment: Environment): Propertie
425
453
  config.properties.forEach((name) => {
426
454
  const definition = getConfigPredicate("property", name, environment);
427
455
  if (!definition) return;
428
- expandTemporal(definition.body, undefined, environment, true).forEach((item) => {
456
+ expandTemporal(definition.body, undefined, environment, true, name).forEach((item) => {
429
457
  const conjunct = item.expression;
430
458
  if (isConstantTrue(item, environment, "property")) return;
431
459
  if (conjunct.kind === "Always" && conjunct.expression.kind === "BoxAction") {
432
460
  properties.actionProperties.push({
433
- name,
461
+ name: item.name,
434
462
  box: conjunct.expression,
435
463
  action: conjunct.expression.action,
436
464
  subscript: conjunct.expression.subscript,
@@ -442,12 +470,22 @@ const getProperties = (config: ModelConfig, environment: Environment): Propertie
442
470
  conjunct.kind === "Always" &&
443
471
  getLevel(conjunct.expression, item.scope, environment) <= 1
444
472
  ) {
445
- properties.invariants.push({ name, expression: conjunct.expression, scope: item.scope });
473
+ // TLC names the invariant []P after P when P is an operator name.
474
+ const expression = conjunct.expression;
475
+ properties.invariants.push({
476
+ name: expression.kind === "Identifier" ? expression.name : item.name,
477
+ expression,
478
+ scope: item.scope,
479
+ });
446
480
  return;
447
481
  }
448
482
  const level = getLevel(conjunct, item.scope, environment);
449
483
  if (level < ACTION_LEVEL) {
450
- properties.initialPredicates.push({ name, expression: conjunct, scope: item.scope });
484
+ properties.initialPredicates.push({
485
+ name: item.name,
486
+ expression: conjunct,
487
+ scope: item.scope,
488
+ });
451
489
  return;
452
490
  }
453
491
  if (level === ACTION_LEVEL) {
@@ -507,7 +545,9 @@ const getMembership = (
507
545
  const getStateChecks = (named: NamedExpression[], environment: Environment): StateCheck[] =>
508
546
  named.flatMap((item) =>
509
547
  getConjuncts(item.expression, environment).map((expression) => {
510
- const variables = getReadVariables(expression, environment);
548
+ // A LET or an argument in the scope can read variables the expression doesn't name.
549
+ const variables =
550
+ item.scope === undefined ? getReadVariables(expression, environment) : undefined;
511
551
  return {
512
552
  name: item.name,
513
553
  expression,
@@ -754,11 +794,13 @@ export const createSearch = (
754
794
  if (view !== undefined || isFingerprintedLikeTlc) {
755
795
  return BigInt64Array.from(states, getTlcStateFingerprint);
756
796
  }
757
- const indices = getTlcOrder();
758
- const getFingerprint = createTlcFingerprinter();
759
- return BigInt64Array.from(fingerprintStates, (state) =>
760
- getFingerprint(indices.map((index) => state[index])),
797
+ const fingerprints = new BigInt64Array(fingerprintStates.length);
798
+ const fingerprint = createTlcFingerprinter(
799
+ getTlcOrder(),
800
+ new Int32Array(fingerprints.buffer),
761
801
  );
802
+ fingerprintStates.forEach(fingerprint);
803
+ return fingerprints;
762
804
  },
763
805
  getFingerprintState: (state) => {
764
806
  if (isFingerprintedLikeTlc) return [String(getTlcStateFingerprint(state))];
@@ -820,7 +862,10 @@ export const createSearch = (
820
862
  )
821
863
  );
822
864
  } catch (error) {
823
- throw withHeadline(error, `Evaluating action property ${property.name} failed.`);
865
+ throw withHeadline(
866
+ withNextStateExitCode(error),
867
+ `Evaluating action property ${property.name} failed.`,
868
+ );
824
869
  }
825
870
  }),
826
871
  satisfiesActionConstraints: (state, next) =>
@@ -828,8 +873,7 @@ export const createSearch = (
828
873
  holdsLikeTlc(
829
874
  constraint.expression,
830
875
  getContext(environment, state, next),
831
- (expression) =>
832
- `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)}`,
876
+ (expression) => `${UNEXPECTED_EXCEPTION}${getExpectedBoolean(expression, environment)}`,
833
877
  ),
834
878
  ),
835
879
  trackStatePossible:
@@ -857,6 +901,23 @@ export const createSearch = (
857
901
  };
858
902
  };
859
903
 
904
+ // TLC exits with the code of a standard module's failure only when the failure escapes the
905
+ // computation of next states. In every other phase, the phase decides the code.
906
+ const withNextStateExitCode = (error: unknown) =>
907
+ error instanceof TlaModuleError ? setExitCode(error, error.exitCode) : error;
908
+
909
+ // TLC reports a failure of the next-state relation as an unexpected exception, unless a standard
910
+ // module raised it as an EvalException.
911
+ const toNextStateError = (error: unknown) =>
912
+ error instanceof TlaEvaluationError &&
913
+ !(error instanceof TlaModuleError) &&
914
+ !(error instanceof TlaIncompleteStateError)
915
+ ? setExitCode(
916
+ new TlaEvaluationError(`${UNEXPECTED_EXCEPTION}${error.message}`, error),
917
+ getErrorExitCode(error),
918
+ )
919
+ : withNextStateExitCode(error);
920
+
860
921
  const withHeadline = (error: unknown, headline: string) =>
861
922
  error instanceof TlaEvaluationError
862
923
  ? setExitCode(
@@ -865,8 +926,15 @@ const withHeadline = (error: unknown, headline: string) =>
865
926
  )
866
927
  : error;
867
928
 
929
+ // TLC finishes the -dump file whether or not the search finds a violation.
868
930
  export const checkSequentially = (options: CheckOptions): CheckResult => {
869
- setNextStatePhase(false);
931
+ const stateWriter = options.dump && createStateWriter(options.dump, options.writeFile);
932
+ const result = searchStates(options, stateWriter);
933
+ stateWriter?.close();
934
+ return result;
935
+ };
936
+
937
+ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefined): CheckResult => {
870
938
  const config = typeof options.config === "string" ? parseConfig(options.config) : options.config;
871
939
  const onPrint = options.onPrint ?? console.log;
872
940
  // TLC prints again while it rebuilds a trace, between the states it prints. Printing those lines
@@ -936,7 +1004,7 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
936
1004
  });
937
1005
 
938
1006
  const search = createSearch(config, environment, () =>
939
- getTlcVariableOrder(options.source, options.loadModule),
1007
+ getTlcDeclarationOrder(options.source, options.loadModule, "variable"),
940
1008
  );
941
1009
  const assumptionViolation = findAssumptionViolation(specification.assumptions, environment);
942
1010
  if (assumptionViolation) return createResult("assumption-violation", assumptionViolation);
@@ -962,8 +1030,36 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
962
1030
  const getFingerprintState = search.getFingerprintState;
963
1031
  const nextActions = { value: undefined as SpecAction[] | undefined };
964
1032
  const isReducing = config.view !== undefined || config.symmetry !== undefined;
1033
+ const tlcFingerprints: number[] = [];
965
1034
  const liveness = withLivenessExitCode(() =>
966
- createLivenessChecker(search.properties.liveness, spec.temporals, environment),
1035
+ createLivenessChecker(search.properties.liveness, spec.temporals, environment, {
1036
+ getFingerprint: (index) =>
1037
+ (tlcFingerprints[index] ??= Number(
1038
+ BigInt.asIntN(32, runtime.getFingerprint(states[index])),
1039
+ )),
1040
+ getSuccessors: (state) => {
1041
+ const successors: LiveSuccessor[] = [];
1042
+ if (spec.next === undefined) return successors;
1043
+ forEachSuccessor(
1044
+ spec.next,
1045
+ state,
1046
+ environment,
1047
+ (successor) => {
1048
+ canonicalizeState(successor.state);
1049
+ const isInModel =
1050
+ search.satisfiesConstraints(successor.state, state) &&
1051
+ search.satisfiesActionConstraints(state, successor.state);
1052
+ if (!isInModel) return false;
1053
+ const fingerprintState = getFingerprintState(successor.state);
1054
+ const index = findStateIndex(getStateHash(fingerprintState), fingerprintState);
1055
+ successors.push({ index, state: successor.state });
1056
+ return false;
1057
+ },
1058
+ spec.scope,
1059
+ );
1060
+ return successors;
1061
+ },
1062
+ }),
967
1063
  );
968
1064
  const isCanonicalizedFirst = search.isSymmetric || liveness !== undefined;
969
1065
 
@@ -972,7 +1068,9 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
972
1068
  const parents: number[] = [];
973
1069
  const actions: (string | undefined)[] = [];
974
1070
  const depths: number[] = [];
975
- const buckets = new Map<number, number | number[]>();
1071
+ // A Map holds at most 2^24 entries, so an open-addressing table keeps each seen state's hash
1072
+ // and its index plus one side by side, probed by the hash.
1073
+ const seen = { slots: new Int32Array(1 << 17), size: 0, shift: 16 };
976
1074
  const canonicalizeState = createCanonicalizer();
977
1075
 
978
1076
  const toRecord = (state: Value[]): Record<string, Value> =>
@@ -985,11 +1083,16 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
985
1083
  position: number,
986
1084
  loopStart: number | undefined,
987
1085
  ) => {
988
- const state = steps[position].state;
989
- const next = (steps[position + 1] ?? steps[loopStart ?? position]).state;
990
1086
  // TLC evaluates TLCGet("level") and Trace in an alias at the state's position in the trace.
991
1087
  runtime.getLevel = () => position + 1;
992
1088
  runtime.getBehavior = () => steps.slice(0, position + 1).map((step) => step.state);
1089
+ return evaluateAlias(
1090
+ alias,
1091
+ steps[position].state,
1092
+ (steps[position + 1] ?? steps[loopStart ?? position]).state,
1093
+ );
1094
+ };
1095
+ const evaluateAlias = (alias: string, state: Value[], next: Value[] | undefined) => {
993
1096
  try {
994
1097
  const body = getConfigDefinition("alias", alias, environment).body;
995
1098
  const value = evaluate(createIdentifier(alias), getContext(environment, state, next));
@@ -1104,7 +1207,7 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1104
1207
  outDegrees: failureOutDegrees,
1105
1208
  };
1106
1209
  };
1107
- const getPathTrace = (path: number[], loopStart?: number) => {
1210
+ const getPathSteps = (path: number[], loopStart?: number) => {
1108
1211
  const steps = getPathStates(path, NEXT_RECOVERY_FAILURE);
1109
1212
  const last = steps[steps.length - 1].state;
1110
1213
  const isClosed =
@@ -1113,7 +1216,7 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1113
1216
  loopStart === path.length - 1 ||
1114
1217
  findSuccessorWithFingerprint(last, path[loopStart]) !== undefined;
1115
1218
  if (!isClosed) throw new TlaEvaluationError(NEXT_RECOVERY_FAILURE);
1116
- return toTrace(steps, path, loopStart);
1219
+ return steps;
1117
1220
  };
1118
1221
  const getStateHash = (state: Value[]) => {
1119
1222
  let hash = 0x811c9dc5;
@@ -1127,19 +1230,35 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1127
1230
  }
1128
1231
  return true;
1129
1232
  };
1233
+ const getSlot = (hash: number) => (Math.imul(hash, 0x9e3779b1) >>> seen.shift) << 1;
1130
1234
  const findStateIndex = (hash: number, state: Value[]) => {
1131
- const bucket = buckets.get(hash);
1132
- if (bucket === undefined) return -1;
1133
- if (typeof bucket === "number") {
1134
- return isSameState(fingerprintStates[bucket], state) ? bucket : -1;
1235
+ const mask = seen.slots.length - 1;
1236
+ for (let slot = getSlot(hash); ; slot = (slot + 2) & mask) {
1237
+ const entry = seen.slots[slot + 1];
1238
+ if (entry === 0) return -1;
1239
+ if (seen.slots[slot] === hash && isSameState(fingerprintStates[entry - 1], state)) {
1240
+ return entry - 1;
1241
+ }
1135
1242
  }
1136
- return bucket.find((index) => isSameState(fingerprintStates[index], state)) ?? -1;
1243
+ };
1244
+ const insertSeen = (hash: number, entry: number) => {
1245
+ const mask = seen.slots.length - 1;
1246
+ let slot = getSlot(hash);
1247
+ while (seen.slots[slot + 1] !== 0) slot = (slot + 2) & mask;
1248
+ seen.slots[slot] = hash;
1249
+ seen.slots[slot + 1] = entry;
1137
1250
  };
1138
1251
  const markSeen = (hash: number, index: number) => {
1139
- const bucket = buckets.get(hash);
1140
- if (bucket === undefined) buckets.set(hash, index);
1141
- else if (typeof bucket === "number") buckets.set(hash, [bucket, index]);
1142
- else bucket.push(index);
1252
+ seen.size++;
1253
+ if (seen.size * 4 > seen.slots.length) {
1254
+ const slots = seen.slots;
1255
+ seen.slots = new Int32Array(slots.length * 2);
1256
+ seen.shift--;
1257
+ for (let slot = 0; slot < slots.length; slot += 2) {
1258
+ if (slots[slot + 1] !== 0) insertSeen(slots[slot], slots[slot + 1]);
1259
+ }
1260
+ }
1261
+ insertSeen(hash, index + 1);
1143
1262
  };
1144
1263
  const countDistinctState = (depth: number) => {
1145
1264
  runtime.distinctStates = states.length + 1;
@@ -1179,7 +1298,7 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1179
1298
  };
1180
1299
  runtime.getCurrentState = () => (current.index === -1 ? undefined : states[current.index]);
1181
1300
  runtime.setLivenessSource = (index) => {
1182
- current.livenessSource = index;
1301
+ current.livenessSource = index ?? -1;
1183
1302
  };
1184
1303
  runtime.getLevel = (state) => {
1185
1304
  const source = current.livenessSource;
@@ -1190,6 +1309,18 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1190
1309
  return current.isExpanding ? depths[current.index] + 1 : 0;
1191
1310
  };
1192
1311
 
1312
+ const getGraphState = (state: Value[], level: number): GraphState => ({
1313
+ fingerprint: BigInt.asIntN(64, runtime.getFingerprint(state)),
1314
+ level,
1315
+ getLabel: () =>
1316
+ formatState(
1317
+ config.alias === undefined
1318
+ ? toRecord(state)
1319
+ : evaluateAlias(config.alias, state, undefined),
1320
+ ),
1321
+ getText: () => formatState(toRecord(state)),
1322
+ });
1323
+
1193
1324
  const visitInitialState = (state: Value[]) => {
1194
1325
  canonicalizeState(state);
1195
1326
  runtime.generatedStates++;
@@ -1206,6 +1337,7 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1206
1337
  countDistinctState(1);
1207
1338
  runtime.queueSize++;
1208
1339
  liveness?.addInitialState(states.length, state);
1340
+ stateWriter?.writeInitialState(getGraphState(state, 1));
1209
1341
  }
1210
1342
  const violated = search.findViolatedInvariant(state);
1211
1343
  if (violated) {
@@ -1226,7 +1358,13 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1226
1358
  addState(state, fingerprintState, -1, undefined);
1227
1359
  return undefined;
1228
1360
  };
1229
- const visitSuccessor = (index: number, successor: Successor, liveSuccessors: LiveSuccessor[]) => {
1361
+ const visitSuccessor = (
1362
+ index: number,
1363
+ successor: Successor,
1364
+ liveSuccessors: LiveSuccessor[],
1365
+ source: GraphState | undefined,
1366
+ action: SpecAction | undefined,
1367
+ ) => {
1230
1368
  const state = states[index];
1231
1369
  runtime.generatedStates++;
1232
1370
  current.candidate = successor.state;
@@ -1240,6 +1378,14 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1240
1378
  const isInModel = isStateInModel && search.satisfiesActionConstraints(state, successor.state);
1241
1379
  if (isInModel) search.trackActionPossible(state, successor.state);
1242
1380
  const existing = isInModel ? found : -1;
1381
+ if (source && isInModel) {
1382
+ stateWriter?.writeSuccessor(
1383
+ source,
1384
+ getGraphState(successor.state, depths[index] + 1),
1385
+ existing !== -1,
1386
+ action && { name: action.name, signature: getActionSignature(action) },
1387
+ );
1388
+ }
1243
1389
  if (existing !== -1 && liveness) {
1244
1390
  const stored = states[existing];
1245
1391
  const isStored = stored.every((value, position) => value === successor.state[position]);
@@ -1311,23 +1457,55 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1311
1457
  }
1312
1458
  return createSuccess();
1313
1459
  }
1460
+ // TLC labels and colors an edge of the -dump state graph by the action that generated it. When
1461
+ // the graph names its edges, the search generates successors action by action, as TLC does.
1462
+ const isNamingEdges = Boolean(
1463
+ options.dump?.dot && (options.dump.actionLabels || options.dump.colorize),
1464
+ );
1465
+ const forEachActionSuccessor = (
1466
+ state: Value[],
1467
+ onSuccessor: (successor: Successor, action: SpecAction | undefined) => boolean,
1468
+ ) => {
1469
+ if (!isNamingEdges) {
1470
+ return forEachSuccessor(
1471
+ next,
1472
+ state,
1473
+ environment,
1474
+ (successor) => onSuccessor(successor, undefined),
1475
+ spec.scope,
1476
+ );
1477
+ }
1478
+ nextActions.value ??= getNextActions(config, environment, specification.instanceActions);
1479
+ const progress = { isStopped: false };
1480
+ return nextActions.value.reduce((count, action) => {
1481
+ if (progress.isStopped) return count;
1482
+ return (
1483
+ count +
1484
+ forEachSuccessor(
1485
+ action.expression,
1486
+ state,
1487
+ environment,
1488
+ (successor) => {
1489
+ progress.isStopped = onSuccessor(successor, action);
1490
+ return progress.isStopped;
1491
+ },
1492
+ action.scope,
1493
+ )
1494
+ );
1495
+ }, 0);
1496
+ };
1314
1497
  const expandState = (index: number) => {
1315
1498
  const state = states[index];
1316
1499
  const liveSuccessors: LiveSuccessor[] = [];
1317
- const successorCount = forEachSuccessor(
1318
- next,
1319
- state,
1320
- environment,
1321
- (successor) => {
1322
- try {
1323
- outcome.result = visitSuccessor(index, successor, liveSuccessors);
1324
- } catch (error) {
1325
- outcome.result = toFailure(error, getTrace(index, successor));
1326
- }
1327
- return outcome.result !== undefined;
1328
- },
1329
- spec.scope,
1330
- );
1500
+ const source = stateWriter && getGraphState(state, depths[index]);
1501
+ const successorCount = forEachActionSuccessor(state, (successor, action) => {
1502
+ try {
1503
+ outcome.result = visitSuccessor(index, successor, liveSuccessors, source, action);
1504
+ } catch (error) {
1505
+ outcome.result = toFailure(error, getTrace(index, successor));
1506
+ }
1507
+ return outcome.result !== undefined;
1508
+ });
1331
1509
  current.isExpanding = false;
1332
1510
  if (outcome.result) return outcome.result;
1333
1511
  if (successorCount === 0 && config.checkDeadlock) {
@@ -1335,32 +1513,43 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1335
1513
  }
1336
1514
  try {
1337
1515
  const accepted = liveness?.addState(index, state, liveSuccessors);
1338
- current.livenessSource = -1;
1339
- if (!accepted) return undefined;
1516
+ if (!liveness || !accepted) return undefined;
1517
+ const steps = getPathSteps(accepted);
1518
+ const properties = liveness.getViolatedProperties(
1519
+ steps.map((step) => step.state),
1520
+ steps.length - 1,
1521
+ );
1340
1522
  return reportViolation("property-violation", {
1341
- name: accepted.name,
1342
- trace: getPathTrace(accepted.path),
1523
+ name: properties[0],
1524
+ properties,
1525
+ trace: toTrace(steps, accepted),
1343
1526
  });
1344
1527
  } catch (error) {
1345
1528
  return toFailure(error, getStateTrace(index), undefined, getPartialOutDegrees());
1346
1529
  }
1347
1530
  };
1348
- const reportLasso = (lasso: Lasso) => {
1531
+ // TLC names the properties and the step back into the cycle from the states it prints.
1532
+ const reportLasso = (checker: LivenessChecker, lasso: Lasso) => {
1349
1533
  const path = [...lasso.prefix, ...lasso.cycle];
1350
- const trace = getPathTrace(path, lasso.prefix.length);
1351
- const back = path[lasso.prefix.length];
1534
+ const loopStart = lasso.prefix.length;
1535
+ const steps = getPathSteps(path, loopStart);
1536
+ const trace = toTrace(steps, path, loopStart);
1537
+ const properties = checker.getViolatedProperties(
1538
+ steps.map((step) => step.state),
1539
+ loopStart,
1540
+ );
1541
+ const back = path[loopStart];
1352
1542
  const last = path[path.length - 1];
1543
+ const lastState = steps[steps.length - 1].state;
1353
1544
  const loopLabel =
1354
- back === last ? undefined : withoutOutput(() => getLabel(last, states[last], states[back]));
1545
+ back === last ? undefined : withoutOutput(() => getLabel(last, lastState, states[back]));
1355
1546
  return reportViolation(
1356
1547
  "liveness-violation",
1357
- { name: lasso.name, trace, loopStart: lasso.prefix.length, loopLabel },
1548
+ { name: properties[0], properties, trace, loopStart, loopLabel },
1358
1549
  () =>
1359
1550
  back === last
1360
1551
  ? trace[trace.length - 1].action
1361
- : getTraceSuccessors(states[last]).find((successor) =>
1362
- isSameState(successor.state, states[back]),
1363
- )?.action,
1552
+ : findSuccessorWithFingerprint(lastState, back)?.action,
1364
1553
  );
1365
1554
  };
1366
1555
  const isPeriodic = liveness !== undefined && options.livenessCheck !== "final";
@@ -1373,11 +1562,9 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1373
1562
  if (!isGrown || periodic.time > (now - startedAt) * LIVENESS_RATIO) return undefined;
1374
1563
  periodic.size = expanded;
1375
1564
  const lasso = liveness?.findViolation();
1376
- current.livenessSource = -1;
1377
1565
  periodic.time += performance.now() - now;
1378
1566
  return lasso;
1379
1567
  };
1380
- setNextStatePhase(true);
1381
1568
  for (let index = 0; index < states.length && !runtime.isStopped; index++) {
1382
1569
  current.index = index;
1383
1570
  current.candidate = undefined;
@@ -1386,22 +1573,21 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1386
1573
  try {
1387
1574
  outcome.result = expandState(index);
1388
1575
  } catch (error) {
1389
- outcome.result = toFailure(error, getStateTrace(index));
1576
+ outcome.result = toFailure(toNextStateError(error), getStateTrace(index));
1390
1577
  }
1391
1578
  if (outcome.result) return outcome.result;
1392
1579
  outDegrees[getOutDegreeBucket()]++;
1393
1580
  expansion.newStates = 0;
1394
1581
  if (isPeriodic && performance.now() >= periodic.at) {
1395
1582
  const lasso = findPeriodicViolation(index + 1);
1396
- if (lasso) return reportLasso(lasso);
1583
+ if (liveness && lasso) return reportLasso(liveness, lasso);
1397
1584
  }
1398
1585
  }
1399
1586
 
1400
1587
  current.index = -1;
1401
1588
  current.candidate = undefined;
1402
1589
  const lasso = liveness?.findViolation();
1403
- current.livenessSource = -1;
1404
- if (lasso) return reportLasso(lasso);
1590
+ if (liveness && lasso) return reportLasso(liveness, lasso);
1405
1591
 
1406
1592
  const postconditionViolation = search.findPostconditionViolation();
1407
1593
  if (postconditionViolation) {
@@ -2,6 +2,8 @@ export interface OptionSpec {
2
2
  flag: string;
3
3
  isRequired?: boolean;
4
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;
5
7
  }
6
8
 
7
9
  export interface ParsedOption {
@@ -29,27 +31,31 @@ export const defineCommand = (usage: string, specs: OptionSpec[]) => {
29
31
  const arities = new Map(
30
32
  specs.map((spec) => {
31
33
  const [name, ...values] = spec.flag.split(" ");
32
- return [name, values.length];
34
+ return [name, spec.getArity ?? (() => values.length)];
33
35
  }),
34
36
  );
35
37
  const parse = (args: string[]): ParsedArgs => {
36
38
  const options: ParsedOption[] = [];
37
39
  const positionals: string[] = [];
38
40
  const unknown: string[] = [];
41
+ const incomplete: ParsedOption[] = [];
39
42
  for (let index = 0; index < args.length; index++) {
40
- const arity = arities.get(args[index]);
41
- if (arity === undefined) {
43
+ const getArity = arities.get(args[index]);
44
+ if (getArity === undefined) {
42
45
  (args[index].startsWith("-") ? unknown : positionals).push(args[index]);
43
46
  continue;
44
47
  }
45
- options.push({ name: args[index], values: args.slice(index + 1, index + 1 + arity) });
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);
46
52
  index += arity;
47
53
  }
48
54
  return {
49
55
  options,
50
56
  positionals,
51
57
  unknown,
52
- incomplete: options.find((option) => option.values.length < (arities.get(option.name) ?? 0)),
58
+ incomplete: incomplete[0],
53
59
  has: (name) => options.some((option) => option.name === name),
54
60
  get: (name) => options.findLast((option) => option.name === name)?.values,
55
61
  };