tla-ts 0.0.3-dev.037ac3b → 0.0.3-dev.0e500e5

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 (47) hide show
  1. package/dist/index.cjs +1 -1
  2. package/dist/index.d.cts +58 -22
  3. package/dist/index.d.ts +58 -22
  4. package/dist/index.js +1 -1
  5. package/dist/parallel-worker.cjs +1 -1
  6. package/dist/parallel-worker.js +2 -2
  7. package/dist/parallel.cjs +1 -1
  8. package/dist/parallel.js +2 -2
  9. package/dist/run-cli.cjs +14 -12
  10. package/dist/run-cli.js +22 -20
  11. package/dist/transfer.cjs +39 -21
  12. package/dist/transfer.js +39 -21
  13. package/package.json +1 -1
  14. package/src/ast.ts +26 -4
  15. package/src/builtins.ts +9 -3
  16. package/src/check.ts +309 -61
  17. package/src/codegen.ts +6 -3
  18. package/src/config.ts +224 -170
  19. package/src/environment.ts +223 -84
  20. package/src/errors.ts +100 -1
  21. package/src/evaluate.ts +172 -19
  22. package/src/exit-codes.ts +22 -3
  23. package/src/fingerprints.ts +2 -1
  24. package/src/instances.ts +1 -1
  25. package/src/levels.ts +176 -36
  26. package/src/live-check.ts +129 -49
  27. package/src/liveness.ts +68 -10
  28. package/src/parallel-worker.ts +2 -2
  29. package/src/parallel.ts +2 -2
  30. package/src/parser.ts +152 -48
  31. package/src/resolve.ts +878 -338
  32. package/src/run-cli.ts +61 -11
  33. package/src/sany-lexer.ts +615 -0
  34. package/src/sany-parse-error.ts +3143 -0
  35. package/src/spec-description.ts +1 -2
  36. package/src/standard-modules.ts +52 -38
  37. package/src/standard-ranges.ts +116 -0
  38. package/src/subexpressions.ts +25 -13
  39. package/src/substitution-levels.ts +38 -17
  40. package/src/successors.ts +111 -31
  41. package/src/symmetry.ts +16 -6
  42. package/src/tableau.ts +1 -1
  43. package/src/tlc-module.ts +6 -6
  44. package/src/tlc-modules.ts +4 -0
  45. package/src/tlc-order.ts +8 -4
  46. package/src/value-sources.ts +29 -0
  47. package/src/values.ts +184 -51
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tla-ts",
3
- "version": "0.0.3-dev.037ac3b",
3
+ "version": "0.0.3-dev.0e500e5",
4
4
  "description": "A TLA+ interpreter and model checker in TypeScript, 2× faster than TLC",
