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

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.e946acb",
3
+ "version": "0.0.3-dev.fb38eba",
4
4
  "description": "A TLA+ interpreter and model checker in TypeScript, 2× faster than TLC",
5
5
  "keywords": [
6
6
  "formal verification",
package/src/ast.ts CHANGED
@@ -486,3 +486,93 @@ export interface Module {
486
486
  uses: UseOrHide[];
487
487
  units: ModuleUnit[];
488
488
  }
489
+
490
+ export const getChildren = (expression: Expression): Expression[] => {
491
+ switch (expression.kind) {
492
+ case "Number":
493
+ case "Decimal":
494
+ case "String":
495
+ case "Identifier":
496
+ case "OperatorReference":
497
+ case "ExceptAt":
498
+ return [];
499
+ case "Apply":
500
+ return expression.args;
501
+ case "Lambda":
502
+ return [expression.body];
503
+ case "And":
504
+ case "Or":
505
+ return expression.operands;
506
+ case "Prime":
507
+ case "Unchanged":
508
+ case "Enabled":
509
+ case "Always":
510
+ case "Eventually":
511
+ return [expression.expression];
512
+ case "If":
513
+ return [expression.condition, expression.consequent, expression.alternative];
514
+ case "Case":
515
+ return [
516
+ ...expression.arms.flatMap((arm) => [arm.condition, arm.body]),
517
+ ...(expression.other ? [expression.other] : []),
518
+ ];
519
+ case "Let":
520
+ return [
521
+ ...expression.definitions.flatMap((definition) =>
522
+ definition.kind === "Function"
523
+ ? [...definition.bounds.map((bound) => bound.set), definition.body]
524
+ : [definition.body],
525
+ ),
526
+ expression.body,
527
+ ];
528
+ case "Forall":
529
+ case "Exists":
530
+ return [...expression.bounds.map((bound) => bound.set), expression.body];
531
+ case "UnboundedQuantifier":
532
+ return [expression.body];
533
+ case "Choose":
534
+ return [...(expression.set ? [expression.set] : []), expression.body];
535
+ case "SetEnumeration":
536
+ case "Tuple":
537
+ return expression.elements;
538
+ case "SetFilter":
539
+ return [expression.bound.set, expression.predicate];
540
+ case "SetMap":
541
+ return [expression.expression, ...expression.bounds.map((bound) => bound.set)];
542
+ case "FunctionConstruction":
543
+ return [...expression.bounds.map((bound) => bound.set), expression.body];
544
+ case "FunctionSet":
545
+ return [expression.domain, expression.range];
546
+ case "Record":
547
+ case "RecordSet":
548
+ return expression.fields.map((field) => field.value);
549
+ case "Except":
550
+ return [
551
+ expression.function,
552
+ ...expression.updates.flatMap((update) => [
553
+ ...update.path.flatMap((step) => (step.kind === "Index" ? step.args : [])),
554
+ update.value,
555
+ ]),
556
+ ];
557
+ case "FunctionApplication":
558
+ return [expression.function, ...expression.args];
559
+ case "FieldAccess":
560
+ return [expression.record];
561
+ case "Product":
562
+ return expression.factors;
563
+ case "BoxAction":
564
+ case "AngleAction":
565
+ return [expression.action, expression.subscript];
566
+ case "WeakFairness":
567
+ case "StrongFairness":
568
+ return [expression.subscript, expression.action];
569
+ case "Label":
570
+ return [expression.body];
571
+ case "Subexpression":
572
+ return expression.selectors.flatMap((selector) => ("args" in selector ? selector.args : []));
573
+ }
574
+ };
575
+
576
+ export const isLocallyResolved = (expression: Expression) =>
577
+ (expression.kind === "Identifier" || expression.kind === "Apply") &&
578
+ expression.resolution?.kind === "Local";
package/src/check.ts CHANGED
@@ -1,32 +1,41 @@
1
- import type { Assumption, Definition, Expression, SourceLocation } from "./ast";
1
+ import {
2
+ getChildren,
3
+ isLocallyResolved,
4
+ type Assumption,
5
+ type Definition,
6
+ type Expression,
7
+ type SourceLocation,
8
+ } from "./ast";
2
9
  import { parseConfig, type ConfigValue, type ModelConfig } from "./config";
3
10
  import { getReadVariables } from "./dependencies";
4
11
  import { createEnvironment } from "./environment";
5
- import { getErrorExitCode, TlaConfigError, TlaEvaluationError, TlaModuleError } from "./errors";
6
- import { EXIT_STATUS, setExitCode, setNextStatePhase, withLivenessExitCode } from "./exit-codes";
12
+ import {
13
+ getErrorExitCode,
14
+ TlaConfigError,
15
+ TlaEvaluationError,
16
+ TlaModuleError,
17
+ UNEXPECTED_EXCEPTION,
18
+ } from "./errors";
19
+ import { EXIT_STATUS, setExitCode, withLivenessExitCode } from "./exit-codes";
7
20
  import {
8
21
  describeRange,
9
22
  evaluate,
10
23
  expectBoolean,
11
24
  formatRange,
12
- getChildren,
13
25
  getDefinition,
14
26
  isConstantLevel,
15
27
  isImpure,
16
- isLocallyResolved,
17
28
  type Context,
18
29
  type Environment,
19
30
  type Scope,
20
31
  } from "./evaluate";
21
32
  import {
22
33
  createLivenessChecker,
23
- expandTemporal,
24
- getLevel,
25
34
  type Lasso,
35
+ type LivenessChecker,
26
36
  type LiveSuccessor,
27
- type ScopedExpression,
28
- type TemporalProperty,
29
- } from "./liveness";
37
+ } from "./live-check";
38
+ import { expandTemporal, getLevel, type ScopedExpression, type TemporalProperty } from "./liveness";
30
39
  import { ACTION_LEVEL, createLevelAnalyzer, TEMPORAL_LEVEL } from "./levels";
