tla-ts 0.0.3-dev.fb38eba → 0.0.3-dev.fd18eec

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/errors.ts CHANGED
@@ -1,10 +1,19 @@
1
+ import type { SourceRange } from "./ast";
1
2
  import { EXIT_STATUS, getExitCode } from "./exit-codes";
3
+ import type { Value } from "./values";
2
4
 
3
5
  // How TLC reports a RuntimeException it did not expect, such as one raised while computing next
4
6
  // states.
5
7
  export const UNEXPECTED_EXCEPTION =
6
8
  "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: ";
7
9
 
10
+ // How TLC reports a Java StackOverflowError, which V8 raises as this RangeError.
11
+ export const STACK_OVERFLOW =
12
+ "This was a Java StackOverflowError. It was probably the result\nof an incorrect recursive function definition that caused TLC to enter\nan infinite loop when trying to compute the function or its application\nto an element in its putative domain.";
13
+
14
+ export const isStackOverflow = (error: unknown) =>
15
+ error instanceof RangeError && error.message === "Maximum call stack size exceeded";
16
+
8
17
  export class TlaError extends Error {
9
18
  constructor(message: string, cause?: unknown) {
10
19
  super(message, { cause });
@@ -19,16 +28,44 @@ export interface SyntaxFailure {
19
28
  isEnd: boolean;
20
29
  }
21
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
+
22
43
  export class TlaSyntaxError extends TlaError {
23
44
  failure: SyntaxFailure | undefined;
45
+ sany: SanyReport | undefined;
24
46
 
25
- constructor(message: string, cause?: unknown, failure?: SyntaxFailure) {
47
+ constructor(message: string, cause?: unknown, failure?: SyntaxFailure, sany?: SanyReport) {
26
48
  super(message, cause);
27
49
  this.name = "TlaSyntaxError";
28
50
  this.failure = failure;
51
+ this.sany = sany;
29
52
  }
30
53
  }
31
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
+
32
69
  export class TlaConfigError extends TlaError {
33
70
  constructor(message: string, cause?: unknown) {
34
71
  super(message, cause);
@@ -55,6 +92,24 @@ export class TlaModuleError extends TlaEvaluationError {
55
92
  }
56
93
  }
57
94
 
95
+ // TLC reports a successor state that the next-state relation leaves incomplete as an error of its
96
+ // own, not as an exception. It keeps the name TlaEvaluationError, and index.ts doesn't export it.
97
+ export class TlaIncompleteStateError extends TlaEvaluationError {
98
+ state: (Value | undefined)[];
99
+ action: string | undefined;
100
+ missing: string[];
101
+
102
+ constructor(state: (Value | undefined)[], action: string | undefined, missing: string[]) {
103
+ super(
104
+ `Successor state is not completely specified by the next-state action. The following variable${missing.length > 1 ? "s are" : " is"} not defined: ${missing.join(", ")}.\n`,
105
+ );
106
+ this.name = "TlaEvaluationError";
107
+ this.state = state;
108
+ this.action = action;
109
+ this.missing = missing;
110
+ }
111
+ }
112
+
58
113
  export interface TlapmReport {
59
114
  failure?: string;
60
115
  exception?: string;
package/src/evaluate.ts CHANGED
@@ -10,11 +10,10 @@ import {
10
10
  type NumberExpression,
11
11
  type OperatorParam,
12
12
  type RecordField,
13
- type SourceRange,
14
13
  } from "./ast";
15
14
  import { getKindString } from "./builtins";
16
- import { TlaEvaluationError } from "./errors";
17
- import { EXIT_STATUS, setExitCode } from "./exit-codes";
15
+ import { formatRange, TlaEvaluationError } from "./errors";
16
+ import { EXIT_STATUS, setExitCode, setOwnExitCode } from "./exit-codes";
18
17
  import { generateEvaluator } from "./codegen";
19
18
  import type { CheckerRuntime } from "./runtime";
20
19
  import { getReadVariables } from "./dependencies";
@@ -30,23 +29,26 @@ import {
30
29
  createSortedSet,
31
30
  createWrittenRecord,
32
31
  createTuple,
32
+ describeMissingField,
33
33
  formatValue,
34
34
  getDomain,
35
35
  getFunctionDomain,
36
36
  getIntervalElements,
37
37
  getSequenceElements,
38
38
  getValueHash,
39
- isEnumerable,
40
39
  isFunctionValue,
41
40
  isOverriddenSet,
41
+ isRecordValue,
42
42
  isSameValue,
43
43
  markLambdaFunction,
44
+ isReducible,
44
45
  isSetValue,
45
46
  MAXIMUM_INTEGER,
46
47
  MINIMUM_INTEGER,
47
48
  toFiniteSet,
48
49
  updateFunction,
49
50
  valuesEqual,
51
+ type FunctionValue,
50
52
  type LazyFunctionSource,
51
53
  type LazyFunctionValue,
52
54
  type Value,
@@ -143,9 +145,6 @@ const EXCEPT_AT = "@";
143
145
  export const describeLocation = (expression: Expression) =>
144
146
  `line ${expression.location.line}, column ${expression.location.column}`;
145
147
 
146
- export const formatRange = (range: SourceRange) =>
147
- `line ${range.start.line}, col ${range.start.column} to line ${range.end.line}, col ${range.end.column} of module ${range.module}`;
148
-
149
148
  export const describeRange = (expression: Expression) => {
150
149
  const range = expression.location.range;
151
150
  return range ? formatRange(range) : describeLocation(expression);
@@ -182,8 +181,17 @@ export const getConjunctError = (
182
181
  };
183
182
 
184
183
  export const getFieldError =
185
- (expression: Expression & { kind: "FieldAccess" }) => (record: Value) =>
186
- `Attempted to select nonexistent field "${expression.field}" from the record\n${formatValue(record)}\n${describeRange(expression)}`;
184
+ (expression: Expression & { kind: "FieldAccess" }) => (record: FunctionValue) =>
185
+ isRecordValue(record)
186
+ ? `Attempted to select nonexistent field "${expression.field}" from the record\n${formatValue(record)}\n${describeRange(expression)}`
187
+ : describeMissingField(record, expression.field);
188
+
189
+ export const getNonFunctionError = (expression: Expression) => (value: Value) =>
190
+ `A non-function (${getKindString(value)}) was applied as a function.\n${describeRange(expression)}`;
191
+
192
+ export const getNonRecordError =
193
+ (expression: Expression & { kind: "FieldAccess" }) => (value: Value) =>
194
+ `Attempted to select field "${expression.field}" from a non-record value ${formatValue(value)}\n${describeRange(expression)}`;
187
195
 
188
196
  export const getDomainOperator = (expression: Expression) => (value: Value) => {
189
197
  if (!isFunctionValue(value)) {
@@ -1027,7 +1035,7 @@ export const getEvaluator = (expression: Expression, environment: Environment):
1027
1035
 
1028
1036
  const entryEvaluators = new WeakMap<Expression, Evaluator>();
1029
1037
 
1030
- const getEntryEvaluator = (expression: Expression, environment: Environment) => {
1038
+ export const getEntryEvaluator = (expression: Expression, environment: Environment) => {
1031
1039
  const cached = entryEvaluators.get(expression);
1032
1040
  if (cached) return cached;
1033
1041
  const evaluator =
@@ -1325,6 +1333,11 @@ const compileApply = (
1325
1333
  if (definition?.kind === "Function") {
1326
1334
  throw new TlaEvaluationError(`${expression.operator} is a function; apply it with brackets`);
1327
1335
  }
1336
+ if (expression.operator === "\\cdot") {
1337
+ throw new TlaEvaluationError(
1338
+ "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.",
1339
+ );
1340
+ }
1328
1341
  throw new TlaEvaluationError(
1329
1342
  `Unknown operator ${expression.operator} at ${describeLocation(expression)}`,
1330
1343
  );
@@ -1420,7 +1433,13 @@ const compileFunctionConstruction = (
1420
1433
  const set = getEvaluator(bound.set, environment);
1421
1434
  return (context) => {
1422
1435
  const domain = isSingleName ? set(context) : getBoundsDomain(bounds, context);
1423
- if (expression.isRecursive || isKeptLazy || !isEnumerable(domain)) {
1436
+ // TLC builds the function only when it reduces every domain, and evaluates the body lazily
1437
+ // otherwise.
1438
+ const domains =
1439
+ typeof domain === "object" && domain.kind === "ProductSet" && bounds.length > 1
1440
+ ? domain.factors
1441
+ : [domain];
1442
+ if (expression.isRecursive || isKeptLazy || !domains.every(isReducible)) {
1424
1443
  const functionValue = createLazyFunction(
1425
1444
  domain,
1426
1445
  (argument) => body(withScope(context, bindArgument(bounds, context.scope, argument))),
@@ -1514,10 +1533,7 @@ const compileSetComprehension = (
1514
1533
  predicate(withScope(context, bindPattern(context.scope, pattern, element))),
1515
1534
  "a set filter predicate",
1516
1535
  );
1517
- const isReducible =
1518
- typeof base === "object" &&
1519
- (base.kind === "Set" || base.kind === "MixedSet" || base.kind === "Interval");
1520
- if (!isReducible) {
1536
+ if (!isReducible(base)) {
1521
1537
  if (isSetValue(base)) return { kind: "FilteredSet", base, test };
1522
1538
  throw new TlaEvaluationError(
1523
1539
  `TLC encountered a non-enumerable quantifier bound ${formatValue(base)} at ${describeLocation(expression.bound.set)}`,
@@ -1571,7 +1587,12 @@ export const hasDuplicateFields = (sortedFields: RecordField[]) =>
1571
1587
  sortedFields.some((field, index) => index > 0 && sortedFields[index - 1].name === field.name);
1572
1588
 
1573
1589
  export const createUnassignedError = (name: string, expression: Expression) =>
1574
- new TlaEvaluationError(`The variable ${name} is not assigned at ${describeLocation(expression)}`);
1590
+ setOwnExitCode(
1591
+ new TlaEvaluationError(
1592
+ `In evaluation, the identifier ${name} is either undefined or not an operator.\n${describeRange(expression)}`,
1593
+ ),
1594
+ EXIT_STATUS.configParseError,
1595
+ );
1575
1596
 
1576
1597
  export const createPrimeOutsideActionError = (expression: Expression) =>
1577
1598
  new TlaEvaluationError(
@@ -1759,18 +1780,31 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
1759
1780
  keepLazy(expression.function);
1760
1781
  const evaluateFunction = child(expression.function);
1761
1782
  const args = expression.args.map(child);
1783
+ const describeNonFunction = getNonFunctionError(expression);
1762
1784
  if (args.length === 1) {
1763
1785
  const argument = args[0];
1764
- return (context) => applyFunction(evaluateFunction(context), argument(context));
1786
+ return (context) =>
1787
+ applyFunction(
1788
+ evaluateFunction(context),
1789
+ argument(context),
1790
+ undefined,
1791
+ describeNonFunction,
1792
+ );
1765
1793
  }
1766
1794
  return (context) =>
1767
- applyFunction(evaluateFunction(context), createTuple(args.map((arg) => arg(context))));
1795
+ applyFunction(
1796
+ evaluateFunction(context),
1797
+ createTuple(args.map((arg) => arg(context))),
1798
+ undefined,
1799
+ describeNonFunction,
1800
+ );
1768
1801
  }
1769
1802
  case "FieldAccess": {
1770
1803
  const record = child(expression.record);
1771
1804
  const field = expression.field;
1772
1805
  const describeMissing = getFieldError(expression);
1773
- return (context) => applyFunction(record(context), field, describeMissing);
1806
+ const describeNonRecord = getNonRecordError(expression);
1807
+ return (context) => applyFunction(record(context), field, describeMissing, describeNonRecord);
1774
1808
  }
1775
1809
  case "Product": {
1776
1810
  const factors = expression.factors.map(child);
package/src/exit-codes.ts CHANGED
@@ -26,7 +26,19 @@ export const setExitCode = <Thrown>(error: Thrown, code: number) => {
26
26
 
27
27
  export const getExitCode = (error: Error) => exitCodes.get(error);
28
28
 
29
- // TLC exits with 255 when it fails to process or evaluate a liveness property, in any phase.
29
+ const ownExitCodes = new WeakMap<Error, number>();
30
+
31
+ // The exit status of the error code TLC gives an EvalException, which TLC uses only where it
32
+ // doesn't report the error again as a nested expression.
33
+ export const setOwnExitCode = <Thrown extends Error>(error: Thrown, code: number) => {
34
+ ownExitCodes.set(error, code);
35
+ return error;
36
+ };
37
+
38
+ export const getOwnExitCode = (error: unknown) =>
39
+ error instanceof Error ? ownExitCodes.get(error) : undefined;
40
+
41
+ // TLC exits with 255 when it fails to process or evaluate a liveness property.
30
42
  const withErrorExitCode = <Result>(run: () => Result) => {
31
43
  try {
32
44
  return run();
@@ -41,8 +53,15 @@ export const withLivenessExitCode = (
41
53
  const checker = withErrorExitCode(create);
42
54
  return (
43
55
  checker && {
44
- addInitialState: (index, state) =>
45
- withErrorExitCode(() => checker.addInitialState(index, state)),
56
+ // TLC replays the initial states to report an error, but skips the liveness check of a
57
+ // state it has already seen, so it exits with the status of the error's own code.
58
+ addInitialState: (index, state) => {
59
+ try {
60
+ checker.addInitialState(index, state);
61
+ } catch (error) {
62
+ throw setExitCode(error, getOwnExitCode(error) ?? EXIT_STATUS.error);
63
+ }
64
+ },
46
65
  addState: (index, state, successors) =>
47
66
  withErrorExitCode(() => checker.addState(index, state, successors)),
48
67
  findViolation: () => withErrorExitCode(() => checker.findViolation()),
package/src/instances.ts CHANGED
@@ -219,7 +219,7 @@ interface Instantiation {
219
219
  variables: Set<string>;
220
220
  getDefinition: (key: string) => Definition | undefined;
221
221
  isParameterized: (key: string) => boolean;
222
- addDefinition: (name: string, create: (key: string) => Definition) => string;
222
+ addDefinition: (source: string, name: string, create: (key: string) => Definition) => string;
223
223
  createName: (name: string) => string;
224
224
  }
225
225
 
@@ -640,7 +640,7 @@ const copyDefinition = (rewrite: Rewrite, key: string): string => {
640
640
  const instantiation = rewrite.instantiation;
641
641
  const definition = instantiation.getDefinition(key);
642
642
  if (!definition) return key;
643
- return instantiation.addDefinition(definition.name, (copyKey) => {
643
+ return instantiation.addDefinition(key, definition.name, (copyKey) => {
644
644
  rewrite.copies.set(key, copyKey);
645
645
  const rename = createRenamer(rewrite);
646
646
  const mapped = renameParams(
@@ -679,7 +679,7 @@ export const createInstantiation = (instantiation: Instantiation) => {
679
679
  if (copy !== undefined) return copy;
680
680
  const definition = instantiation.getDefinition(key);
681
681
  if (!definition) return key;
682
- return instantiation.addDefinition(definition.name, () =>
682
+ return instantiation.addDefinition(key, definition.name, () =>
683
683
  withInstanceParams(definition, instantiation.params, definition.location),
684
684
  );
685
685
  },