tla-ts 0.0.3-dev.d9ff6f2 → 0.0.3-dev.e5b05b9

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.d9ff6f2",
3
+ "version": "0.0.3-dev.e5b05b9",
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
  }
@@ -49,6 +52,9 @@ export interface ApplyExpression {
49
52
  argumentCounts?: number[];
50
53
  // The range of the parenthesized arguments of a named operator, where SANY reports their count.
51
54
  argumentsRange?: SourceRange;
55
+ selectorRanges?: SourceRange[];
56
+ // The range of the arguments of each part of a name like F(x)!l(y), for a part that takes some.
57
+ argumentRanges?: (SourceRange | undefined)[];
52
58
  location: SourceLocation;
53
59
  resolution?: LocalResolution;
54
60
  }
@@ -62,6 +68,7 @@ export interface OperatorReferenceExpression {
62
68
  export interface LambdaExpression {
63
69
  kind: "Lambda";
64
70
  params: string[];
71
+ paramRanges?: SourceRange[];
65
72
  body: Expression;
66
73
  location: SourceLocation;
67
74
  }
@@ -119,7 +126,10 @@ export interface LetExpression {
119
126
  location: SourceLocation;
120
127
  }
121
128
 
122
- export type BoundPattern = { kind: "Name"; name: string } | { kind: "Tuple"; names: string[] };
129
+ // ranges holds the range of each name the pattern binds.
130
+ export type BoundPattern =
131
+ | { kind: "Name"; name: string; ranges?: SourceRange[] }
132
+ | { kind: "Tuple"; names: string[]; ranges?: SourceRange[] };
123
133
 
124
134
  export interface Bound {
125
135
  pattern: BoundPattern;
@@ -137,6 +147,7 @@ export interface UnboundedQuantifierExpression {
137
147
  kind: "UnboundedQuantifier";
138
148
  quantifier: "Forall" | "Exists";
139
149
  names: string[];
150
+ nameRanges?: SourceRange[];
140
151
  isTemporal?: boolean;
141
152
  body: Expression;
142
153
  location: SourceLocation;
@@ -269,6 +280,7 @@ export interface LabelExpression {
269
280
  kind: "Label";
270
281
  name: string;
271
282
  params: string[];
283
+ paramRanges?: SourceRange[];
272
284
  body: Expression;
273
285
  location: SourceLocation;
274
286
  }
@@ -283,6 +295,8 @@ export type Selector =
283
295
  export interface SubexpressionExpression {
284
296
  kind: "Subexpression";
285
297
  selectors: Selector[];
298
+ selectorRanges?: SourceRange[];
299
+ argumentRanges?: (SourceRange | undefined)[];
286
300
  location: SourceLocation;
287
301
  }
288
302
 
@@ -366,6 +380,7 @@ export interface Assumption {
366
380
 
367
381
  export interface InstanceSubstitution {
368
382
  name: string;
383
+ nameRange: SourceRange;
369
384
  expression: Expression;
370
385
  }
371
386
 
@@ -387,6 +402,7 @@ export interface NewSymbol {
387
402
  arity: number;
388
403
  level: "Constant" | "Variable" | "State" | "Action" | "Temporal";
389
404
  set: Expression | undefined;
405
+ nameRange?: SourceRange;
390
406
  location: SourceLocation;
391
407
  }
392
408
 
@@ -438,19 +454,27 @@ export type StepBody =
438
454
  | Instance
439
455
  | DefineStep
440
456
  | { kind: "Have"; expression: Expression }
441
- | { kind: "Take"; names: string[]; bounds: Bound[] }
457
+ | { kind: "Take"; names: string[]; nameRanges?: SourceRange[]; bounds: Bound[] }
442
458
  | { kind: "Witness"; expressions: Expression[] }
443
- | { kind: "Pick"; names: string[]; bounds: Bound[]; body: Expression }
459
+ | {
460
+ kind: "Pick";
461
+ names: string[];
462
+ nameRanges?: SourceRange[];
463
+ bounds: Bound[];
464
+ body: Expression;
465
+ }
444
466
  | { kind: "Case"; expression: Expression }
445
467
  | { kind: "Assert"; isSuffices: boolean; statement: Expression | AssumeProve }
446
468
  | { kind: "Qed" };
447
469
 
448
- // head is the range of the step number and its statement, without the proof.
470
+ // head is the range of the step number and its statement, without the proof, and statement is the
471
+ // range of the statement alone.
449
472
  export interface ProofStep {
450
473
  name: string | undefined;
451
474
  token: string;
452
475
  body: StepBody;
453
476
  head: SourceRange;
477
+ statement: SourceRange;
454
478
  proof: Proof | undefined;
455
479
  location: SourceLocation;
456
480
  }
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
@@ -16,6 +16,7 @@ import {
16
16
  STACK_OVERFLOW,
17
17
  TlaConfigError,
18
18
  TlaEvaluationError,
19
+ TlaIllegalStateError,
19
20
  TlaIncompleteStateError,
20
21
  TlaModuleError,
21
22
  UNEXPECTED_EXCEPTION,
@@ -35,6 +36,7 @@ import {
35
36
  import {
36
37
  createLivenessChecker,
37
38
  type Lasso,
39
+ type LiveGraph,
38
40
  type LivenessChecker,
39
41
  type LiveSuccessor,
40
42
  } from "./live-check";
@@ -67,8 +69,10 @@ import { createTlcFingerprinter, getTlcFingerprint } from "./tlc-random";
67
69
  import { createCanonicalizer } from "./canonical";
68
70
  import { getPossibleCounts, type CheckerRuntime } from "./runtime";
69
71
  import { createCounterExample } from "./tlc-ext";
72
+ import { getFingerprintTrace, valueSources } from "./value-sources";
70
73
  import { getFingerprintDistance, OUT_DEGREE_BUCKETS } from "./tlc-summary";
71
74
  import {
75
+ assertFingerprintable,
72
76
  combineHash,
73
77
  createModelValue,
74
78
  formatState,
@@ -141,12 +145,24 @@ export interface EvaluationFailure {
141
145
  initialState: Record<string, Value> | undefined;
142
146
  exitCode: number;
143
147
  replay?: Replay;
148
+ isWithoutStatistics?: boolean;
144
149
  }
145
150
 
146
151
  // TLC replays a failed step to print the expressions it was evaluating when the replay failed.
147
152
  export interface Replay {
148
153
  output: string[];
149
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;
150
166
  }
151
167
 
152
168
  export interface CheckResult {
@@ -922,8 +938,8 @@ export const createSearch = (
922
938
  const withNextStateExitCode = (error: unknown) =>
923
939
  error instanceof TlaModuleError ? setExitCode(error, error.exitCode) : error;
924
940
 
925
- // TLC reports a failure of the next-state relation as an unexpected exception, unless a standard
926
- // module raised it as an EvalException.
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.
927
943
  const toNextStateError = (error: unknown) =>
928
944
  error instanceof TlaEvaluationError &&
929
945
  !(error instanceof TlaModuleError) &&
@@ -934,15 +950,30 @@ const toNextStateError = (error: unknown) =>
934
950
  )
935
951
  : withNextStateExitCode(error);
936
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
+
937
965
  // TLC keeps the stack only when an evaluation fails, and prints each expression on it once, however
938
966
  // many times in a row it pushed it.
939
- const getReplayedCallStack = (replay: () => void, trace: Expression[]) => {
967
+ const getReplayedCallStack = (
968
+ replay: () => void,
969
+ trace: Expression[],
970
+ ): Pick<Replay, "callStack" | "fingerprint"> => {
940
971
  try {
941
972
  replay();
942
- return undefined;
973
+ return { callStack: undefined };
943
974
  } catch (error) {
944
- if (!(error instanceof TlaEvaluationError)) return [];
945
- return trace
975
+ if (!(error instanceof TlaEvaluationError)) return { callStack: [] };
976
+ const callStack = trace
946
977
  .flatMap((expression) => {
947
978
  const range = expression.location.range;
948
979
  return range
@@ -951,7 +982,12 @@ const getReplayedCallStack = (replay: () => void, trace: Expression[]) => {
951
982
  ]
952
983
  : [];
953
984
  })
954
- .filter((frame, index, frames) => index === 0 || frames[index - 1] !== frame);
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
+ };
955
991
  }
956
992
  };
957
993
 
@@ -1077,6 +1113,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1077
1113
  const replayFailure = (
1078
1114
  result: CheckResult,
1079
1115
  replay: (tracedSearch: Search, traced: Environment) => void,
1116
+ isBeforeError = false,
1080
1117
  ): CheckResult => {
1081
1118
  if (!result.failure) return result;
1082
1119
  const trace: Expression[] = [];
@@ -1085,9 +1122,24 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1085
1122
  if (!tracedSearch) return result;
1086
1123
  const replayed: string[] = [];
1087
1124
  output.replayed = replayed;
1088
- const callStack = getReplayedCallStack(() => replay(tracedSearch, traced), trace);
1125
+ valueSources.current = new WeakMap();
1126
+ const replayedStack = getReplayedCallStack(() => replay(tracedSearch, traced), trace);
1127
+ valueSources.current = undefined;
1089
1128
  output.replayed = undefined;
1090
- return { ...result, failure: { ...result.failure, replay: { output: replayed, callStack } } };
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
+ }
1091
1143
  };
1092
1144
  // TLC checks every initial state again, as when it first generated them.
1093
1145
  const replayInitialStates = (result: CheckResult) =>
@@ -1097,7 +1149,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1097
1149
  spec.init,
1098
1150
  traced,
1099
1151
  (state) => {
1100
- tracedSearch.satisfiesConstraints(state);
1152
+ if (tracedSearch.satisfiesConstraints(state)) fingerprintReplayed(state, traced);
1101
1153
  return (
1102
1154
  tracedSearch.findViolatedInvariant(state) !== undefined ||
1103
1155
  tracedSearch.findFailedInitialPredicate(state) !== undefined
@@ -1128,6 +1180,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1128
1180
  const isInModel =
1129
1181
  tracedSearch.satisfiesConstraints(successor.state) &&
1130
1182
  tracedSearch.satisfiesActionConstraints(state, successor.state);
1183
+ if (isInModel) fingerprintReplayed(successor.state, traced);
1131
1184
  return (
1132
1185
  (!isInModel && tracedSearch.findViolatedInvariant(successor.state) !== undefined) ||
1133
1186
  tracedSearch.findViolatedActionProperty(state, successor.state) !== undefined
@@ -1137,35 +1190,34 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1137
1190
  });
1138
1191
  const isReducing = config.view !== undefined || config.symmetry !== undefined;
1139
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
+ };
1140
1219
  const liveness = withLivenessExitCode(() =>
1141
- createLivenessChecker(search.properties.liveness, spec.temporals, environment, {
1142
- getFingerprint: (index) =>
1143
- (tlcFingerprints[index] ??= Number(
1144
- BigInt.asIntN(32, runtime.getFingerprint(states[index])),
1145
- )),
1146
- getSuccessors: (state) => {
1147
- const successors: LiveSuccessor[] = [];
1148
- if (spec.next === undefined) return successors;
1149
- forEachSuccessor(
1150
- spec.next,
1151
- state,
1152
- environment,
1153
- (successor) => {
1154
- canonicalizeState(successor.state);
1155
- const isInModel =
1156
- search.satisfiesConstraints(successor.state, state) &&
1157
- search.satisfiesActionConstraints(state, successor.state);
1158
- if (!isInModel) return false;
1159
- const fingerprintState = getFingerprintState(successor.state);
1160
- const index = findStateIndex(getStateHash(fingerprintState), fingerprintState);
1161
- successors.push({ index, state: successor.state });
1162
- return false;
1163
- },
1164
- spec.scope,
1165
- );
1166
- return successors;
1167
- },
1168
- }),
1220
+ createLivenessChecker(search.properties.liveness, spec.temporals, environment, liveGraph),
1169
1221
  );
1170
1222
  const isCanonicalizedFirst = search.isSymmetric || liveness !== undefined;
1171
1223
 
@@ -1338,6 +1390,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1338
1390
  let hash = 0x811c9dc5;
1339
1391
  for (let index = 0; index < state.length; index++)
1340
1392
  hash = combineHash(hash, getValueHash(state[index]));
1393
+ assertFingerprintable(state);
1341
1394
  return hash & 0x3fffffff;
1342
1395
  };
1343
1396
  const isSameState = (stored: Value[], state: Value[]) => {
@@ -1562,7 +1615,19 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1562
1615
  spec.scope,
1563
1616
  );
1564
1617
  } catch (error) {
1565
- return replayInitialStates(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
+ };
1566
1631
  }
1567
1632
  }
1568
1633
  if (outcome.result) return replayInitialStates(outcome.result);
@@ -1647,7 +1712,17 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1647
1712
  trace: toTrace(steps, accepted),
1648
1713
  });
1649
1714
  } catch (error) {
1650
- 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
+ );
1651
1726
  }
1652
1727
  };
1653
1728
  // TLC names the action when the next-state relation has more than one, and prints the