5
5
  "keywords": [
6
6
  "formal verification",
package/src/ast.ts CHANGED
@@ -33,9 +33,12 @@ export interface StringExpression {
33
33
  location: SourceLocation;
34
34
  }
35
35
 
36
+ // selectorRanges holds the range of each part of a name such as foo!lab, where SANY reports an
37
+ // error in selecting that part.
36
38
  export interface IdentifierExpression {
37
39
  kind: "Identifier";
38
40
  name: string;
41
+ selectorRanges?: SourceRange[];
39
42
  location: SourceLocation;
40
43
  resolution?: LocalResolution;
41
44
  }
@@ -47,6 +50,9 @@ export interface ApplyExpression {
47
50
  // The number of args each part of a name like F(x)!l(y) takes, when a part before the last takes
48
51
  // some.
49
52
  argumentCounts?: number[];
53
+ // The range of the parenthesized arguments of a named operator, where SANY reports their count.
54
+ argumentsRange?: SourceRange;
55
+ selectorRanges?: SourceRange[];
50
56
  location: SourceLocation;
51
57
  resolution?: LocalResolution;
52
58
  }
@@ -60,6 +66,7 @@ export interface OperatorReferenceExpression {
60
66
  export interface LambdaExpression {
61
67
  kind: "Lambda";
62
68
  params: string[];
69
+ paramRanges?: SourceRange[];
63
70
  body: Expression;
64
71
  location: SourceLocation;
65
72
  }
@@ -117,7 +124,10 @@ export interface LetExpression {
117
124
  location: SourceLocation;
118
125
  }
119
126
 
120
- export type BoundPattern = { kind: "Name"; name: string } | { kind: "Tuple"; names: string[] };
127
+ // ranges holds the range of each name the pattern binds.
128
+ export type BoundPattern =
129
+ | { kind: "Name"; name: string; ranges?: SourceRange[] }
130
+ | { kind: "Tuple"; names: string[]; ranges?: SourceRange[] };
121
131
 
122
132
  export interface Bound {
123
133
  pattern: BoundPattern;
@@ -135,6 +145,7 @@ export interface UnboundedQuantifierExpression {
135
145
  kind: "UnboundedQuantifier";
136
146
  quantifier: "Forall" | "Exists";
137
147
  names: string[];
148
+ nameRanges?: SourceRange[];
138
149
  isTemporal?: boolean;
139
150
  body: Expression;
140
151
  location: SourceLocation;
@@ -192,6 +203,7 @@ export interface FunctionSetExpression {
192
203
  export interface RecordField {
193
204
  name: string;
194
205
  value: Expression;
206
+ location: SourceLocation;
195
207
  }
196
208
 
197
209
  export interface RecordExpression {
@@ -280,6 +292,7 @@ export type Selector =
280
292
  export interface SubexpressionExpression {
281
293
  kind: "Subexpression";
282
294
  selectors: Selector[];
295
+ selectorRanges?: SourceRange[];
283
296
  location: SourceLocation;
284
297
  }
285
298
 
@@ -384,6 +397,7 @@ export interface NewSymbol {
384
397
  arity: number;
385
398
  level: "Constant" | "Variable" | "State" | "Action" | "Temporal";
386
399
  set: Expression | undefined;
400
+ nameRange?: SourceRange;
387
401
  location: SourceLocation;
388
402
  }
389
403
 
@@ -435,19 +449,27 @@ export type StepBody =
435
449
  | Instance
436
450
  | DefineStep
437
451
  | { kind: "Have"; expression: Expression }
438
- | { kind: "Take"; names: string[]; bounds: Bound[] }
452
+ | { kind: "Take"; names: string[]; nameRanges?: SourceRange[]; bounds: Bound[] }
439
453
  | { kind: "Witness"; expressions: Expression[] }
440
- | { kind: "Pick"; names: string[]; bounds: Bound[]; body: Expression }
454
+ | {
455
+ kind: "Pick";
456
+ names: string[];
457
+ nameRanges?: SourceRange[];
458
+ bounds: Bound[];
459
+ body: Expression;
460
+ }
441
461
  | { kind: "Case"; expression: Expression }
442
462
  | { kind: "Assert"; isSuffices: boolean; statement: Expression | AssumeProve }
443
463
  | { kind: "Qed" };
444
464
 
445
- // head is the range of the step number and its statement, without the proof.
465
+ // head is the range of the step number and its statement, without the proof, and statement is the
466
+ // range of the statement alone.
446
467
  export interface ProofStep {
447
468
  name: string | undefined;
448
469
  token: string;
449
470
  body: StepBody;
450
471
  head: SourceRange;
472
+ statement: SourceRange;
451
473
  proof: Proof | undefined;
452
474
  location: SourceLocation;
453
475
  }
package/src/builtins.ts CHANGED
@@ -297,15 +297,21 @@ export const getJavaInteger = (value: Value, signature: string) => {
297
297
  return value;
298
298
  };
299
299
 
300
- export const getIntegersSignature = (method: string, result: string, arity: number) =>
301
- `public static tlc2.value.impl.${result} tlc2.module.Integers.${method}(${Array.from({ length: arity }, () => "tlc2.value.impl.IntValue").join(",")})`;
300
+ export const getArithmeticSignature = (
301
+ javaClass: "Naturals" | "Integers",
302
+ method: string,
303
+ result: string,
304
+ arity: number,
305
+ ) =>
306
+ `public static tlc2.value.impl.${result} tlc2.module.${javaClass}.${method}(${Array.from({ length: arity }, () => "tlc2.value.impl.IntValue").join(",")})`;
302
307
 
303
308
  export const defineArithmetic = (
309
+ javaClass: "Naturals" | "Integers",
304
310
  name: string,
305
311
  method: string,
306
312
  compute: (left: number, right: number) => number,
307
313
  ) => {
308
- const signature = getIntegersSignature(method, "IntValue", 2);
314
+ const signature = getArithmeticSignature(javaClass, method, "IntValue", 2);
309
315
  return defineBinary(name, (left, right) => {
310
316
  const leftNumber = getJavaInteger(left, signature);
311
317
  const rightNumber = getJavaInteger(right, signature);
package/src/check.ts CHANGED
@@ -11,8 +11,13 @@ import { getReadVariables } from "./dependencies";
11
11
  import { createEnvironment } from "./environment";
12
12
  import {
13
13
  getErrorExitCode,
14
+ isStackOverflow,
15
+ formatRange,
16
+ STACK_OVERFLOW,
14
17
  TlaConfigError,
15
18
  TlaEvaluationError,
19
+ TlaIllegalStateError,
20
+ TlaIncompleteStateError,
16
21
  TlaModuleError,
17
22
  UNEXPECTED_EXCEPTION,
18
23
  } from "./errors";
@@ -21,7 +26,6 @@ import {
21
26
  describeRange,
22
27
  evaluate,
23
28
  expectBoolean,
24
- formatRange,
25
29
  getDefinition,
26
30
  isConstantLevel,
27
31
  isImpure,
@@ -32,6 +36,7 @@ import {
32
36
  import {
33
37
  createLivenessChecker,
34
38
  type Lasso,
39
+ type LiveGraph,
35
40
  type LivenessChecker,
36
41
  type LiveSuccessor,
37
42
  } from "./live-check";
@@ -59,14 +64,17 @@ import {
59
64
  type StateWriter,
60
65
  } from "./state-graph";
61
66
  import { getRepresentative, getSymmetryGroup } from "./symmetry";
62
- import { getTlcStringOrder, getTlcVariableOrder } from "./tlc-order";
67
+ import { getTlcStringOrder, getTlcDeclarationOrder } from "./tlc-order";
63
68
  import { createTlcFingerprinter, getTlcFingerprint } from "./tlc-random";
64
69
  import { createCanonicalizer } from "./canonical";
65
70
  import { getPossibleCounts, type CheckerRuntime } from "./runtime";
66
71
  import { createCounterExample } from "./tlc-ext";
72
+ import { getFingerprintTrace, valueSources } from "./value-sources";
67
73
  import { getFingerprintDistance, OUT_DEGREE_BUCKETS } from "./tlc-summary";
68
74
  import {
75
+ assertFingerprintable,
69
76
  combineHash,
77
+ createModelValue,
70
78
  formatState,
71
79
  formatValue,
72
80
  getValueHash,
@@ -136,6 +144,25 @@ export interface EvaluationFailure {
136
144
  trace: TraceStep[];
137
145
  initialState: Record<string, Value> | undefined;
138
146
  exitCode: number;
147
+ replay?: Replay;
148
+ isWithoutStatistics?: boolean;
149
+ }
150
+
151
+ // TLC replays a failed step to print the expressions it was evaluating when the replay failed.
152
+ export interface Replay {
153
+ output: string[];
154
+ callStack: string[] | undefined;
155
+ fingerprint?: Fingerprint;
156
+ // The worker that fails to check liveness replays the step at once, so TLC prints the stack
157
+ // before the error, and only when it holds a frame.
158
+ isBeforeError?: boolean;
159
+ }
160
+
161
+ // TLC reports an error from a method of a value that has a source as one it was unable to
162
+ // fingerprint. With an empty stack, it lists the sources of the values instead.
163
+ export interface Fingerprint {
164
+ sources: string[];
165
+ reason: string;
139
166
  }
140
167
 
141
168
  export interface CheckResult {
@@ -247,7 +274,7 @@ const getConstantValue = (name: string, definition: Definition, environment: Env
247
274
  try {
248
275
  return evaluate(createIdentifier(name), getContext(environment, undefined, undefined));
249
276
  } catch (error) {
250
- if (error instanceof TlaEvaluationError) return undefined;
277
+ if (error instanceof TlaEvaluationError || isStackOverflow(error)) return undefined;
251
278
  throw error;
252
279
  }
253
280
  };
@@ -276,8 +303,11 @@ const getInvariants = (names: string[], environment: Environment) => {
276
303
  levels.params.size === 0
277
304
  ? ""
278
305
  : "\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.";
279
- throw new TlaConfigError(
280
- `The invariant ${name} is not a state predicate (one with no primes or temporal operators).${note}`,
306
+ throw setExitCode(
307
+ new TlaConfigError(
308
+ `The invariant ${name} is not a state predicate (one with no primes or temporal operators).${note}`,
309
+ ),
310
+ EXIT_STATUS.safetyEvaluationFailure,
281
311
  );
282
312
  }
283
313
  return [{ name, expression: createIdentifier(name), scope: undefined }];
@@ -375,8 +405,11 @@ const getSpecification = (config: ModelConfig, environment: Environment): Specif
375
405
  conjunct.kind === "Always" &&
376
406
  getLevel(conjunct.expression, item.scope, environment) < ACTION_LEVEL
377
407
  ) {
378
- throw new TlaConfigError(
379
- `TLC cannot handle []P in the specification ${config.specification} when P is a state predicate`,
408
+ throw setExitCode(
409
+ new TlaConfigError(
410
+ `TLC cannot handle the temporal formula ${describeRange(conjunct.expression)}`,
411
+ ),
412
+ EXIT_STATUS.error,
380
413
  );
381
414
  }
382
415
  const level = getLevel(conjunct, item.scope, environment);
@@ -825,11 +858,17 @@ export const createSearch = (
825
858
  }
826
859
  }),
827
860
  satisfiesConstraints: (state, parent) =>
828
- constraints.every(
829
- (constraint) =>
830
- isUnchangedFor(constraint, state, parent) ||
831
- holdsLikeTlc(constraint.expression, getContext(environment, state, undefined)),
832
- ),
861
+ constraints.every((constraint) => {
862
+ try {
863
+ return (
864
+ isUnchangedFor(constraint, state, parent) ||
865
+ holdsLikeTlc(constraint.expression, getContext(environment, state, undefined))
866
+ );
867
+ } catch (error) {
868
+ // TLC reports a failing constraint on a successor like a failure of the next-state relation.
869
+ throw parent ? toNextStateError(error) : error;
870
+ }
871
+ }),
833
872
  findFailedInitialPredicate: (state) =>
834
873
  properties.initialPredicates.find(
835
874
  (predicate) =>
@@ -862,13 +901,13 @@ export const createSearch = (
862
901
  }
863
902
  }),
864
903
  satisfiesActionConstraints: (state, next) =>
865
- actionConstraints.every((constraint) =>
866
- holdsLikeTlc(
867
- constraint.expression,
868
- getContext(environment, state, next),
869
- (expression) => `${UNEXPECTED_EXCEPTION}${getExpectedBoolean(expression, environment)}`,
870
- ),
871
- ),
904
+ actionConstraints.every((constraint) => {
905
+ try {
906
+ return holdsLikeTlc(constraint.expression, getContext(environment, state, next));
907
+ } catch (error) {
908
+ throw toNextStateError(error);
909
+ }
910
+ }),
872
911
  trackStatePossible:
873
912
  statePossible.length === 0
874
913
  ? ignorePossible
@@ -899,6 +938,59 @@ export const createSearch = (
899
938
  const withNextStateExitCode = (error: unknown) =>
900
939
  error instanceof TlaModuleError ? setExitCode(error, error.exitCode) : error;
901
940
 
941
+ // TLC reports a failure of the next-state relation, or of the liveness check of a step, as an
942
+ // unexpected exception, unless a standard module raised it as an EvalException.
943
+ const toNextStateError = (error: unknown) =>
944
+ error instanceof TlaEvaluationError &&
945
+ !(error instanceof TlaModuleError) &&
946
+ !(error instanceof TlaIncompleteStateError)
947
+ ? setExitCode(
948
+ new TlaEvaluationError(`${UNEXPECTED_EXCEPTION}${error.message}`, error),
949
+ getErrorExitCode(error),
950
+ )
951
+ : withNextStateExitCode(error);
952
+
953
+ const isRepeated = (frame: string, index: number, frames: string[]) =>
954
+ index > 0 && frames[index - 1] === frame;
955
+
956
+ // FingerprintException#getTrace numbers the sources from the outermost value and lists the innermost
957
+ // first.
958
+ const getSourceTrace = (sources: Expression[]) =>
959
+ sources
960
+ .flatMap((source) => (source.location.range ? [formatRange(source.location.range)] : []))
961
+ .filter((source, index, all) => !isRepeated(source, index, all))
962
+ .map((source, index) => `${index}) ${source}`)
963
+ .reverse();
964
+
965
+ // TLC keeps the stack only when an evaluation fails, and prints each expression on it once, however
966
+ // many times in a row it pushed it.
967
+ const getReplayedCallStack = (
968
+ replay: () => void,
969
+ trace: Expression[],
970
+ ): Pick<Replay, "callStack" | "fingerprint"> => {
971
+ try {
972
+ replay();
973
+ return { callStack: undefined };
974
+ } catch (error) {
975
+ if (!(error instanceof TlaEvaluationError)) return { callStack: [] };
976
+ const callStack = trace
977
+ .flatMap((expression) => {
978
+ const range = expression.location.range;
979
+ return range
980
+ ? [
981
+ `Line ${range.start.line}, column ${range.start.column} to line ${range.end.line}, column ${range.end.column} in ${range.module}`,
982
+ ]
983
+ : [];
984
+ })
985
+ .filter((frame, index, frames) => !isRepeated(frame, index, frames));
986
+ const sources = getFingerprintTrace(error);
987
+ return {
988
+ callStack,
989
+ fingerprint: sources && { sources: getSourceTrace(sources), reason: error.message },
990
+ };
991
+ }
992
+ };
993
+
902
994
  const withHeadline = (error: unknown, headline: string) =>
903
995
  error instanceof TlaEvaluationError
904
996
  ? setExitCode(
@@ -910,9 +1002,16 @@ const withHeadline = (error: unknown, headline: string) =>
910
1002
  // TLC finishes the -dump file whether or not the search finds a violation.
911
1003
  export const checkSequentially = (options: CheckOptions): CheckResult => {
912
1004
  const stateWriter = options.dump && createStateWriter(options.dump, options.writeFile);
913
- const result = searchStates(options, stateWriter);
914
- stateWriter?.close();
915
- return result;
1005
+ try {
1006
+ return searchStates(options, stateWriter);
1007
+ } catch (error) {
1008
+ // TLC reports a stack overflow outside the search as a failure of its own, with exit code 255.
1009
+ throw isStackOverflow(error)
1010
+ ? setExitCode(new TlaEvaluationError(STACK_OVERFLOW), EXIT_STATUS.error)
1011
+ : error;
1012
+ } finally {
1013
+ stateWriter?.close();
1014
+ }
916
1015
  };
917
1016
 
918
1017
  const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefined): CheckResult => {
@@ -920,9 +1019,10 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
920
1019
  const onPrint = options.onPrint ?? console.log;
921
1020
  // TLC prints again while it rebuilds a trace, between the states it prints. Printing those lines
922
1021
  // before the trace would misplace them, so rebuilding a trace prints nothing.
923
- const output = { isMuted: false };
1022
+ const output = { isMuted: false, replayed: undefined as string[] | undefined };
924
1023
  const print = (text: string) => {
925
- if (!output.isMuted) onPrint(text);
1024
+ if (output.replayed) output.replayed.push(text);
1025
+ else if (!output.isMuted) onPrint(text);
926
1026
  };
927
1027
  const withoutOutput = <Result>(rebuild: () => Result) => {
928
1028
  output.isMuted = true;
@@ -984,9 +1084,9 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
984
1084
  ),
985
1085
  });
986
1086
 
987
- const search = createSearch(config, environment, () =>
988
- getTlcVariableOrder(options.source, options.loadModule),
989
- );
1087
+ const getVariableOrder = () =>
1088
+ getTlcDeclarationOrder(options.source, options.loadModule, "variable");
1089
+ const search = createSearch(config, environment, getVariableOrder);
990
1090
  const assumptionViolation = findAssumptionViolation(specification.assumptions, environment);
991
1091
  if (assumptionViolation) return createResult("assumption-violation", assumptionViolation);
992
1092
  if (!search) return createSuccess();
@@ -1010,37 +1110,114 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1010
1110
  const spec = search.spec;
1011
1111
  const getFingerprintState = search.getFingerprintState;
1012
1112
  const nextActions = { value: undefined as SpecAction[] | undefined };
1113
+ const replayFailure = (
1114
+ result: CheckResult,
1115
+ replay: (tracedSearch: Search, traced: Environment) => void,
1116
+ isBeforeError = false,
1117
+ ): CheckResult => {
1118
+ if (!result.failure) return result;
1119
+ const trace: Expression[] = [];
1120
+ const traced: Environment = { ...environment, evaluators: new WeakMap(), trace };
1121
+ const tracedSearch = createSearch(config, traced, getVariableOrder);
1122
+ if (!tracedSearch) return result;
1123
+ const replayed: string[] = [];
1124
+ output.replayed = replayed;
1125
+ valueSources.current = new WeakMap();
1126
+ const replayedStack = getReplayedCallStack(() => replay(tracedSearch, traced), trace);
1127
+ valueSources.current = undefined;
1128
+ output.replayed = undefined;
1129
+ return {
1130
+ ...result,
1131
+ failure: { ...result.failure, replay: { output: replayed, ...replayedStack, isBeforeError } },
1132
+ };
1133
+ };
1134
+ // TLC fingerprints a state outside CallStackTool, so a failure of a value with a source leaves
1135
+ // the stack empty. Any other failure keeps the stack of the initial predicate.
1136
+ const fingerprintReplayed = (state: Value[], traced: Environment) => {
1137
+ try {
1138
+ getStateHash(getFingerprintState(state));
1139
+ } catch (error) {
1140
+ if (traced.trace && getFingerprintTrace(error)) traced.trace.length = 0;
1141
+ throw error;
1142
+ }
1143
+ };
1144
+ // TLC checks every initial state again, as when it first generated them.
1145
+ const replayInitialStates = (result: CheckResult) =>
1146
+ replayFailure(result, (tracedSearch, traced) => {
1147
+ if (spec.init === undefined) return;
1148
+ forEachInitialState(
1149
+ spec.init,
1150
+ traced,
1151
+ (state) => {
1152
+ if (tracedSearch.satisfiesConstraints(state)) fingerprintReplayed(state, traced);
1153
+ return (
1154
+ tracedSearch.findViolatedInvariant(state) !== undefined ||
1155
+ tracedSearch.findFailedInitialPredicate(state) !== undefined
1156
+ );
1157
+ },
1158
+ spec.scope,
1159
+ );
1160
+ });
1161
+ // TLC rebuilds the behavior up to the state it expanded before it replays the step.
1162
+ const rebuildBehavior = (index: number): void => {
1163
+ const parent = parents[index];
1164
+ if (parent === -1) {
1165
+ getSpecInitialStates();
1166
+ return;
1167
+ }
1168
+ rebuildBehavior(parent);
1169
+ getLabel(parent, states[parent], states[index]);
1170
+ };
1171
+ // TLC generates the successors of each action before it checks them. It checks the invariants
1172
+ // only of a successor outside the model, since it has seen the others.
1173
+ const replaySuccessors = (result: CheckResult, index: number) =>
1174
+ replayFailure(result, (tracedSearch, traced) => {
1175
+ rebuildBehavior(index);
1176
+ const state = states[index];
1177
+ nextActions.value ??= getNextActions(config, environment, specification.instanceActions);
1178
+ nextActions.value.find((action) =>
1179
+ getSuccessors(action.expression, state, traced, action.scope).some((successor) => {
1180
+ const isInModel =
1181
+ tracedSearch.satisfiesConstraints(successor.state) &&
1182
+ tracedSearch.satisfiesActionConstraints(state, successor.state);
1183
+ if (isInModel) fingerprintReplayed(successor.state, traced);
1184
+ return (
1185
+ (!isInModel && tracedSearch.findViolatedInvariant(successor.state) !== undefined) ||
1186
+ tracedSearch.findViolatedActionProperty(state, successor.state) !== undefined
1187
+ );
1188
+ }),
1189
+ );
1190
+ });
1013
1191
  const isReducing = config.view !== undefined || config.symmetry !== undefined;
1014
1192
  const tlcFingerprints: number[] = [];
1193
+ const liveGraph: LiveGraph = {
1194
+ getFingerprint: (index) =>
1195
+ (tlcFingerprints[index] ??= Number(BigInt.asIntN(32, runtime.getFingerprint(states[index])))),
1196
+ getSuccessors: (state) => {
1197
+ const successors: LiveSuccessor[] = [];
1198
+ if (spec.next === undefined) return successors;
1199
+ forEachSuccessor(
1200
+ spec.next,
1201
+ state,
1202
+ environment,
1203
+ (successor) => {
1204
+ canonicalizeState(successor.state);
1205
+ const isInModel =
1206
+ search.satisfiesConstraints(successor.state, state) &&
1207
+ search.satisfiesActionConstraints(state, successor.state);
1208
+ if (!isInModel) return false;
1209
+ const fingerprintState = getFingerprintState(successor.state);
1210
+ const index = findStateIndex(getStateHash(fingerprintState), fingerprintState);
1211
+ successors.push({ index, state: successor.state });
1212
+ return false;
1213
+ },
1214
+ spec.scope,
1215
+ );
1216
+ return successors;
1217
+ },
1218
+ };
1015
1219
  const liveness = withLivenessExitCode(() =>
1016
- createLivenessChecker(search.properties.liveness, spec.temporals, environment, {
1017
- getFingerprint: (index) =>
1018
- (tlcFingerprints[index] ??= Number(
1019
- BigInt.asIntN(32, runtime.getFingerprint(states[index])),
1020
- )),
1021
- getSuccessors: (state) => {
1022
- const successors: LiveSuccessor[] = [];
1023
- if (spec.next === undefined) return successors;
1024
- forEachSuccessor(
1025
- spec.next,
1026
- state,
1027
- environment,
1028
- (successor) => {
1029
- canonicalizeState(successor.state);
1030
- const isInModel =
1031
- search.satisfiesConstraints(successor.state, state) &&
1032
- search.satisfiesActionConstraints(state, successor.state);
1033
- if (!isInModel) return false;
1034
- const fingerprintState = getFingerprintState(successor.state);
1035
- const index = findStateIndex(getStateHash(fingerprintState), fingerprintState);
1036
- successors.push({ index, state: successor.state });
1037
- return false;
1038
- },
1039
- spec.scope,
1040
- );
1041
- return successors;
1042
- },
1043
- }),
1220
+ createLivenessChecker(search.properties.liveness, spec.temporals, environment, liveGraph),
1044
1221
  );
1045
1222
  const isCanonicalizedFirst = search.isSymmetric || liveness !== undefined;
1046
1223
 
@@ -1175,7 +1352,17 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1175
1352
  trace: TraceStep[],
1176
1353
  initialState?: Value[],
1177
1354
  failureOutDegrees?: number[],
1178
- ) => {
1355
+ ): CheckResult => {
1356
+ // TLC exits with 255 on a stack overflow while it computes next states, and prints the
1357
+ // behavior up to the state it was expanding.
1358
+ if (isStackOverflow(error)) {
1359
+ return current.isExpanding
1360
+ ? toFailure(
1361
+ setExitCode(new TlaEvaluationError(STACK_OVERFLOW), EXIT_STATUS.error),
1362
+ getStateTrace(current.index),
1363
+ )
1364
+ : toFailure(new TlaEvaluationError(STACK_OVERFLOW), trace, initialState);
1365
+ }
1179
1366
  if (!(error instanceof TlaEvaluationError)) throw error;
1180
1367
  return {
1181
1368
  ...createResult("error", undefined, {
@@ -1203,6 +1390,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1203
1390
  let hash = 0x811c9dc5;
1204
1391
  for (let index = 0; index < state.length; index++)
1205
1392
  hash = combineHash(hash, getValueHash(state[index]));
1393
+ assertFingerprintable(state);
1206
1394
  return hash & 0x3fffffff;
1207
1395
  };
1208
1396
  const isSameState = (stored: Value[], state: Value[]) => {
@@ -1265,6 +1453,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1265
1453
  isExpanding: false,
1266
1454
  candidate: undefined as Value[] | undefined,
1267
1455
  candidateLevel: 0,
1456
+ isFingerprinting: false,
1268
1457
  livenessSource: -1,
1269
1458
  };
1270
1459
  const getPath = (index: number): Value[][] =>
@@ -1351,8 +1540,10 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1351
1540
  current.candidate = successor.state;
1352
1541
  current.candidateLevel = depths[index] + 1;
1353
1542
  if (isCanonicalizedFirst) canonicalizeState(successor.state);
1543
+ current.isFingerprinting = true;
1354
1544
  const fingerprintState = getFingerprintState(successor.state);
1355
1545
  const hash = getStateHash(fingerprintState);
1546
+ current.isFingerprinting = false;
1356
1547
  const found = findStateIndex(hash, fingerprintState);
1357
1548
  const isStateInModel = search.satisfiesConstraints(successor.state, state);
1358
1549
  if (isStateInModel) search.trackStatePossible(successor.state);
@@ -1424,10 +1615,22 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1424
1615
  spec.scope,
1425
1616
  );
1426
1617
  } catch (error) {
1427
- return toFailure(error, []);
1618
+ if (!(error instanceof TlaIllegalStateError))
1619
+ return replayInitialStates(toFailure(error, []));
1620
+ // TLC prints an illegal initial state with null for each variable it leaves undefined, and
1621
+ // stops before it prints the statistics.
1622
+ const illegal = toFailure(
1623
+ error,
1624
+ [],
1625
+ error.state.map((value) => value ?? createModelValue("null")),
1626
+ );
1627
+ return {
1628
+ ...illegal,
1629
+ failure: illegal.failure && { ...illegal.failure, isWithoutStatistics: true },
1630
+ };
1428
1631
  }
1429
1632
  }
1430
- if (outcome.result) return outcome.result;
1633
+ if (outcome.result) return replayInitialStates(outcome.result);
1431
1634
 
1432
1635
  const next = spec.next;
1433
1636
  if (next === undefined) {
@@ -1483,7 +1686,10 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1483
1686
  try {
1484
1687
  outcome.result = visitSuccessor(index, successor, liveSuccessors, source, action);
1485
1688
  } catch (error) {
1486
- outcome.result = toFailure(error, getTrace(index, successor));
1689
+ // TLC reports a successor it cannot fingerprint as a failure of the state it expands.
1690
+ if (current.isFingerprinting) throw error;
1691
+ const failure = toFailure(error, getTrace(index, successor));
1692
+ outcome.result = isStackOverflow(error) ? failure : replaySuccessors(failure, index);
1487
1693
  }
1488
1694
  return outcome.result !== undefined;
1489
1695
  });
@@ -1506,9 +1712,44 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1506
1712
  trace: toTrace(steps, accepted),
1507
1713
  });
1508
1714
  } catch (error) {
1509
- return toFailure(error, getStateTrace(index), undefined, getPartialOutDegrees());
1715
+ return replayFailure(
1716
+ toFailure(toNextStateError(error), getStateTrace(index), undefined, getPartialOutDegrees()),
1717
+ (_, traced) =>
1718
+ createLivenessChecker(
1719
+ search.properties.liveness,
1720
+ spec.temporals,
1721
+ traced,
1722
+ liveGraph,
1723
+ )?.addState(index, state, liveSuccessors),
1724
+ true,
1725
+ );
1510
1726
  }
1511
1727
  };
1728
+ // TLC names the action when the next-state relation has more than one, and prints the
1729
+ // incomplete successor with null for each variable it leaves undefined.
1730
+ const reportIncompleteSuccessor = (error: TlaIncompleteStateError, index: number) => {
1731
+ nextActions.value ??= getNextActions(config, environment, specification.instanceActions);
1732
+ const actions = nextActions.value;
1733
+ const action =
1734
+ actions.length === 1 ? actions[0] : actions.find((item) => item.name === error.action);
1735
+ const variables = `variable${error.missing.length > 1 ? "s are" : " is"} not defined: ${error.missing.join(", ")}.\n`;
1736
+ runtime.generatedStates++;
1737
+ return toFailure(
1738
+ actions.length === 1
1739
+ ? error
1740
+ : new TlaEvaluationError(
1741
+ `Successor state is not completely specified by action ${error.action} of the next-state relation. The following ${variables}`,
1742
+ ),
1743
+ [
1744
+ ...getStateTrace(index),
1745
+ {
1746
+ action: error.action,
1747
+ label: action && getActionLabel(action),
1748
+ state: toRecord(error.state.map((value) => value ?? createModelValue("null"))),
1749
+ },
1750
+ ],
1751
+ );
1752
+ };
1512
1753
  // TLC names the properties and the step back into the cycle from the states it prints.
1513
1754
  const reportLasso = (checker: LivenessChecker, lasso: Lasso) => {
1514
1755
  const path = [...lasso.prefix, ...lasso.cycle];
@@ -1554,7 +1795,14 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1554
1795
  try {
1555
1796
  outcome.result = expandState(index);
1556
1797
  } catch (error) {
1557
- outcome.result = toFailure(withNextStateExitCode(error), getStateTrace(index));
1798
+ const failure =
1799
+ error instanceof TlaIncompleteStateError
1800
+ ? reportIncompleteSuccessor(error, index)
1801
+ : toFailure(toNextStateError(error), getStateTrace(index));
1802
+ outcome.result =
1803
+ error instanceof TlaIncompleteStateError || isStackOverflow(error)
1804
+ ? failure
1805
+ : replaySuccessors(failure, index);
1558
1806
  }
1559
1807
  if (outcome.result) return outcome.result;
1560
1808
  outDegrees[getOutDegreeBucket()]++;