31
40
  import { prettyPrint } from "./pretty-print";
32
41
  import {
@@ -95,6 +104,8 @@ export interface TraceStep {
95
104
 
96
105
  export interface Violation {
97
106
  name: string;
107
+ // Every temporal property that a liveness counterexample violates, in the configuration's order.
108
+ properties?: string[];
98
109
  trace: TraceStep[];
99
110
  loopStart: number | undefined;
100
111
  loopLabel?: string;
@@ -820,7 +831,10 @@ export const createSearch = (
820
831
  )
821
832
  );
822
833
  } catch (error) {
823
- throw withHeadline(error, `Evaluating action property ${property.name} failed.`);
834
+ throw withHeadline(
835
+ withNextStateExitCode(error),
836
+ `Evaluating action property ${property.name} failed.`,
837
+ );
824
838
  }
825
839
  }),
826
840
  satisfiesActionConstraints: (state, next) =>
@@ -828,8 +842,7 @@ export const createSearch = (
828
842
  holdsLikeTlc(
829
843
  constraint.expression,
830
844
  getContext(environment, state, next),
831
- (expression) =>
832
- `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: ${getExpectedBoolean(expression, environment)}`,
845
+ (expression) => `${UNEXPECTED_EXCEPTION}${getExpectedBoolean(expression, environment)}`,
833
846
  ),
834
847
  ),
835
848
  trackStatePossible:
@@ -857,6 +870,11 @@ export const createSearch = (
857
870
  };
858
871
  };
859
872
 
873
+ // TLC exits with the code of a standard module's failure only when the failure escapes the
874
+ // computation of next states. In every other phase, the phase decides the code.
875
+ const withNextStateExitCode = (error: unknown) =>
876
+ error instanceof TlaModuleError ? setExitCode(error, error.exitCode) : error;
877
+
860
878
  const withHeadline = (error: unknown, headline: string) =>
861
879
  error instanceof TlaEvaluationError
