tla-ts 0.0.3-dev.eba78ea → 0.0.3-dev.f6f300a

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.eba78ea",
3
+ "version": "0.0.3-dev.f6f300a",
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";
@@ -247,7 +250,7 @@ const getConstantValue = (name: string, definition: Definition, environment: Env
247
250
  try {
248
251
  return evaluate(createIdentifier(name), getContext(environment, undefined, undefined));
249
252
  } catch (error) {
250
- if (error instanceof TlaEvaluationError) return undefined;
253
+ if (error instanceof TlaEvaluationError || isStackOverflow(error)) return undefined;
251
254
  throw error;
252
255
  }
253
256
  };
@@ -276,8 +279,11 @@ const getInvariants = (names: string[], environment: Environment) => {
276
279
  levels.params.size === 0
277
280
  ? ""
278
281
  : "\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}`,
282
+ throw setExitCode(
283
+ new TlaConfigError(
284
+ `The invariant ${name} is not a state predicate (one with no primes or temporal operators).${note}`,
285
+ ),
286
+ EXIT_STATUS.safetyEvaluationFailure,
281
287
  );
282
288
  }
283
289
  return [{ name, expression: createIdentifier(name), scope: undefined }];
@@ -375,8 +381,11 @@ const getSpecification = (config: ModelConfig, environment: Environment): Specif
375
381
  conjunct.kind === "Always" &&
376
382
  getLevel(conjunct.expression, item.scope, environment) < ACTION_LEVEL
