tla-ts 0.0.3-dev.9c2dda8 → 0.0.3-dev.b1578d0

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,7 +17,6 @@ import { EXIT_STATUS, setExitCode } from "./exit-codes";
16
17
  import {
17
18
  createBigNumberError,
18
19
  createRealNumberError,
19
- getChildren,
20
20
  isConstantLevel,
21
21
  isTlcInteger,
22
22
  type Builtin,
package/src/errors.ts CHANGED
@@ -1,4 +1,9 @@
1
- import { EXIT_STATUS, getExitCode, setModuleExitCode } from "./exit-codes";
1
+ import { EXIT_STATUS, getExitCode } from "./exit-codes";
2
+
3
+ // How TLC reports a RuntimeException it did not expect, such as one raised while computing next
4
+ // states.
5
+ export const UNEXPECTED_EXCEPTION =
6
+ "TLC threw an unexpected exception.\nThis was probably caused by an error in the spec or model.\nSee the User Output or TLC Console for clues to what happened.\nThe exception was a java.lang.RuntimeException\n: ";
2
7
 
3
8
  export class TlaError extends Error {
4
9
  constructor(message: string, cause?: unknown) {
@@ -41,10 +46,12 @@ export class TlaEvaluationError extends TlaError {
41
46
  // An evaluation error that TLC raises as an EvalException from a standard module's Java code. It
42
47
  // keeps the name TlaEvaluationError, and index.ts doesn't export it.
43
48
  export class TlaModuleError extends TlaEvaluationError {
49
+ exitCode: number;
50
+
44
51
  constructor(message: string, exitCode: number = EXIT_STATUS.error) {
45
52
  super(message);
46
53
  this.name = "TlaEvaluationError";
47
- setModuleExitCode(this, exitCode);
54
+ this.exitCode = exitCode;
48
55
  }
49
56
  }
50
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";
@@ -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;
@@ -889,14 +797,29 @@ const IMPURE_BUILTINS = new Set([
889
797
  export const isImpureBuiltin = (name: string, environment: Environment) =>
890
798
  IMPURE_BUILTINS.has(name) || environment.builtins.get(name)?.isStateLevel === true;
891
799
 
892
- const impureDefinitions = new WeakMap<Definition, boolean>();
800
+ interface Impurity {
801
+ builtins: Set<string>;
802
+ definitions: WeakMap<Definition, boolean>;
803
+ }
804
+
805
+ const ANY_EFFECT: Impurity = { builtins: IMPURE_BUILTINS, definitions: new WeakMap() };
806
+
807
+ // An Assert that held holds again, so evaluating it twice looks the same as evaluating it once.
808
+ const REPEATED_EFFECT: Impurity = {
809
+ builtins: new Set([...IMPURE_BUILTINS].filter((name) => name !== "Assert")),
810
+ definitions: new WeakMap(),
811
+ };
893
812
 
894
813
  const isEvaluatedOnce = (definition: Definition, environment: Environment) =>
895
814
  definition.kind === "Operator" &&
896
815
  definition.params.length === 0 &&
897
816
  isConstantLevel(definition, environment);
898
817
 
899
- const callsImpureBuiltin = (expression: Expression, environment: Environment): boolean => {
818
+ const callsImpureBuiltin = (
819
+ expression: Expression,
820
+ environment: Environment,
821
+ impurity: Impurity,
822
+ ): boolean => {
900
823
  const name =
901
824
  expression.kind === "Identifier"
902
825
  ? expression.name
@@ -905,29 +828,35 @@ const callsImpureBuiltin = (expression: Expression, environment: Environment): b
905
828
  : undefined;
906
829
  if (name !== undefined && !isLocallyResolved(expression)) {
907
830
  const definition = getDefinition(name, environment);
908
- if (!definition && isImpureBuiltin(name, environment)) return true;
831
+ const isImpureCall =
832
+ impurity.builtins.has(name) || environment.builtins.get(name)?.isStateLevel === true;
833
+ if (!definition && isImpureCall) return true;
909
834
  if (
910
835
  definition &&
911
836
  !isEvaluatedOnce(definition, environment) &&
912
- isImpureDefinition(definition, environment)
837
+ isImpureDefinition(definition, environment, impurity)
913
838
  ) {
914
839
  return true;
915
840
  }
916
841
  }
917
- return getChildren(expression).some((child) => callsImpureBuiltin(child, environment));
842
+ return getChildren(expression).some((child) => callsImpureBuiltin(child, environment, impurity));
918
843
  };
919
844
 
920
845
  // TLC evaluates a constant definition without parameters once, so only other definitions pass
921
846
  // 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);
847
+ const isImpureDefinition = (
848
+ definition: Definition,
849
+ environment: Environment,
850
+ impurity = ANY_EFFECT,
851
+ ): boolean => {
852
+ const cached = impurity.definitions.get(definition);
924
853
  if (cached !== undefined) return cached;
925
- impureDefinitions.set(definition, false);
854
+ impurity.definitions.set(definition, false);
926
855
  const isImpure =
927
- callsImpureBuiltin(definition.body, environment) ||
856
+ callsImpureBuiltin(definition.body, environment, impurity) ||
928
857
  (definition.kind === "Function" &&
929
- definition.bounds.some((bound) => callsImpureBuiltin(bound.set, environment)));
930
- impureDefinitions.set(definition, isImpure);
858
+ definition.bounds.some((bound) => callsImpureBuiltin(bound.set, environment, impurity)));
859
+ impurity.definitions.set(definition, isImpure);
931
860
  return isImpure;
932
861
  };
933
862
 
@@ -941,6 +870,12 @@ export const isImpure = (environment: Environment) =>
941
870
  isImpureDefinition(definition, environment),
942
871
  );
943
872
 
873
+ // Whether evaluating a definition again can show, such as by printing twice.
874
+ export const hasRepeatedEffects = (environment: Environment) =>
875
+ [...environment.definitions.values()].some((definition) =>
876
+ isImpureDefinition(definition, environment, REPEATED_EFFECT),
877
+ );
878
+
944
879
  const closedConstants = new WeakMap<Expression, boolean>();
945
880
 
946
881
  export const isClosedConstant = (expression: Expression, environment: Environment): boolean => {
@@ -1116,11 +1051,7 @@ const compileIdentifier = (
1116
1051
  const index = global.index;
1117
1052
  return (context) => {
1118
1053
  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
- }
1054
+ if (value === undefined) throw createUnassignedError(name, expression);
1124
1055
  return value;
1125
1056
  };
1126
1057
  }
@@ -1632,11 +1563,24 @@ const compileSetComprehension = (
1632
1563
  };
1633
1564
  };
1634
1565
 
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,
1566
+ // TLC orders a record's fields by name.
1567
+ export const getSortedFields = (fields: RecordField[]) =>
1568
+ [...fields].sort((left, right) => compareValues(left.name, right.name));
1569
+
1570
+ export const hasDuplicateFields = (sortedFields: RecordField[]) =>
1571
+ sortedFields.some((field, index) => index > 0 && sortedFields[index - 1].name === field.name);
1572
+
1573
+ export const createUnassignedError = (name: string, expression: Expression) =>
1574
+ new TlaEvaluationError(`The variable ${name} is not assigned at ${describeLocation(expression)}`);
1575
+
1576
+ export const createPrimeOutsideActionError = (expression: Expression) =>
1577
+ new TlaEvaluationError(
1578
+ `A primed expression appears outside an action at ${describeLocation(expression)}`,
1639
1579
  );
1580
+
1581
+ const compileRecord = (recordFields: RecordField[], environment: Environment): Evaluator => {
1582
+ const fields = getSortedFields(recordFields);
1583
+ const hasDuplicates = hasDuplicateFields(fields);
1640
1584
  const values = fields.map((field) => getEvaluator(field.value, environment));
1641
1585
  if (hasDuplicates) {
1642
1586
  return (context) =>
@@ -1714,11 +1658,7 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
1714
1658
  case "Prime": {
1715
1659
  const inner = child(expression.expression);
1716
1660
  return (context) => {
1717
- if (!context.next) {
1718
- throw new TlaEvaluationError(
1719
- `A primed expression appears outside an action at ${describeLocation(expression)}`,
1720
- );
1721
- }
1661
+ if (!context.next) throw createPrimeOutsideActionError(expression);
1722
1662
  return inner({
1723
1663
  environment: context.environment,
1724
1664
  scope: context.scope,
@@ -1757,7 +1697,9 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
1757
1697
  if (expectBoolean(arm.condition(context), "a CASE guard")) return arm.body(context);
1758
1698
  }
1759
1699
  if (other) return other(context);
1760
- throw new TlaEvaluationError(`No CASE guard is true at ${describeLocation(expression)}`);
1700
+ throw new TlaEvaluationError(
1701
+ `Attempted to evaluate a CASE with no conditions true.\n${describeRange(expression)}`,
1702
+ );
1761
1703
  };
1762
1704
  }
1763
1705
  case "Let": {
@@ -1796,9 +1738,7 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
1796
1738
  case "Record":
1797
1739
  return compileRecord(expression.fields, environment);
1798
1740
  case "RecordSet": {
1799
- const fields = [...expression.fields].sort((left, right) =>
1800
- compareValues(left.name, right.name),
1801
- );
1741
+ const fields = getSortedFields(expression.fields);
1802
1742
  const names = fields.map((field) => field.name);
1803
1743
  const sets = fields.map((field) => child(field.value));
1804
1744
  return (context) => ({ kind: "RecordSet", names, sets: sets.map((set) => set(context)) });
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,30 @@ 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
- export const withLivenessExitCode = (
43
- create: () => LivenessChecker | undefined,
44
- ): LivenessChecker | undefined => {
30
+ const withErrorExitCode = <Result>(run: () => Result) => {
45
31
  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
- );
32
+ return run();
72
33
  } catch (error) {
73
34
  throw setExitCode(error, EXIT_STATUS.error);
74
35
  }
75
36
  };
37
+
38
+ export const withLivenessExitCode = (
39
+ create: () => LivenessChecker | undefined,
40
+ ): LivenessChecker | undefined => {
41
+ const checker = withErrorExitCode(create);
42
+ return (
43
+ checker && {
44
+ addInitialState: (index, state) =>
45
+ withErrorExitCode(() => checker.addInitialState(index, state)),
46
+ addState: (index, state, successors) =>
47
+ withErrorExitCode(() => checker.addState(index, state, successors)),
48
+ findViolation: () => withErrorExitCode(() => checker.findViolation()),
49
+ getViolatedProperties: (path, cycleStart) =>
50
+ withErrorExitCode(() => checker.getViolatedProperties(path, cycleStart)),
51
+ }
52
+ );
53
+ };
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>();
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";