tla-ts 0.0.3-dev.f6f300a → 0.0.3-dev.fca2ca8

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.f6f300a",
3
+ "version": "0.0.3-dev.fca2ca8",
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
@@ -70,6 +70,7 @@ import { createCounterExample } from "./tlc-ext";
70
70
  import { getFingerprintDistance, OUT_DEGREE_BUCKETS } from "./tlc-summary";
71
71
  import {
72
72
  combineHash,
73
+ createModelValue,
73
74
  formatState,
74
75
  formatValue,
75
76
  getValueHash,
@@ -834,11 +835,17 @@ export const createSearch = (
834
835
  }
835
836
  }),
836
837
  satisfiesConstraints: (state, parent) =>
837
- constraints.every(
838
- (constraint) =>
839
- isUnchangedFor(constraint, state, parent) ||
840
- holdsLikeTlc(constraint.expression, getContext(environment, state, undefined)),
841
- ),
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
+ }),
842
849
  findFailedInitialPredicate: (state) =>
843
850
  properties.initialPredicates.find(
844
851
  (predicate) =>
@@ -871,13 +878,13 @@ export const createSearch = (
871
878
  }
872
879
  }),
873
880
  satisfiesActionConstraints: (state, next) =>
874
- actionConstraints.every((constraint) =>
875
- holdsLikeTlc(
876
- constraint.expression,
877
- getContext(environment, state, next),
878
- (expression) => `${UNEXPECTED_EXCEPTION}${getExpectedBoolean(expression, environment)}`,
879
- ),
880
- ),
881
+ actionConstraints.every((constraint) => {
882
+ try {
883
+ return holdsLikeTlc(constraint.expression, getContext(environment, state, next));
884
+ } catch (error) {
885
+ throw toNextStateError(error);
886
+ }
887
+ }),
881
888
  trackStatePossible:
882
889
  statePossible.length === 0
883
890
  ? ignorePossible
@@ -1303,6 +1310,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1303
1310
  isExpanding: false,
1304
1311
  candidate: undefined as Value[] | undefined,
1305
1312
  candidateLevel: 0,
1313
+ isFingerprinting: false,
1306
1314
  livenessSource: -1,
1307
1315
  };
1308
1316
  const getPath = (index: number): Value[][] =>
@@ -1389,8 +1397,10 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1389
1397
  current.candidate = successor.state;
1390
1398
  current.candidateLevel = depths[index] + 1;
1391
1399
  if (isCanonicalizedFirst) canonicalizeState(successor.state);
1400
+ current.isFingerprinting = true;
1392
1401
  const fingerprintState = getFingerprintState(successor.state);
1393
1402
  const hash = getStateHash(fingerprintState);
1403
+ current.isFingerprinting = false;
1394
1404
  const found = findStateIndex(hash, fingerprintState);
1395
1405
  const isStateInModel = search.satisfiesConstraints(successor.state, state);
1396
1406
  if (isStateInModel) search.trackStatePossible(successor.state);
@@ -1521,6 +1531,8 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1521
1531
  try {
1522
1532
  outcome.result = visitSuccessor(index, successor, liveSuccessors, source, action);
1523
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;
1524
1536
  outcome.result = toFailure(error, getTrace(index, successor));
1525
1537
  }
1526
1538
  return outcome.result !== undefined;
@@ -1547,6 +1559,31 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1547
1559
  return toFailure(error, getStateTrace(index), undefined, getPartialOutDegrees());
1548
1560
  }
1549
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
+ };
1550
1587
  // TLC names the properties and the step back into the cycle from the states it prints.
