tla-ts 0.0.3-dev.a57ca4f → 0.0.3-dev.b0d11a3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tla-ts",
3
- "version": "0.0.3-dev.a57ca4f",
3
+ "version": "0.0.3-dev.b0d11a3",
4
4
  "description": "A TLA+ interpreter and model checker in TypeScript, 2× faster than TLC",
5
5
  "keywords": [
6
6
  "formal verification",
package/src/check.ts CHANGED
@@ -11,8 +11,11 @@ import { getReadVariables } from "./dependencies";
11
11
  import { createEnvironment } from "./environment";
12
12
  import {
13
13
  getErrorExitCode,
14
+ isStackOverflow,
15
+ STACK_OVERFLOW,
14
16
  TlaConfigError,
15
17
  TlaEvaluationError,
18
+ TlaIncompleteStateError,
16
19
  TlaModuleError,
17
20
  UNEXPECTED_EXCEPTION,
18
21
  } from "./errors";
@@ -59,7 +62,7 @@ import {
59
62
  type StateWriter,
60
63
  } from "./state-graph";
61
64
  import { getRepresentative, getSymmetryGroup } from "./symmetry";
62
- import { getTlcStringOrder, getTlcVariableOrder } from "./tlc-order";
65
+ import { getTlcStringOrder, getTlcDeclarationOrder } from "./tlc-order";
63
66
  import { createTlcFingerprinter, getTlcFingerprint } from "./tlc-random";
64
67
  import { createCanonicalizer } from "./canonical";
65
68
  import { getPossibleCounts, type CheckerRuntime } from "./runtime";
@@ -67,6 +70,7 @@ import { createCounterExample } from "./tlc-ext";
67
70
  import { getFingerprintDistance, OUT_DEGREE_BUCKETS } from "./tlc-summary";
68
71
  import {
69
72
  combineHash,
73
+ createModelValue,
70
74
  formatState,
71
75
  formatValue,
72
76
  getValueHash,
@@ -247,7 +251,7 @@ const getConstantValue = (name: string, definition: Definition, environment: Env
247
251
  try {
248
252
  return evaluate(createIdentifier(name), getContext(environment, undefined, undefined));
249
253
  } catch (error) {
250
- if (error instanceof TlaEvaluationError) return undefined;
254
+ if (error instanceof TlaEvaluationError || isStackOverflow(error)) return undefined;
251
255
  throw error;
252
256
  }
253
257
  };
@@ -276,8 +280,11 @@ const getInvariants = (names: string[], environment: Environment) => {
276
280
  levels.params.size === 0
277
281
  ? ""
278
282
  : "\nNote that a bug can cause TLC to incorrectly report this error.\nIf you believe your TLA+ or PlusCal specification to be correct,\nplease check if this bug described in LevelNode.java starting at line 590ff affects you.";
279
- throw new TlaConfigError(
280
- `The invariant ${name} is not a state predicate (one with no primes or temporal operators).${note}`,
283
+ throw setExitCode(
284
+ new TlaConfigError(
285
+ `The invariant ${name} is not a state predicate (one with no primes or temporal operators).${note}`,
286
+ ),
287
+ EXIT_STATUS.safetyEvaluationFailure,
281
288
  );
282
289
  }
283
290
  return [{ name, expression: createIdentifier(name), scope: undefined }];
@@ -375,8 +382,11 @@ const getSpecification = (config: ModelConfig, environment: Environment): Specif
375
382
  conjunct.kind === "Always" &&
376
383
  getLevel(conjunct.expression, item.scope, environment) < ACTION_LEVEL
377
384
  ) {
378
- throw new TlaConfigError(
379
- `TLC cannot handle []P in the specification ${config.specification} when P is a state predicate`,
385
+ throw setExitCode(
386
+ new TlaConfigError(
387
+ `TLC cannot handle the temporal formula ${describeRange(conjunct.expression)}`,
388
+ ),
389
+ EXIT_STATUS.error,
380
390
  );
381
391
  }
382
392
  const level = getLevel(conjunct, item.scope, environment);
@@ -787,11 +797,13 @@ export const createSearch = (
787
797
  if (view !== undefined || isFingerprintedLikeTlc) {
788
798
  return BigInt64Array.from(states, getTlcStateFingerprint);
789
799
  }
790
- const indices = getTlcOrder();
791
- const getFingerprint = createTlcFingerprinter();
792
- return BigInt64Array.from(fingerprintStates, (state) =>
793
- getFingerprint(indices.map((index) => state[index])),
800
+ const fingerprints = new BigInt64Array(fingerprintStates.length);
801
+ const fingerprint = createTlcFingerprinter(
802
+ getTlcOrder(),
803
+ new Int32Array(fingerprints.buffer),
794
804
  );
805
+ fingerprintStates.forEach(fingerprint);
806
+ return fingerprints;
795
807
  },
796
808
  getFingerprintState: (state) => {
797
809
  if (isFingerprintedLikeTlc) return [String(getTlcStateFingerprint(state))];
@@ -897,6 +909,18 @@ export const createSearch = (
897
909
  const withNextStateExitCode = (error: unknown) =>
898
910
  error instanceof TlaModuleError ? setExitCode(error, error.exitCode) : error;
899
911
 
912
+ // TLC reports a failure of the next-state relation as an unexpected exception, unless a standard
913
+ // module raised it as an EvalException.
914
+ const toNextStateError = (error: unknown) =>
915
+ error instanceof TlaEvaluationError &&
916
+ !(error instanceof TlaModuleError) &&
917
+ !(error instanceof TlaIncompleteStateError)
918
+ ? setExitCode(
919
+ new TlaEvaluationError(`${UNEXPECTED_EXCEPTION}${error.message}`, error),
920
+ getErrorExitCode(error),
921
+ )
922
+ : withNextStateExitCode(error);
923
+
900
924
  const withHeadline = (error: unknown, headline: string) =>
901
925
  error instanceof TlaEvaluationError
902
926
  ? setExitCode(
@@ -908,9 +932,16 @@ const withHeadline = (error: unknown, headline: string) =>
908
932
  // TLC finishes the -dump file whether or not the search finds a violation.
909
933
  export const checkSequentially = (options: CheckOptions): CheckResult => {
910
934
  const stateWriter = options.dump && createStateWriter(options.dump, options.writeFile);
911
- const result = searchStates(options, stateWriter);
912
- stateWriter?.close();
913
- return result;
935
+ try {
936
+ return searchStates(options, stateWriter);
937
+ } catch (error) {
938
+ // TLC reports a stack overflow outside the search as a failure of its own, with exit code 255.
939
+ throw isStackOverflow(error)
940
+ ? setExitCode(new TlaEvaluationError(STACK_OVERFLOW), EXIT_STATUS.error)
941
+ : error;
942
+ } finally {
943
+ stateWriter?.close();
944
+ }
914
945
  };
915
946
 
916
947
  const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefined): CheckResult => {
@@ -983,7 +1014,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
983
1014
  });
984
1015
 
985
1016
  const search = createSearch(config, environment, () =>
986
- getTlcVariableOrder(options.source, options.loadModule),
1017
+ getTlcDeclarationOrder(options.source, options.loadModule, "variable"),
987
1018
  );
988
1019
  const assumptionViolation = findAssumptionViolation(specification.assumptions, environment);
989
1020
  if (assumptionViolation) return createResult("assumption-violation", assumptionViolation);
@@ -1173,7 +1204,17 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1173
1204
  trace: TraceStep[],
1174
1205
  initialState?: Value[],
1175
1206
  failureOutDegrees?: number[],
1176
- ) => {
1207
+ ): CheckResult => {
1208
+ // TLC exits with 255 on a stack overflow while it computes next states, and prints the
1209
+ // behavior up to the state it was expanding.
1210
+ if (isStackOverflow(error)) {
1211
+ return current.isExpanding
1212
+ ? toFailure(
1213
+ setExitCode(new TlaEvaluationError(STACK_OVERFLOW), EXIT_STATUS.error),
1214
+ getStateTrace(current.index),
1215
+ )
1216
+ : toFailure(new TlaEvaluationError(STACK_OVERFLOW), trace, initialState);
1217
+ }
1177
1218
  if (!(error instanceof TlaEvaluationError)) throw error;
1178
1219
  return {
1179
1220
  ...createResult("error", undefined, {
@@ -1507,6 +1548,31 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1507
1548
  return toFailure(error, getStateTrace(index), undefined, getPartialOutDegrees());
1508
1549
  }
1509
1550
  };
1551
+ // TLC names the action when the next-state relation has more than one, and prints the
1552
+ // incomplete successor with null for each variable it leaves undefined.
1553
+ const reportIncompleteSuccessor = (error: TlaIncompleteStateError, index: number) => {
1554
+ nextActions.value ??= getNextActions(config, environment, specification.instanceActions);
1555
+ const actions = nextActions.value;
1556
+ const action =
1557
+ actions.length === 1 ? actions[0] : actions.find((item) => item.name === error.action);
1558
+ const variables = `variable${error.missing.length > 1 ? "s are" : " is"} not defined: ${error.missing.join(", ")}.\n`;
1559
+ runtime.generatedStates++;
1560
+ return toFailure(
1561
+ actions.length === 1
1562
+ ? error
1563
+ : new TlaEvaluationError(
1564
+ `Successor state is not completely specified by action ${error.action} of the next-state relation. The following ${variables}`,
1565
+ ),
1566
+ [
1567
+ ...getStateTrace(index),
1568
+ {
1569
+ action: error.action,
1570
+ label: action && getActionLabel(action),
1571
+ state: toRecord(error.state.map((value) => value ?? createModelValue("null"))),
1572
+ },
1573
+ ],
1574
+ );
1575
+ };
1510
1576
  // TLC names the properties and the step back into the cycle from the states it prints.
1511
1577
  const reportLasso = (checker: LivenessChecker, lasso: Lasso) => {
1512
1578
  const path = [...lasso.prefix, ...lasso.cycle];
@@ -1552,7 +1618,10 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1552
1618
  try {
1553
1619
  outcome.result = expandState(index);
1554
1620
  } catch (error) {
1555
- outcome.result = toFailure(withNextStateExitCode(error), getStateTrace(index));
1621
+ outcome.result =
1622
+ error instanceof TlaIncompleteStateError
1623
+ ? reportIncompleteSuccessor(error, index)
1624
+ : toFailure(toNextStateError(error), getStateTrace(index));
1556
1625
  }
1557
1626
  if (outcome.result) return outcome.result;
1558
1627
  outDegrees[getOutDegreeBucket()]++;
package/src/codegen.ts CHANGED
@@ -10,6 +10,8 @@ import {
10
10
  getSubsetOperator,
11
11
  getEvaluator,
12
12
  getFieldError,
13
+ getNonFunctionError,
14
+ getNonRecordError,
13
15
  isClosedConstant,
14
16
  isTlcInteger,
15
17
  isValueArgument,
@@ -250,12 +252,13 @@ const generateExpression = (generator: Generator, expression: Expression, frame:
250
252
  case "FunctionApplication": {
251
253
  keepLazy(expression.function);
252
254
  const functionCode = generate(expression.function);
255
+ const describeNonFunction = addReference(generator, getNonFunctionError(expression));
253
256
  if (expression.args.length === 1)
254
- return `apply(${functionCode}, ${generate(expression.args[0])})`;
255
- return `apply(${functionCode}, tuple([${expression.args.map((arg) => generate(arg)).join(", ")}]))`;
257
+ return `apply(${functionCode}, ${generate(expression.args[0])}, undefined, ${describeNonFunction})`;
258
+ return `apply(${functionCode}, tuple([${expression.args.map((arg) => generate(arg)).join(", ")}]), undefined, ${describeNonFunction})`;
256
259
  }
257
260
  case "FieldAccess":
258
- return `apply(${generate(expression.record)}, ${JSON.stringify(expression.field)}, ${addReference(generator, getFieldError(expression))})`;
261
+ return `apply(${generate(expression.record)}, ${JSON.stringify(expression.field)}, ${addReference(generator, getFieldError(expression))}, ${addReference(generator, getNonRecordError(expression))})`;
259
262
  case "Record": {
260
263
  const fields = getSortedFields(expression.fields);
261
264
  if (hasDuplicateFields(fields)) return generateDelegate(generator, expression, frame);
@@ -12,7 +12,7 @@ import {
12
12
  import { BUNDLED_MODULES } from "./bundled-modules";
13
13
  import type { ConfigValue, ModelConfig } from "./config";
14
14
  import type { FileSystem } from "./json";
15
- import { TlaConfigError, TlaEvaluationError, TlaSyntaxError } from "./errors";
15
+ import { TlaConfigError, TlaEvaluationError, TlaModuleError, TlaSyntaxError } from "./errors";
16
16
  import { EXIT_STATUS, setExitCode } from "./exit-codes";
17
17
  import {
18
18
  createBigNumberError,
@@ -47,6 +47,7 @@ import { CORE_OPERATORS, getStandardModule, STANDARD_DEPENDENCIES } from "./stan
47
47
  import { resolveInstanceSubexpressions, resolveModuleSubexpressions } from "./subexpressions";
48
48
  import { checkModuleLevels, createLevelAnalyzer } from "./levels";
49
49
  import { checkInstances, type InstanceCheck } from "./substitution-levels";
50
+ import { getTlcDeclarationOrder } from "./tlc-order";
50
51
  import {
51
52
  checkInteger,
52
53
  createModelValue,
@@ -908,11 +909,19 @@ export const createEnvironment = (
908
909
  if (symbol.key === key && name !== key) definitions.set(name, alias);
909
910
  });
910
911
  });
911
- declaredConstants.forEach((name) => {
912
- if (!constants.has(name) && !substitutions.has(name) && !operatorKeys.has(name)) {
913
- throw new TlaConfigError(`The constant ${name} is not assigned a value by the configuration`);
914
- }
915
- });
912
+ const unassigned = declaredConstants.filter(
913
+ (name) => !constants.has(name) && !substitutions.has(name) && !operatorKeys.has(name),
914
+ );
915
+ if (unassigned.length > 0) {
916
+ // TLC reports the first constant it finds unassigned in SANY's order of declarations.
917
+ const name =
918
+ getTlcDeclarationOrder(options.source, options.loadModule, "constant").find((constant) =>
919
+ unassigned.includes(constant),
920
+ ) ?? unassigned[0];
921
+ throw new TlaConfigError(
922
+ `The constant parameter ${name} is not assigned a value by the configuration file.`,
923
+ );
924
+ }
916
925
 
917
926
  const environment: Environment = {
918
927
  runtime,
@@ -954,26 +963,28 @@ export const createEnvironment = (
954
963
  ]),
955
964
  getDefinition: (name) => getDefinition(name, environment),
956
965
  });
957
- const isEvaluable = (body: Expression) => {
966
+ const getEvaluationError = (body: Expression) => {
958
967
  try {
959
968
  evaluate(body, { environment, scope: undefined, state: undefined, next: undefined });
960
- return true;
969
+ return undefined;
961
970
  } catch (error) {
962
- if (error instanceof TlaEvaluationError) return false;
971
+ if (error instanceof TlaEvaluationError) return error;
963
972
  throw error;
964
973
  }
965
974
  };
966
975
  substitutions.forEach((target, name) => {
967
976
  const definition = definitions.get(target);
968
- if (
977
+ const error =
969
978
  declaredConstants.includes(name) &&
970
979
  definition?.kind === "Operator" &&
971
980
  definition.params.length === 0 &&
972
- analyzer.analyzeDefinition(definition, new Map()).level > 0 &&
973
- !isEvaluable(definition.body)
974
- ) {
981
+ analyzer.analyzeDefinition(definition, new Map()).level > 0
982
+ ? getEvaluationError(definition.body)
983
+ : undefined;
984
+ // TLC adds the reason unless a standard module's Java code failed.
985
+ if (error) {
975
986
  throw new TlaConfigError(
976
- `The configuration file substitutes constant ${name} with non-constant ${target}`,
987
+ `The configuration file substitutes constant ${name} with non-constant ${target}${error instanceof TlaModuleError ? "" : ` - specifically: ${error.message}`}`,
977
988
  );
978
989
  }
979
990
  });
package/src/errors.ts CHANGED
@@ -1,10 +1,18 @@
1
1
  import { EXIT_STATUS, getExitCode } from "./exit-codes";
2
+ import type { Value } from "./values";
2
3
 
3
4
  // How TLC reports a RuntimeException it did not expect, such as one raised while computing next
4
5
  // states.
5
6
  export const UNEXPECTED_EXCEPTION =
6
7
  "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
8
 
9
+ // How TLC reports a Java StackOverflowError, which V8 raises as this RangeError.
10
+ export const STACK_OVERFLOW =
11
+ "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.";
12
+
13
+ export const isStackOverflow = (error: unknown) =>
14
+ error instanceof RangeError && error.message === "Maximum call stack size exceeded";
15
+
8
16
  export class TlaError extends Error {
9
17
  constructor(message: string, cause?: unknown) {
10
18
  super(message, { cause });
@@ -55,6 +63,24 @@ export class TlaModuleError extends TlaEvaluationError {
55
63
  }
56
64
  }
57
65
 
66
+ // TLC reports a successor state that the next-state relation leaves incomplete as an error of its
67
+ // own, not as an exception. It keeps the name TlaEvaluationError, and index.ts doesn't export it.
68
+ export class TlaIncompleteStateError extends TlaEvaluationError {
69
+ state: (Value | undefined)[];
70
+ action: string | undefined;
71
+ missing: string[];
72
+
73
+ constructor(state: (Value | undefined)[], action: string | undefined, missing: string[]) {
74
+ super(
75
+ `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`,
76
+ );
77
+ this.name = "TlaEvaluationError";
78
+ this.state = state;
79
+ this.action = action;
80
+ this.missing = missing;
81
+ }
82
+ }
83
+
58
84
  export interface TlapmReport {
59
85
  failure?: string;
60
86
  exception?: string;
package/src/evaluate.ts CHANGED
@@ -30,6 +30,7 @@ import {
30
30
  createSortedSet,
31
31
  createWrittenRecord,
32
32
  createTuple,
33
+ describeMissingField,
33
34
  formatValue,
34
35
  getDomain,
35
36
  getFunctionDomain,
@@ -38,6 +39,7 @@ import {
38
39
  getValueHash,
39
40
  isFunctionValue,
40
41
  isOverriddenSet,
42
+ isRecordValue,
41
43
  isSameValue,
42
44
  markLambdaFunction,
43
45
  isReducible,
@@ -47,6 +49,7 @@ import {
47
49
  toFiniteSet,
48
50
  updateFunction,
49
51
  valuesEqual,
52
+ type FunctionValue,
50
53
  type LazyFunctionSource,
51
54
  type LazyFunctionValue,
52
55
  type Value,
@@ -182,8 +185,17 @@ export const getConjunctError = (
182
185
  };
183
186
 
184
187
  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)}`;
188
+ (expression: Expression & { kind: "FieldAccess" }) => (record: FunctionValue) =>
189
+ isRecordValue(record)
190
+ ? `Attempted to select nonexistent field "${expression.field}" from the record\n${formatValue(record)}\n${describeRange(expression)}`
191
+ : describeMissingField(record, expression.field);
192
+
193
+ export const getNonFunctionError = (expression: Expression) => (value: Value) =>
194
+ `A non-function (${getKindString(value)}) was applied as a function.\n${describeRange(expression)}`;
195
+
196
+ export const getNonRecordError =
197
+ (expression: Expression & { kind: "FieldAccess" }) => (value: Value) =>
198
+ `Attempted to select field "${expression.field}" from a non-record value ${formatValue(value)}\n${describeRange(expression)}`;
187
199
 
188
200
  export const getDomainOperator = (expression: Expression) => (value: Value) => {
189
201
  if (!isFunctionValue(value)) {
@@ -1027,7 +1039,7 @@ export const getEvaluator = (expression: Expression, environment: Environment):
1027
1039
 
1028
1040
  const entryEvaluators = new WeakMap<Expression, Evaluator>();
1029
1041
 
1030
- const getEntryEvaluator = (expression: Expression, environment: Environment) => {
1042
+ export const getEntryEvaluator = (expression: Expression, environment: Environment) => {
1031
1043
  const cached = entryEvaluators.get(expression);
1032
1044
  if (cached) return cached;
1033
1045
  const evaluator =
@@ -1325,6 +1337,11 @@ const compileApply = (
1325
1337
  if (definition?.kind === "Function") {
1326
1338
  throw new TlaEvaluationError(`${expression.operator} is a function; apply it with brackets`);
1327
1339
  }
1340
+ if (expression.operator === "\\cdot") {
1341
+ throw new TlaEvaluationError(
1342
+ "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.",
1343
+ );
1344
+ }
1328
1345
  throw new TlaEvaluationError(
1329
1346
  `Unknown operator ${expression.operator} at ${describeLocation(expression)}`,
1330
1347
  );
@@ -1574,7 +1591,9 @@ export const hasDuplicateFields = (sortedFields: RecordField[]) =>
1574
1591
  sortedFields.some((field, index) => index > 0 && sortedFields[index - 1].name === field.name);
1575
1592
 
1576
1593
  export const createUnassignedError = (name: string, expression: Expression) =>
1577
- new TlaEvaluationError(`The variable ${name} is not assigned at ${describeLocation(expression)}`);
1594
+ new TlaEvaluationError(
1595
+ `In evaluation, the identifier ${name} is either undefined or not an operator.\n${describeRange(expression)}`,
1596
+ );
1578
1597
 
1579
1598
  export const createPrimeOutsideActionError = (expression: Expression) =>
1580
1599
  new TlaEvaluationError(
@@ -1762,18 +1781,31 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
1762
1781
  keepLazy(expression.function);
1763
1782
  const evaluateFunction = child(expression.function);
1764
1783
  const args = expression.args.map(child);
1784
+ const describeNonFunction = getNonFunctionError(expression);
1765
1785
  if (args.length === 1) {
1766
1786
  const argument = args[0];
1767
- return (context) => applyFunction(evaluateFunction(context), argument(context));
1787
+ return (context) =>
1788
+ applyFunction(
1789
+ evaluateFunction(context),
1790
+ argument(context),
1791
+ undefined,
1792
+ describeNonFunction,
1793
+ );
1768
1794
  }
1769
1795
  return (context) =>
1770
- applyFunction(evaluateFunction(context), createTuple(args.map((arg) => arg(context))));
1796
+ applyFunction(
1797
+ evaluateFunction(context),
1798
+ createTuple(args.map((arg) => arg(context))),
1799
+ undefined,
1800
+ describeNonFunction,
1801
+ );
1771
1802
  }
1772
1803
  case "FieldAccess": {
1773
1804
  const record = child(expression.record);
1774
1805
  const field = expression.field;
1775
1806
  const describeMissing = getFieldError(expression);
1776
- return (context) => applyFunction(record(context), field, describeMissing);
1807
+ const describeNonRecord = getNonRecordError(expression);
1808
+ return (context) => applyFunction(record(context), field, describeMissing, describeNonRecord);
1777
1809
  }
1778
1810
  case "Product": {
1779
1811
  const factors = expression.factors.map(child);