tla-ts 0.0.3-dev.27a0c3a → 0.0.3-dev.3082068

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.27a0c3a",
3
+ "version": "0.0.3-dev.3082068",
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
@@ -12,9 +12,11 @@ import { createEnvironment } from "./environment";
12
12
  import {
13
13
  getErrorExitCode,
14
14
  isStackOverflow,
15
+ formatRange,
15
16
  STACK_OVERFLOW,
16
17
  TlaConfigError,
17
18
  TlaEvaluationError,
19
+ TlaIllegalStateError,
18
20
  TlaIncompleteStateError,
19
21
  TlaModuleError,
20
22
  UNEXPECTED_EXCEPTION,
@@ -24,7 +26,6 @@ import {
24
26
  describeRange,
25
27
  evaluate,
26
28
  expectBoolean,
27
- formatRange,
28
29
  getDefinition,
29
30
  isConstantLevel,
30
31
  isImpure,
@@ -140,6 +141,14 @@ export interface EvaluationFailure {
140
141
  trace: TraceStep[];
141
142
  initialState: Record<string, Value> | undefined;
142
143
  exitCode: number;
144
+ replay?: Replay;
145
+ isWithoutStatistics?: boolean;
146
+ }
147
+
148
+ // TLC replays a failed step to print the expressions it was evaluating when the replay failed.
149
+ export interface Replay {
150
+ output: string[];
151
+ callStack: string[] | undefined;
143
152
  }
144
153
 
145
154
  export interface CheckResult {
@@ -927,6 +936,27 @@ const toNextStateError = (error: unknown) =>
927
936
  )
928
937
  : withNextStateExitCode(error);
929
938
 
939
+ // TLC keeps the stack only when an evaluation fails, and prints each expression on it once, however
940
+ // many times in a row it pushed it.
941
+ const getReplayedCallStack = (replay: () => void, trace: Expression[]) => {
942
+ try {
943
+ replay();
944
+ return undefined;
945
+ } catch (error) {
946
+ if (!(error instanceof TlaEvaluationError)) return [];
947
+ return trace
948
+ .flatMap((expression) => {
949
+ const range = expression.location.range;
950
+ return range
951
+ ? [
952
+ `Line ${range.start.line}, column ${range.start.column} to line ${range.end.line}, column ${range.end.column} in ${range.module}`,
953
+ ]
954
+ : [];
955
+ })
956
+ .filter((frame, index, frames) => index === 0 || frames[index - 1] !== frame);
957
+ }
958
+ };
959
+
930
960
  const withHeadline = (error: unknown, headline: string) =>
931
961
  error instanceof TlaEvaluationError
932
962
  ? setExitCode(
@@ -955,9 +985,10 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
955
985
  const onPrint = options.onPrint ?? console.log;
956
986
  // TLC prints again while it rebuilds a trace, between the states it prints. Printing those lines
957
987
  // before the trace would misplace them, so rebuilding a trace prints nothing.
958
- const output = { isMuted: false };
988
+ const output = { isMuted: false, replayed: undefined as string[] | undefined };
959
989
  const print = (text: string) => {
960
- if (!output.isMuted) onPrint(text);
990
+ if (output.replayed) output.replayed.push(text);
991
+ else if (!output.isMuted) onPrint(text);
961
992
  };
962
993
  const withoutOutput = <Result>(rebuild: () => Result) => {
963
994
  output.isMuted = true;
@@ -1019,9 +1050,9 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1019
1050
  ),
1020
1051
  });
1021
1052
 
1022
- const search = createSearch(config, environment, () =>
1023
- getTlcDeclarationOrder(options.source, options.loadModule, "variable"),
1024
- );
1053
+ const getVariableOrder = () =>
1054
+ getTlcDeclarationOrder(options.source, options.loadModule, "variable");
1055
+ const search = createSearch(config, environment, getVariableOrder);
1025
1056
  const assumptionViolation = findAssumptionViolation(specification.assumptions, environment);
1026
1057
  if (assumptionViolation) return createResult("assumption-violation", assumptionViolation);
1027
1058
  if (!search) return createSuccess();
@@ -1045,6 +1076,67 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1045
1076
  const spec = search.spec;
1046
1077
  const getFingerprintState = search.getFingerprintState;
1047
1078
  const nextActions = { value: undefined as SpecAction[] | undefined };
1079
+ const replayFailure = (
1080
+ result: CheckResult,
1081
+ replay: (tracedSearch: Search, traced: Environment) => void,
1082
+ ): CheckResult => {
1083
+ if (!result.failure) return result;
1084
+ const trace: Expression[] = [];
1085
+ const traced: Environment = { ...environment, evaluators: new WeakMap(), trace };
1086
+ const tracedSearch = createSearch(config, traced, getVariableOrder);
1087
+ if (!tracedSearch) return result;
1088
+ const replayed: string[] = [];
1089
+ output.replayed = replayed;
1090
+ const callStack = getReplayedCallStack(() => replay(tracedSearch, traced), trace);
1091
+ output.replayed = undefined;
1092
+ return { ...result, failure: { ...result.failure, replay: { output: replayed, callStack } } };
1093
+ };
1094
+ // TLC checks every initial state again, as when it first generated them.
1095
+ const replayInitialStates = (result: CheckResult) =>
1096
+ replayFailure(result, (tracedSearch, traced) => {
1097
+ if (spec.init === undefined) return;
1098
+ forEachInitialState(
1099
+ spec.init,
1100
+ traced,
1101
+ (state) => {
1102
+ tracedSearch.satisfiesConstraints(state);
1103
+ return (
1104
+ tracedSearch.findViolatedInvariant(state) !== undefined ||
1105
+ tracedSearch.findFailedInitialPredicate(state) !== undefined
1106
+ );
1107
+ },
1108
+ spec.scope,
1109
+ );
1110
+ });
1111
+ // TLC rebuilds the behavior up to the state it expanded before it replays the step.
1112
+ const rebuildBehavior = (index: number): void => {
1113
+ const parent = parents[index];
1114
+ if (parent === -1) {
1115
+ getSpecInitialStates();
1116
+ return;
1117
+ }
1118
+ rebuildBehavior(parent);
1119
+ getLabel(parent, states[parent], states[index]);
1120
+ };
1121
+ // TLC generates the successors of each action before it checks them. It checks the invariants
1122
+ // only of a successor outside the model, since it has seen the others.
1123
+ const replaySuccessors = (result: CheckResult, index: number) =>
1124
+ replayFailure(result, (tracedSearch, traced) => {
1125
+ rebuildBehavior(index);
1126
+ const state = states[index];
1127
+ nextActions.value ??= getNextActions(config, environment, specification.instanceActions);
1128
+ nextActions.value.find((action) =>
1129
+ getSuccessors(action.expression, state, traced, action.scope).some((successor) => {
1130
+ const isInModel =
1131
+ tracedSearch.satisfiesConstraints(successor.state) &&
1132
+ tracedSearch.satisfiesActionConstraints(state, successor.state);
1133
+ return (
1134
+ (!isInModel && tracedSearch.findViolatedInvariant(successor.state) !== undefined) ||
1135
+ tracedSearch.findViolatedActionProperty(state, successor.state) !== undefined
1136
+ );
1137
+ }),
1138
+ );
1139
+ });
1048
1140
  const isReducing = config.view !== undefined || config.symmetry !== undefined;
1049
1141
  const tlcFingerprints: number[] = [];
1050
1142
  const liveness = withLivenessExitCode(() =>
@@ -1472,10 +1564,22 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1472
1564
  spec.scope,
1473
1565
  );
1474
1566
  } catch (error) {
1475
- return toFailure(error, []);
1567
+ if (!(error instanceof TlaIllegalStateError))
1568
+ return replayInitialStates(toFailure(error, []));
1569
+ // TLC prints an illegal initial state with null for each variable it leaves undefined, and
1570
+ // stops before it prints the statistics.
1571
+ const illegal = toFailure(
1572
+ error,
1573
+ [],
1574
+ error.state.map((value) => value ?? createModelValue("null")),
1575
+ );
1576
+ return {
1577
+ ...illegal,
1578
+ failure: illegal.failure && { ...illegal.failure, isWithoutStatistics: true },
1579
+ };
1476
1580
  }
