tla-ts 0.0.3-dev.4b28a29 → 0.0.3-dev.4cf9a33

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/src/evaluate.ts CHANGED
@@ -10,11 +10,10 @@ import {
10
10
  type NumberExpression,
11
11
  type OperatorParam,
12
12
  type RecordField,
13
- type SourceRange,
14
13
  } from "./ast";
15
14
  import { getKindString } from "./builtins";
16
- import { TlaEvaluationError } from "./errors";
17
- import { EXIT_STATUS, setExitCode } from "./exit-codes";
15
+ import { formatRange, TlaEvaluationError } from "./errors";
16
+ import { EXIT_STATUS, setExitCode, setOwnExitCode } from "./exit-codes";
18
17
  import { generateEvaluator } from "./codegen";
19
18
  import type { CheckerRuntime } from "./runtime";
20
19
  import { getReadVariables } from "./dependencies";
@@ -30,6 +29,7 @@ import {
30
29
  createSortedSet,
31
30
  createWrittenRecord,
32
31
  createTuple,
32
+ describeMissingField,
33
33
  formatValue,
34
34
  getDomain,
35
35
  getFunctionDomain,
@@ -38,6 +38,7 @@ import {
38
38
  getValueHash,
39
39
  isFunctionValue,
40
40
  isOverriddenSet,
41
+ isRecordValue,
41
42
  isSameValue,
42
43
  markLambdaFunction,
43
44
  isReducible,
@@ -47,6 +48,8 @@ import {
47
48
  toFiniteSet,
48
49
  updateFunction,
49
50
  valuesEqual,
51
+ type FilteredSetValue,
52
+ type FunctionValue,
50
53
  type LazyFunctionSource,
51
54
  type LazyFunctionValue,
52
55
  type Value,
@@ -114,6 +117,7 @@ export interface Environment {
114
117
  definitionValues: Map<Definition, Value>;
115
118
  constantLevels: Map<Definition, boolean>;
116
119
  evaluators: WeakMap<Expression, Evaluator>;
120
+ trace?: Expression[];
117
121
  }
118
122
 
119
123
  export interface Context {
@@ -143,9 +147,6 @@ const EXCEPT_AT = "@";
143
147
  export const describeLocation = (expression: Expression) =>
144
148
  `line ${expression.location.line}, column ${expression.location.column}`;
145
149
 
146
- export const formatRange = (range: SourceRange) =>
147
- `line ${range.start.line}, col ${range.start.column} to line ${range.end.line}, col ${range.end.column} of module ${range.module}`;
148
-
149
150
  export const describeRange = (expression: Expression) => {
150
151
  const range = expression.location.range;
151
152
  return range ? formatRange(range) : describeLocation(expression);
@@ -182,8 +183,17 @@ export const getConjunctError = (
182
183
  };
183
184
 
184
185
  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)}`;
186
+ (expression: Expression & { kind: "FieldAccess" }) => (record: FunctionValue) =>
187
+ isRecordValue(record)
188
+ ? `Attempted to select nonexistent field "${expression.field}" from the record\n${formatValue(record)}\n${describeRange(expression)}`
189
+ : describeMissingField(record, expression.field);
190
+
191
+ export const getNonFunctionError = (expression: Expression) => (value: Value) =>
192
+ `A non-function (${getKindString(value)}) was applied as a function.\n${describeRange(expression)}`;
193
+
194
+ export const getNonRecordError =
195
+ (expression: Expression & { kind: "FieldAccess" }) => (value: Value) =>
196
+ `Attempted to select field "${expression.field}" from a non-record value ${formatValue(value)}\n${describeRange(expression)}`;
187
197
 
188
198
  export const getDomainOperator = (expression: Expression) => (value: Value) => {
189
199
  if (!isFunctionValue(value)) {
@@ -1011,16 +1021,38 @@ const isStateCached = (expression: Expression, environment: Environment) =>
1011
1021
  getReadVariables(expression, environment) !== undefined &&
1012
1022
  !hasFreeLocals(expression, NO_BOUND_NAMES);
1013
1023
 
1024
+ // CallStackTool also evaluates the predicate of a lazy set filter it returns, even one that TLC
1025
+ // made before the replay.
1026
+ const filteredSetRetracers = new WeakMap<
1027
+ FilteredSetValue,
1028
+ (environment: Environment) => FilteredSetValue
1029
+ >();
1030
+
1014
1031
  export const getEvaluator = (expression: Expression, environment: Environment): Evaluator => {
1015
1032
  const cached = environment.evaluators.get(expression);
1016
1033
  if (cached) return cached;
1017
1034
  const compiled = compile(expression, environment);
1018
- const evaluator =
1035
+ const cachedEvaluator =
1019
1036
  isWorthCaching(expression) && isClosedConstant(expression, environment)
1020
1037
  ? cacheFirstValue(compiled)
1021
1038
  : isStateCached(expression, environment)
1022
1039
  ? cacheStateValue(compiled)
1023
1040
  : compiled;
1041
+ const trace = environment.trace;
1042
+ // TLC's CallStackTool pushes each expression it evaluates and keeps the stack when one fails.
1043
+ const evaluator: Evaluator = trace
1044
+ ? (context) => {
1045
+ const depth = trace.length;
1046
+ trace.push(expression);
1047
+ const value = cachedEvaluator(context);
1048
+ trace.length = depth;
1049
+ const retrace =
1050
+ typeof value === "object" && value.kind === "FilteredSet"
1051
+ ? filteredSetRetracers.get(value)
1052
+ : undefined;
1053
+ return retrace ? retrace(environment) : value;
1054
+ }
1055
+ : cachedEvaluator;
1024
1056
  environment.evaluators.set(expression, evaluator);
1025
1057
  return evaluator;
1026
1058
  };
@@ -1028,6 +1060,7 @@ export const getEvaluator = (expression: Expression, environment: Environment):
1028
1060
  const entryEvaluators = new WeakMap<Expression, Evaluator>();
1029
1061
 
1030
1062
  export const getEntryEvaluator = (expression: Expression, environment: Environment) => {
1063
+ if (environment.trace) return getEvaluator(expression, environment);
1031
1064
  const cached = entryEvaluators.get(expression);
1032
1065
  if (cached) return cached;
1033
1066
  const evaluator =
@@ -1325,6 +1358,11 @@ const compileApply = (
1325
1358
  if (definition?.kind === "Function") {
1326
1359
  throw new TlaEvaluationError(`${expression.operator} is a function; apply it with brackets`);
1327
1360
  }
1361
+ if (expression.operator === "\\cdot") {
1362
+ throw new TlaEvaluationError(
1363
+ "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.",
1364
+ );
1365
+ }
1328
1366
  throw new TlaEvaluationError(
1329
1367
  `Unknown operator ${expression.operator} at ${describeLocation(expression)}`,
1330
1368
  );
@@ -1515,13 +1553,21 @@ const compileSetComprehension = (
1515
1553
  const pattern = expression.bound.pattern;
1516
1554
  return (context) => {
1517
1555
  const base = set(context);
1518
- const test = (element: Value) =>
1556
+ const getTest = (evaluatePredicate: Evaluator) => (element: Value) =>
1519
1557
  expectBoolean(
1520
- predicate(withScope(context, bindPattern(context.scope, pattern, element))),
1558
+ evaluatePredicate(withScope(context, bindPattern(context.scope, pattern, element))),
1521
1559
  "a set filter predicate",
1522
1560
  );
1561
+ const test = getTest(predicate);
1523
1562
  if (!isReducible(base)) {
1524
- if (isSetValue(base)) return { kind: "FilteredSet", base, test };
1563
+ if (isSetValue(base)) {
1564
+ const filtered: FilteredSetValue = { kind: "FilteredSet", base, test };
1565
+ filteredSetRetracers.set(filtered, (traced) => ({
1566
+ ...filtered,
1567
+ test: getTest(getEvaluator(expression.predicate, traced)),
1568
+ }));
1569
+ return filtered;
1570
+ }
1525
1571
  throw new TlaEvaluationError(
1526
1572
  `TLC encountered a non-enumerable quantifier bound ${formatValue(base)} at ${describeLocation(expression.bound.set)}`,
1527
1573
  );
@@ -1574,7 +1620,12 @@ export const hasDuplicateFields = (sortedFields: RecordField[]) =>
1574
1620
  sortedFields.some((field, index) => index > 0 && sortedFields[index - 1].name === field.name);
1575
1621
 
1576
1622
  export const createUnassignedError = (name: string, expression: Expression) =>
1577
- new TlaEvaluationError(`The variable ${name} is not assigned at ${describeLocation(expression)}`);
1623
+ setOwnExitCode(
1624
+ new TlaEvaluationError(
1625
+ `In evaluation, the identifier ${name} is either undefined or not an operator.\n${describeRange(expression)}`,
1626
+ ),
1627
+ EXIT_STATUS.configParseError,
1628
+ );
1578
1629
 
1579
1630
  export const createPrimeOutsideActionError = (expression: Expression) =>
1580
1631
  new TlaEvaluationError(
@@ -1762,18 +1813,31 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
1762
1813
  keepLazy(expression.function);
1763
1814
  const evaluateFunction = child(expression.function);
1764
1815
  const args = expression.args.map(child);
1816
+ const describeNonFunction = getNonFunctionError(expression);
1765
1817
  if (args.length === 1) {
1766
1818
  const argument = args[0];
1767
- return (context) => applyFunction(evaluateFunction(context), argument(context));
1819
+ return (context) =>
1820
+ applyFunction(
1821
+ evaluateFunction(context),
1822
+ argument(context),
1823
+ undefined,
1824
+ describeNonFunction,
1825
+ );
1768
1826
  }
1769
1827
  return (context) =>
1770
- applyFunction(evaluateFunction(context), createTuple(args.map((arg) => arg(context))));
1828
+ applyFunction(
1829
+ evaluateFunction(context),
1830
+ createTuple(args.map((arg) => arg(context))),
1831
+ undefined,
1832
+ describeNonFunction,
1833
+ );
1771
1834
  }
1772
1835
  case "FieldAccess": {
1773
1836
  const record = child(expression.record);
1774
1837
  const field = expression.field;
1775
1838
  const describeMissing = getFieldError(expression);
1776
- return (context) => applyFunction(record(context), field, describeMissing);
1839
+ const describeNonRecord = getNonRecordError(expression);
1840
+ return (context) => applyFunction(record(context), field, describeMissing, describeNonRecord);
1777
1841
  }
1778
1842
  case "Product": {
1779
1843
  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/instances.ts CHANGED
@@ -164,7 +164,7 @@ export const mapChildren = (
164
164
  case "RecordSet":
165
165
  return {
166
166
  ...expression,
167
- fields: expression.fields.map((field) => ({ name: field.name, value: plain(field.value) })),
167
+ fields: expression.fields.map((field) => ({ ...field, value: plain(field.value) })),
168
168
  };
169
169
  case "Except":
170
170
  return {
package/src/levels.ts CHANGED
@@ -5,11 +5,10 @@ import {
5
5
  type Expression,
6
6
  type Module,
7
7
  type OperatorParam,
8
- type SourceLocation,
9
8
  } from "./ast";
10
- import { TlaSyntaxError } from "./errors";
9
+ import { createSemanticError, TlaSyntaxError } from "./errors";
11
10
  import { mapChildren } from "./instances";
12
- import { getBoundNames, getPatternNames } from "./resolve";
11
+ import { collectSemanticErrors, getBoundNames, getPatternNames } from "./resolve";
13
12
  import { STANDARD_LEVELS } from "./standard-levels";
14
13
 
15
14
  interface LevelData {
@@ -176,8 +175,13 @@ export const ACTION_LEVEL = 2;
176
175
 
177
176
  export const TEMPORAL_LEVEL = 3;
178
177
 
179
- const createLevelError = (message: string, location: SourceLocation) =>
180
- new TlaSyntaxError(`${message} at line ${location.line}, column ${location.column}`);
178
+ // SANY reports a level error at the range of the expression it rejects.
179
+ const createLevelError = (message: string, expression: Expression) =>
180
+ expression.location.range
181
+ ? createSemanticError(`${message}.`, expression.location.range)
182
+ : new TlaSyntaxError(
183
+ `${message} at line ${expression.location.line}, column ${expression.location.column}`,
184
+ );
181
185
 
182
186
  const LOGICAL_OPERATORS = new Set(["/\\", "\\/", "=>", "<=>"]);
183
187
 
@@ -237,13 +241,13 @@ export const createLevelAnalyzer = (context: LevelContext) => {
237
241
  if (operand.operator || operand.declared) return;
238
242
  if (operand.data.level > getMaxLevel(operator, index)) {
239
243
  throw new TlaSyntaxError(
240
- `Level error in applying operator ${operator.name}: The level of argument ${index + 1} exceeds the maximum level allowed by the operator.`,
244
+ `Level error in applying operator ${operator.name}:\nThe level of argument ${index + 1} exceeds the maximum level allowed by the operator`,
241
245
  );
242
246
  }
243
247
  });
244
248
  if (ranges.some((range) => range.level > ACTION_LEVEL)) {
245
249
  throw new TlaSyntaxError(
246
- `Level error in applying operator ${operator.name}: The level of the range for a bounded variable exceeds the maximum level allowed by the operator.`,
250
+ `Level error in applying operator ${operator.name}:\nThe level of the range for a bounded variable exceeds the maximum level allowed by the operator`,
247
251
  );
248
252
  }
249
253
  const getOperand = (formal: string) => {
@@ -444,10 +448,13 @@ export const createLevelAnalyzer = (context: LevelContext) => {
444
448
  ? applyDeclared(resolved.name, resolved.level, operands)
445
449
  : applyDefined(resolved.levels, operands);
446
450
 
447
- const checkJunction = (operands: Operand[], location: SourceLocation) => {
451
+ const checkJunction = (operands: Operand[], expression: Expression) => {
448
452
  const levels = operands.map((operand) => operand.data.level);
449
453
  if (levels.includes(ACTION_LEVEL) && levels.includes(TEMPORAL_LEVEL)) {
450
- throw createLevelError("Formula has both temporal formula and action as arguments", location);
454
+ throw createLevelError(
455
+ "Formula has both temporal formula and action as arguments",
456
+ expression,
457
+ );
451
458
  }
452
459
  };
453
460
 
@@ -456,10 +463,10 @@ export const createLevelAnalyzer = (context: LevelContext) => {
456
463
  if (isLeadsTo && operands.some((operand) => operand.data.level === ACTION_LEVEL)) {
457
464
  throw createLevelError(
458
465
  "Action used where only temporal formula or state predicate allowed",
459
- expression.location,
466
+ expression,
460
467
  );
461
468
  }
462
- if (LOGICAL_OPERATORS.has(expression.operator)) checkJunction(operands, expression.location);
469
+ if (LOGICAL_OPERATORS.has(expression.operator)) checkJunction(operands, expression);
463
470
  };
464
471
 
465
472
  const checkTemporal = (
@@ -473,7 +480,7 @@ export const createLevelAnalyzer = (context: LevelContext) => {
473
480
  expression.kind === "Always"
474
481
  ? "[] followed by action not of form [A]_v"
475
482
  : "<> followed by action not of form <<A>>_v",
476
- expression.location,
483
+ expression,
477
484
  );
478
485
  };
479
486
 
@@ -501,7 +508,17 @@ export const createLevelAnalyzer = (context: LevelContext) => {
501
508
  return data;
502
509
  };
503
510
 
511
+ // SANY reports a level error of an operator's arguments at the application.
504
512
  const analyze = (expression: Expression, scope: Scope): LevelData => {
513
+ try {
514
+ return analyzeNode(expression, scope);
515
+ } catch (error) {
516
+ if (!(error instanceof TlaSyntaxError) || error.sany) throw error;
517
+ throw createLevelError(error.message, expression);
518
+ }
519
+ };
520
+
521
+ const analyzeNode = (expression: Expression, scope: Scope): LevelData => {
505
522
  switch (expression.kind) {
506
523
  case "Number":
507
524
  case "Decimal":
@@ -521,7 +538,7 @@ export const createLevelAnalyzer = (context: LevelContext) => {
521
538
  case "And":
522
539
  case "Or": {
523
540
  const operands = toOperands(expression.operands, scope);
524
- checkJunction(operands, expression.location);
541
+ checkJunction(operands, expression);
525
542
  return applyDefined(JUNCTION_LEVELS, operands);
526
543
  }
527
544
  case "Prime":
@@ -561,13 +578,14 @@ export const createLevelAnalyzer = (context: LevelContext) => {
561
578
  expression.bounds.map((bound) => bound.set),
562
579
  getBoundNames(expression.bounds),
563
580
  );
564
- if (
565
- data.level === TEMPORAL_LEVEL &&
566
- expression.bounds.some((bound) => analyze(bound.set, scope).level === ACTION_LEVEL)
567
- ) {
581
+ const actionBound =
582
+ data.level === TEMPORAL_LEVEL
583
+ ? expression.bounds.find((bound) => analyze(bound.set, scope).level === ACTION_LEVEL)
584
+ : undefined;
585
+ if (actionBound) {
568
586
  throw createLevelError(
569
587
  "Action-level bound of quantified temporal formula",
570
- expression.location,
588
+ actionBound.set,
571
589
  );
572
590
  }
573
591
  return data;
@@ -838,13 +856,23 @@ const analyzeAssumeProve = (
838
856
  // SANY checks the level of every definition, assumption, and theorem of a module.
839
857
  export const checkModuleLevels = (module: Module, context: LevelContext) => {
840
858
  const analyzer = createLevelAnalyzer(context);
841
- module.definitions
842
- .filter((definition) => !definition.name.includes("!"))
843
- .forEach((definition) => analyzer.analyzeDefinition(definition, new Map()));
844
- module.assumptions.forEach((assumption) => analyzer.analyze(assumption.expression, new Map()));
845
- module.theorems.forEach((theorem) =>
846
- theorem.statement.kind === "AssumeProve"
847
- ? analyzeAssumeProve(theorem.statement, new Map(), analyzer)
848
- : analyzer.analyze(theorem.statement, new Map()),
849
- );
859
+ collectSemanticErrors([
860
+ ...module.definitions
861
+ .filter((definition) => !definition.name.includes("!"))
862
+ .map((definition) => ({
863
+ location: definition.location,
864
+ check: () => analyzer.analyzeDefinition(definition, new Map()),
865
+ })),
866
+ ...module.assumptions.map((assumption) => ({
867
+ location: assumption.location,
868
+ check: () => analyzer.analyze(assumption.expression, new Map()),
869
+ })),
870
+ ...module.theorems.map((theorem) => ({
871
+ location: theorem.location,
872
+ check: () =>
873
+ theorem.statement.kind === "AssumeProve"
874
+ ? analyzeAssumeProve(theorem.statement, new Map(), analyzer)
875
+ : analyzer.analyze(theorem.statement, new Map()),
876
+ })),
877
+ ]);
850
878
  };
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,
@@ -99,7 +100,9 @@ const getNodeSlot = (table: NodeTable, state: number, tableauNode: number) => {
99
100
  }
100
101
  };
101
102
 
102
- 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;
103
106
 
104
107
  const getPending = (check: Check, node: number) => (check.pending[node] ??= []);
105
108
 
@@ -137,7 +140,10 @@ export const createLivenessChecker = (
137
140
  fairness.length === 0 ? violation : createJunction("And", [...fairness, violation]);
138
141
  const solutions = getSolutions(formula);
139
142
  if (solutions.length === 0) {
140
- throw new TlaEvaluationError(TAUTOLOGY_MESSAGE);
143
+ throw setExitCode(
144
+ new TlaEvaluationError(TAUTOLOGY_MESSAGE),
145
+ EXIT_STATUS.livenessEvaluationFailure,
146
+ );
141
147
  }
142
148
  const actionIds = new Map<string, number>();
143
149
  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,14 +208,18 @@ 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
- return expand(
213
+ const expanded = expand(
197
214
  definition.body,
198
215
  undefined,
199
216
  expression.name,
200
217
  new Set([...expanding, definition]),
201
218
  );
219
+ // TLC takes the body of a state-level definition in a specification as one initial predicate.
220
+ return !isProperty && getDefinitionLevel(definition, environment) < ACTION_LEVEL
221
+ ? [{ expression: definition.body, scope: undefined, name: expression.name }]
222
+ : expanded;
202
223
  }
203
224
  }
204
225
  const context = getConstantContext(environment, scope);
@@ -278,7 +299,7 @@ export const toLiveExpression = (
278
299
  ): LiveExpression => {
279
300
  const atomLevel = level === 0 ? getLevel(expression, scope, environment) : level;
280
301
  if (atomLevel === 0) {
281
- const value = evaluate(expression, getConstantContext(environment, scope));
302
+ const value = evaluateConstant(expression, getConstantContext(environment, scope));
282
303
  if (typeof value !== "boolean") {
283
304
  throw new TlaEvaluationError(
284
305
  `TLC expected a boolean in the temporal formula at ${describeLocation(expression)}`,
@@ -299,9 +320,7 @@ export const toLiveExpression = (
299
320
  scope: Scope | undefined,
300
321
  ) => {
301
322
  if (expansion.depth >= MAXIMUM_EXPANSION_DEPTH) {
302
- throw new TlaEvaluationError(
303
- `TLC overflowed the stack while expanding the temporal formula at ${describeLocation(expression)}`,
304
- );
323
+ throw setExitCode(new TlaEvaluationError(STACK_OVERFLOW), EXIT_STATUS.error);
305
324
  }
306
325
  expansion.depth++;
307
326
  const result = convert(body, bodyScope);
@@ -356,9 +375,45 @@ export const toLiveExpression = (
356
375
  return level > ACTION_LEVEL ? result : toAtom(expression, scope, level);
357
376
  };
358
377
 
378
+ // TLC translates the operands of a connective even when the whole formula is a state or action
379
+ // predicate, so it fails on a constant operand before it checks any state.
380
+ const convertOperands = (expression: Expression, scope: Scope | undefined) => {
381
+ switch (expression.kind) {
382
+ case "Label":
383
+ convert(expression.body, scope);
384
+ return;
385
+ case "Let":
386
+ convert(expression.body, bindLetDefinitions(expression, scope, environment));
387
+ return;
388
+ case "And":
389
+ case "Or":
390
+ for (const operand of expression.operands) convert(operand, scope);
391
+ return;
392
+ case "Apply":
393
+ if (
394
+ expression.operator === "=>" ||
395
+ (expression.operator === "~" && !isLocallyResolved(expression))
396
+ ) {
397
+ for (const operand of expression.args) convert(operand, scope);
398
+ }
399
+ return;
400
+ case "If": {
401
+ const condition = convert(expression.condition, scope);
402
+ const branches =
403
+ condition.kind === "Boolean"
404
+ ? [condition.value ? expression.consequent : expression.alternative]
405
+ : [expression.consequent, expression.alternative];
406
+ for (const branch of branches) convert(branch, scope);
407
+ }
408
+ }
409
+ };
410
+
359
411
  const convert = (expression: Expression, scope: Scope | undefined): LiveExpression => {
360
412
  const level = getLevel(expression, scope, environment);
361
- if (level <= ACTION_LEVEL) return toAtom(expression, scope, level);
413
+ if (level <= ACTION_LEVEL) {
414
+ convertOperands(expression, scope);
415
+ return toAtom(expression, scope, level);
416
+ }
362
417
  switch (expression.kind) {
363
418
  case "Label":
364
419
  return convert(expression.body, scope);
@@ -401,7 +456,10 @@ export const toLiveExpression = (
401
456
  return convertQuantifier(expression, scope);
402
457
  case "If": {
403
458
  if (getLevel(expression.condition, scope, environment) === 0) {
404
- const condition = evaluate(expression.condition, getConstantContext(environment, scope));
459
+ const condition = evaluateConstant(
460
+ expression.condition,
461
+ getConstantContext(environment, scope),
462
+ );
405
463
  if (typeof condition === "boolean") {
406
464
  return convert(condition ? expression.consequent : expression.alternative, scope);
407
465
  }
@@ -15,7 +15,7 @@ import type {
15
15
  WorkerMessage,
16
16
  } from "./parallel";
17
17
  import { getSuccessors, type Successor } from "./successors";
18
- import { getTlcStringOrder, getTlcVariableOrder } from "./tlc-order";
18
+ import { getTlcStringOrder, getTlcDeclarationOrder } from "./tlc-order";
19
19
  import { OUT_DEGREE_BUCKETS } from "./tlc-summary";
20
20
  import { createStateDecoder, createStateEncoder, type EncodedStates } from "./transfer";
21
21
  import { getRankedStringCount, setStringOrder, type Value } from "./values";
@@ -61,7 +61,7 @@ const run = (start: StartMessage, parent: Port) => {
61
61
  });
62
62
  const environment = specification.environment;
63
63
  const search = createSearch(start.config, environment, () =>
64
- getTlcVariableOrder(start.source, loadModule),
64
+ getTlcDeclarationOrder(start.source, loadModule, "variable"),
65
65
  );
66
66
  const nextAction = search?.spec.next;
67
67
  if (!search || nextAction === undefined)
package/src/parallel.ts CHANGED
@@ -20,7 +20,7 @@ import {
20
20
  type SharedFingerprints,
21
21
  } from "./fingerprints";
22
22
  import { getInitialStates } from "./successors";
23
- import { getTlcStringOrder, getTlcVariableOrder } from "./tlc-order";
23
+ import { getTlcStringOrder, getTlcDeclarationOrder } from "./tlc-order";
24
24
  import { getFingerprintDistance, OUT_DEGREE_BUCKETS } from "./tlc-summary";
25
25
  import { createStateEncoder, type EncodedStates } from "./transfer";
26
26
  import { getRankedStringCount, setStringOrder, type Value } from "./values";
@@ -150,7 +150,7 @@ export const check = async (options: CheckOptions): Promise<CheckResult> => {
150
150
  });
151
151
  const environment = specification.environment;
152
152
  const search = createSearch(config, environment, () =>
153
- getTlcVariableOrder(options.source, loadModule),
153
+ getTlcDeclarationOrder(options.source, loadModule, "variable"),
154
154
  );
155
155
  if (findAssumptionViolation(specification.assumptions, environment)) return fallBack();
156
156
  if (