377
383
  ) {
378
- throw new TlaConfigError(
379
- `TLC cannot handle []P in the specification ${config.specification} when P is a state predicate`,
384
+ throw setExitCode(
385
+ new TlaConfigError(
386
+ `TLC cannot handle the temporal formula ${describeRange(conjunct.expression)}`,
387
+ ),
388
+ EXIT_STATUS.error,
380
389
  );
381
390
  }
382
391
  const level = getLevel(conjunct, item.scope, environment);
@@ -446,12 +455,12 @@ const getProperties = (config: ModelConfig, environment: Environment): Propertie
446
455
  config.properties.forEach((name) => {
447
456
  const definition = getConfigPredicate("property", name, environment);
448
457
  if (!definition) return;
449
- expandTemporal(definition.body, undefined, environment, true).forEach((item) => {
458
+ expandTemporal(definition.body, undefined, environment, true, name).forEach((item) => {
450
459
  const conjunct = item.expression;
451
460
  if (isConstantTrue(item, environment, "property")) return;
452
461
  if (conjunct.kind === "Always" && conjunct.expression.kind === "BoxAction") {
453
462
  properties.actionProperties.push({
454
- name,
463
+ name: item.name,
455
464
  box: conjunct.expression,
456
465
  action: conjunct.expression.action,
457
466
  subscript: conjunct.expression.subscript,
@@ -463,12 +472,22 @@ const getProperties = (config: ModelConfig, environment: Environment): Propertie
463
472
  conjunct.kind === "Always" &&
464
473
  getLevel(conjunct.expression, item.scope, environment) <= 1
465
474
  ) {
466
- properties.invariants.push({ name, expression: conjunct.expression, scope: item.scope });
475
+ // TLC names the invariant []P after P when P is an operator name.
476
+ const expression = conjunct.expression;
477
+ properties.invariants.push({
478
+ name: expression.kind === "Identifier" ? expression.name : item.name,
479
+ expression,
480
+ scope: item.scope,
481
+ });
467
482
  return;
468
483
  }
469
484
  const level = getLevel(conjunct, item.scope, environment);
470
485
  if (level < ACTION_LEVEL) {
471
- properties.initialPredicates.push({ name, expression: conjunct, scope: item.scope });
486
+ properties.initialPredicates.push({
487
+ name: item.name,
488
+ expression: conjunct,
489
+ scope: item.scope,
490
+ });
472
491
  return;
473
492
  }
474
493
  if (level === ACTION_LEVEL) {
@@ -777,11 +796,13 @@ export const createSearch = (
777
796
  if (view !== undefined || isFingerprintedLikeTlc) {
778
797
  return BigInt64Array.from(states, getTlcStateFingerprint);
779
798
  }
780
- const indices = getTlcOrder();
781
- const getFingerprint = createTlcFingerprinter();
782
- return BigInt64Array.from(fingerprintStates, (state) =>
783
- getFingerprint(indices.map((index) => state[index])),
799
+ const fingerprints = new BigInt64Array(fingerprintStates.length);
800
+ const fingerprint = createTlcFingerprinter(
801
+ getTlcOrder(),
802
+ new Int32Array(fingerprints.buffer),
784
803
  );
804
+ fingerprintStates.forEach(fingerprint);
805
+ return fingerprints;
785
806
  },
786
807
  getFingerprintState: (state) => {
787
808
  if (isFingerprintedLikeTlc) return [String(getTlcStateFingerprint(state))];
@@ -887,6 +908,18 @@ export const createSearch = (
887
908
  const withNextStateExitCode = (error: unknown) =>
888
909
  error instanceof TlaModuleError ? setExitCode(error, error.exitCode) : error;
889
910
 
911
+ // TLC reports a failure of the next-state relation as an unexpected exception, unless a standard
912
+ // module raised it as an EvalException.
913
+ const toNextStateError = (error: unknown) =>
914
+ error instanceof TlaEvaluationError &&
915
+ !(error instanceof TlaModuleError) &&
916
+ !(error instanceof TlaIncompleteStateError)
917
+ ? setExitCode(
918
+ new TlaEvaluationError(`${UNEXPECTED_EXCEPTION}${error.message}`, error),
919
+ getErrorExitCode(error),
920
+ )
921
+ : withNextStateExitCode(error);
922
+
890
923
  const withHeadline = (error: unknown, headline: string) =>
891
924
  error instanceof TlaEvaluationError
892
925
  ? setExitCode(
@@ -898,9 +931,16 @@ const withHeadline = (error: unknown, headline: string) =>
898
931
  // TLC finishes the -dump file whether or not the search finds a violation.
899
932
  export const checkSequentially = (options: CheckOptions): CheckResult => {
900
933
  const stateWriter = options.dump && createStateWriter(options.dump, options.writeFile);
901
- const result = searchStates(options, stateWriter);
902
- stateWriter?.close();
903
- return result;
934
+ try {
935
+ return searchStates(options, stateWriter);
936
+ } catch (error) {
937
+ // TLC reports a stack overflow outside the search as a failure of its own, with exit code 255.
938
+ throw isStackOverflow(error)
939
+ ? setExitCode(new TlaEvaluationError(STACK_OVERFLOW), EXIT_STATUS.error)
940
+ : error;
941
+ } finally {
942
+ stateWriter?.close();
943
+ }
904
944
  };
905
945
 
906
946
  const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefined): CheckResult => {
@@ -973,7 +1013,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
973
1013
  });
974
1014
 
975
1015
  const search = createSearch(config, environment, () =>
976
- getTlcVariableOrder(options.source, options.loadModule),
1016
+ getTlcDeclarationOrder(options.source, options.loadModule, "variable"),
977
1017
  );
978
1018
  const assumptionViolation = findAssumptionViolation(specification.assumptions, environment);
979
1019
  if (assumptionViolation) return createResult("assumption-violation", assumptionViolation);
@@ -1163,7 +1203,17 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1163
1203
  trace: TraceStep[],
1164
1204
  initialState?: Value[],
1165
1205
  failureOutDegrees?: number[],
1166
- ) => {
1206
+ ): CheckResult => {
1207
+ // TLC exits with 255 on a stack overflow while it computes next states, and prints the
1208
+ // behavior up to the state it was expanding.
1209
+ if (isStackOverflow(error)) {
1210
+ return current.isExpanding
1211
+ ? toFailure(
1212
+ setExitCode(new TlaEvaluationError(STACK_OVERFLOW), EXIT_STATUS.error),
1213
+ getStateTrace(current.index),
1214
+ )
1215
+ : toFailure(new TlaEvaluationError(STACK_OVERFLOW), trace, initialState);
1216
+ }
1167
1217
  if (!(error instanceof TlaEvaluationError)) throw error;
1168
1218
  return {
1169
1219
  ...createResult("error", undefined, {
@@ -1542,7 +1592,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1542
1592
  try {
1543
1593
  outcome.result = expandState(index);
1544
1594
  } catch (error) {
1545
- outcome.result = toFailure(withNextStateExitCode(error), getStateTrace(index));
1595
+ outcome.result = toFailure(toNextStateError(error), getStateTrace(index));
1546
1596
  }
1547
1597
  if (outcome.result) return outcome.result;
1548
1598
  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
@@ -5,6 +5,13 @@ import { EXIT_STATUS, getExitCode } from "./exit-codes";
5
5
  export const UNEXPECTED_EXCEPTION =
6
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: ";
7
7
 
8
+ // How TLC reports a Java StackOverflowError, which V8 raises as this RangeError.
9
+ export const STACK_OVERFLOW =
10
+ "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.";
11
+
12
+ export const isStackOverflow = (error: unknown) =>
13
+ error instanceof RangeError && error.message === "Maximum call stack size exceeded";
14
+
8
15
  export class TlaError extends Error {
9
16
  constructor(message: string, cause?: unknown) {
10
17
  super(message, { cause });
@@ -55,6 +62,15 @@ export class TlaModuleError extends TlaEvaluationError {
55
62
  }
56
63
  }
57
64
 
65
+ // TLC reports a successor state that the next-state relation leaves incomplete as an error of its
66
+ // own, not as an exception. It keeps the name TlaEvaluationError, and index.ts doesn't export it.
67
+ export class TlaIncompleteStateError extends TlaEvaluationError {
68
+ constructor(message: string) {
69
+ super(message);
70
+ this.name = "TlaEvaluationError";
71
+ }
72
+ }
73
+
58
74
  export interface TlapmReport {
59
75
  failure?: string;
60
76
  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);