1477
1581
  }
1478
- if (outcome.result) return outcome.result;
1582
+ if (outcome.result) return replayInitialStates(outcome.result);
1479
1583
 
1480
1584
  const next = spec.next;
1481
1585
  if (next === undefined) {
@@ -1533,7 +1637,8 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1533
1637
  } catch (error) {
1534
1638
  // TLC reports a successor it cannot fingerprint as a failure of the state it expands.
1535
1639
  if (current.isFingerprinting) throw error;
1536
- outcome.result = toFailure(error, getTrace(index, successor));
1640
+ const failure = toFailure(error, getTrace(index, successor));
1641
+ outcome.result = isStackOverflow(error) ? failure : replaySuccessors(failure, index);
1537
1642
  }
1538
1643
  return outcome.result !== undefined;
1539
1644
  });
@@ -1629,10 +1734,14 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1629
1734
  try {
1630
1735
  outcome.result = expandState(index);
1631
1736
  } catch (error) {
1632
- outcome.result =
1737
+ const failure =
1633
1738
  error instanceof TlaIncompleteStateError
1634
1739
  ? reportIncompleteSuccessor(error, index)
1635
1740
  : toFailure(toNextStateError(error), getStateTrace(index));
1741
+ outcome.result =
1742
+ error instanceof TlaIncompleteStateError || isStackOverflow(error)
1743
+ ? failure
1744
+ : replaySuccessors(failure, index);
1636
1745
  }