862
880
  ? setExitCode(
@@ -866,7 +884,6 @@ const withHeadline = (error: unknown, headline: string) =>
866
884
  : error;
867
885
 
868
886
  export const checkSequentially = (options: CheckOptions): CheckResult => {
869
- setNextStatePhase(false);
870
887
  const config = typeof options.config === "string" ? parseConfig(options.config) : options.config;
871
888
  const onPrint = options.onPrint ?? console.log;
872
889
  // TLC prints again while it rebuilds a trace, between the states it prints. Printing those lines
@@ -962,8 +979,36 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
962
979
  const getFingerprintState = search.getFingerprintState;
963
980
  const nextActions = { value: undefined as SpecAction[] | undefined };
964
981
  const isReducing = config.view !== undefined || config.symmetry !== undefined;
982
+ const tlcFingerprints: number[] = [];
965
983
  const liveness = withLivenessExitCode(() =>
966
- createLivenessChecker(search.properties.liveness, spec.temporals, environment),
984
+ createLivenessChecker(search.properties.liveness, spec.temporals, environment, {
985
+ getFingerprint: (index) =>
986
+ (tlcFingerprints[index] ??= Number(
987
+ BigInt.asIntN(32, runtime.getFingerprint(states[index])),
988
+ )),
989
+ getSuccessors: (state) => {
990
+ const successors: LiveSuccessor[] = [];
991
+ if (spec.next === undefined) return successors;
992
+ forEachSuccessor(
993
+ spec.next,
994
+ state,
995
+ environment,
996
+ (successor) => {
997
+ canonicalizeState(successor.state);
998
+ const isInModel =
999
+ search.satisfiesConstraints(successor.state, state) &&
1000
+ search.satisfiesActionConstraints(state, successor.state);
1001
+ if (!isInModel) return false;
1002
+ const fingerprintState = getFingerprintState(successor.state);
1003
+ const index = findStateIndex(getStateHash(fingerprintState), fingerprintState);
1004
+ successors.push({ index, state: successor.state });
1005
+ return false;
1006
+ },
1007
+ spec.scope,
1008
+ );
1009
+ return successors;
1010
+ },
1011
+ }),
967
1012
  );
968
1013
  const isCanonicalizedFirst = search.isSymmetric || liveness !== undefined;
969
1014
 
@@ -1104,7 +1149,7 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1104
1149
  outDegrees: failureOutDegrees,
1105
1150
  };
1106
1151
  };
1107
- const getPathTrace = (path: number[], loopStart?: number) => {
1152
+ const getPathSteps = (path: number[], loopStart?: number) => {
1108
1153
  const steps = getPathStates(path, NEXT_RECOVERY_FAILURE);
1109
1154
  const last = steps[steps.length - 1].state;
1110
1155
  const isClosed =
@@ -1113,7 +1158,7 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1113
1158
  loopStart === path.length - 1 ||
1114
1159
  findSuccessorWithFingerprint(last, path[loopStart]) !== undefined;
1115
1160
  if (!isClosed) throw new TlaEvaluationError(NEXT_RECOVERY_FAILURE);
1116
- return toTrace(steps, path, loopStart);
1161
+ return steps;
1117
1162
  };
1118
1163
  const getStateHash = (state: Value[]) => {
1119
1164
  let hash = 0x811c9dc5;
@@ -1179,7 +1224,7 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1179
1224
  };
1180
1225
  runtime.getCurrentState = () => (current.index === -1 ? undefined : states[current.index]);
1181
1226
  runtime.setLivenessSource = (index) => {
1182
- current.livenessSource = index;
1227
+ current.livenessSource = index ?? -1;
1183
1228
  };
1184
1229
  runtime.getLevel = (state) => {
1185
1230
  const source = current.livenessSource;
@@ -1335,32 +1380,43 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1335
1380
  }
1336
1381
  try {
1337
1382
  const accepted = liveness?.addState(index, state, liveSuccessors);
1338
- current.livenessSource = -1;
1339
- if (!accepted) return undefined;
1383
+ if (!liveness || !accepted) return undefined;
1384
+ const steps = getPathSteps(accepted);
1385
+ const properties = liveness.getViolatedProperties(
1386
+ steps.map((step) => step.state),
1387
+ steps.length - 1,
1388
+ );
1340
1389
  return reportViolation("property-violation", {
1341
- name: accepted.name,
1342
- trace: getPathTrace(accepted.path),
1390
+ name: properties[0],
1391
+ properties,
1392
+ trace: toTrace(steps, accepted),
1343
1393
  });
1344
1394
  } catch (error) {
1345
1395
  return toFailure(error, getStateTrace(index), undefined, getPartialOutDegrees());
1346
1396
  }
1347
1397
  };
