tla-ts 0.0.3-dev.30014f9 → 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.
Files changed (48) hide show
  1. package/README.md +5 -1
  2. package/dist/index.cjs +1 -1
  3. package/dist/index.d.cts +48 -22
  4. package/dist/index.d.ts +48 -22
  5. package/dist/index.js +1 -1
  6. package/dist/parallel-worker.cjs +1 -1
  7. package/dist/parallel-worker.js +2 -2
  8. package/dist/parallel.cjs +1 -1
  9. package/dist/parallel.js +2 -2
  10. package/dist/run-cli.cjs +19 -16
  11. package/dist/run-cli.js +20 -17
  12. package/dist/transfer.cjs +36 -15
  13. package/dist/transfer.js +36 -15
  14. package/package.json +1 -1
  15. package/src/ast.ts +93 -0
  16. package/src/check.ts +452 -98
  17. package/src/cli-options.ts +11 -5
  18. package/src/codegen.ts +15 -22
  19. package/src/config.ts +224 -170
  20. package/src/dependencies.ts +2 -2
  21. package/src/environment.ts +116 -28
  22. package/src/errors.ts +76 -3
  23. package/src/evaluate.ts +163 -156
  24. package/src/exit-codes.ts +39 -42
  25. package/src/instances.ts +16 -15
  26. package/src/levels.ts +62 -34
  27. package/src/live-check.ts +772 -0
  28. package/src/liveness.ts +120 -543
  29. package/src/parallel-worker.ts +2 -2
  30. package/src/parallel.ts +5 -2
  31. package/src/parser.ts +21 -10
  32. package/src/resolve.ts +122 -44
  33. package/src/run-cli.ts +92 -19
  34. package/src/runtime.ts +3 -1
  35. package/src/spec-description.ts +19 -8
  36. package/src/standard-modules.ts +9 -8
  37. package/src/state-graph.ts +157 -0
  38. package/src/subexpressions.ts +10 -10
  39. package/src/successors.ts +146 -35
  40. package/src/symmetry.ts +16 -6
  41. package/src/tableau.ts +51 -24
  42. package/src/tlc-ext.ts +29 -12
  43. package/src/tlc-module.ts +14 -33
  44. package/src/tlc-modules.ts +4 -0
  45. package/src/tlc-order.ts +8 -4
  46. package/src/tlc-random.ts +9 -6
  47. package/src/tlc-summary.ts +20 -5
  48. package/src/values.ts +124 -21
package/src/evaluate.ts CHANGED
@@ -1,18 +1,19 @@
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,
12
13
  } from "./ast";
13
14
  import { getKindString } from "./builtins";
14
- import { TlaEvaluationError } from "./errors";
15
- import { EXIT_STATUS, setExitCode } from "./exit-codes";
15
+ import { formatRange, TlaEvaluationError } from "./errors";
16
+ import { EXIT_STATUS, setExitCode, setOwnExitCode } from "./exit-codes";
16
17
  import { generateEvaluator } from "./codegen";
17
18
  import type { CheckerRuntime } from "./runtime";
18
19
  import { getReadVariables } from "./dependencies";
