tla-ts 0.0.3-dev.6979965 → 0.0.3-dev.6a30eee

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.6979965",
3
+ "version": "0.0.3-dev.6a30eee",
4
4
  "description": "A TLA+ interpreter and model checker in TypeScript, 2× faster than TLC",
5
5
  "keywords": [
6
6
  "formal verification",
package/src/check.ts CHANGED
@@ -2,7 +2,13 @@ import type { Assumption, Definition, Expression, SourceLocation } from "./ast";
2
2
  import { parseConfig, type ConfigValue, type ModelConfig } from "./config";
3
3
  import { getReadVariables } from "./dependencies";
4
4
  import { createEnvironment } from "./environment";
5
- import { getErrorExitCode, TlaConfigError, TlaEvaluationError, TlaModuleError } from "./errors";
5
+ import {
6
+ getErrorExitCode,
7
+ TlaConfigError,
8
+ TlaEvaluationError,
9
+ TlaModuleError,
10
+ UNEXPECTED_EXCEPTION,
11
+ } from "./errors";
6
12
  import { EXIT_STATUS, setExitCode, setNextStatePhase, withLivenessExitCode } from "./exit-codes";
7
13
  import {
8
14
  describeRange,
@@ -20,13 +26,11 @@ import {
20
26
  } from "./evaluate";
21
27
  import {
22
28
  createLivenessChecker,
23
- expandTemporal,
24
- getLevel,
25
29
  type Lasso,
30
+ type LivenessChecker,
26
31
  type LiveSuccessor,
27
- type ScopedExpression,
28
- type TemporalProperty,
29
- } from "./liveness";
32
+ } from "./live-check";
33
+ import { expandTemporal, getLevel, type ScopedExpression, type TemporalProperty } from "./liveness";
30
34
  import { ACTION_LEVEL, createLevelAnalyzer, TEMPORAL_LEVEL } from "./levels";
31
35
  import { prettyPrint } from "./pretty-print";
32
36
  import {
@@ -95,6 +99,8 @@ export interface TraceStep {
95
99
 
96
100
  export interface Violation {
97
101
  name: string;
102
+ // Every temporal property that a liveness counterexample violates, in the configuration's order.
103
+ properties?: string[];
98
104
  trace: TraceStep[];
99
105
  loopStart: number | undefined;
100
106
  loopLabel?: string;
@@ -828,8 +834,7 @@ export const createSearch = (
828
834
  holdsLikeTlc(
829
835
  constraint.expression,
830
836
  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)}`,
837
+ (expression) => `${UNEXPECTED_EXCEPTION}${getExpectedBoolean(expression, environment)}`,
833
838
  ),
834
839
  ),
835
840
  trackStatePossible:
@@ -962,8 +967,36 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
962
967
  const getFingerprintState = search.getFingerprintState;
963
968
  const nextActions = { value: undefined as SpecAction[] | undefined };
964
969
  const isReducing = config.view !== undefined || config.symmetry !== undefined;
970
+ const tlcFingerprints: number[] = [];
965
971
  const liveness = withLivenessExitCode(() =>
966
- createLivenessChecker(search.properties.liveness, spec.temporals, environment),
972
+ createLivenessChecker(search.properties.liveness, spec.temporals, environment, {
973
+ getFingerprint: (index) =>
974
+ (tlcFingerprints[index] ??= Number(
975
+ BigInt.asIntN(32, runtime.getFingerprint(states[index])),
976
+ )),
977
+ getSuccessors: (state) => {
978
+ const successors: LiveSuccessor[] = [];
979
+ if (spec.next === undefined) return successors;
980
+ forEachSuccessor(
981
+ spec.next,
982
+ state,
983
+ environment,
984
+ (successor) => {
985
+ canonicalizeState(successor.state);
986
+ const isInModel =
987
+ search.satisfiesConstraints(successor.state, state) &&
988
+ search.satisfiesActionConstraints(state, successor.state);
989
+ if (!isInModel) return false;
990
+ const fingerprintState = getFingerprintState(successor.state);
991
+ const index = findStateIndex(getStateHash(fingerprintState), fingerprintState);
992
+ successors.push({ index, state: successor.state });
993
+ return false;
994
+ },
995
+ spec.scope,
996
+ );
997
+ return successors;
998
+ },
999
+ }),
967
1000
  );
968
1001
  const isCanonicalizedFirst = search.isSymmetric || liveness !== undefined;
969
1002
 
@@ -1104,7 +1137,7 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1104
1137
  outDegrees: failureOutDegrees,
1105
1138
  };
1106
1139
  };
1107
- const getPathTrace = (path: number[], loopStart?: number) => {
1140
+ const getPathSteps = (path: number[], loopStart?: number) => {
1108
1141
  const steps = getPathStates(path, NEXT_RECOVERY_FAILURE);
1109
1142
  const last = steps[steps.length - 1].state;
1110
1143
  const isClosed =
@@ -1113,7 +1146,7 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1113
1146
  loopStart === path.length - 1 ||
1114
1147
  findSuccessorWithFingerprint(last, path[loopStart]) !== undefined;
1115
1148
  if (!isClosed) throw new TlaEvaluationError(NEXT_RECOVERY_FAILURE);
1116
- return toTrace(steps, path, loopStart);
1149
+ return steps;
1117
1150
  };
1118
1151
  const getStateHash = (state: Value[]) => {
1119
1152
  let hash = 0x811c9dc5;
@@ -1179,7 +1212,7 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1179
1212
  };
1180
1213
  runtime.getCurrentState = () => (current.index === -1 ? undefined : states[current.index]);
1181
1214
  runtime.setLivenessSource = (index) => {
1182
- current.livenessSource = index;
1215
+ current.livenessSource = index ?? -1;
1183
1216
  };
1184
1217
  runtime.getLevel = (state) => {
1185
1218
  const source = current.livenessSource;
@@ -1335,32 +1368,43 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1335
1368
  }
1336
1369
  try {
1337
1370
  const accepted = liveness?.addState(index, state, liveSuccessors);
1338
- current.livenessSource = -1;
1339
- if (!accepted) return undefined;
1371
+ if (!liveness || !accepted) return undefined;
1372
+ const steps = getPathSteps(accepted);
1373
+ const properties = liveness.getViolatedProperties(
1374
+ steps.map((step) => step.state),
1375
+ steps.length - 1,
1376
+ );
1340
1377
  return reportViolation("property-violation", {
1341
- name: accepted.name,
1342
- trace: getPathTrace(accepted.path),
1378
+ name: properties[0],
1379
+ properties,
1380
+ trace: toTrace(steps, accepted),
1343
1381
  });
1344
1382
  } catch (error) {
1345
1383
  return toFailure(error, getStateTrace(index), undefined, getPartialOutDegrees());
1346
1384
  }
1347
1385
  };
1348
- const reportLasso = (lasso: Lasso) => {
1386
+ // TLC names the properties and the step back into the cycle from the states it prints.
1387
+ const reportLasso = (checker: LivenessChecker, lasso: Lasso) => {
1349
1388
  const path = [...lasso.prefix, ...lasso.cycle];
1350
- const trace = getPathTrace(path, lasso.prefix.length);
1351
- const back = path[lasso.prefix.length];
1389
+ const loopStart = lasso.prefix.length;
1390
+ const steps = getPathSteps(path, loopStart);
1391
+ const trace = toTrace(steps, path, loopStart);
1392
+ const properties = checker.getViolatedProperties(
1393
+ steps.map((step) => step.state),
1394
+ loopStart,
1395
+ );
1396
+ const back = path[loopStart];
1352
1397
  const last = path[path.length - 1];
1398
+ const lastState = steps[steps.length - 1].state;
1353
1399
  const loopLabel =
1354
- back === last ? undefined : withoutOutput(() => getLabel(last, states[last], states[back]));
1400
+ back === last ? undefined : withoutOutput(() => getLabel(last, lastState, states[back]));
1355
1401
  return reportViolation(
1356
1402
  "liveness-violation",
1357
- { name: lasso.name, trace, loopStart: lasso.prefix.length, loopLabel },
1403
+ { name: properties[0], properties, trace, loopStart, loopLabel },
1358
1404
  () =>
1359
1405
  back === last
1360
1406
  ? trace[trace.length - 1].action
1361
- : getTraceSuccessors(states[last]).find((successor) =>
1362
- isSameState(successor.state, states[back]),
1363
- )?.action,
1407
+ : findSuccessorWithFingerprint(lastState, back)?.action,
1364
1408
  );
1365
1409
  };
1366
1410
  const isPeriodic = liveness !== undefined && options.livenessCheck !== "final";
@@ -1373,7 +1417,6 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1373
1417
  if (!isGrown || periodic.time > (now - startedAt) * LIVENESS_RATIO) return undefined;
1374
1418
  periodic.size = expanded;
1375
1419
  const lasso = liveness?.findViolation();
1376
- current.livenessSource = -1;
1377
1420
  periodic.time += performance.now() - now;
1378
1421
  return lasso;
1379
1422
  };
@@ -1393,15 +1436,14 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1393
1436
  expansion.newStates = 0;
1394
1437
  if (isPeriodic && performance.now() >= periodic.at) {
1395
1438
  const lasso = findPeriodicViolation(index + 1);
1396
- if (lasso) return reportLasso(lasso);
1439
+ if (liveness && lasso) return reportLasso(liveness, lasso);
1397
1440
  }
1398
1441
  }
1399
1442
 
1400
1443
  current.index = -1;
1401
1444
  current.candidate = undefined;
1402
1445
  const lasso = liveness?.findViolation();
1403
- current.livenessSource = -1;
1404
- if (lasso) return reportLasso(lasso);
1446
+ if (liveness && lasso) return reportLasso(liveness, lasso);
1405
1447
 
1406
1448
  const postconditionViolation = search.findPostconditionViolation();
1407
1449
  if (postconditionViolation) {
package/src/errors.ts CHANGED
@@ -1,5 +1,10 @@
1
1
  import { EXIT_STATUS, getExitCode, setModuleExitCode } from "./exit-codes";
2
2
 
3
+ // How TLC reports a RuntimeException it did not expect, such as one raised while computing next
4
+ // states.
5
+ export const UNEXPECTED_EXCEPTION =
6
+ "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: ";
7
+
3
8
  export class TlaError extends Error {
4
9
  constructor(message: string, cause?: unknown) {
5
10
  super(message, { cause });
package/src/evaluate.ts CHANGED
@@ -889,14 +889,29 @@ const IMPURE_BUILTINS = new Set([
889
889
  export const isImpureBuiltin = (name: string, environment: Environment) =>
890
890
  IMPURE_BUILTINS.has(name) || environment.builtins.get(name)?.isStateLevel === true;
891
891
 
892
- const impureDefinitions = new WeakMap<Definition, boolean>();
892
+ interface Impurity {
893
+ builtins: Set<string>;
894
+ definitions: WeakMap<Definition, boolean>;
895
+ }
896
+
897
+ const ANY_EFFECT: Impurity = { builtins: IMPURE_BUILTINS, definitions: new WeakMap() };
898
+
899
+ // An Assert that held holds again, so evaluating it twice looks the same as evaluating it once.
900
+ const REPEATED_EFFECT: Impurity = {
901
+ builtins: new Set([...IMPURE_BUILTINS].filter((name) => name !== "Assert")),
902
+ definitions: new WeakMap(),
903
+ };
893
904
 
894
905
  const isEvaluatedOnce = (definition: Definition, environment: Environment) =>
895
906
  definition.kind === "Operator" &&
896
907
  definition.params.length === 0 &&
897
908
  isConstantLevel(definition, environment);
898
909
 
899
- const callsImpureBuiltin = (expression: Expression, environment: Environment): boolean => {
910
+ const callsImpureBuiltin = (
911
+ expression: Expression,
912
+ environment: Environment,
913
+ impurity: Impurity,
914
+ ): boolean => {
900
915
  const name =
901
916
  expression.kind === "Identifier"
902
917
  ? expression.name
@@ -905,29 +920,35 @@ const callsImpureBuiltin = (expression: Expression, environment: Environment): b
905
920
  : undefined;
906
921
  if (name !== undefined && !isLocallyResolved(expression)) {
907
922
  const definition = getDefinition(name, environment);
908
- if (!definition && isImpureBuiltin(name, environment)) return true;
923
+ const isImpureCall =
924
+ impurity.builtins.has(name) || environment.builtins.get(name)?.isStateLevel === true;
925
+ if (!definition && isImpureCall) return true;
909
926
  if (
910
927
  definition &&
911
928
  !isEvaluatedOnce(definition, environment) &&
912
- isImpureDefinition(definition, environment)
929
+ isImpureDefinition(definition, environment, impurity)
913
930
  ) {
914
931
  return true;
915
932
  }
916
933
  }
917
- return getChildren(expression).some((child) => callsImpureBuiltin(child, environment));
934
+ return getChildren(expression).some((child) => callsImpureBuiltin(child, environment, impurity));
918
935
  };
919
936
 
920
937
  // TLC evaluates a constant definition without parameters once, so only other definitions pass
921
938
  // on the side effects and random choices of the builtins they call.
922
- const isImpureDefinition = (definition: Definition, environment: Environment): boolean => {
923
- const cached = impureDefinitions.get(definition);
939
+ const isImpureDefinition = (
940
+ definition: Definition,
941
+ environment: Environment,
942
+ impurity = ANY_EFFECT,
943
+ ): boolean => {
944
+ const cached = impurity.definitions.get(definition);
924
945
  if (cached !== undefined) return cached;
925
- impureDefinitions.set(definition, false);
946
+ impurity.definitions.set(definition, false);
926
947
  const isImpure =
927
- callsImpureBuiltin(definition.body, environment) ||
948
+ callsImpureBuiltin(definition.body, environment, impurity) ||
928
949
  (definition.kind === "Function" &&
929
- definition.bounds.some((bound) => callsImpureBuiltin(bound.set, environment)));
930
- impureDefinitions.set(definition, isImpure);
950
+ definition.bounds.some((bound) => callsImpureBuiltin(bound.set, environment, impurity)));
951
+ impurity.definitions.set(definition, isImpure);
931
952
  return isImpure;
932
953
  };
933
954
 
@@ -941,6 +962,12 @@ export const isImpure = (environment: Environment) =>
941
962
  isImpureDefinition(definition, environment),
942
963
  );
943
964
 
965
+ // Whether evaluating a definition again can show, such as by printing twice.
966
+ export const hasRepeatedEffects = (environment: Environment) =>
967
+ [...environment.definitions.values()].some((definition) =>
968
+ isImpureDefinition(definition, environment, REPEATED_EFFECT),
969
+ );
970
+
944
971
  const closedConstants = new WeakMap<Expression, boolean>();
945
972
 
946
973
  export const isClosedConstant = (expression: Expression, environment: Environment): boolean => {
@@ -1757,7 +1784,9 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
1757
1784
  if (expectBoolean(arm.condition(context), "a CASE guard")) return arm.body(context);
1758
1785
  }
1759
1786
  if (other) return other(context);
1760
- throw new TlaEvaluationError(`No CASE guard is true at ${describeLocation(expression)}`);
1787
+ throw new TlaEvaluationError(
1788
+ `Attempted to evaluate a CASE with no conditions true.\n${describeRange(expression)}`,
1789
+ );
1761
1790
  };
1762
1791
  }
1763
1792
  case "Let": {
package/src/exit-codes.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { LivenessChecker } from "./liveness";
1
+ import type { LivenessChecker } from "./live-check";
2
2
 
3
3
  // TLC's exit statuses, from EC.ExitStatus.
4
4
  export const EXIT_STATUS = {
@@ -39,37 +39,27 @@ export const setModuleExitCode = (error: Error, code: number) => {
39
39
  export const getExitCode = (error: Error) => exitCodes.get(error) ?? moduleExitCodes.get(error);
40
40
 
41
41
  // TLC exits with 255 when it fails to process or evaluate a liveness property, in any phase.
42
- export const withLivenessExitCode = (
43
- create: () => LivenessChecker | undefined,
44
- ): LivenessChecker | undefined => {
42
+ const withErrorExitCode = <Result>(run: () => Result) => {
45
43
  try {
46
- const checker = create();
47
- return (
48
- checker && {
49
- addInitialState: (index, state) => {
50
- try {
51
- checker.addInitialState(index, state);
52
- } catch (error) {
53
- throw setExitCode(error, EXIT_STATUS.error);
54
- }
55
- },
56
- addState: (index, state, successors) => {
57
- try {
58
- return checker.addState(index, state, successors);
59
- } catch (error) {
60
- throw setExitCode(error, EXIT_STATUS.error);
61
- }
62
- },
63
- findViolation: () => {
64
- try {
65
- return checker.findViolation();
66
- } catch (error) {
67
- throw setExitCode(error, EXIT_STATUS.error);
68
- }
69
- },
70
- }
71
- );
44
+ return run();
72
45
  } catch (error) {
73
46
  throw setExitCode(error, EXIT_STATUS.error);
74
47
  }
75
48
  };
49
+
50
+ export const withLivenessExitCode = (
51
+ create: () => LivenessChecker | undefined,
52
+ ): LivenessChecker | undefined => {
53
+ const checker = withErrorExitCode(create);
54
+ return (
55
+ checker && {
56
+ addInitialState: (index, state) =>
57
+ withErrorExitCode(() => checker.addInitialState(index, state)),
58
+ addState: (index, state, successors) =>
59
+ withErrorExitCode(() => checker.addState(index, state, successors)),
60
+ findViolation: () => withErrorExitCode(() => checker.findViolation()),
61
+ getViolatedProperties: (path, cycleStart) =>
62
+ withErrorExitCode(() => checker.getViolatedProperties(path, cycleStart)),
63
+ }
64
+ );
65
+ };
package/src/lexer.ts CHANGED
@@ -345,6 +345,8 @@ export const tokenize = (source: string): Token[] => {
345
345
  if (!headerMatch)
346
346
  throw new TlaSyntaxError("Expected a module header such as ---- MODULE Name ----");
347
347
  const tokens: Token[] = [];
348
+ // Each name is one string object, so looking a name up in a scope compares pointers.
349
+ const names = new Map<string, string>();
348
350
  const prefixLines = source.slice(0, headerMatch.index).split("\n");
349
351
  const cursor = {
350
352
  index: headerMatch.index,
@@ -481,7 +483,9 @@ export const tokenize = (source: string): Token[] => {
481
483
  pushToken("Keyword", word.slice(0, 3), 3);
482
484
  continue;
483
485
  }
484
- pushToken(KEYWORDS.has(word) ? "Keyword" : "Identifier", word, word.length);
486
+ const name = names.get(word) ?? word;
487
+ names.set(name, name);
488
+ pushToken(KEYWORDS.has(word) ? "Keyword" : "Identifier", name, word.length);
485
489
  continue;
486
490
  }
487
491
  const stepLength = matchStep(source, cursor.index);