tla-ts 0.0.3-dev.bffbba3 → 0.0.3-dev.c949d82

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.bffbba3",
3
+ "version": "0.0.3-dev.c949d82",
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
  }
package/src/check.ts CHANGED
@@ -11,8 +11,12 @@ 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
+ TlaIncompleteStateError,
16
20
  TlaModuleError,
17
21
  UNEXPECTED_EXCEPTION,
18
22
  } from "./errors";
@@ -21,7 +25,6 @@ import {
21
25
  describeRange,
22
26
  evaluate,
23
27
  expectBoolean,
24
- formatRange,
25
28
  getDefinition,
26
29
  isConstantLevel,
27
30
  isImpure,
@@ -59,7 +62,7 @@ import {
59
62
  type StateWriter,
60
63
  } from "./state-graph";
61
64
  import { getRepresentative, getSymmetryGroup } from "./symmetry";
62
- import { getTlcStringOrder, getTlcVariableOrder } from "./tlc-order";
65
+ import { getTlcStringOrder, getTlcDeclarationOrder } from "./tlc-order";
63
66
  import { createTlcFingerprinter, getTlcFingerprint } from "./tlc-random";
64
67
  import { createCanonicalizer } from "./canonical";
65
68
  import { getPossibleCounts, type CheckerRuntime } from "./runtime";
@@ -67,6 +70,7 @@ import { createCounterExample } from "./tlc-ext";
67
70
  import { getFingerprintDistance, OUT_DEGREE_BUCKETS } from "./tlc-summary";
68
71
  import {
69
72
  combineHash,
73
+ createModelValue,
70
74
  formatState,
71
75
  formatValue,
72
76
  getValueHash,
@@ -247,7 +251,7 @@ const getConstantValue = (name: string, definition: Definition, environment: Env
247
251
  try {
248
252
  return evaluate(createIdentifier(name), getContext(environment, undefined, undefined));
249
253
  } catch (error) {
250
- if (error instanceof TlaEvaluationError) return undefined;
254
+ if (error instanceof TlaEvaluationError || isStackOverflow(error)) return undefined;
251
255
  throw error;
252
256
  }
253
257
  };
@@ -276,8 +280,11 @@ const getInvariants = (names: string[], environment: Environment) => {
276
280
  levels.params.size === 0
277
281
  ? ""
278
282
  : "\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}`,
283
+ throw setExitCode(
284
+ new TlaConfigError(
285
+ `The invariant ${name} is not a state predicate (one with no primes or temporal operators).${note}`,
286
+ ),
287
+ EXIT_STATUS.safetyEvaluationFailure,
281
288
  );
282
289
  }
283
290
  return [{ name, expression: createIdentifier(name), scope: undefined }];
@@ -375,8 +382,11 @@ const getSpecification = (config: ModelConfig, environment: Environment): Specif
375
382
  conjunct.kind === "Always" &&
376
383
  getLevel(conjunct.expression, item.scope, environment) < ACTION_LEVEL
377
384
  ) {
378
- throw new TlaConfigError(
379
- `TLC cannot handle []P in the specification ${config.specification} when P is a state predicate`,
385
+ throw setExitCode(
386
+ new TlaConfigError(
387
+ `TLC cannot handle the temporal formula ${describeRange(conjunct.expression)}`,
388
+ ),
389
+ EXIT_STATUS.error,
380
390
  );
381
391
  }
382
392
  const level = getLevel(conjunct, item.scope, environment);
@@ -787,11 +797,13 @@ export const createSearch = (
787
797
  if (view !== undefined || isFingerprintedLikeTlc) {
788
798
  return BigInt64Array.from(states, getTlcStateFingerprint);
789
799
  }
790
- const indices = getTlcOrder();
791
- const getFingerprint = createTlcFingerprinter();
792
- return BigInt64Array.from(fingerprintStates, (state) =>
793
- getFingerprint(indices.map((index) => state[index])),
800
+ const fingerprints = new BigInt64Array(fingerprintStates.length);
801
+ const fingerprint = createTlcFingerprinter(
802
+ getTlcOrder(),
803
+ new Int32Array(fingerprints.buffer),
794
804
  );
805
+ fingerprintStates.forEach(fingerprint);
806
+ return fingerprints;
795
807
  },
796
808
  getFingerprintState: (state) => {
797
809
  if (isFingerprintedLikeTlc) return [String(getTlcStateFingerprint(state))];
@@ -823,11 +835,17 @@ export const createSearch = (
823
835
  }
824
836
  }),
825
837
  satisfiesConstraints: (state, parent) =>
826
- constraints.every(
827
- (constraint) =>
828
- isUnchangedFor(constraint, state, parent) ||
829
- holdsLikeTlc(constraint.expression, getContext(environment, state, undefined)),
830
- ),
838
+ constraints.every((constraint) => {
839
+ try {
840
+ return (
841
+ isUnchangedFor(constraint, state, parent) ||
842
+ holdsLikeTlc(constraint.expression, getContext(environment, state, undefined))
843
+ );
844
+ } catch (error) {
845
+ // TLC reports a failing constraint on a successor like a failure of the next-state relation.
846
+ throw parent ? toNextStateError(error) : error;
847
+ }
848
+ }),
831
849
  findFailedInitialPredicate: (state) =>
832
850
  properties.initialPredicates.find(
833
851
  (predicate) =>
@@ -860,13 +878,13 @@ export const createSearch = (
860
878
  }
861
879
  }),
862
880
  satisfiesActionConstraints: (state, next) =>
863
- actionConstraints.every((constraint) =>
864
- holdsLikeTlc(
865
- constraint.expression,
866
- getContext(environment, state, next),
867
- (expression) => `${UNEXPECTED_EXCEPTION}${getExpectedBoolean(expression, environment)}`,
868
- ),
869
- ),
881
+ actionConstraints.every((constraint) => {
882
+ try {
883
+ return holdsLikeTlc(constraint.expression, getContext(environment, state, next));
884
+ } catch (error) {
885
+ throw toNextStateError(error);
886
+ }
887
+ }),
870
888
  trackStatePossible:
871
889
  statePossible.length === 0
872
890
  ? ignorePossible
@@ -897,6 +915,18 @@ export const createSearch = (
897
915
  const withNextStateExitCode = (error: unknown) =>
898
916
  error instanceof TlaModuleError ? setExitCode(error, error.exitCode) : error;
899
917
 
918
+ // TLC reports a failure of the next-state relation as an unexpected exception, unless a standard
919
+ // module raised it as an EvalException.
920
+ const toNextStateError = (error: unknown) =>
921
+ error instanceof TlaEvaluationError &&
922
+ !(error instanceof TlaModuleError) &&
923
+ !(error instanceof TlaIncompleteStateError)
924
+ ? setExitCode(
925
+ new TlaEvaluationError(`${UNEXPECTED_EXCEPTION}${error.message}`, error),
926
+ getErrorExitCode(error),
927
+ )
928
+ : withNextStateExitCode(error);
929
+
900
930
  const withHeadline = (error: unknown, headline: string) =>
901
931
  error instanceof TlaEvaluationError
902
932
  ? setExitCode(
@@ -908,9 +938,16 @@ const withHeadline = (error: unknown, headline: string) =>
908
938
  // TLC finishes the -dump file whether or not the search finds a violation.
909
939
  export const checkSequentially = (options: CheckOptions): CheckResult => {
910
940
  const stateWriter = options.dump && createStateWriter(options.dump, options.writeFile);
911
- const result = searchStates(options, stateWriter);
912
- stateWriter?.close();
913
- return result;
941
+ try {
942
+ return searchStates(options, stateWriter);
943
+ } catch (error) {
944
+ // TLC reports a stack overflow outside the search as a failure of its own, with exit code 255.
945
+ throw isStackOverflow(error)
946
+ ? setExitCode(new TlaEvaluationError(STACK_OVERFLOW), EXIT_STATUS.error)
947
+ : error;
948
+ } finally {
949
+ stateWriter?.close();
950
+ }
914
951
  };
915
952
 
916
953
  const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefined): CheckResult => {
@@ -983,7 +1020,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
983
1020
  });
984
1021
 
985
1022
  const search = createSearch(config, environment, () =>
986
- getTlcVariableOrder(options.source, options.loadModule),
1023
+ getTlcDeclarationOrder(options.source, options.loadModule, "variable"),
987
1024
  );
988
1025
  const assumptionViolation = findAssumptionViolation(specification.assumptions, environment);
989
1026
  if (assumptionViolation) return createResult("assumption-violation", assumptionViolation);
@@ -1173,7 +1210,17 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1173
1210
  trace: TraceStep[],
1174
1211
  initialState?: Value[],
1175
1212
  failureOutDegrees?: number[],
1176
- ) => {
1213
+ ): CheckResult => {
1214
+ // TLC exits with 255 on a stack overflow while it computes next states, and prints the
1215
+ // behavior up to the state it was expanding.
1216
+ if (isStackOverflow(error)) {
1217
+ return current.isExpanding
1218
+ ? toFailure(
1219
+ setExitCode(new TlaEvaluationError(STACK_OVERFLOW), EXIT_STATUS.error),
1220
+ getStateTrace(current.index),
1221
+ )
1222
+ : toFailure(new TlaEvaluationError(STACK_OVERFLOW), trace, initialState);
1223
+ }
1177
1224
  if (!(error instanceof TlaEvaluationError)) throw error;
1178
1225
  return {
1179
1226
  ...createResult("error", undefined, {
@@ -1263,6 +1310,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1263
1310
  isExpanding: false,
1264
1311
  candidate: undefined as Value[] | undefined,
1265
1312
  candidateLevel: 0,
1313
+ isFingerprinting: false,
1266
1314
  livenessSource: -1,
1267
1315
  };
1268
1316
  const getPath = (index: number): Value[][] =>
@@ -1349,8 +1397,10 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1349
1397
  current.candidate = successor.state;
1350
1398
  current.candidateLevel = depths[index] + 1;
1351
1399
  if (isCanonicalizedFirst) canonicalizeState(successor.state);
1400
+ current.isFingerprinting = true;
1352
1401
  const fingerprintState = getFingerprintState(successor.state);
1353
1402
  const hash = getStateHash(fingerprintState);
1403
+ current.isFingerprinting = false;
1354
1404
  const found = findStateIndex(hash, fingerprintState);
1355
1405
  const isStateInModel = search.satisfiesConstraints(successor.state, state);
1356
1406
  if (isStateInModel) search.trackStatePossible(successor.state);
@@ -1481,6 +1531,8 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1481
1531
  try {
1482
1532
  outcome.result = visitSuccessor(index, successor, liveSuccessors, source, action);
1483
1533
  } catch (error) {
1534
+ // TLC reports a successor it cannot fingerprint as a failure of the state it expands.
1535
+ if (current.isFingerprinting) throw error;
1484
1536
  outcome.result = toFailure(error, getTrace(index, successor));
1485
1537
  }
1486
1538
  return outcome.result !== undefined;
@@ -1507,6 +1559,31 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1507
1559
  return toFailure(error, getStateTrace(index), undefined, getPartialOutDegrees());
1508
1560
  }
1509
1561
  };
1562
+ // TLC names the action when the next-state relation has more than one, and prints the
1563
+ // incomplete successor with null for each variable it leaves undefined.
1564
+ const reportIncompleteSuccessor = (error: TlaIncompleteStateError, index: number) => {
1565
+ nextActions.value ??= getNextActions(config, environment, specification.instanceActions);
1566
+ const actions = nextActions.value;
1567
+ const action =
1568
+ actions.length === 1 ? actions[0] : actions.find((item) => item.name === error.action);
1569
+ const variables = `variable${error.missing.length > 1 ? "s are" : " is"} not defined: ${error.missing.join(", ")}.\n`;
1570
+ runtime.generatedStates++;
1571
+ return toFailure(
1572
+ actions.length === 1
1573
+ ? error
1574
+ : new TlaEvaluationError(
1575
+ `Successor state is not completely specified by action ${error.action} of the next-state relation. The following ${variables}`,
1576
+ ),
1577
+ [
1578
+ ...getStateTrace(index),
1579
+ {
1580
+ action: error.action,
1581
+ label: action && getActionLabel(action),
1582
+ state: toRecord(error.state.map((value) => value ?? createModelValue("null"))),
1583
+ },
1584
+ ],
1585
+ );
1586
+ };
1510
1587
  // TLC names the properties and the step back into the cycle from the states it prints.
1511
1588
  const reportLasso = (checker: LivenessChecker, lasso: Lasso) => {
1512
1589
  const path = [...lasso.prefix, ...lasso.cycle];
@@ -1552,7 +1629,10 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1552
1629
  try {
1553
1630
  outcome.result = expandState(index);
1554
1631
  } catch (error) {
1555
- outcome.result = toFailure(withNextStateExitCode(error), getStateTrace(index));
1632
+ outcome.result =
1633
+ error instanceof TlaIncompleteStateError
1634
+ ? reportIncompleteSuccessor(error, index)
1635
+ : toFailure(toNextStateError(error), getStateTrace(index));
1556
1636
  }
1557
1637
  if (outcome.result) return outcome.result;
1558
1638
  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);