1348
- const reportLasso = (lasso: Lasso) => {
1398
+ // TLC names the properties and the step back into the cycle from the states it prints.
1399
+ const reportLasso = (checker: LivenessChecker, lasso: Lasso) => {
1349
1400
  const path = [...lasso.prefix, ...lasso.cycle];
1350
- const trace = getPathTrace(path, lasso.prefix.length);
1351
- const back = path[lasso.prefix.length];
1401
+ const loopStart = lasso.prefix.length;
1402
+ const steps = getPathSteps(path, loopStart);
1403
+ const trace = toTrace(steps, path, loopStart);
1404
+ const properties = checker.getViolatedProperties(
1405
+ steps.map((step) => step.state),
1406
+ loopStart,
1407
+ );
1408
+ const back = path[loopStart];
1352
1409
  const last = path[path.length - 1];
1410
+ const lastState = steps[steps.length - 1].state;
1353
1411
  const loopLabel =
1354
- back === last ? undefined : withoutOutput(() => getLabel(last, states[last], states[back]));
1412
+ back === last ? undefined : withoutOutput(() => getLabel(last, lastState, states[back]));
1355
1413
  return reportViolation(
1356
1414
  "liveness-violation",
1357
- { name: lasso.name, trace, loopStart: lasso.prefix.length, loopLabel },
1415
+ { name: properties[0], properties, trace, loopStart, loopLabel },
1358
1416
  () =>
1359
1417
  back === last
1360
1418
  ? trace[trace.length - 1].action
1361
- : getTraceSuccessors(states[last]).find((successor) =>
1362
- isSameState(successor.state, states[back]),
1363
- )?.action,
1419
+ : findSuccessorWithFingerprint(lastState, back)?.action,
1364
1420
  );
1365
1421
  };
1366
1422
  const isPeriodic = liveness !== undefined && options.livenessCheck !== "final";
@@ -1373,11 +1429,9 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1373
1429
  if (!isGrown || periodic.time > (now - startedAt) * LIVENESS_RATIO) return undefined;
1374
1430
  periodic.size = expanded;
1375
1431
  const lasso = liveness?.findViolation();
1376
- current.livenessSource = -1;
1377
1432
  periodic.time += performance.now() - now;
1378
1433
  return lasso;
1379
1434
  };
1380
- setNextStatePhase(true);
1381
1435
  for (let index = 0; index < states.length && !runtime.isStopped; index++) {
1382
1436
  current.index = index;
1383
1437
  current.candidate = undefined;
@@ -1386,22 +1440,21 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1386
1440
  try {
1387
1441
  outcome.result = expandState(index);
1388
1442
  } catch (error) {
1389
- outcome.result = toFailure(error, getStateTrace(index));
1443
+ outcome.result = toFailure(withNextStateExitCode(error), getStateTrace(index));
1390
1444
  }
1391
1445
  if (outcome.result) return outcome.result;
1392
1446
  outDegrees[getOutDegreeBucket()]++;
1393
1447
  expansion.newStates = 0;
1394
1448
  if (isPeriodic && performance.now() >= periodic.at) {
1395
1449
  const lasso = findPeriodicViolation(index + 1);
1396
- if (lasso) return reportLasso(lasso);
1450
+ if (liveness && lasso) return reportLasso(liveness, lasso);
1397
1451
  }
1398
1452
  }
