tla-ts 0.0.3-dev.bcfa494 → 0.0.3-dev.bfd303f

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.bcfa494",
3
+ "version": "0.0.3-dev.bfd303f",
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
@@ -11,6 +11,8 @@ import { getReadVariables } from "./dependencies";
11
11
  import { createEnvironment } from "./environment";
12
12
  import {
13
13
  getErrorExitCode,
14
+ isStackOverflow,
15
+ STACK_OVERFLOW,
14
16
  TlaConfigError,
15
17
  TlaEvaluationError,
16
18
  TlaIncompleteStateError,
@@ -68,6 +70,7 @@ import { createCounterExample } from "./tlc-ext";
68
70
  import { getFingerprintDistance, OUT_DEGREE_BUCKETS } from "./tlc-summary";
69
71
  import {
70
72
  combineHash,
73
+ createModelValue,
71
74
  formatState,
72
75
  formatValue,
73
76
  getValueHash,
@@ -248,7 +251,7 @@ const getConstantValue = (name: string, definition: Definition, environment: Env
248
251
  try {
249
252
  return evaluate(createIdentifier(name), getContext(environment, undefined, undefined));
250
253
  } catch (error) {
251
- if (error instanceof TlaEvaluationError) return undefined;
254
+ if (error instanceof TlaEvaluationError || isStackOverflow(error)) return undefined;
252
255
  throw error;
253
256
  }
254
257
  };
@@ -277,8 +280,11 @@ const getInvariants = (names: string[], environment: Environment) => {
277
280
  levels.params.size === 0
278
281
  ? ""
279
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.";
280
- throw new TlaConfigError(
281
- `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,
282
288
  );
283
289
  }
284
290
  return [{ name, expression: createIdentifier(name), scope: undefined }];
@@ -376,8 +382,11 @@ const getSpecification = (config: ModelConfig, environment: Environment): Specif
376
382
  conjunct.kind === "Always" &&
377
383
  getLevel(conjunct.expression, item.scope, environment) < ACTION_LEVEL
378
384
  ) {
379
- throw new TlaConfigError(
380
- `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,
381
390
  );
382
391
  }
383
392
  const level = getLevel(conjunct, item.scope, environment);
@@ -923,9 +932,16 @@ const withHeadline = (error: unknown, headline: string) =>
923
932
  // TLC finishes the -dump file whether or not the search finds a violation.
924
933
  export const checkSequentially = (options: CheckOptions): CheckResult => {
925
934
  const stateWriter = options.dump && createStateWriter(options.dump, options.writeFile);
926
- const result = searchStates(options, stateWriter);
927
- stateWriter?.close();
928
- return result;
935
+ try {
936
+ return searchStates(options, stateWriter);
937
+ } catch (error) {
938
+ // TLC reports a stack overflow outside the search as a failure of its own, with exit code 255.
939
+ throw isStackOverflow(error)
940
+ ? setExitCode(new TlaEvaluationError(STACK_OVERFLOW), EXIT_STATUS.error)
941
+ : error;
942
+ } finally {
943
+ stateWriter?.close();
944
+ }
929
945
  };
930
946
 
931
947
  const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefined): CheckResult => {
@@ -1188,7 +1204,17 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1188
1204
  trace: TraceStep[],
1189
1205
  initialState?: Value[],
1190
1206
  failureOutDegrees?: number[],
1191
- ) => {
1207
+ ): CheckResult => {
1208
+ // TLC exits with 255 on a stack overflow while it computes next states, and prints the
1209
+ // behavior up to the state it was expanding.
1210
+ if (isStackOverflow(error)) {
1211
+ return current.isExpanding
1212
+ ? toFailure(
1213
+ setExitCode(new TlaEvaluationError(STACK_OVERFLOW), EXIT_STATUS.error),
1214
+ getStateTrace(current.index),
1215
+ )
1216
+ : toFailure(new TlaEvaluationError(STACK_OVERFLOW), trace, initialState);
1217
+ }
1192
1218
  if (!(error instanceof TlaEvaluationError)) throw error;
1193
1219
  return {
1194
1220
  ...createResult("error", undefined, {
@@ -1522,6 +1548,31 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1522
1548
  return toFailure(error, getStateTrace(index), undefined, getPartialOutDegrees());
1523
1549
  }
1524
1550
  };
1551
+ // TLC names the action when the next-state relation has more than one, and prints the
1552
+ // incomplete successor with null for each variable it leaves undefined.
1553
+ const reportIncompleteSuccessor = (error: TlaIncompleteStateError, index: number) => {
1554
+ nextActions.value ??= getNextActions(config, environment, specification.instanceActions);
1555
+ const actions = nextActions.value;
1556
+ const action =
1557
+ actions.length === 1 ? actions[0] : actions.find((item) => item.name === error.action);
1558
+ const variables = `variable${error.missing.length > 1 ? "s are" : " is"} not defined: ${error.missing.join(", ")}.\n`;
1559
+ runtime.generatedStates++;
1560
+ return toFailure(
1561
+ actions.length === 1
1562
+ ? error
1563
+ : new TlaEvaluationError(
1564
+ `Successor state is not completely specified by action ${error.action} of the next-state relation. The following ${variables}`,
1565
+ ),
1566
+ [
1567
+ ...getStateTrace(index),
1568
+ {
1569
+ action: error.action,
1570
+ label: action && getActionLabel(action),
1571
+ state: toRecord(error.state.map((value) => value ?? createModelValue("null"))),
1572
+ },
1573
+ ],
1574
+ );
1575
+ };
1525
1576
  // TLC names the properties and the step back into the cycle from the states it prints.
1526
1577
  const reportLasso = (checker: LivenessChecker, lasso: Lasso) => {
1527
1578
  const path = [...lasso.prefix, ...lasso.cycle];
@@ -1567,7 +1618,10 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1567
1618
  try {
1568
1619
  outcome.result = expandState(index);
1569
1620
  } catch (error) {
1570
- outcome.result = toFailure(toNextStateError(error), getStateTrace(index));
1621
+ outcome.result =
1622
+ error instanceof TlaIncompleteStateError
1623
+ ? reportIncompleteSuccessor(error, index)
1624
+ : toFailure(toNextStateError(error), getStateTrace(index));
1571
1625
  }
1572
1626
  if (outcome.result) return outcome.result;
1573
1627
  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);
@@ -12,7 +12,7 @@ import {
12
12
  import { BUNDLED_MODULES } from "./bundled-modules";
13
13
  import type { ConfigValue, ModelConfig } from "./config";
14
14
  import type { FileSystem } from "./json";
15
- import { TlaConfigError, TlaEvaluationError, TlaSyntaxError } from "./errors";
15
+ import { TlaConfigError, TlaEvaluationError, TlaModuleError, TlaSyntaxError } from "./errors";
16
16
  import { EXIT_STATUS, setExitCode } from "./exit-codes";
17
17
  import {
18
18
  createBigNumberError,
@@ -963,26 +963,28 @@ export const createEnvironment = (
963
963
  ]),
964
964
  getDefinition: (name) => getDefinition(name, environment),
965
965
  });
966
- const isEvaluable = (body: Expression) => {
966
+ const getEvaluationError = (body: Expression) => {
967
967
  try {
968
968
  evaluate(body, { environment, scope: undefined, state: undefined, next: undefined });
969
- return true;
969
+ return undefined;
970
970
  } catch (error) {
971
- if (error instanceof TlaEvaluationError) return false;
971
+ if (error instanceof TlaEvaluationError) return error;
972
972
  throw error;
973
973
  }
974
974
  };
975
975
  substitutions.forEach((target, name) => {
976
976
  const definition = definitions.get(target);
977
- if (
977
+ const error =
978
978
  declaredConstants.includes(name) &&
979
979
  definition?.kind === "Operator" &&
980
980
  definition.params.length === 0 &&
981
- analyzer.analyzeDefinition(definition, new Map()).level > 0 &&
982
- !isEvaluable(definition.body)
983
- ) {
981
+ analyzer.analyzeDefinition(definition, new Map()).level > 0
982
+ ? getEvaluationError(definition.body)
983
+ : undefined;
984
+ // TLC adds the reason unless a standard module's Java code failed.
985
+ if (error) {
984
986
  throw new TlaConfigError(
985
- `The configuration file substitutes constant ${name} with non-constant ${target}`,
987
+ `The configuration file substitutes constant ${name} with non-constant ${target}${error instanceof TlaModuleError ? "" : ` - specifically: ${error.message}`}`,
986
988
  );
987
989
  }
988
990
  });
package/src/errors.ts CHANGED
@@ -1,10 +1,18 @@
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.
5
6
  export const UNEXPECTED_EXCEPTION =
6
7
  "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
8
 
9
+ // How TLC reports a Java StackOverflowError, which V8 raises as this RangeError.
10
+ export const STACK_OVERFLOW =
11
+ "This was a Java StackOverflowError. It was probably the result\nof an incorrect recursive function definition that caused TLC to enter\nan infinite loop when trying to compute the function or its application\nto an element in its putative domain.";
12
+
13
+ export const isStackOverflow = (error: unknown) =>
14
+ error instanceof RangeError && error.message === "Maximum call stack size exceeded";
15
+
8
16
  export class TlaError extends Error {
9
17
  constructor(message: string, cause?: unknown) {
10
18
  super(message, { cause });
@@ -58,9 +66,18 @@ export class TlaModuleError extends TlaEvaluationError {
58
66
  // TLC reports a successor state that the next-state relation leaves incomplete as an error of its
59
67
  // own, not as an exception. It keeps the name TlaEvaluationError, and index.ts doesn't export it.
60
68
  export class TlaIncompleteStateError extends TlaEvaluationError {
61
- constructor(message: string) {
62
- 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
+ );
63
77
  this.name = "TlaEvaluationError";
78
+ this.state = state;
79
+ this.action = action;
80
+ this.missing = missing;
64
81
  }
65
82
  }
66
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";
@@ -30,6 +30,7 @@ import {
30
30
  createSortedSet,
31
31
  createWrittenRecord,
32
32
  createTuple,
33
+ describeMissingField,
33
34
  formatValue,
34
35
  getDomain,
35
36
  getFunctionDomain,
@@ -38,6 +39,7 @@ import {
38
39
  getValueHash,
39
40
  isFunctionValue,
40
41
  isOverriddenSet,
42
+ isRecordValue,
41
43
  isSameValue,
42
44
  markLambdaFunction,
43
45
  isReducible,
@@ -47,6 +49,7 @@ import {
47
49
  toFiniteSet,
48
50
  updateFunction,
49
51
  valuesEqual,
52
+ type FunctionValue,
50
53
  type LazyFunctionSource,
51
54
  type LazyFunctionValue,
52
55
  type Value,
@@ -182,8 +185,17 @@ export const getConjunctError = (
182
185
  };
183
186
 
184
187
  export const getFieldError =
185
- (expression: Expression & { kind: "FieldAccess" }) => (record: Value) =>
186
- `Attempted to select nonexistent field "${expression.field}" from the record\n${formatValue(record)}\n${describeRange(expression)}`;
188
+ (expression: Expression & { kind: "FieldAccess" }) => (record: FunctionValue) =>
189
+ isRecordValue(record)
190
+ ? `Attempted to select nonexistent field "${expression.field}" from the record\n${formatValue(record)}\n${describeRange(expression)}`
191
+ : describeMissingField(record, expression.field);
192
+
193
+ export const getNonFunctionError = (expression: Expression) => (value: Value) =>
194
+ `A non-function (${getKindString(value)}) was applied as a function.\n${describeRange(expression)}`;
195
+
196
+ export const getNonRecordError =
197
+ (expression: Expression & { kind: "FieldAccess" }) => (value: Value) =>
198
+ `Attempted to select field "${expression.field}" from a non-record value ${formatValue(value)}\n${describeRange(expression)}`;
187
199
 
188
200
  export const getDomainOperator = (expression: Expression) => (value: Value) => {
189
201
  if (!isFunctionValue(value)) {
@@ -1325,6 +1337,11 @@ const compileApply = (
1325
1337
  if (definition?.kind === "Function") {
1326
1338
  throw new TlaEvaluationError(`${expression.operator} is a function; apply it with brackets`);
1327
1339
  }
1340
+ if (expression.operator === "\\cdot") {
1341
+ throw new TlaEvaluationError(
1342
+ "The current version of TLC does not support action composition. An incomplete implementation can be enabled via the tlc2.tool.impl.Tool.cdot=true java property.",
1343
+ );
1344
+ }
1328
1345
  throw new TlaEvaluationError(
1329
1346
  `Unknown operator ${expression.operator} at ${describeLocation(expression)}`,
1330
1347
  );
@@ -1574,7 +1591,12 @@ export const hasDuplicateFields = (sortedFields: RecordField[]) =>
1574
1591
  sortedFields.some((field, index) => index > 0 && sortedFields[index - 1].name === field.name);
1575
1592
 
1576
1593
  export const createUnassignedError = (name: string, expression: Expression) =>
1577
- new TlaEvaluationError(`The variable ${name} is not assigned at ${describeLocation(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,
1599
+ );
1578
1600
 
1579
1601
  export const createPrimeOutsideActionError = (expression: Expression) =>
1580
1602
  new TlaEvaluationError(
@@ -1762,18 +1784,31 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
1762
1784
  keepLazy(expression.function);
1763
1785
  const evaluateFunction = child(expression.function);
1764
1786
  const args = expression.args.map(child);
1787
+ const describeNonFunction = getNonFunctionError(expression);
1765
1788
  if (args.length === 1) {
1766
1789
  const argument = args[0];
1767
- return (context) => applyFunction(evaluateFunction(context), argument(context));
1790
+ return (context) =>
1791
+ applyFunction(
1792
+ evaluateFunction(context),
1793
+ argument(context),
1794
+ undefined,
1795
+ describeNonFunction,
1796
+ );
1768
1797
  }
1769
1798
  return (context) =>
1770
- applyFunction(evaluateFunction(context), createTuple(args.map((arg) => arg(context))));
1799
+ applyFunction(
1800
+ evaluateFunction(context),
1801
+ createTuple(args.map((arg) => arg(context))),
1802
+ undefined,
1803
+ describeNonFunction,
1804
+ );
1771
1805
  }
1772
1806
  case "FieldAccess": {
1773
1807
  const record = child(expression.record);
1774
1808
  const field = expression.field;
1775
1809
  const describeMissing = getFieldError(expression);
1776
- return (context) => applyFunction(record(context), field, describeMissing);
1810
+ const describeNonRecord = getNonRecordError(expression);
1811
+ return (context) => applyFunction(record(context), field, describeMissing, describeNonRecord);
1777
1812
  }
1778
1813
  case "Product": {
1779
1814
  const factors = expression.factors.map(child);
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
@@ -1,4 +1,5 @@
1
1
  import { TlaEvaluationError } from "./errors";
2
+ import { EXIT_STATUS, setExitCode } from "./exit-codes";
2
3
  import { hasRepeatedEffects, type Environment } from "./evaluate";
3
4
  import {
4
5
  evaluateLive,
@@ -137,7 +138,10 @@ export const createLivenessChecker = (
137
138
  fairness.length === 0 ? violation : createJunction("And", [...fairness, violation]);
138
139
  const solutions = getSolutions(formula);
139
140
  if (solutions.length === 0) {
140
- throw new TlaEvaluationError(TAUTOLOGY_MESSAGE);
141
+ throw setExitCode(
142
+ new TlaEvaluationError(TAUTOLOGY_MESSAGE),
143
+ EXIT_STATUS.livenessEvaluationFailure,
144
+ );
141
145
  }
142
146
  const actionIds = new Map<string, number>();
143
147
  const checks = solutions.map((solution): Check => ({
package/src/liveness.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { isLocallyResolved, type Definition, type Expression } from "./ast";
2
- import { TlaConfigError, 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)}`,
@@ -191,7 +208,7 @@ export const expandTemporal = (
191
208
  getDefinitionLevel(definition, environment) > 0
192
209
  ) {
193
210
  if (expanding.has(definition)) {
194
- throw new TlaConfigError(`The definition of ${expression.name} refers to itself`);
211
+ throw setExitCode(new TlaEvaluationError(STACK_OVERFLOW), EXIT_STATUS.error);
195
212
  }
196
213
  return expand(
197
214
  definition.body,
@@ -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)}`,
@@ -299,9 +316,7 @@ export const toLiveExpression = (
299
316
  scope: Scope | undefined,
300
317
  ) => {
301
318
  if (expansion.depth >= MAXIMUM_EXPANSION_DEPTH) {
302
- throw new TlaEvaluationError(
303
- `TLC overflowed the stack while expanding the temporal formula at ${describeLocation(expression)}`,
304
- );
319
+ throw setExitCode(new TlaEvaluationError(STACK_OVERFLOW), EXIT_STATUS.error);
305
320
  }
306
321
  expansion.depth++;
307
322
  const result = convert(body, bodyScope);
@@ -356,9 +371,45 @@ export const toLiveExpression = (
356
371
  return level > ACTION_LEVEL ? result : toAtom(expression, scope, level);
357
372
  };
358
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
+
359
407
  const convert = (expression: Expression, scope: Scope | undefined): LiveExpression => {
360
408
  const level = getLevel(expression, scope, environment);
361
- 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
+ }
362
413
  switch (expression.kind) {
363
414
  case "Label":
364
415
  return convert(expression.body, scope);
@@ -401,7 +452,10 @@ export const toLiveExpression = (
401
452
  return convertQuantifier(expression, scope);
402
453
  case "If": {
403
454
  if (getLevel(expression.condition, scope, environment) === 0) {
404
- const condition = evaluate(expression.condition, getConstantContext(environment, scope));
455
+ const condition = evaluateConstant(
456
+ expression.condition,
457
+ getConstantContext(environment, scope),
458
+ );
405
459
  if (typeof condition === "boolean") {
406
460
  return convert(condition ? expression.consequent : expression.alternative, scope);
407
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 =>
@@ -419,7 +427,7 @@ const compileMembership = (
419
427
  expression.operator === "\\subseteq" ? { kind: "Subset", base: evaluated } : evaluated;
420
428
  if (!isEnumerable(value)) {
421
429
  throw new TlaEvaluationError(
422
- `In computing next states, the right side of \\in is not enumerable: ${formatValue(value)} at ${describeLocation(expression)}`,
430
+ `In computing ${run.isInit ? "initial" : "next"} states, the right side of \\IN is not enumerable.\n${describeRange(expression)}`,
423
431
  );
424
432
  }
425
433
  const elements = getStreamedElements(value);
@@ -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++;
package/src/symmetry.ts CHANGED
@@ -1,5 +1,6 @@
1
- import { TlaConfigError } from "./errors";
1
+ import { TlaConfigError, TlaEvaluationError, UNEXPECTED_EXCEPTION } from "./errors";
2
2
  import { evaluate, type Environment } from "./evaluate";
3
+ import { EXIT_STATUS, setExitCode } from "./exit-codes";
3
4
  import {
4
5
  compareValues,
5
6
  createFunction,
@@ -47,9 +48,13 @@ const composePermutations = (first: Images, second: Images) => {
47
48
  return composed;
48
49
  };
49
50
 
50
- const toImages = (value: Value, name: string) => {
51
+ // TLC checks the symmetry set outside any phase that reports an error itself.
52
+ const createSymmetryError = (message: string) =>
53
+ setExitCode(new TlaEvaluationError(`${UNEXPECTED_EXCEPTION}${message}`), EXIT_STATUS.error);
54
+
55
+ const toImages = (value: Value) => {
51
56
  if (!isFunctionValue(value)) {
52
- throw new TlaConfigError(`The symmetry values of ${name} must be functions`);
57
+ throw createSymmetryError("The symmetry values must be function records.");
53
58
  }
54
59
  const functionValue = toFiniteFunction(value);
55
60
  const permutation: Images = new Map();
@@ -65,8 +70,13 @@ const toImages = (value: Value, name: string) => {
65
70
 
66
71
  export const getSymmetryGroup = (name: string, environment: Environment): Permutation[] => {
67
72
  const definition = environment.definitions.get(name);
73
+ if (definition === undefined && !environment.constants.has(name)) {
74
+ throw new TlaConfigError(
75
+ `The symmetry function ${name} specified in the configuration file\nis not defined in the specification.`,
76
+ );
77
+ }
68
78
  if (definition?.kind !== "Operator" || definition.params.length > 0) {
69
- throw new TlaConfigError(`The symmetry function ${name} must specify a set of permutations`);
79
+ throw createSymmetryError(`The symmetry function ${name} must specify a set of permutations.`);
70
80
  }
71
81
  const value = evaluate(definition.body, {
72
82
  environment,
@@ -75,9 +85,9 @@ export const getSymmetryGroup = (name: string, environment: Environment): Permut
75
85
  next: undefined,
76
86
  });
77
87
  if (!isSetValue(value) || !isEnumerable(value)) {
78
- throw new TlaConfigError("The symmetry operator must specify a set of functions");
88
+ throw createSymmetryError("The symmetry operator must specify a set of functions.");
79
89
  }
80
- const permutations = toFiniteSet(value).elements.map((element) => toImages(element, name));
90
+ const permutations = toFiniteSet(value).elements.map(toImages);
81
91
  const isDisabled =
82
92
  definition.body.kind === "Apply" && definition.body.args.length >= permutations.length;
83
93
  if (isDisabled) return [];