@@ -28,23 +29,27 @@ import {
28
29
  createSortedSet,
29
30
  createWrittenRecord,
30
31
  createTuple,
32
+ describeMissingField,
31
33
  formatValue,
32
34
  getDomain,
33
35
  getFunctionDomain,
34
36
  getIntervalElements,
35
37
  getSequenceElements,
36
38
  getValueHash,
37
- isEnumerable,
38
39
  isFunctionValue,
39
40
  isOverriddenSet,
41
+ isRecordValue,
40
42
  isSameValue,
41
43
  markLambdaFunction,
44
+ isReducible,
42
45
  isSetValue,
43
46
  MAXIMUM_INTEGER,
44
47
  MINIMUM_INTEGER,
45
48
  toFiniteSet,
46
49
  updateFunction,
47
50
  valuesEqual,
51
+ type FilteredSetValue,
52
+ type FunctionValue,
48
53
  type LazyFunctionSource,
49
54
  type LazyFunctionValue,
50
55
  type Value,
@@ -112,6 +117,7 @@ export interface Environment {
112
117
  definitionValues: Map<Definition, Value>;
113
118
  constantLevels: Map<Definition, boolean>;
114
119
  evaluators: WeakMap<Expression, Evaluator>;
120
+ trace?: Expression[];
115
121
  }
116
122
 
117
123
  export interface Context {
@@ -141,9 +147,6 @@ const EXCEPT_AT = "@";
141
147
  export const describeLocation = (expression: Expression) =>
142
148
  `line ${expression.location.line}, column ${expression.location.column}`;
143
149
 
144
- export const formatRange = (range: SourceRange) =>
145
- `line ${range.start.line}, col ${range.start.column} to line ${range.end.line}, col ${range.end.column} of module ${range.module}`;
146
-
147
150
  export const describeRange = (expression: Expression) => {
148
151
  const range = expression.location.range;
149
152
  return range ? formatRange(range) : describeLocation(expression);
@@ -180,8 +183,17 @@ export const getConjunctError = (
180
183
  };
181
184
 
182
185
  export const getFieldError =
183
- (expression: Expression & { kind: "FieldAccess" }) => (record: Value) =>
184
- `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)}`;
185
197
 
186
198
  export const getDomainOperator = (expression: Expression) => (value: Value) => {
187
199
  if (!isFunctionValue(value)) {
@@ -262,96 +274,6 @@ export const expectBoolean = (value: Value, description: string) => {
262
274
  return value;
263
275
  };
264
276
 
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
277
  export const getDefinition = (name: string, environment: Environment) =>
356
278
  environment.definitions.get(environment.substitutions.get(name) ?? name);
357
279
 
@@ -859,11 +781,7 @@ const evaluateLocalIdentifier = (name: string, expression: Expression, context:
859
781
  const global = findGlobalName(name, context.environment);
860
782
  if (global?.kind === "Variable") {
861
783
  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
- }
784
+ if (value === undefined) throw createUnassignedError(name, expression);
867
785
  return value;
868
786
  }
869
787
  if (global?.kind === "Value") return global.value;
@@ -889,14 +807,29 @@ const IMPURE_BUILTINS = new Set([
889
807
  export const isImpureBuiltin = (name: string, environment: Environment) =>
890
808
  IMPURE_BUILTINS.has(name) || environment.builtins.get(name)?.isStateLevel === true;
891
809
 
892
- const impureDefinitions = new WeakMap<Definition, boolean>();
810
+ interface Impurity {
811
+ builtins: Set<string>;
812
+ definitions: WeakMap<Definition, boolean>;
813
+ }
814
+
815
+ const ANY_EFFECT: Impurity = { builtins: IMPURE_BUILTINS, definitions: new WeakMap() };
816
+
817
+ // An Assert that held holds again, so evaluating it twice looks the same as evaluating it once.
818
+ const REPEATED_EFFECT: Impurity = {
819
+ builtins: new Set([...IMPURE_BUILTINS].filter((name) => name !== "Assert")),
820
+ definitions: new WeakMap(),
821
+ };
893
822
 
894
823
  const isEvaluatedOnce = (definition: Definition, environment: Environment) =>
895
824
  definition.kind === "Operator" &&
896
825
  definition.params.length === 0 &&
897
826
  isConstantLevel(definition, environment);
898
827
 
899
- const callsImpureBuiltin = (expression: Expression, environment: Environment): boolean => {
828
+ const callsImpureBuiltin = (
829
+ expression: Expression,
830
+ environment: Environment,
831
+ impurity: Impurity,
832
+ ): boolean => {
900
833
  const name =
901
834
  expression.kind === "Identifier"
902
835
  ? expression.name
@@ -905,29 +838,35 @@ const callsImpureBuiltin = (expression: Expression, environment: Environment): b
905
838
  : undefined;
906
839
  if (name !== undefined && !isLocallyResolved(expression)) {
907
840
  const definition = getDefinition(name, environment);
908
- if (!definition && isImpureBuiltin(name, environment)) return true;
841
+ const isImpureCall =
842
+ impurity.builtins.has(name) || environment.builtins.get(name)?.isStateLevel === true;
843
+ if (!definition && isImpureCall) return true;
909
844
  if (
910
845
  definition &&
911
846
  !isEvaluatedOnce(definition, environment) &&
912
- isImpureDefinition(definition, environment)
847
+ isImpureDefinition(definition, environment, impurity)
913
848
  ) {
914
849
  return true;
915
850
  }
916
851
  }
917
- return getChildren(expression).some((child) => callsImpureBuiltin(child, environment));
852
+ return getChildren(expression).some((child) => callsImpureBuiltin(child, environment, impurity));
918
853
  };
919
854
 
920
855
  // TLC evaluates a constant definition without parameters once, so only other definitions pass
921
856
  // on the side effects and random choices of the builtins they call.
922
- const isImpureDefinition = (definition: Definition, environment: Environment): boolean => {
923
- const cached = impureDefinitions.get(definition);
857
+ const isImpureDefinition = (
858
+ definition: Definition,
859
+ environment: Environment,
860
+ impurity = ANY_EFFECT,
861
+ ): boolean => {
862
+ const cached = impurity.definitions.get(definition);
924
863
  if (cached !== undefined) return cached;
925
- impureDefinitions.set(definition, false);
864
+ impurity.definitions.set(definition, false);
926
865
  const isImpure =
927
- callsImpureBuiltin(definition.body, environment) ||
866
+ callsImpureBuiltin(definition.body, environment, impurity) ||
928
867
  (definition.kind === "Function" &&
929
- definition.bounds.some((bound) => callsImpureBuiltin(bound.set, environment)));
930
- impureDefinitions.set(definition, isImpure);
868
+ definition.bounds.some((bound) => callsImpureBuiltin(bound.set, environment, impurity)));
869
+ impurity.definitions.set(definition, isImpure);
931
870
  return isImpure;
932
871
  };
933
872
 
@@ -941,6 +880,12 @@ export const isImpure = (environment: Environment) =>
941
880
  isImpureDefinition(definition, environment),
942
881
  );
943
882
 
883
+ // Whether evaluating a definition again can show, such as by printing twice.
884
+ export const hasRepeatedEffects = (environment: Environment) =>
885
+ [...environment.definitions.values()].some((definition) =>
886
+ isImpureDefinition(definition, environment, REPEATED_EFFECT),
887
+ );
888
+
944
889
  const closedConstants = new WeakMap<Expression, boolean>();
945
890
 
946
891
  export const isClosedConstant = (expression: Expression, environment: Environment): boolean => {
@@ -1076,23 +1021,46 @@ const isStateCached = (expression: Expression, environment: Environment) =>
1076
1021
  getReadVariables(expression, environment) !== undefined &&
1077
1022
  !hasFreeLocals(expression, NO_BOUND_NAMES);
1078
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
+
1079
1031
  export const getEvaluator = (expression: Expression, environment: Environment): Evaluator => {
1080
1032
  const cached = environment.evaluators.get(expression);
1081
1033
  if (cached) return cached;
1082
1034
  const compiled = compile(expression, environment);
1083
- const evaluator =
1035
+ const cachedEvaluator =
1084
1036
  isWorthCaching(expression) && isClosedConstant(expression, environment)
1085
1037
  ? cacheFirstValue(compiled)
1086
1038
  : isStateCached(expression, environment)
1087
1039
  ? cacheStateValue(compiled)
1088
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;
1089
1056
  environment.evaluators.set(expression, evaluator);
1090
1057
  return evaluator;
1091
1058
  };
1092
1059
 
1093
1060
  const entryEvaluators = new WeakMap<Expression, Evaluator>();
1094
1061
 
1095
- const getEntryEvaluator = (expression: Expression, environment: Environment) => {
1062
+ export const getEntryEvaluator = (expression: Expression, environment: Environment) => {
1063
+ if (environment.trace) return getEvaluator(expression, environment);
1096
1064
  const cached = entryEvaluators.get(expression);
1097
1065
  if (cached) return cached;
1098
1066
  const evaluator =
@@ -1116,11 +1084,7 @@ const compileIdentifier = (
1116
1084
  const index = global.index;
1117
1085
  return (context) => {
1118
1086
  const value = context.state?.[index];
1119
- if (value === undefined) {
1120
- throw new TlaEvaluationError(
1121
- `The variable ${name} is not assigned at ${describeLocation(expression)}`,
1122
- );
1123
- }
1087
+ if (value === undefined) throw createUnassignedError(name, expression);
1124
1088
  return value;
1125
1089
  };
1126
1090
  }
@@ -1394,6 +1358,11 @@ const compileApply = (
1394
1358
  if (definition?.kind === "Function") {
1395
1359
  throw new TlaEvaluationError(`${expression.operator} is a function; apply it with brackets`);
1396
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
+ }
1397
1366
  throw new TlaEvaluationError(
1398
1367
  `Unknown operator ${expression.operator} at ${describeLocation(expression)}`,
1399
1368
  );
@@ -1489,7 +1458,13 @@ const compileFunctionConstruction = (
1489
1458
  const set = getEvaluator(bound.set, environment);
1490
1459
  return (context) => {
1491
1460
  const domain = isSingleName ? set(context) : getBoundsDomain(bounds, context);
1492
- if (expression.isRecursive || isKeptLazy || !isEnumerable(domain)) {
1461
+ // TLC builds the function only when it reduces every domain, and evaluates the body lazily
1462
+ // otherwise.
1463
+ const domains =
1464
+ typeof domain === "object" && domain.kind === "ProductSet" && bounds.length > 1
1465
+ ? domain.factors
1466
+ : [domain];
1467
+ if (expression.isRecursive || isKeptLazy || !domains.every(isReducible)) {
1493
1468
  const functionValue = createLazyFunction(
1494
1469
  domain,
1495
1470
  (argument) => body(withScope(context, bindArgument(bounds, context.scope, argument))),
@@ -1578,16 +1553,21 @@ const compileSetComprehension = (
1578
1553
  const pattern = expression.bound.pattern;
1579
1554
  return (context) => {
1580
1555
  const base = set(context);
1581
- const test = (element: Value) =>
1556
+ const getTest = (evaluatePredicate: Evaluator) => (element: Value) =>
1582
1557
  expectBoolean(
1583
- predicate(withScope(context, bindPattern(context.scope, pattern, element))),
1558
+ evaluatePredicate(withScope(context, bindPattern(context.scope, pattern, element))),
1584
1559
  "a set filter predicate",
1585
1560
  );
1586
- const isReducible =
1587
- typeof base === "object" &&
1588
- (base.kind === "Set" || base.kind === "MixedSet" || base.kind === "Interval");
1589
- if (!isReducible) {
1590
- if (isSetValue(base)) return { kind: "FilteredSet", base, test };
1561
+ const test = getTest(predicate);
1562
+ if (!isReducible(base)) {
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
+ }
1591
1571
  throw new TlaEvaluationError(
1592
1572
  `TLC encountered a non-enumerable quantifier bound ${formatValue(base)} at ${describeLocation(expression.bound.set)}`,
1593
1573
  );
@@ -1632,11 +1612,29 @@ const compileSetComprehension = (
1632
1612
  };
1633
1613
  };
1634
1614
 
1635
- const compileRecord = (recordFields: RecordField[], environment: Environment): Evaluator => {
1636
- const fields = [...recordFields].sort((left, right) => compareValues(left.name, right.name));
1637
- const hasDuplicates = fields.some(
1638
- (field, index) => index > 0 && fields[index - 1].name === field.name,
1615
+ // TLC orders a record's fields by name.
1616
+ export const getSortedFields = (fields: RecordField[]) =>
1617
+ [...fields].sort((left, right) => compareValues(left.name, right.name));
1618
+
1619
+ export const hasDuplicateFields = (sortedFields: RecordField[]) =>
1620
+ sortedFields.some((field, index) => index > 0 && sortedFields[index - 1].name === field.name);
1621
+
1622
+ export const createUnassignedError = (name: string, expression: 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,
1639
1628
  );
1629
+
1630
+ export const createPrimeOutsideActionError = (expression: Expression) =>
1631
+ new TlaEvaluationError(
1632
+ `A primed expression appears outside an action at ${describeLocation(expression)}`,
1633
+ );
1634
+
1635
+ const compileRecord = (recordFields: RecordField[], environment: Environment): Evaluator => {
1636
+ const fields = getSortedFields(recordFields);
1637
+ const hasDuplicates = hasDuplicateFields(fields);
1640
1638
  const values = fields.map((field) => getEvaluator(field.value, environment));
1641
1639
  if (hasDuplicates) {
1642
1640
  return (context) =>
@@ -1714,11 +1712,7 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
1714
1712
  case "Prime": {
1715
1713
  const inner = child(expression.expression);
1716
1714
  return (context) => {
1717
- if (!context.next) {
1718
- throw new TlaEvaluationError(
1719
- `A primed expression appears outside an action at ${describeLocation(expression)}`,
1720
- );
1721
- }
1715
+ if (!context.next) throw createPrimeOutsideActionError(expression);
1722
1716
  return inner({
1723
1717
  environment: context.environment,
1724
1718
  scope: context.scope,
@@ -1757,7 +1751,9 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
1757
1751
  if (expectBoolean(arm.condition(context), "a CASE guard")) return arm.body(context);
1758
1752
  }
1759
1753
  if (other) return other(context);
1760
- throw new TlaEvaluationError(`No CASE guard is true at ${describeLocation(expression)}`);
1754
+ throw new TlaEvaluationError(
1755
+ `Attempted to evaluate a CASE with no conditions true.\n${describeRange(expression)}`,
1756
+ );
1761
1757
  };
1762
1758
  }
1763
1759
  case "Let": {
@@ -1796,9 +1792,7 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
1796
1792
  case "Record":
1797
1793
  return compileRecord(expression.fields, environment);
1798
1794
  case "RecordSet": {
1799
- const fields = [...expression.fields].sort((left, right) =>
1800
- compareValues(left.name, right.name),
1801
- );
1795
+ const fields = getSortedFields(expression.fields);
1802
1796
  const names = fields.map((field) => field.name);
1803
1797
  const sets = fields.map((field) => child(field.value));
1804
1798
  return (context) => ({ kind: "RecordSet", names, sets: sets.map((set) => set(context)) });
@@ -1819,18 +1813,31 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
1819
1813
  keepLazy(expression.function);
1820
1814
  const evaluateFunction = child(expression.function);
1821
1815
  const args = expression.args.map(child);
1816
+ const describeNonFunction = getNonFunctionError(expression);
1822
1817
  if (args.length === 1) {
1823
1818
  const argument = args[0];
1824
- return (context) => applyFunction(evaluateFunction(context), argument(context));
1819
+ return (context) =>
1820
+ applyFunction(
1821
+ evaluateFunction(context),
1822
+ argument(context),
1823
+ undefined,
1824
+ describeNonFunction,
1825
+ );
1825
1826
  }
1826
1827
  return (context) =>
1827
- 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
+ );
1828
1834
  }
1829
1835
  case "FieldAccess": {
1830
1836
  const record = child(expression.record);
1831
1837
  const field = expression.field;
1832
1838
  const describeMissing = getFieldError(expression);
1833
- return (context) => applyFunction(record(context), field, describeMissing);
1839
+ const describeNonRecord = getNonRecordError(expression);
1840
+ return (context) => applyFunction(record(context), field, describeMissing, describeNonRecord);
1834
1841
  }
1835
1842
  case "Product": {
1836
1843
  const factors = expression.factors.map(child);
package/src/exit-codes.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { LivenessChecker } from "./liveness";
1
+ import type { LivenessChecker } from "./live-check";
2
2
 
3
3
  // TLC's exit statuses, from EC.ExitStatus.
4
4
  export const EXIT_STATUS = {
@@ -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,46 +24,49 @@ 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);
27
+ export const getExitCode = (error: Error) => exitCodes.get(error);
28
+
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;
37
36
  };
38
37
 
39
- export const getExitCode = (error: Error) => exitCodes.get(error) ?? moduleExitCodes.get(error);
38
+ export const getOwnExitCode = (error: unknown) =>
39
+ error instanceof Error ? ownExitCodes.get(error) : undefined;
40
40
 
41
- // TLC exits with 255 when it fails to process or evaluate a liveness property, in any phase.
42
- export const withLivenessExitCode = (
43
- create: () => LivenessChecker | undefined,
44
- ): LivenessChecker | undefined => {
41
+ // TLC exits with 255 when it fails to process or evaluate a liveness property.
42
+ const withErrorExitCode = <Result>(run: () => Result) => {
45
43
  try {
46
- const checker = create();
47
- return (
48
- checker && {
49
- addInitialState: (index, state) => {
50
- try {
51
- checker.addInitialState(index, state);
52
- } catch (error) {
53
- throw setExitCode(error, EXIT_STATUS.error);
54
- }
55
- },
56
- addState: (index, state, successors) => {
57
- try {
58
- return checker.addState(index, state, successors);
59
- } catch (error) {
60
- throw setExitCode(error, EXIT_STATUS.error);
61
- }
62
- },
63
- findViolation: () => {
64
- try {
65
- return checker.findViolation();
66
- } catch (error) {
67
- throw setExitCode(error, EXIT_STATUS.error);
68
- }
69
- },
70
- }
71
- );
44
+ return run();
72
45
  } catch (error) {
73
46
  throw setExitCode(error, EXIT_STATUS.error);
74
47
  }
75
48
  };
49
+
50
+ export const withLivenessExitCode = (
51
+ create: () => LivenessChecker | undefined,
52
+ ): LivenessChecker | undefined => {
53
+ const checker = withErrorExitCode(create);
54
+ return (
55
+ checker && {
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
+ },
65
+ addState: (index, state, successors) =>
66
+ withErrorExitCode(() => checker.addState(index, state, successors)),
67
+ findViolation: () => withErrorExitCode(() => checker.findViolation()),
68
+ getViolatedProperties: (path, cycleStart) =>
69
+ withErrorExitCode(() => checker.getViolatedProperties(path, cycleStart)),
70
+ }
71
+ );
72
+ };
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>();
@@ -163,7 +164,7 @@ export const mapChildren = (
163
164
  case "RecordSet":
164
165
  return {
165
166
  ...expression,
166
- fields: expression.fields.map((field) => ({ name: field.name, value: plain(field.value) })),
167
+ fields: expression.fields.map((field) => ({ ...field, value: plain(field.value) })),
167
168
  };
168
169
  case "Except":
169
170
  return {
@@ -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
  },