1637
1746
  if (outcome.result) return outcome.result;
1638
1747
  outDegrees[getOutDegreeBucket()]++;
@@ -12,7 +12,13 @@ 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, TlaModuleError, TlaSyntaxError } from "./errors";
15
+ import {
16
+ createSanyError,
17
+ TlaConfigError,
18
+ TlaEvaluationError,
19
+ TlaModuleError,
20
+ TlaSyntaxError,
21
+ } from "./errors";
16
22
  import { EXIT_STATUS, setExitCode } from "./exit-codes";
17
23
  import {
18
24
  createBigNumberError,
@@ -289,13 +295,25 @@ export const createEnvironment = (
289
295
  BUNDLED_MODULES.get(name) ??
290
296
  extractModule(options.source, name);
291
297
  if (source === undefined)
292
- throw new TlaSyntaxError(
293
- `Cannot find source file for module ${name} imported in module ${importer}.`,
298
+ throw createSanyError(
299
+ [
300
+ {
301
+ location: `In module ${importer}`,
302
+ message: `Cannot find source file for module ${name} imported in module ${importer}.`,
303
+ },
304
+ ],
305
+ true,
294
306
  );
295
307
  const module = parseModule(source);
296
308
  if (module.name !== name) {
297
- throw new TlaSyntaxError(
298
- `File name '${name}' does not match the name '${module.name}' of the top level module it contains.`,
309
+ throw createSanyError(
310
+ [
311
+ {
312
+ location: "Unknown location",
313
+ message: `File name '${name}' does not match the name '${module.name}' of the top level module it contains.`,
314
+ },
315
+ ],
316
+ true,
299
317
  );
300
318
  }
301
319
  return rejectModuleLiterals(module);
package/src/errors.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { SourceRange } from "./ast";
1
2
  import { EXIT_STATUS, getExitCode } from "./exit-codes";
2
3
  import type { Value } from "./values";
3
4
 
@@ -27,16 +28,44 @@ export interface SyntaxFailure {
27
28
  isEnd: boolean;
28
29
  }
29
30
 
31
+ // An error SANY reports at a location, such as "In module M" or a range in a module.
32
+ export interface SanyError {
33
+ location: string;
34
+ message: string;
35
+ }
36
+
37
+ // The errors SANY reports for a spec. A fatal error stops it before semantic analysis.
38
+ export interface SanyReport {
39
+ errors: SanyError[];
40
+ isFatal: boolean;
41
+ }
42
+
30
43
  export class TlaSyntaxError extends TlaError {
31
44
  failure: SyntaxFailure | undefined;
45
+ sany: SanyReport | undefined;
32
46
 
33
- constructor(message: string, cause?: unknown, failure?: SyntaxFailure) {
47
+ constructor(message: string, cause?: unknown, failure?: SyntaxFailure, sany?: SanyReport) {
34
48
  super(message, cause);
35
49
  this.name = "TlaSyntaxError";
36
50
  this.failure = failure;
51
+ this.sany = sany;
37
52
  }
38
53
  }
39
54
 
55
+ export const createSanyError = (errors: SanyError[], isFatal = false) =>
56
+ new TlaSyntaxError(
57
+ errors.map((error) => `${error.location}\n\n${error.message}`).join("\n\n"),
58
+ undefined,
59
+ undefined,
60
+ { errors, isFatal },
61
+ );
62
+
63
+ export const formatRange = (range: SourceRange) =>
64
+ `line ${range.start.line}, col ${range.start.column} to line ${range.end.line}, col ${range.end.column} of module ${range.module}`;
65
+
66
+ export const createSemanticError = (message: string, range: SourceRange) =>
67
+ createSanyError([{ location: formatRange(range), message }]);
68
+
40
69
  export class TlaConfigError extends TlaError {
41
70
  constructor(message: string, cause?: unknown) {
42
71
  super(message, cause);
@@ -81,6 +110,17 @@ export class TlaIncompleteStateError extends TlaEvaluationError {
81
110
  }
82
111
  }
83
112
 
113
+ // TLC reports an initial state that the initial predicate leaves incomplete as an illegal state.
114
+ export class TlaIllegalStateError extends TlaEvaluationError {
115
+ state: (Value | undefined)[];
116
+
117
+ constructor(state: (Value | undefined)[]) {
118
+ super("current state is not a legal state");
119
+ this.name = "TlaEvaluationError";
120
+ this.state = state;
121
+ }
122
+ }
123
+
84
124
  export interface TlapmReport {
85
125
  failure?: string;
86
126
  exception?: string;
package/src/evaluate.ts CHANGED
@@ -10,10 +10,9 @@ 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";
15
+ import { formatRange, TlaEvaluationError } from "./errors";
17
16
  import { EXIT_STATUS, setExitCode, setOwnExitCode } from "./exit-codes";
18
17
  import { generateEvaluator } from "./codegen";
19
18
  import type { CheckerRuntime } from "./runtime";
@@ -49,6 +48,7 @@ import {
49
48
  toFiniteSet,
50
49
  updateFunction,
51
50
  valuesEqual,
51
+ type FilteredSetValue,
52
52
  type FunctionValue,
53
53
  type LazyFunctionSource,
54
54
  type LazyFunctionValue,
@@ -117,6 +117,7 @@ export interface Environment {
117
117
  definitionValues: Map<Definition, Value>;
118
118
  constantLevels: Map<Definition, boolean>;
119
119
  evaluators: WeakMap<Expression, Evaluator>;
120
+ trace?: Expression[];
120
121
  }
121
122
 
122
123
  export interface Context {
@@ -146,9 +147,6 @@ const EXCEPT_AT = "@";
146
147
  export const describeLocation = (expression: Expression) =>
147
148
  `line ${expression.location.line}, column ${expression.location.column}`;
148
149
 
149
- export const formatRange = (range: SourceRange) =>
150
- `line ${range.start.line}, col ${range.start.column} to line ${range.end.line}, col ${range.end.column} of module ${range.module}`;
151
-
152
150
  export const describeRange = (expression: Expression) => {
153
151
  const range = expression.location.range;
154
152
  return range ? formatRange(range) : describeLocation(expression);
@@ -1023,16 +1021,38 @@ const isStateCached = (expression: Expression, environment: Environment) =>
1023
1021
  getReadVariables(expression, environment) !== undefined &&
1024
1022
  !hasFreeLocals(expression, NO_BOUND_NAMES);
1025
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
+
1026
1031
  export const getEvaluator = (expression: Expression, environment: Environment): Evaluator => {
1027
1032
  const cached = environment.evaluators.get(expression);
1028
1033
  if (cached) return cached;
1029
1034
  const compiled = compile(expression, environment);
1030
- const evaluator =
1035
+ const cachedEvaluator =
1031
1036
  isWorthCaching(expression) && isClosedConstant(expression, environment)
1032
1037
  ? cacheFirstValue(compiled)
1033
1038
  : isStateCached(expression, environment)
1034
1039
  ? cacheStateValue(compiled)
1035
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;
1036
1056
  environment.evaluators.set(expression, evaluator);
1037
1057
  return evaluator;
1038
1058
  };
@@ -1040,6 +1060,7 @@ export const getEvaluator = (expression: Expression, environment: Environment):
1040
1060
  const entryEvaluators = new WeakMap<Expression, Evaluator>();
1041
1061
 
1042
1062
  export const getEntryEvaluator = (expression: Expression, environment: Environment) => {
1063
+ if (environment.trace) return getEvaluator(expression, environment);
1043
1064
  const cached = entryEvaluators.get(expression);
1044
1065
  if (cached) return cached;
1045
1066
  const evaluator =
@@ -1532,13 +1553,21 @@ const compileSetComprehension = (
1532
1553
  const pattern = expression.bound.pattern;
1533
1554
  return (context) => {
1534
1555
  const base = set(context);
1535
- const test = (element: Value) =>
1556
+ const getTest = (evaluatePredicate: Evaluator) => (element: Value) =>
1536
1557
  expectBoolean(
1537
- predicate(withScope(context, bindPattern(context.scope, pattern, element))),
1558
+ evaluatePredicate(withScope(context, bindPattern(context.scope, pattern, element))),
1538
1559
  "a set filter predicate",
1539
1560
  );
1561
+ const test = getTest(predicate);
1540
1562
  if (!isReducible(base)) {
1541
- 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
+ }
1542
1571
  throw new TlaEvaluationError(
1543
1572
  `TLC encountered a non-enumerable quantifier bound ${formatValue(base)} at ${describeLocation(expression.bound.set)}`,
1544
1573
  );
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/liveness.ts CHANGED
@@ -210,12 +210,16 @@ export const expandTemporal = (
210
210
  if (expanding.has(definition)) {
211
211
  throw setExitCode(new TlaEvaluationError(STACK_OVERFLOW), EXIT_STATUS.error);
212
212
  }
213
- return expand(
213
+ const expanded = expand(
214
214
  definition.body,
215
215
  undefined,
216
216
  expression.name,
217
217
  new Set([...expanding, definition]),
218
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;
219
223
  }
220
224
  }
221
225
  const context = getConstantContext(environment, scope);