1399
1453
 
1400
1454
  current.index = -1;
1401
1455
  current.candidate = undefined;
1402
1456
  const lasso = liveness?.findViolation();
1403
- current.livenessSource = -1;
1404
- if (lasso) return reportLasso(lasso);
1457
+ if (liveness && lasso) return reportLasso(liveness, lasso);
1405
1458
 
1406
1459
  const postconditionViolation = search.findPostconditionViolation();
1407
1460
  if (postconditionViolation) {
package/src/codegen.ts CHANGED
@@ -1,11 +1,8 @@
1
- import type { Expression } from "./ast";
2
- import { TlaEvaluationError } from "./errors";
1
+ import { getChildren, isLocallyResolved, type Expression } from "./ast";
3
2
  import {
4
- describeLocation,
5
3
  bindValue,
6
4
  expectBoolean,
7
5
  findGlobalName,
8
- getChildren,
9
6
  getEnumeratedElements,
10
7
  getConditionError,
11
8
  getConjunctError,
@@ -14,19 +11,21 @@ import {
14
11
  getEvaluator,
15
12
  getFieldError,
16
13
  isClosedConstant,
17
- isLocallyResolved,
18
14
  isTlcInteger,
19
15
  isValueArgument,
20
16
  isWorthCaching,
21
17
  keepLazy,
22
18
  resolveGlobalOperator,
19
+ createPrimeOutsideActionError,
20
+ createUnassignedError,
21
+ getSortedFields,
22
+ hasDuplicateFields,
23
23
  type Context,
24
24
  type Environment,
25
25
  type Evaluator,
26
26
  } from "./evaluate";
27
27
  import {
28
28
  applyFunction,
29
- compareValues,
30
29
  createEnumeratedSet,
31
30
  createSortedFunction,
32
31
  createTuple,
@@ -84,14 +83,10 @@ const createRuntime = () => ({
84
83
  equal: valuesEqual,
85
84
  enumerate: getEnumeratedElements,
86
85
  unassigned: (name: string, expression: Expression): never => {
87
- throw new TlaEvaluationError(
88
- `The variable ${name} is not assigned at ${describeLocation(expression)}`,
89
- );
86
+ throw createUnassignedError(name, expression);
90
87
  },
91
88
  primeOutsideAction: (expression: Expression): never => {
92
- throw new TlaEvaluationError(
93
- `A primed expression appears outside an action at ${describeLocation(expression)}`,
94
- );
89
+ throw createPrimeOutsideActionError(expression);
95
90
  },
96
91
  prime: (context: Context): Context => ({
97
92
  environment: context.environment,
@@ -262,13 +257,8 @@ const generateExpression = (generator: Generator, expression: Expression, frame:
262
257
  case "FieldAccess":
263
258
  return `apply(${generate(expression.record)}, ${JSON.stringify(expression.field)}, ${addReference(generator, getFieldError(expression))})`;
264
259
  case "Record": {
265
- const fields = [...expression.fields].sort((left, right) =>
266
- compareValues(left.name, right.name),
267
- );
268
- const hasDuplicates = fields.some(
269
- (field, index) => index > 0 && fields[index - 1].name === field.name,
270
- );
271
- if (hasDuplicates) return generateDelegate(generator, expression, frame);
260
+ const fields = getSortedFields(expression.fields);
261
+ if (hasDuplicateFields(fields)) return generateDelegate(generator, expression, frame);
272
262
  const names = addReference(
273
263
  generator,
274
264
  fields.map((field) => field.name),
@@ -1,5 +1,5 @@
1
- import type { Definition, Expression } from "./ast";
2
- import { getChildren, isImpureBuiltin, type Environment } from "./evaluate";
1
+ import { getChildren, type Definition, type Expression } from "./ast";
2
+ import { isImpureBuiltin, type Environment } from "./evaluate";
3
3
 
4
4
  const STATE_INDEPENDENT_KINDS = new Set([
5
5
  "Prime",
@@ -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