tla-ts 0.0.3-dev.037ac3b → 0.0.3-dev.14337b3

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.037ac3b",
3
+ "version": "0.0.3-dev.14337b3",
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,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);
@@ -825,11 +835,17 @@ export const createSearch = (
825
835
  }
826
836
  }),
827
837
  satisfiesConstraints: (state, parent) =>
828
- constraints.every(
829
- (constraint) =>
830
- isUnchangedFor(constraint, state, parent) ||
831
- holdsLikeTlc(constraint.expression, getContext(environment, state, undefined)),
832
- ),
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
+ }),
833
849
  findFailedInitialPredicate: (state) =>
834
850
  properties.initialPredicates.find(
835
851
  (predicate) =>
@@ -862,13 +878,13 @@ export const createSearch = (
862
878
  }
863
879
  }),
864
880
  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
- ),
881
+ actionConstraints.every((constraint) => {
882
+ try {
883
+ return holdsLikeTlc(constraint.expression, getContext(environment, state, next));
884
+ } catch (error) {
885
+ throw toNextStateError(error);
886
+ }
887
+ }),
872
888
  trackStatePossible:
873
889
  statePossible.length === 0
874
890
  ? ignorePossible
@@ -899,6 +915,18 @@ export const createSearch = (
899
915
  const withNextStateExitCode = (error: unknown) =>
900
916
  error instanceof TlaModuleError ? setExitCode(error, error.exitCode) : error;
901
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
+
902
930
  const withHeadline = (error: unknown, headline: string) =>
903
931
  error instanceof TlaEvaluationError
904
932
  ? setExitCode(
@@ -910,9 +938,16 @@ const withHeadline = (error: unknown, headline: string) =>
910
938
  // TLC finishes the -dump file whether or not the search finds a violation.
911
939
  export const checkSequentially = (options: CheckOptions): CheckResult => {
912
940
  const stateWriter = options.dump && createStateWriter(options.dump, options.writeFile);
913
- const result = searchStates(options, stateWriter);
914
- stateWriter?.close();
915
- 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
+ }
916
951
  };
917
952
 
918
953
  const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefined): CheckResult => {
@@ -985,7 +1020,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
985
1020
  });
986
1021
 
987
1022
  const search = createSearch(config, environment, () =>
988
- getTlcVariableOrder(options.source, options.loadModule),
1023
+ getTlcDeclarationOrder(options.source, options.loadModule, "variable"),
989
1024
  );
990
1025
  const assumptionViolation = findAssumptionViolation(specification.assumptions, environment);
991
1026
  if (assumptionViolation) return createResult("assumption-violation", assumptionViolation);
@@ -1175,7 +1210,17 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1175
1210
  trace: TraceStep[],
1176
1211
  initialState?: Value[],
1177
1212
  failureOutDegrees?: number[],
1178
- ) => {
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
+ }
1179
1224
  if (!(error instanceof TlaEvaluationError)) throw error;
1180
1225
  return {
1181
1226
  ...createResult("error", undefined, {
@@ -1265,6 +1310,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1265
1310
  isExpanding: false,
1266
1311
  candidate: undefined as Value[] | undefined,
1267
1312
  candidateLevel: 0,
1313
+ isFingerprinting: false,
1268
1314
  livenessSource: -1,
1269
1315
  };
1270
1316
  const getPath = (index: number): Value[][] =>
@@ -1351,8 +1397,10 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1351
1397
  current.candidate = successor.state;
1352
1398
  current.candidateLevel = depths[index] + 1;
1353
1399
  if (isCanonicalizedFirst) canonicalizeState(successor.state);
1400
+ current.isFingerprinting = true;
1354
1401
  const fingerprintState = getFingerprintState(successor.state);
1355
1402
  const hash = getStateHash(fingerprintState);
1403
+ current.isFingerprinting = false;
1356
1404
  const found = findStateIndex(hash, fingerprintState);
1357
1405
  const isStateInModel = search.satisfiesConstraints(successor.state, state);
1358
1406
  if (isStateInModel) search.trackStatePossible(successor.state);
@@ -1483,6 +1531,8 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1483
1531
  try {
1484
1532
  outcome.result = visitSuccessor(index, successor, liveSuccessors, source, action);
1485
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;
1486
1536
  outcome.result = toFailure(error, getTrace(index, successor));
1487
1537
  }
1488
1538
  return outcome.result !== undefined;
@@ -1509,6 +1559,31 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1509
1559
  return toFailure(error, getStateTrace(index), undefined, getPartialOutDegrees());
1510
1560
  }
1511
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
+ };
1512
1587
  // TLC names the properties and the step back into the cycle from the states it prints.
1513
1588
  const reportLasso = (checker: LivenessChecker, lasso: Lasso) => {
1514
1589
  const path = [...lasso.prefix, ...lasso.cycle];
@@ -1554,7 +1629,10 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1554
1629
  try {
1555
1630
  outcome.result = expandState(index);
1556
1631
  } catch (error) {
1557
- outcome.result = toFailure(withNextStateExitCode(error), getStateTrace(index));
1632
+ outcome.result =
1633
+ error instanceof TlaIncompleteStateError
1634
+ ? reportIncompleteSuccessor(error, index)
1635
+ : toFailure(toNextStateError(error), getStateTrace(index));
1558
1636
  }
1559
1637
  if (outcome.result) return outcome.result;
1560
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);