tla-ts 0.0.3-dev.b1578d0 → 0.0.3-dev.bb5b28b

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tla-ts",
3
- "version": "0.0.3-dev.b1578d0",
3
+ "version": "0.0.3-dev.bb5b28b",
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
@@ -47,6 +47,8 @@ export interface ApplyExpression {
47
47
  // The number of args each part of a name like F(x)!l(y) takes, when a part before the last takes
48
48
  // some.
49
49
  argumentCounts?: number[];
50
+ // The range of the parenthesized arguments of a named operator, where SANY reports their count.
51
+ argumentsRange?: SourceRange;
50
52
  location: SourceLocation;
51
53
  resolution?: LocalResolution;
52
54
  }
@@ -192,6 +194,7 @@ export interface FunctionSetExpression {
192
194
  export interface RecordField {
193
195
  name: string;
194
196
  value: Expression;
197
+ location: SourceLocation;
195
198
  }
196
199
 
197
200
  export interface RecordExpression {
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,
@@ -59,14 +63,16 @@ import {
59
63
  type StateWriter,
60
64
  } from "./state-graph";
61
65
  import { getRepresentative, getSymmetryGroup } from "./symmetry";
62
- import { getTlcStringOrder, getTlcVariableOrder } from "./tlc-order";
66
+ import { getTlcStringOrder, getTlcDeclarationOrder } from "./tlc-order";
63
67
  import { createTlcFingerprinter, getTlcFingerprint } from "./tlc-random";
64
68
  import { createCanonicalizer } from "./canonical";
65
69
  import { getPossibleCounts, type CheckerRuntime } from "./runtime";
66
70
  import { createCounterExample } from "./tlc-ext";
71
+ import { getFingerprintTrace, valueSources } from "./value-sources";
67
72
  import { getFingerprintDistance, OUT_DEGREE_BUCKETS } from "./tlc-summary";
68
73
  import {
69
74
  combineHash,
75
+ createModelValue,
70
76
  formatState,
71
77
  formatValue,
72
78
  getValueHash,
@@ -136,6 +142,22 @@ export interface EvaluationFailure {
136
142
  trace: TraceStep[];
137
143
  initialState: Record<string, Value> | undefined;
138
144
  exitCode: number;
145
+ replay?: Replay;
146
+ isWithoutStatistics?: boolean;
147
+ }
148
+
149
+ // TLC replays a failed step to print the expressions it was evaluating when the replay failed.
150
+ export interface Replay {
151
+ output: string[];
152
+ callStack: string[] | undefined;
153
+ fingerprint?: Fingerprint;
154
+ }
155
+
156
+ // TLC reports an error from a method of a value that has a source as one it was unable to
157
+ // fingerprint. With an empty stack, it lists the sources of the values instead.
158
+ export interface Fingerprint {
159
+ sources: string[];
160
+ reason: string;
139
161
  }
140
162
 
141
163
  export interface CheckResult {
@@ -247,7 +269,7 @@ const getConstantValue = (name: string, definition: Definition, environment: Env
247
269
  try {
248
270
  return evaluate(createIdentifier(name), getContext(environment, undefined, undefined));
249
271
  } catch (error) {
250
- if (error instanceof TlaEvaluationError) return undefined;
272
+ if (error instanceof TlaEvaluationError || isStackOverflow(error)) return undefined;
251
273
  throw error;
252
274
  }
253
275
  };
@@ -276,8 +298,11 @@ const getInvariants = (names: string[], environment: Environment) => {
276
298
  levels.params.size === 0
277
299
  ? ""
278
300
  : "\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}`,
301
+ throw setExitCode(
302
+ new TlaConfigError(
303
+ `The invariant ${name} is not a state predicate (one with no primes or temporal operators).${note}`,
304
+ ),
305
+ EXIT_STATUS.safetyEvaluationFailure,
281
306
  );
282
307
  }
283
308
  return [{ name, expression: createIdentifier(name), scope: undefined }];
@@ -375,8 +400,11 @@ const getSpecification = (config: ModelConfig, environment: Environment): Specif
375
400
  conjunct.kind === "Always" &&
376
401
  getLevel(conjunct.expression, item.scope, environment) < ACTION_LEVEL
377
402
  ) {
378
- throw new TlaConfigError(
379
- `TLC cannot handle []P in the specification ${config.specification} when P is a state predicate`,
403
+ throw setExitCode(
404
+ new TlaConfigError(
405
+ `TLC cannot handle the temporal formula ${describeRange(conjunct.expression)}`,
406
+ ),
407
+ EXIT_STATUS.error,
380
408
  );
381
409
  }
382
410
  const level = getLevel(conjunct, item.scope, environment);
@@ -446,12 +474,12 @@ const getProperties = (config: ModelConfig, environment: Environment): Propertie
446
474
  config.properties.forEach((name) => {
447
475
  const definition = getConfigPredicate("property", name, environment);
448
476
  if (!definition) return;
449
- expandTemporal(definition.body, undefined, environment, true).forEach((item) => {
477
+ expandTemporal(definition.body, undefined, environment, true, name).forEach((item) => {
450
478
  const conjunct = item.expression;
451
479
  if (isConstantTrue(item, environment, "property")) return;
452
480
  if (conjunct.kind === "Always" && conjunct.expression.kind === "BoxAction") {
453
481
  properties.actionProperties.push({
454
- name,
482
+ name: item.name,
455
483
  box: conjunct.expression,
456
484
  action: conjunct.expression.action,
457
485
  subscript: conjunct.expression.subscript,
@@ -463,12 +491,22 @@ const getProperties = (config: ModelConfig, environment: Environment): Propertie
463
491
  conjunct.kind === "Always" &&
464
492
  getLevel(conjunct.expression, item.scope, environment) <= 1
465
493
  ) {
466
- properties.invariants.push({ name, expression: conjunct.expression, scope: item.scope });
494
+ // TLC names the invariant []P after P when P is an operator name.
495
+ const expression = conjunct.expression;
496
+ properties.invariants.push({
497
+ name: expression.kind === "Identifier" ? expression.name : item.name,
498
+ expression,
499
+ scope: item.scope,
500
+ });
467
501
  return;
468
502
  }
469
503
  const level = getLevel(conjunct, item.scope, environment);
470
504
  if (level < ACTION_LEVEL) {
471
- properties.initialPredicates.push({ name, expression: conjunct, scope: item.scope });
505
+ properties.initialPredicates.push({
506
+ name: item.name,
507
+ expression: conjunct,
508
+ scope: item.scope,
509
+ });
472
510
  return;
473
511
  }
474
512
  if (level === ACTION_LEVEL) {
@@ -528,7 +566,9 @@ const getMembership = (
528
566
  const getStateChecks = (named: NamedExpression[], environment: Environment): StateCheck[] =>
529
567
  named.flatMap((item) =>
530
568
  getConjuncts(item.expression, environment).map((expression) => {
531
- const variables = getReadVariables(expression, environment);
569
+ // A LET or an argument in the scope can read variables the expression doesn't name.
570
+ const variables =
571
+ item.scope === undefined ? getReadVariables(expression, environment) : undefined;
532
572
  return {
533
573
  name: item.name,
534
574
  expression,
@@ -775,11 +815,13 @@ export const createSearch = (
775
815
  if (view !== undefined || isFingerprintedLikeTlc) {
776
816
  return BigInt64Array.from(states, getTlcStateFingerprint);
777
817
  }
778
- const indices = getTlcOrder();
779
- const getFingerprint = createTlcFingerprinter();
780
- return BigInt64Array.from(fingerprintStates, (state) =>
781
- getFingerprint(indices.map((index) => state[index])),
818
+ const fingerprints = new BigInt64Array(fingerprintStates.length);
819
+ const fingerprint = createTlcFingerprinter(
820
+ getTlcOrder(),
821
+ new Int32Array(fingerprints.buffer),
782
822
  );
823
+ fingerprintStates.forEach(fingerprint);
824
+ return fingerprints;
783
825
  },
784
826
  getFingerprintState: (state) => {
785
827
  if (isFingerprintedLikeTlc) return [String(getTlcStateFingerprint(state))];
@@ -811,11 +853,17 @@ export const createSearch = (
811
853
  }
812
854
  }),
813
855
  satisfiesConstraints: (state, parent) =>
814
- constraints.every(
815
- (constraint) =>
816
- isUnchangedFor(constraint, state, parent) ||
817
- holdsLikeTlc(constraint.expression, getContext(environment, state, undefined)),
818
- ),
856
+ constraints.every((constraint) => {
857
+ try {
858
+ return (
859
+ isUnchangedFor(constraint, state, parent) ||
860
+ holdsLikeTlc(constraint.expression, getContext(environment, state, undefined))
861
+ );
862
+ } catch (error) {
863
+ // TLC reports a failing constraint on a successor like a failure of the next-state relation.
864
+ throw parent ? toNextStateError(error) : error;
865
+ }
866
+ }),
819
867
  findFailedInitialPredicate: (state) =>
820
868
  properties.initialPredicates.find(
821
869
  (predicate) =>
@@ -848,13 +896,13 @@ export const createSearch = (
848
896
  }
849
897
  }),
850
898
  satisfiesActionConstraints: (state, next) =>
851
- actionConstraints.every((constraint) =>
852
- holdsLikeTlc(
853
- constraint.expression,
854
- getContext(environment, state, next),
855
- (expression) => `${UNEXPECTED_EXCEPTION}${getExpectedBoolean(expression, environment)}`,
856
- ),
857
- ),
899
+ actionConstraints.every((constraint) => {
900
+ try {
901
+ return holdsLikeTlc(constraint.expression, getContext(environment, state, next));
902
+ } catch (error) {
903
+ throw toNextStateError(error);
904
+ }
905
+ }),
858
906
  trackStatePossible:
859
907
  statePossible.length === 0
860
908
  ? ignorePossible
@@ -885,6 +933,59 @@ export const createSearch = (
885
933
  const withNextStateExitCode = (error: unknown) =>
886
934
  error instanceof TlaModuleError ? setExitCode(error, error.exitCode) : error;
887
935
 
936
+ // TLC reports a failure of the next-state relation as an unexpected exception, unless a standard
937
+ // module raised it as an EvalException.
938
+ const toNextStateError = (error: unknown) =>
939
+ error instanceof TlaEvaluationError &&
940
+ !(error instanceof TlaModuleError) &&
941
+ !(error instanceof TlaIncompleteStateError)
942
+ ? setExitCode(
943
+ new TlaEvaluationError(`${UNEXPECTED_EXCEPTION}${error.message}`, error),
944
+ getErrorExitCode(error),
945
+ )
946
+ : withNextStateExitCode(error);
947
+
948
+ const isRepeated = (frame: string, index: number, frames: string[]) =>
949
+ index > 0 && frames[index - 1] === frame;
950
+
951
+ // FingerprintException#getTrace numbers the sources from the outermost value and lists the innermost
952
+ // first.
953
+ const getSourceTrace = (sources: Expression[]) =>
954
+ sources
955
+ .flatMap((source) => (source.location.range ? [formatRange(source.location.range)] : []))
956
+ .filter((source, index, all) => !isRepeated(source, index, all))
957
+ .map((source, index) => `${index}) ${source}`)
958
+ .reverse();
959
+
960
+ // TLC keeps the stack only when an evaluation fails, and prints each expression on it once, however
961
+ // many times in a row it pushed it.
962
+ const getReplayedCallStack = (
963
+ replay: () => void,
964
+ trace: Expression[],
965
+ ): Pick<Replay, "callStack" | "fingerprint"> => {
966
+ try {
967
+ replay();
968
+ return { callStack: undefined };
969
+ } catch (error) {
970
+ if (!(error instanceof TlaEvaluationError)) return { callStack: [] };
971
+ const callStack = trace
972
+ .flatMap((expression) => {
973
+ const range = expression.location.range;
974
+ return range
975
+ ? [
976
+ `Line ${range.start.line}, column ${range.start.column} to line ${range.end.line}, column ${range.end.column} in ${range.module}`,
977
+ ]
978
+ : [];
979
+ })
980
+ .filter((frame, index, frames) => !isRepeated(frame, index, frames));
981
+ const sources = getFingerprintTrace(error);
982
+ return {
983
+ callStack,
984
+ fingerprint: sources && { sources: getSourceTrace(sources), reason: error.message },
985
+ };
986
+ }
987
+ };
988
+
888
989
  const withHeadline = (error: unknown, headline: string) =>
889
990
  error instanceof TlaEvaluationError
890
991
  ? setExitCode(
@@ -896,9 +997,16 @@ const withHeadline = (error: unknown, headline: string) =>
896
997
  // TLC finishes the -dump file whether or not the search finds a violation.
897
998
  export const checkSequentially = (options: CheckOptions): CheckResult => {
898
999
  const stateWriter = options.dump && createStateWriter(options.dump, options.writeFile);
899
- const result = searchStates(options, stateWriter);
900
- stateWriter?.close();
901
- return result;
1000
+ try {
1001
+ return searchStates(options, stateWriter);
1002
+ } catch (error) {
1003
+ // TLC reports a stack overflow outside the search as a failure of its own, with exit code 255.
1004
+ throw isStackOverflow(error)
1005
+ ? setExitCode(new TlaEvaluationError(STACK_OVERFLOW), EXIT_STATUS.error)
1006
+ : error;
1007
+ } finally {
1008
+ stateWriter?.close();
1009
+ }
902
1010
  };
903
1011
 
904
1012
  const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefined): CheckResult => {
@@ -906,9 +1014,10 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
906
1014
  const onPrint = options.onPrint ?? console.log;
907
1015
  // TLC prints again while it rebuilds a trace, between the states it prints. Printing those lines
908
1016
  // before the trace would misplace them, so rebuilding a trace prints nothing.
909
- const output = { isMuted: false };
1017
+ const output = { isMuted: false, replayed: undefined as string[] | undefined };
910
1018
  const print = (text: string) => {
911
- if (!output.isMuted) onPrint(text);
1019
+ if (output.replayed) output.replayed.push(text);
1020
+ else if (!output.isMuted) onPrint(text);
912
1021
  };
913
1022
  const withoutOutput = <Result>(rebuild: () => Result) => {
914
1023
  output.isMuted = true;
@@ -970,9 +1079,9 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
970
1079
  ),
971
1080
  });
972
1081
 
973
- const search = createSearch(config, environment, () =>
974
- getTlcVariableOrder(options.source, options.loadModule),
975
- );
1082
+ const getVariableOrder = () =>
1083
+ getTlcDeclarationOrder(options.source, options.loadModule, "variable");
1084
+ const search = createSearch(config, environment, getVariableOrder);
976
1085
  const assumptionViolation = findAssumptionViolation(specification.assumptions, environment);
977
1086
  if (assumptionViolation) return createResult("assumption-violation", assumptionViolation);
978
1087
  if (!search) return createSuccess();
@@ -996,6 +1105,82 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
996
1105
  const spec = search.spec;
997
1106
  const getFingerprintState = search.getFingerprintState;
998
1107
  const nextActions = { value: undefined as SpecAction[] | undefined };
1108
+ const replayFailure = (
1109
+ result: CheckResult,
1110
+ replay: (tracedSearch: Search, traced: Environment) => void,
1111
+ ): CheckResult => {
1112
+ if (!result.failure) return result;
1113
+ const trace: Expression[] = [];
1114
+ const traced: Environment = { ...environment, evaluators: new WeakMap(), trace };
1115
+ const tracedSearch = createSearch(config, traced, getVariableOrder);
1116
+ if (!tracedSearch) return result;
1117
+ const replayed: string[] = [];
1118
+ output.replayed = replayed;
1119
+ valueSources.current = new WeakMap();
1120
+ const replayedStack = getReplayedCallStack(() => replay(tracedSearch, traced), trace);
1121
+ valueSources.current = undefined;
1122
+ output.replayed = undefined;
1123
+ return {
1124
+ ...result,
1125
+ failure: { ...result.failure, replay: { output: replayed, ...replayedStack } },
1126
+ };
1127
+ };
1128
+ // TLC fingerprints a state outside CallStackTool, so a failure leaves the stack empty.
1129
+ const fingerprintReplayed = (state: Value[], traced: Environment) => {
1130
+ try {
1131
+ getStateHash(getFingerprintState(state));
1132
+ } catch (error) {
1133
+ if (traced.trace) traced.trace.length = 0;
1134
+ throw error;
1135
+ }
1136
+ };
1137
+ // TLC checks every initial state again, as when it first generated them.
1138
+ const replayInitialStates = (result: CheckResult) =>
1139
+ replayFailure(result, (tracedSearch, traced) => {
1140
+ if (spec.init === undefined) return;
1141
+ forEachInitialState(
1142
+ spec.init,
1143
+ traced,
1144
+ (state) => {
1145
+ if (tracedSearch.satisfiesConstraints(state)) fingerprintReplayed(state, traced);
1146
+ return (
1147
+ tracedSearch.findViolatedInvariant(state) !== undefined ||
1148
+ tracedSearch.findFailedInitialPredicate(state) !== undefined
1149
+ );
1150
+ },
1151
+ spec.scope,
1152
+ );
1153
+ });
1154
+ // TLC rebuilds the behavior up to the state it expanded before it replays the step.
1155
+ const rebuildBehavior = (index: number): void => {
1156
+ const parent = parents[index];
1157
+ if (parent === -1) {
1158
+ getSpecInitialStates();
1159
+ return;
1160
+ }
1161
+ rebuildBehavior(parent);
1162
+ getLabel(parent, states[parent], states[index]);
1163
+ };
1164
+ // TLC generates the successors of each action before it checks them. It checks the invariants
1165
+ // only of a successor outside the model, since it has seen the others.
1166
+ const replaySuccessors = (result: CheckResult, index: number) =>
1167
+ replayFailure(result, (tracedSearch, traced) => {
1168
+ rebuildBehavior(index);
1169
+ const state = states[index];
1170
+ nextActions.value ??= getNextActions(config, environment, specification.instanceActions);
1171
+ nextActions.value.find((action) =>
1172
+ getSuccessors(action.expression, state, traced, action.scope).some((successor) => {
1173
+ const isInModel =
1174
+ tracedSearch.satisfiesConstraints(successor.state) &&
1175
+ tracedSearch.satisfiesActionConstraints(state, successor.state);
1176
+ if (isInModel) fingerprintReplayed(successor.state, traced);
1177
+ return (
1178
+ (!isInModel && tracedSearch.findViolatedInvariant(successor.state) !== undefined) ||
1179
+ tracedSearch.findViolatedActionProperty(state, successor.state) !== undefined
1180
+ );
1181
+ }),
1182
+ );
1183
+ });
999
1184
  const isReducing = config.view !== undefined || config.symmetry !== undefined;
1000
1185
  const tlcFingerprints: number[] = [];
1001
1186
  const liveness = withLivenessExitCode(() =>
@@ -1035,7 +1220,9 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1035
1220
  const parents: number[] = [];
1036
1221
  const actions: (string | undefined)[] = [];
1037
1222
  const depths: number[] = [];
1038
- const buckets = new Map<number, number | number[]>();
1223
+ // A Map holds at most 2^24 entries, so an open-addressing table keeps each seen state's hash
1224
+ // and its index plus one side by side, probed by the hash.
1225
+ const seen = { slots: new Int32Array(1 << 17), size: 0, shift: 16 };
1039
1226
  const canonicalizeState = createCanonicalizer();
1040
1227
 
1041
1228
  const toRecord = (state: Value[]): Record<string, Value> =>
@@ -1159,7 +1346,17 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1159
1346
  trace: TraceStep[],
1160
1347
  initialState?: Value[],
1161
1348
  failureOutDegrees?: number[],
1162
- ) => {
1349
+ ): CheckResult => {
1350
+ // TLC exits with 255 on a stack overflow while it computes next states, and prints the
1351
+ // behavior up to the state it was expanding.
1352
+ if (isStackOverflow(error)) {
1353
+ return current.isExpanding
1354
+ ? toFailure(
1355
+ setExitCode(new TlaEvaluationError(STACK_OVERFLOW), EXIT_STATUS.error),
1356
+ getStateTrace(current.index),
1357
+ )
1358
+ : toFailure(new TlaEvaluationError(STACK_OVERFLOW), trace, initialState);
1359
+ }
1163
1360
  if (!(error instanceof TlaEvaluationError)) throw error;
1164
1361
  return {
1165
1362
  ...createResult("error", undefined, {
@@ -1195,19 +1392,35 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1195
1392
  }
1196
1393
  return true;
1197
1394
  };
1395
+ const getSlot = (hash: number) => (Math.imul(hash, 0x9e3779b1) >>> seen.shift) << 1;
1198
1396
  const findStateIndex = (hash: number, state: Value[]) => {
1199
- const bucket = buckets.get(hash);
1200
- if (bucket === undefined) return -1;
1201
- if (typeof bucket === "number") {
1202
- return isSameState(fingerprintStates[bucket], state) ? bucket : -1;
1397
+ const mask = seen.slots.length - 1;
1398
+ for (let slot = getSlot(hash); ; slot = (slot + 2) & mask) {
1399
+ const entry = seen.slots[slot + 1];
1400
+ if (entry === 0) return -1;
1401
+ if (seen.slots[slot] === hash && isSameState(fingerprintStates[entry - 1], state)) {
1402
+ return entry - 1;
1403
+ }
1203
1404
  }
1204
- return bucket.find((index) => isSameState(fingerprintStates[index], state)) ?? -1;
1405
+ };
1406
+ const insertSeen = (hash: number, entry: number) => {
1407
+ const mask = seen.slots.length - 1;
1408
+ let slot = getSlot(hash);
1409
+ while (seen.slots[slot + 1] !== 0) slot = (slot + 2) & mask;
1410
+ seen.slots[slot] = hash;
1411
+ seen.slots[slot + 1] = entry;
1205
1412
  };
1206
1413
  const markSeen = (hash: number, index: number) => {
1207
- const bucket = buckets.get(hash);
1208
- if (bucket === undefined) buckets.set(hash, index);
1209
- else if (typeof bucket === "number") buckets.set(hash, [bucket, index]);
1210
- else bucket.push(index);
1414
+ seen.size++;
1415
+ if (seen.size * 4 > seen.slots.length) {
1416
+ const slots = seen.slots;
1417
+ seen.slots = new Int32Array(slots.length * 2);
1418
+ seen.shift--;
1419
+ for (let slot = 0; slot < slots.length; slot += 2) {
1420
+ if (slots[slot + 1] !== 0) insertSeen(slots[slot], slots[slot + 1]);
1421
+ }
1422
+ }
1423
+ insertSeen(hash, index + 1);
1211
1424
  };
1212
1425
  const countDistinctState = (depth: number) => {
1213
1426
  runtime.distinctStates = states.length + 1;
@@ -1233,6 +1446,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1233
1446
  isExpanding: false,
1234
1447
  candidate: undefined as Value[] | undefined,
1235
1448
  candidateLevel: 0,
1449
+ isFingerprinting: false,
1236
1450
  livenessSource: -1,
1237
1451
  };
1238
1452
  const getPath = (index: number): Value[][] =>
@@ -1319,8 +1533,10 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1319
1533
  current.candidate = successor.state;
1320
1534
  current.candidateLevel = depths[index] + 1;
1321
1535
  if (isCanonicalizedFirst) canonicalizeState(successor.state);
1536
+ current.isFingerprinting = true;
1322
1537
  const fingerprintState = getFingerprintState(successor.state);
1323
1538
  const hash = getStateHash(fingerprintState);
1539
+ current.isFingerprinting = false;
1324
1540
  const found = findStateIndex(hash, fingerprintState);
1325
1541
  const isStateInModel = search.satisfiesConstraints(successor.state, state);
1326
1542
  if (isStateInModel) search.trackStatePossible(successor.state);
@@ -1392,10 +1608,22 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1392
1608
  spec.scope,
1393
1609
  );
1394
1610
  } catch (error) {
1395
- return toFailure(error, []);
1611
+ if (!(error instanceof TlaIllegalStateError))
1612
+ return replayInitialStates(toFailure(error, []));
1613
+ // TLC prints an illegal initial state with null for each variable it leaves undefined, and
1614
+ // stops before it prints the statistics.
1615
+ const illegal = toFailure(
1616
+ error,
1617
+ [],
1618
+ error.state.map((value) => value ?? createModelValue("null")),
1619
+ );
1620
+ return {
1621
+ ...illegal,
1622
+ failure: illegal.failure && { ...illegal.failure, isWithoutStatistics: true },
1623
+ };
1396
1624
  }
1397
1625
  }
1398
- if (outcome.result) return outcome.result;
1626
+ if (outcome.result) return replayInitialStates(outcome.result);
1399
1627
 
1400
1628
  const next = spec.next;
1401
1629
  if (next === undefined) {
@@ -1451,7 +1679,10 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1451
1679
  try {
1452
1680
  outcome.result = visitSuccessor(index, successor, liveSuccessors, source, action);
1453
1681
  } catch (error) {
1454
- outcome.result = toFailure(error, getTrace(index, successor));
1682
+ // TLC reports a successor it cannot fingerprint as a failure of the state it expands.
1683
+ if (current.isFingerprinting) throw error;
1684
+ const failure = toFailure(error, getTrace(index, successor));
1685
+ outcome.result = isStackOverflow(error) ? failure : replaySuccessors(failure, index);
1455
1686
  }
1456
1687
  return outcome.result !== undefined;
1457
1688
  });
@@ -1477,6 +1708,31 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1477
1708
  return toFailure(error, getStateTrace(index), undefined, getPartialOutDegrees());
1478
1709
  }
1479
1710
  };
1711
+ // TLC names the action when the next-state relation has more than one, and prints the
1712
+ // incomplete successor with null for each variable it leaves undefined.
1713
+ const reportIncompleteSuccessor = (error: TlaIncompleteStateError, index: number) => {
1714
+ nextActions.value ??= getNextActions(config, environment, specification.instanceActions);
1715
+ const actions = nextActions.value;
1716
+ const action =
1717
+ actions.length === 1 ? actions[0] : actions.find((item) => item.name === error.action);
1718
+ const variables = `variable${error.missing.length > 1 ? "s are" : " is"} not defined: ${error.missing.join(", ")}.\n`;
1719
+ runtime.generatedStates++;
1720
+ return toFailure(
1721
+ actions.length === 1
1722
+ ? error
1723
+ : new TlaEvaluationError(
1724
+ `Successor state is not completely specified by action ${error.action} of the next-state relation. The following ${variables}`,
1725
+ ),
1726
+ [
1727
+ ...getStateTrace(index),
1728
+ {
1729
+ action: error.action,
1730
+ label: action && getActionLabel(action),
1731
+ state: toRecord(error.state.map((value) => value ?? createModelValue("null"))),
1732
+ },
1733
+ ],
1734
+ );
1735
+ };
1480
1736
  // TLC names the properties and the step back into the cycle from the states it prints.
1481
1737
  const reportLasso = (checker: LivenessChecker, lasso: Lasso) => {
1482
1738
  const path = [...lasso.prefix, ...lasso.cycle];
@@ -1522,7 +1778,14 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1522
1778
  try {
1523
1779
  outcome.result = expandState(index);
1524
1780
  } catch (error) {
1525
- outcome.result = toFailure(withNextStateExitCode(error), getStateTrace(index));
1781
+ const failure =
1782
+ error instanceof TlaIncompleteStateError
1783
+ ? reportIncompleteSuccessor(error, index)
1784
+ : toFailure(toNextStateError(error), getStateTrace(index));
1785
+ outcome.result =
1786
+ error instanceof TlaIncompleteStateError || isStackOverflow(error)
1787
+ ? failure
1788
+ : replaySuccessors(failure, index);
1526
1789
  }
1527
1790
  if (outcome.result) return outcome.result;
1528
1791
  outDegrees[getOutDegreeBucket()]++;
package/src/codegen.ts CHANGED
@@ -10,6 +10,8 @@ import {
10
10
  getSubsetOperator,
11
11
  getEvaluator,
12
12
  getFieldError,
13
+ getNonFunctionError,
14
+ getNonRecordError,
13
15
  isClosedConstant,
14
16
  isTlcInteger,
15
17
  isValueArgument,
@@ -250,12 +252,13 @@ const generateExpression = (generator: Generator, expression: Expression, frame:
250
252
  case "FunctionApplication": {
251
253
  keepLazy(expression.function);
252
254
  const functionCode = generate(expression.function);
255
+ const describeNonFunction = addReference(generator, getNonFunctionError(expression));
253
256
  if (expression.args.length === 1)
254
- return `apply(${functionCode}, ${generate(expression.args[0])})`;
255
- return `apply(${functionCode}, tuple([${expression.args.map((arg) => generate(arg)).join(", ")}]))`;
257
+ return `apply(${functionCode}, ${generate(expression.args[0])}, undefined, ${describeNonFunction})`;
258
+ return `apply(${functionCode}, tuple([${expression.args.map((arg) => generate(arg)).join(", ")}]), undefined, ${describeNonFunction})`;
256
259
  }
257
260
  case "FieldAccess":
258
- return `apply(${generate(expression.record)}, ${JSON.stringify(expression.field)}, ${addReference(generator, getFieldError(expression))})`;
261
+ return `apply(${generate(expression.record)}, ${JSON.stringify(expression.field)}, ${addReference(generator, getFieldError(expression))}, ${addReference(generator, getNonRecordError(expression))})`;
259
262
  case "Record": {
260
263
  const fields = getSortedFields(expression.fields);
261
264
  if (hasDuplicateFields(fields)) return generateDelegate(generator, expression, frame);