tla-ts 0.0.3-dev.6a30eee → 0.0.3-dev.6f3cbdb

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.
@@ -1,12 +1,13 @@
1
- import type {
2
- Assumption,
3
- Declaration,
4
- Definition,
5
- Expression,
6
- Instance,
7
- Module,
8
- OperatorParam,
9
- SourceLocation,
1
+ import {
2
+ getChildren,
3
+ type Assumption,
4
+ type Declaration,
5
+ type Definition,
6
+ type Expression,
7
+ type Instance,
8
+ type Module,
9
+ type OperatorParam,
10
+ type SourceLocation,
10
11
  } from "./ast";
11
12
  import { BUNDLED_MODULES } from "./bundled-modules";
12
13
  import type { ConfigValue, ModelConfig } from "./config";
@@ -16,8 +17,8 @@ import { EXIT_STATUS, setExitCode } from "./exit-codes";
16
17
  import {
17
18
  createBigNumberError,
18
19
  createRealNumberError,
19
- getChildren,
20
- isConstantLevel,
20
+ evaluate,
21
+ getDefinition,
21
22
  isTlcInteger,
22
23
  type Builtin,
23
24
  type Environment,
@@ -44,7 +45,7 @@ import {
44
45
  import { createRuntime } from "./runtime";
45
46
  import { CORE_OPERATORS, getStandardModule, STANDARD_DEPENDENCIES } from "./standard-modules";
46
47
  import { resolveInstanceSubexpressions, resolveModuleSubexpressions } from "./subexpressions";
47
- import { checkModuleLevels } from "./levels";
48
+ import { checkModuleLevels, createLevelAnalyzer } from "./levels";
48
49
  import { checkInstances, type InstanceCheck } from "./substitution-levels";
49
50
  import {
50
51
  checkInteger,
@@ -212,6 +213,8 @@ export const createEnvironment = (
212
213
  const root = parseModule(options.source);
213
214
  const definitions = new Map<string, Definition>();
214
215
  const parameterized = new Map<string, boolean>();
216
+ // The definition each instance copy came from, and the instance parameters the copy adds.
217
+ const copySources = new Map<string, { source: string; prefix: number }>();
215
218
  const builtins = new Map<string, Builtin>(
216
219
  CORE_OPERATORS.map((operator) => [operator.name, operator]),
217
220
  );
@@ -379,10 +382,11 @@ export const createEnvironment = (
379
382
  variables: new Set(linked.variables),
380
383
  getDefinition: (key) => definitions.get(key),
381
384
  isParameterized: (key) => parameterized.get(key) === true,
382
- addDefinition: (name, create) => {
385
+ addDefinition: (source, name, create) => {
383
386
  const key = createName(`${name}@${module.name}`);
384
387
  definitions.set(key, create(key));
385
388
  parameterized.set(key, !isParameterFree);
389
+ copySources.set(key, { source, prefix: instance.params.length });
386
390
  return key;
387
391
  },
388
392
  createName,
@@ -544,7 +548,7 @@ export const createEnvironment = (
544
548
  variables: new Set(linked.variables),
545
549
  getDefinition: (key) => definitions.get(key),
546
550
  isParameterized: (key) => parameterized.get(key) === true,
547
- addDefinition: (name, create) => {
551
+ addDefinition: (_source, name, create) => {
548
552
  const key = `${name}${KEY_SEPARATOR}${instance.module}${suffix}.${copies.length}`;
549
553
  const definition = create(key);
550
554
  copies.push(
@@ -872,6 +876,38 @@ export const createEnvironment = (
872
876
  );
873
877
  }
874
878
  });
879
+ // TLC sets a module-scoped entry on the body of the module's definition, which every instance of
880
+ // the module shares.
881
+ const scopedKeys = new Set(
882
+ [...config.constants, ...config.substitutions]
883
+ .filter((item) => item.module !== undefined)
884
+ .flatMap(getScopedKeys),
885
+ );
886
+ const getOverride = (
887
+ key: string,
888
+ prefix: number,
889
+ ): { key: string; prefix: number } | undefined => {
890
+ if (scopedKeys.has(key)) return { key, prefix };
891
+ const copy = copySources.get(key);
892
+ return copy && getOverride(copy.source, prefix + copy.prefix);
893
+ };
894
+ copySources.forEach((copy, key) => {
895
+ const override = getOverride(copy.source, copy.prefix);
896
+ const definition = definitions.get(key);
897
+ if (!override || !definition) return;
898
+ const params = definition.kind === "Operator" ? definition.params : [];
899
+ const alias = createLocalAlias(
900
+ key,
901
+ override.key,
902
+ params,
903
+ params.slice(override.prefix),
904
+ definition.location,
905
+ );
906
+ definitions.set(key, alias);
907
+ linkedRoot.visible.forEach((symbol, name) => {
908
+ if (symbol.key === key && name !== key) definitions.set(name, alias);
909
+ });
910
+ });
875
911
  declaredConstants.forEach((name) => {
876
912
  if (!constants.has(name) && !substitutions.has(name) && !operatorKeys.has(name)) {
877
913
  throw new TlaConfigError(`The constant ${name} is not assigned a value by the configuration`);
@@ -907,18 +943,41 @@ export const createEnvironment = (
907
943
  getDefinition: (symbol) => definitions.get(linked.visible.get(symbol)?.key ?? symbol),
908
944
  };
909
945
  });
946
+ // TLC evaluates a substitute at startup and rejects it only when that fails and the level bound it
947
+ // computes is above constant. The bound counts the operators that TLC's Java code overrides with
948
+ // a minimum level as state-level, so the analyzer takes them for variables.
949
+ const analyzer = createLevelAnalyzer({
950
+ constants: new Set(constants.keys()),
951
+ variables: new Set([
952
+ ...variables,
953
+ ...["TLCGet", "Trace", "CounterExample"].filter((name) => builtins.has(name)),
954
+ ]),
955
+ getDefinition: (name) => getDefinition(name, environment),
956
+ });
957
+ const isEvaluable = (body: Expression) => {
958
+ try {
959
+ evaluate(body, { environment, scope: undefined, state: undefined, next: undefined });
960
+ return true;
961
+ } catch (error) {
962
+ if (error instanceof TlaEvaluationError) return false;
963
+ throw error;
964
+ }
965
+ };
910
966
  substitutions.forEach((target, name) => {
911
967
  const definition = definitions.get(target);
912
968
  if (
913
969
  declaredConstants.includes(name) &&
914
- definition &&
915
- !isConstantLevel(definition, environment)
970
+ definition?.kind === "Operator" &&
971
+ definition.params.length === 0 &&
972
+ analyzer.analyzeDefinition(definition, new Map()).level > 0 &&
973
+ !isEvaluable(definition.body)
916
974
  ) {
917
975
  throw new TlaConfigError(
918
976
  `The configuration file substitutes constant ${name} with non-constant ${target}`,
919
977
  );
920
978
  }
921
979
  });
980
+ runtime.isStarted = true;
922
981
  return {
923
982
  environment,
924
983
  assumptions,
package/src/errors.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { EXIT_STATUS, getExitCode, setModuleExitCode } from "./exit-codes";
1
+ import { EXIT_STATUS, getExitCode } from "./exit-codes";
2
2
 
3
3
  // How TLC reports a RuntimeException it did not expect, such as one raised while computing next
4
4
  // states.
@@ -46,10 +46,12 @@ export class TlaEvaluationError extends TlaError {
46
46
  // An evaluation error that TLC raises as an EvalException from a standard module's Java code. It
47
47
  // keeps the name TlaEvaluationError, and index.ts doesn't export it.
48
48
  export class TlaModuleError extends TlaEvaluationError {
49
+ exitCode: number;
50
+
49
51
  constructor(message: string, exitCode: number = EXIT_STATUS.error) {
50
52
  super(message);
51
53
  this.name = "TlaEvaluationError";
52
- setModuleExitCode(this, exitCode);
54
+ this.exitCode = exitCode;
53
55
  }
54
56
  }
55
57
 
package/src/evaluate.ts CHANGED
@@ -1,14 +1,16 @@
1
- import type {
2
- Bound,
3
- BoundPattern,
4
- DecimalExpression,
5
- Definition,
6
- Expression,
7
- FunctionDefinition,
8
- NumberExpression,
9
- OperatorParam,
10
- RecordField,
11
- SourceRange,
1
+ import {
2
+ getChildren,
3
+ isLocallyResolved,
4
+ type Bound,
5
+ type BoundPattern,
6
+ type DecimalExpression,
7
+ type Definition,
8
+ type Expression,
9
+ type FunctionDefinition,
10
+ type NumberExpression,
11
+ type OperatorParam,
12
+ type RecordField,
13
+ type SourceRange,
12
14
  } from "./ast";
13
15
  import { getKindString } from "./builtins";
14
16
  import { TlaEvaluationError } from "./errors";
@@ -34,11 +36,11 @@ import {
34
36
  getIntervalElements,
35
37
  getSequenceElements,
36
38
  getValueHash,
37
- isEnumerable,
38
39
  isFunctionValue,
39
40
  isOverriddenSet,
40
41
  isSameValue,
41
42
  markLambdaFunction,
43
+ isReducible,
42
44
  isSetValue,
43
45
  MAXIMUM_INTEGER,
44
46
  MINIMUM_INTEGER,
@@ -262,96 +264,6 @@ export const expectBoolean = (value: Value, description: string) => {
262
264
  return value;
263
265
  };
264
266
 
265
- export const getChildren = (expression: Expression): Expression[] => {
266
- switch (expression.kind) {
267
- case "Number":
268
- case "Decimal":
269
- case "String":
270
- case "Identifier":
271
- case "OperatorReference":
272
- case "ExceptAt":
273
- return [];
274
- case "Apply":
275
- return expression.args;
276
- case "Lambda":
277
- return [expression.body];
278
- case "And":
279
- case "Or":
280
- return expression.operands;
281
- case "Prime":
282
- case "Unchanged":
283
- case "Enabled":
284
- case "Always":
285
- case "Eventually":
286
- return [expression.expression];
287
- case "If":
288
- return [expression.condition, expression.consequent, expression.alternative];
289
- case "Case":
290
- return [
291
- ...expression.arms.flatMap((arm) => [arm.condition, arm.body]),
292
- ...(expression.other ? [expression.other] : []),
293
- ];
294
- case "Let":
295
- return [
296
- ...expression.definitions.flatMap((definition) =>
297
- definition.kind === "Function"
298
- ? [...definition.bounds.map((bound) => bound.set), definition.body]
299
- : [definition.body],
300
- ),
301
- expression.body,
302
- ];
303
- case "Forall":
304
- case "Exists":
305
- return [...expression.bounds.map((bound) => bound.set), expression.body];
306
- case "UnboundedQuantifier":
307
- return [expression.body];
308
- case "Choose":
309
- return [...(expression.set ? [expression.set] : []), expression.body];
310
- case "SetEnumeration":
311
- case "Tuple":
312
- return expression.elements;
313
- case "SetFilter":
314
- return [expression.bound.set, expression.predicate];
315
- case "SetMap":
316
- return [expression.expression, ...expression.bounds.map((bound) => bound.set)];
317
- case "FunctionConstruction":
318
- return [...expression.bounds.map((bound) => bound.set), expression.body];
319
- case "FunctionSet":
320
- return [expression.domain, expression.range];
321
- case "Record":
322
- case "RecordSet":
323
- return expression.fields.map((field) => field.value);
324
- case "Except":
325
- return [
326
- expression.function,
327
- ...expression.updates.flatMap((update) => [
328
- ...update.path.flatMap((step) => (step.kind === "Index" ? step.args : [])),
329
- update.value,
330
- ]),
331
- ];
332
- case "FunctionApplication":
333
- return [expression.function, ...expression.args];
334
- case "FieldAccess":
335
- return [expression.record];
336
- case "Product":
337
- return expression.factors;
338
- case "BoxAction":
339
- case "AngleAction":
340
- return [expression.action, expression.subscript];
341
- case "WeakFairness":
342
- case "StrongFairness":
343
- return [expression.subscript, expression.action];
344
- case "Label":
345
- return [expression.body];
346
- case "Subexpression":
347
- return expression.selectors.flatMap((selector) => ("args" in selector ? selector.args : []));
348
- }
349
- };
350
-
351
- export const isLocallyResolved = (expression: Expression) =>
352
- (expression.kind === "Identifier" || expression.kind === "Apply") &&
353
- expression.resolution?.kind === "Local";
354
-
355
267
  export const getDefinition = (name: string, environment: Environment) =>
356
268
  environment.definitions.get(environment.substitutions.get(name) ?? name);
357
269
 
@@ -859,11 +771,7 @@ const evaluateLocalIdentifier = (name: string, expression: Expression, context:
859
771
  const global = findGlobalName(name, context.environment);
860
772
  if (global?.kind === "Variable") {
861
773
  const value = context.state?.[global.index];
862
- if (value === undefined) {
863
- throw new TlaEvaluationError(
864
- `The variable ${name} is not assigned at ${describeLocation(expression)}`,
865
- );
866
- }
774
+ if (value === undefined) throw createUnassignedError(name, expression);
867
775
  return value;
868
776
  }
869
777
  if (global?.kind === "Value") return global.value;
@@ -1119,7 +1027,7 @@ export const getEvaluator = (expression: Expression, environment: Environment):
1119
1027
 
1120
1028
  const entryEvaluators = new WeakMap<Expression, Evaluator>();
1121
1029
 
1122
- const getEntryEvaluator = (expression: Expression, environment: Environment) => {
1030
+ export const getEntryEvaluator = (expression: Expression, environment: Environment) => {
1123
1031
  const cached = entryEvaluators.get(expression);
1124
1032
  if (cached) return cached;
1125
1033
  const evaluator =
@@ -1143,11 +1051,7 @@ const compileIdentifier = (
1143
1051
  const index = global.index;
1144
1052
  return (context) => {
1145
1053
  const value = context.state?.[index];
1146
- if (value === undefined) {
1147
- throw new TlaEvaluationError(
1148
- `The variable ${name} is not assigned at ${describeLocation(expression)}`,
1149
- );
1150
- }
1054
+ if (value === undefined) throw createUnassignedError(name, expression);
1151
1055
  return value;
1152
1056
  };
1153
1057
  }
@@ -1516,7 +1420,13 @@ const compileFunctionConstruction = (
1516
1420
  const set = getEvaluator(bound.set, environment);
1517
1421
  return (context) => {
1518
1422
  const domain = isSingleName ? set(context) : getBoundsDomain(bounds, context);
1519
- if (expression.isRecursive || isKeptLazy || !isEnumerable(domain)) {
1423
+ // TLC builds the function only when it reduces every domain, and evaluates the body lazily
1424
+ // otherwise.
1425
+ const domains =
1426
+ typeof domain === "object" && domain.kind === "ProductSet" && bounds.length > 1
1427
+ ? domain.factors
1428
+ : [domain];
1429
+ if (expression.isRecursive || isKeptLazy || !domains.every(isReducible)) {
1520
1430
  const functionValue = createLazyFunction(
1521
1431
  domain,
1522
1432
  (argument) => body(withScope(context, bindArgument(bounds, context.scope, argument))),
@@ -1610,10 +1520,7 @@ const compileSetComprehension = (
1610
1520
  predicate(withScope(context, bindPattern(context.scope, pattern, element))),
1611
1521
  "a set filter predicate",
1612
1522
  );
1613
- const isReducible =
1614
- typeof base === "object" &&
1615
- (base.kind === "Set" || base.kind === "MixedSet" || base.kind === "Interval");
1616
- if (!isReducible) {
1523
+ if (!isReducible(base)) {
1617
1524
  if (isSetValue(base)) return { kind: "FilteredSet", base, test };
1618
1525
  throw new TlaEvaluationError(
1619
1526
  `TLC encountered a non-enumerable quantifier bound ${formatValue(base)} at ${describeLocation(expression.bound.set)}`,
@@ -1659,11 +1566,24 @@ const compileSetComprehension = (
1659
1566
  };
1660
1567
  };
1661
1568
 
1662
- const compileRecord = (recordFields: RecordField[], environment: Environment): Evaluator => {
1663
- const fields = [...recordFields].sort((left, right) => compareValues(left.name, right.name));
1664
- const hasDuplicates = fields.some(
1665
- (field, index) => index > 0 && fields[index - 1].name === field.name,
1569
+ // TLC orders a record's fields by name.
1570
+ export const getSortedFields = (fields: RecordField[]) =>
1571
+ [...fields].sort((left, right) => compareValues(left.name, right.name));
1572
+
1573
+ export const hasDuplicateFields = (sortedFields: RecordField[]) =>
1574
+ sortedFields.some((field, index) => index > 0 && sortedFields[index - 1].name === field.name);
1575
+
1576
+ export const createUnassignedError = (name: string, expression: Expression) =>
1577
+ new TlaEvaluationError(`The variable ${name} is not assigned at ${describeLocation(expression)}`);
1578
+
1579
+ export const createPrimeOutsideActionError = (expression: Expression) =>
1580
+ new TlaEvaluationError(
1581
+ `A primed expression appears outside an action at ${describeLocation(expression)}`,
1666
1582
  );
1583
+
1584
+ const compileRecord = (recordFields: RecordField[], environment: Environment): Evaluator => {
1585
+ const fields = getSortedFields(recordFields);
1586
+ const hasDuplicates = hasDuplicateFields(fields);
1667
1587
  const values = fields.map((field) => getEvaluator(field.value, environment));
1668
1588
  if (hasDuplicates) {
1669
1589
  return (context) =>
@@ -1741,11 +1661,7 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
1741
1661
  case "Prime": {
1742
1662
  const inner = child(expression.expression);
1743
1663
  return (context) => {
1744
- if (!context.next) {
1745
- throw new TlaEvaluationError(
1746
- `A primed expression appears outside an action at ${describeLocation(expression)}`,
1747
- );
1748
- }
1664
+ if (!context.next) throw createPrimeOutsideActionError(expression);
1749
1665
  return inner({
1750
1666
  environment: context.environment,
1751
1667
  scope: context.scope,
@@ -1825,9 +1741,7 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
1825
1741
  case "Record":
1826
1742
  return compileRecord(expression.fields, environment);
1827
1743
  case "RecordSet": {
1828
- const fields = [...expression.fields].sort((left, right) =>
1829
- compareValues(left.name, right.name),
1830
- );
1744
+ const fields = getSortedFields(expression.fields);
1831
1745
  const names = fields.map((field) => field.name);
1832
1746
  const sets = fields.map((field) => child(field.value));
1833
1747
  return (context) => ({ kind: "RecordSet", names, sets: sets.map((set) => set(context)) });
package/src/exit-codes.ts CHANGED
@@ -17,12 +17,6 @@ export const EXIT_STATUS = {
17
17
  } as const;
18
18
 
19
19
  const exitCodes = new WeakMap<Error, number>();
20
- const moduleExitCodes = new WeakMap<Error, number>();
21
- const phase = { isNextState: false };
22
-
23
- export const setNextStatePhase = (isNextState: boolean) => {
24
- phase.isNextState = isNextState;
25
- };
26
20
 
27
21
  // The innermost site that knows TLC's exit status for an error sets it first and wins.
28
22
  export const setExitCode = <Thrown>(error: Thrown, code: number) => {
@@ -30,13 +24,7 @@ export const setExitCode = <Thrown>(error: Thrown, code: number) => {
30
24
  return error;
31
25
  };
32
26
 
33
- // TLC exits with the code of an exception from a standard module's Java code only when the exception
34
- // escapes the computation of next states. In every other phase, the phase decides the code.
35
- export const setModuleExitCode = (error: Error, code: number) => {
36
- if (phase.isNextState) moduleExitCodes.set(error, code);
37
- };
38
-
39
- export const getExitCode = (error: Error) => exitCodes.get(error) ?? moduleExitCodes.get(error);
27
+ export const getExitCode = (error: Error) => exitCodes.get(error);
40
28
 
41
29
  // TLC exits with 255 when it fails to process or evaluate a liveness property, in any phase.
42
30
  const withErrorExitCode = <Result>(run: () => Result) => {
package/src/instances.ts CHANGED
@@ -1,16 +1,17 @@
1
- import type {
2
- Bound,
3
- BoundPattern,
4
- Definition,
5
- Expression,
6
- Instance,
7
- Module,
8
- OperatorParam,
9
- SourceLocation,
10
- Theorem,
1
+ import {
2
+ getChildren,
3
+ isLocallyResolved,
4
+ type Bound,
5
+ type BoundPattern,
6
+ type Definition,
7
+ type Expression,
8
+ type Instance,
9
+ type Module,
10
+ type OperatorParam,
11
+ type SourceLocation,
12
+ type Theorem,
11
13
  } from "./ast";
12
14
  import { TlaSyntaxError } from "./errors";
13
- import { getChildren, isLocallyResolved } from "./evaluate";
14
15
  import { getArity, getBoundNames, getPatternNames, isBefore } from "./resolve";
15
16
 
16
17
  export const substitutedExpressions = new WeakSet<Expression>();
@@ -218,7 +219,7 @@ interface Instantiation {
218
219
  variables: Set<string>;
219
220
  getDefinition: (key: string) => Definition | undefined;
220
221
  isParameterized: (key: string) => boolean;
221
- addDefinition: (name: string, create: (key: string) => Definition) => string;
222
+ addDefinition: (source: string, name: string, create: (key: string) => Definition) => string;
222
223
  createName: (name: string) => string;
223
224
  }
224
225
 
@@ -639,7 +640,7 @@ const copyDefinition = (rewrite: Rewrite, key: string): string => {
639
640
  const instantiation = rewrite.instantiation;
640
641
  const definition = instantiation.getDefinition(key);
641
642
  if (!definition) return key;
642
- return instantiation.addDefinition(definition.name, (copyKey) => {
643
+ return instantiation.addDefinition(key, definition.name, (copyKey) => {
643
644
  rewrite.copies.set(key, copyKey);
644
645
  const rename = createRenamer(rewrite);
645
646
  const mapped = renameParams(
@@ -678,7 +679,7 @@ export const createInstantiation = (instantiation: Instantiation) => {
678
679
  if (copy !== undefined) return copy;
679
680
  const definition = instantiation.getDefinition(key);
680
681
  if (!definition) return key;
681
- return instantiation.addDefinition(definition.name, () =>
682
+ return instantiation.addDefinition(key, definition.name, () =>
682
683
  withInstanceParams(definition, instantiation.params, definition.location),
683
684
  );
684
685
  },
package/src/levels.ts CHANGED
@@ -1,13 +1,13 @@
1
- import type {
2
- AssumeProve,
3
- Definition,
4
- Expression,
5
- Module,
6
- OperatorParam,
7
- SourceLocation,
1
+ import {
2
+ getChildren,
3
+ type AssumeProve,
4
+ type Definition,
5
+ type Expression,
6
+ type Module,
7
+ type OperatorParam,
8
+ type SourceLocation,
8
9
  } from "./ast";
9
10
  import { TlaSyntaxError } from "./errors";
10
- import { getChildren } from "./evaluate";
11
11
  import { mapChildren } from "./instances";
12
12
  import { getBoundNames, getPatternNames } from "./resolve";
13
13
  import { STANDARD_LEVELS } from "./standard-levels";
package/src/live-check.ts CHANGED
@@ -2,6 +2,7 @@ import { TlaEvaluationError } from "./errors";
2
2
  import { hasRepeatedEffects, type Environment } from "./evaluate";
3
3
  import {
4
4
  evaluateLive,
5
+ TAUTOLOGY_MESSAGE,
5
6
  evaluateOnLasso,
6
7
  toLiveExpression,
7
8
  type ScopedExpression,
@@ -121,7 +122,7 @@ export const createLivenessChecker = (
121
122
  fairness.length === 0 ? violation : createJunction("And", [...fairness, violation]);
122
123
  const solutions = getSolutions(formula);
123
124
  if (solutions.length === 0) {
124
- throw new TlaEvaluationError("Temporal formula is a tautology (its negation is unsatisfiable)");
125
+ throw new TlaEvaluationError(TAUTOLOGY_MESSAGE);
125
126
  }
126
127
  const actionIds = new Map<string, number>();
127
128
  const checks = solutions.map((solution): Check => ({
package/src/liveness.ts CHANGED
@@ -1,14 +1,15 @@
1
- import type { Definition, Expression } from "./ast";
1
+ import { isLocallyResolved, type Definition, type Expression } from "./ast";
2
2
  import { TlaConfigError, TlaEvaluationError } from "./errors";
3
+ import { EXIT_STATUS, setExitCode } from "./exit-codes";
3
4
  import {
4
5
  describeLocation,
6
+ describeRange,
5
7
  bindDefinitions,
6
8
  bindOperatorArguments,
7
9
  evaluate,
8
10
  expectBoolean,
9
11
  forEachBinding,
10
12
  getDefinition,
11
- isLocallyResolved,
12
13
  lookupScope,
13
14
  resolveApplyOperator,
14
15
  resolveGlobalOperator,
@@ -37,6 +38,10 @@ export interface ScopedExpression {
37
38
  scope: Scope | undefined;
38
39
  }
39
40
 
41
+ export interface NamedExpression extends ScopedExpression {
42
+ name: string;
43
+ }
44
+
40
45
  export interface TemporalProperty extends ScopedExpression {
41
46
  name: string;
42
47
  }
@@ -145,21 +150,27 @@ const getDefinitionLevel = (definition: Definition, environment: Environment) =>
145
150
  return level;
146
151
  };
147
152
 
153
+ export const TAUTOLOGY_MESSAGE = "Temporal formula is a tautology (its negation is unsatisfiable).";
154
+
155
+ // TLC names each part of a property after the operator it expands, or after the location of the
156
+ // conjunct or quantifier body it splits off.
148
157
  export const expandTemporal = (
149
158
  expression: Expression,
150
159
  scope: Scope | undefined,
151
160
  environment: Environment,
152
- isUnrollingForall: boolean,
161
+ isProperty: boolean,
162
+ name = "",
153
163
  expanding = new Set<Definition>(),
154
- ): ScopedExpression[] => {
164
+ ): NamedExpression[] => {
155
165
  const expand = (
156
166
  child: Expression,
157
167
  childScope: Scope | undefined,
168
+ childName = name,
158
169
  childExpanding = expanding,
159
- ): ScopedExpression[] =>
160
- expandTemporal(child, childScope, environment, isUnrollingForall, childExpanding);
170
+ ): NamedExpression[] =>
171
+ expandTemporal(child, childScope, environment, isProperty, childName, childExpanding);
161
172
  if (expression.kind === "And") {
162
- return expression.operands.flatMap((operand) => expand(operand, scope));
173
+ return expression.operands.flatMap((operand) => expand(operand, scope, describeRange(operand)));
163
174
  }
164
175
  if (expression.kind === "Label") return expand(expression.body, scope);
165
176
  if (expression.kind === "Let") {
@@ -182,33 +193,58 @@ export const expandTemporal = (
182
193
  if (expanding.has(definition)) {
183
194
  throw new TlaConfigError(`The definition of ${expression.name} refers to itself`);
184
195
  }
185
- return expand(definition.body, undefined, new Set([...expanding, definition]));
196
+ return expand(
197
+ definition.body,
198
+ undefined,
199
+ expression.name,
200
+ new Set([...expanding, definition]),
201
+ );
186
202
  }
187
203
  }
188
204
  const context = getConstantContext(environment, scope);
189
- if (expression.kind === "Apply" && getLevel(expression, scope, environment) === TEMPORAL_LEVEL) {
205
+ // A property expands every operator it applies and unrolls every \A over constant sets, but a
206
+ // specification only expands the temporal ones.
207
+ const isExpanded = (child: Expression) =>
208
+ isProperty || getLevel(child, scope, environment) === TEMPORAL_LEVEL;
209
+ if (expression.kind === "Apply" && isExpanded(expression)) {
190
210
  const operator = resolveApplyOperator(expression, context);
191
211
  const definition = isLocallyResolved(expression)
192
212
  ? undefined
193
213
  : getDefinition(expression.operator, environment);
194
- if (operator?.kind === "Closure" && !definition?.isRecursive) {
195
- return expand(operator.body, bindOperatorArguments(operator, expression.args, context));
214
+ const isExpandable =
215
+ operator?.kind === "Closure" &&
216
+ operator.params.length === expression.args.length &&
217
+ !definition?.isRecursive;
218
+ if (isExpandable) {
219
+ return expand(
220
+ operator.body,
221
+ bindOperatorArguments(operator, expression.args, context),
222
+ expression.operator,
223
+ );
196
224
  }
197
225
  }
198
226
  const isUnrolled =
199
- isUnrollingForall &&
227
+ isProperty &&
200
228
  expression.kind === "Forall" &&
201
- getLevel(expression.body, scope, environment) === TEMPORAL_LEVEL &&
202
229
  expression.bounds.every((bound) => getLevel(bound.set, scope, environment) === 0);
203
230
  if (isUnrolled) {
204
- const expanded: ScopedExpression[] = [];
231
+ const expanded: NamedExpression[] = [];
232
+ const bindings = { count: 0 };
205
233
  forEachBinding(expression.bounds, context, (boundScope) => {
206
- expanded.push(...expand(expression.body, boundScope));
234
+ bindings.count++;
235
+ expanded.push(...expand(expression.body, boundScope, describeRange(expression.body)));
207
236
  return false;
208
237
  });
238
+ // TLC rejects a property that quantifies over no elements before it checks anything.
239
+ if (bindings.count === 0) {
240
+ throw setExitCode(
241
+ new TlaEvaluationError(TAUTOLOGY_MESSAGE),
242
+ EXIT_STATUS.livenessEvaluationFailure,
243
+ );
244
+ }
209
245
  return expanded;
210
246
  }
211
- return [{ expression, scope }];
247
+ return [{ expression, scope, name }];
212
248
  };
213
249
 
214
250
  const bindLetDefinitions = (