1551
1588
  const reportLasso = (checker: LivenessChecker, lasso: Lasso) => {
1552
1589
  const path = [...lasso.prefix, ...lasso.cycle];
@@ -1592,7 +1629,10 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1592
1629
  try {
1593
1630
  outcome.result = expandState(index);
1594
1631
  } catch (error) {
1595
- outcome.result = toFailure(toNextStateError(error), getStateTrace(index));
1632
+ outcome.result =
1633
+ error instanceof TlaIncompleteStateError
1634
+ ? reportIncompleteSuccessor(error, index)
1635
+ : toFailure(toNextStateError(error), getStateTrace(index));
1596
1636
  }
1597
1637
  if (outcome.result) return outcome.result;
1598
1638
  outDegrees[getOutDegreeBucket()]++;
package/src/errors.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { EXIT_STATUS, getExitCode } from "./exit-codes";
2
+ import type { Value } from "./values";
2
3
 
3
4
  // How TLC reports a RuntimeException it did not expect, such as one raised while computing next
4
5
  // states.
@@ -65,9 +66,18 @@ export class TlaModuleError extends TlaEvaluationError {
65
66
  // TLC reports a successor state that the next-state relation leaves incomplete as an error of its
66
67
  // own, not as an exception. It keeps the name TlaEvaluationError, and index.ts doesn't export it.
67
68
  export class TlaIncompleteStateError extends TlaEvaluationError {
68
- constructor(message: string) {
69
- super(message);
69
+ state: (Value | undefined)[];
70
+ action: string | undefined;
71
+ missing: string[];
72
+
73
+ constructor(state: (Value | undefined)[], action: string | undefined, missing: string[]) {
74
+ super(
75
+ `Successor state is not completely specified by the next-state action. The following variable${missing.length > 1 ? "s are" : " is"} not defined: ${missing.join(", ")}.\n`,
76
+ );
70
77
  this.name = "TlaEvaluationError";
78
+ this.state = state;
79
+ this.action = action;
80
+ this.missing = missing;
71
81
  }
72
82
  }
73
83
 
package/src/evaluate.ts CHANGED
@@ -14,7 +14,7 @@ import {
14
14
  } from "./ast";
15
15
  import { getKindString } from "./builtins";
16
16
  import { TlaEvaluationError } from "./errors";
17
- import { EXIT_STATUS, setExitCode } from "./exit-codes";
17
+ import { EXIT_STATUS, setExitCode, setOwnExitCode } from "./exit-codes";
18
18
  import { generateEvaluator } from "./codegen";
19
19
  import type { CheckerRuntime } from "./runtime";
20
20
  import { getReadVariables } from "./dependencies";
@@ -1591,8 +1591,11 @@ export const hasDuplicateFields = (sortedFields: RecordField[]) =>
1591
1591
  sortedFields.some((field, index) => index > 0 && sortedFields[index - 1].name === field.name);
1592
1592
 
1593
1593
  export const createUnassignedError = (name: string, expression: Expression) =>
1594
- new TlaEvaluationError(
1595
- `In evaluation, the identifier ${name} is either undefined or not an operator.\n${describeRange(expression)}`,
1594
+ setOwnExitCode(
1595
+ new TlaEvaluationError(
1596
+ `In evaluation, the identifier ${name} is either undefined or not an operator.\n${describeRange(expression)}`,
1597
+ ),
1598
+ EXIT_STATUS.configParseError,
1596
1599
  );
1597
1600
 
1598
1601
  export const createPrimeOutsideActionError = (expression: Expression) =>
package/src/exit-codes.ts CHANGED
@@ -26,7 +26,19 @@ export const setExitCode = <Thrown>(error: Thrown, code: number) => {
26
26
 
27
27
  export const getExitCode = (error: Error) => exitCodes.get(error);
28
28
 
29
- // TLC exits with 255 when it fails to process or evaluate a liveness property, in any phase.
29
+ const ownExitCodes = new WeakMap<Error, number>();
30
+
31
+ // The exit status of the error code TLC gives an EvalException, which TLC uses only where it
32
+ // doesn't report the error again as a nested expression.
33
+ export const setOwnExitCode = <Thrown extends Error>(error: Thrown, code: number) => {
34
+ ownExitCodes.set(error, code);
35
+ return error;
36
+ };
37
+
38
+ export const getOwnExitCode = (error: unknown) =>
39
+ error instanceof Error ? ownExitCodes.get(error) : undefined;
40
+
41
+ // TLC exits with 255 when it fails to process or evaluate a liveness property.
30
42
  const withErrorExitCode = <Result>(run: () => Result) => {
31
43
  try {
32
44
  return run();
@@ -41,8 +53,15 @@ export const withLivenessExitCode = (
41
53
  const checker = withErrorExitCode(create);
42
54
  return (
43
55
  checker && {
44
- addInitialState: (index, state) =>
45
- withErrorExitCode(() => checker.addInitialState(index, state)),
56
+ // TLC replays the initial states to report an error, but skips the liveness check of a
57
+ // state it has already seen, so it exits with the status of the error's own code.
58
+ addInitialState: (index, state) => {
59
+ try {
60
+ checker.addInitialState(index, state);
61
+ } catch (error) {
62
+ throw setExitCode(error, getOwnExitCode(error) ?? EXIT_STATUS.error);
63
+ }
64
+ },
46
65
  addState: (index, state, successors) =>
47
66
  withErrorExitCode(() => checker.addState(index, state, successors)),
48
67
  findViolation: () => withErrorExitCode(() => checker.findViolation()),
package/src/live-check.ts CHANGED
@@ -100,7 +100,9 @@ const getNodeSlot = (table: NodeTable, state: number, tableauNode: number) => {
100
100
  }
101
101
  };
102
102
 
103
- const isWritten = (check: Check, node: number) => check.offsets[node] !== -1;
103
+ // Without a tableau a node is a state, so a successor the search hasn't expanded yet may lie past
104
+ // the per-node arrays.
105
+ const isWritten = (check: Check, node: number) => (check.offsets[node] ?? -1) !== -1;
104
106
 
105
107
  const getPending = (check: Check, node: number) => (check.pending[node] ??= []);
106
108
 
package/src/liveness.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { isLocallyResolved, type Definition, type Expression } from "./ast";
2
- import { STACK_OVERFLOW, TlaEvaluationError } from "./errors";
3
- import { EXIT_STATUS, setExitCode } from "./exit-codes";
2
+ import { STACK_OVERFLOW, TlaEvaluationError, TlaModuleError, UNEXPECTED_EXCEPTION } from "./errors";
3
+ import { EXIT_STATUS, getOwnExitCode, setExitCode } from "./exit-codes";
4
4
  import {
5
5
  describeLocation,
6
6
  describeRange,
@@ -61,6 +61,23 @@ const getConstantContext = (environment: Environment, scope: Scope | undefined):
61
61
  next: undefined,
62
62
  });
63
63
 
64
+ // TLC evaluates the constant parts of a property while it processes the spec. Its top-level handler
65
+ // prints a failure without a TLC error code of its own as an unexpected exception.
66
+ const evaluateConstant = (expression: Expression, context: Context) => {
67
+ try {
68
+ return evaluate(expression, context);
69
+ } catch (error) {
70
+ if (!(error instanceof TlaEvaluationError) || error instanceof TlaModuleError) throw error;
71
+ const code = getOwnExitCode(error);
72
+ throw code === undefined
73
+ ? setExitCode(
74
+ new TlaEvaluationError(`${UNEXPECTED_EXCEPTION}${error.message}`, error),
75
+ EXIT_STATUS.error,
76
+ )
77
+ : setExitCode(error, code);
78
+ }
79
+ };
80
+
64
81
  const createCannotHandleError = (expression: Expression) =>
65
82
  new TlaEvaluationError(
66
83
  `TLC cannot handle the temporal formula at ${describeLocation(expression)}`,
@@ -278,7 +295,7 @@ export const toLiveExpression = (
278
295
  ): LiveExpression => {
279
296
  const atomLevel = level === 0 ? getLevel(expression, scope, environment) : level;
280
297
  if (atomLevel === 0) {
281
- const value = evaluate(expression, getConstantContext(environment, scope));
298
+ const value = evaluateConstant(expression, getConstantContext(environment, scope));
282
299
  if (typeof value !== "boolean") {
283
300
  throw new TlaEvaluationError(
284
301
  `TLC expected a boolean in the temporal formula at ${describeLocation(expression)}`,
@@ -354,9 +371,45 @@ export const toLiveExpression = (
354
371
  return level > ACTION_LEVEL ? result : toAtom(expression, scope, level);
355
372
  };
356
373
 
374
+ // TLC translates the operands of a connective even when the whole formula is a state or action
375
+ // predicate, so it fails on a constant operand before it checks any state.
376
+ const convertOperands = (expression: Expression, scope: Scope | undefined) => {
377
+ switch (expression.kind) {
378
+ case "Label":
379
+ convert(expression.body, scope);
380
+ return;
381
+ case "Let":
382
+ convert(expression.body, bindLetDefinitions(expression, scope, environment));
383
+ return;
384
+ case "And":
385
+ case "Or":
386
+ for (const operand of expression.operands) convert(operand, scope);
387
+ return;
388
+ case "Apply":
389
+ if (
390
+ expression.operator === "=>" ||
391
+ (expression.operator === "~" && !isLocallyResolved(expression))
392
+ ) {
393
+ for (const operand of expression.args) convert(operand, scope);
394
+ }
395
+ return;
396
+ case "If": {
397
+ const condition = convert(expression.condition, scope);
398
+ const branches =
399
+ condition.kind === "Boolean"
400
+ ? [condition.value ? expression.consequent : expression.alternative]
401
+ : [expression.consequent, expression.alternative];
402
+ for (const branch of branches) convert(branch, scope);
403
+ }
404
+ }
405
+ };
406
+
357
407
  const convert = (expression: Expression, scope: Scope | undefined): LiveExpression => {
358
408
  const level = getLevel(expression, scope, environment);
359
- if (level <= ACTION_LEVEL) return toAtom(expression, scope, level);
409
+ if (level <= ACTION_LEVEL) {
410
+ convertOperands(expression, scope);
411
+ return toAtom(expression, scope, level);
412
+ }
360
413
  switch (expression.kind) {
361
414
  case "Label":
362
415
  return convert(expression.body, scope);
@@ -399,7 +452,10 @@ export const toLiveExpression = (
399
452
  return convertQuantifier(expression, scope);
400
453
  case "If": {
401
454
  if (getLevel(expression.condition, scope, environment) === 0) {
402
- const condition = evaluate(expression.condition, getConstantContext(environment, scope));
455
+ const condition = evaluateConstant(
456
+ expression.condition,
457
+ getConstantContext(environment, scope),
458
+ );
403
459
  if (typeof condition === "boolean") {
404
460
  return convert(condition ? expression.consequent : expression.alternative, scope);
405
461
  }
package/src/successors.ts CHANGED
@@ -89,14 +89,25 @@ const assign = (partial: State, index: number, value: Value) => {
89
89
  return copy;
90
90
  };
91
91
 
92
- const holds = (expression: Expression, context: Context, value = evaluate(expression, context)) => {
92
+ // TLC's Tool.getInitStates and Tool.getNextStates report a value where they expect a formula.
93
+ const expectFormula = (expression: Expression, value: Value, isInit: boolean) => {
93
94
  if (typeof value === "boolean") return value;
94
- try {
95
- return expectBoolean(value, `the action at ${describeLocation(expression)}`);
96
- } catch (error) {
97
- // TLC fails with an unexpected exception when the next-state relation isn't a boolean.
98
- throw context.next === undefined ? error : setExitCode(error, EXIT_STATUS.error);
95
+ throw new TlaEvaluationError(
96
+ `In computing ${isInit ? "initial" : "next"} states, TLC expected a boolean expression,\nbut instead found ${formatValue(value)}.\n${describeRange(expression)}`,
97
+ );
98
+ };
99
+
100
+ const holds = (expression: Expression, context: Context, value = evaluate(expression, context)) => {
101
+ // TLC rejects a number in the next-state relation when it splits the relation into actions.
102
+ if (context.next !== undefined && expression.kind === "Number") {
103
+ throw setExitCode(
104
+ new TlaEvaluationError(
105
+ `The next state relation is not a boolean expression.\n${expression.text ?? expression.value}`,
106
+ ),
107
+ EXIT_STATUS.error,
108
+ );
99
109
  }
110
+ return expectFormula(expression, value, context.next === undefined);
100
111
  };
101
112
 
102
113
  const isAssignmentOperator = (operator: string) =>
@@ -391,10 +402,7 @@ const compileConjunction = (
391
402
  };
392
403
 
393
404
  const holdsInInit = (expression: Expression, context: Context) =>
394
- expectBoolean(
395
- evaluate(expression, context),
396
- `the initial predicate at ${describeLocation(expression)}`,
397
- );
405
+ expectFormula(expression, evaluate(expression, context), true);
398
406
 
399
407
  const compileGuard =
400
408
  (expression: Expression): Runner =>
@@ -1058,7 +1066,9 @@ export const forEachSuccessor = (
1058
1066
  if (run.isStopped) return;
1059
1067
  if (!isComplete(partial)) {
1060
1068
  throw new TlaIncompleteStateError(
1061
- `Successor state is not completely specified by action ${action ?? "Next"}. The following variables are not assigned: ${getMissingVariables(partial, environment).join(", ")}`,
1069
+ partial,
1070
+ action,
1071
+ getMissingVariables(partial, environment).sort(),
1062
1072
  );
1063
1073
  }
1064
1074
  counter.successors++;