tla-ts 0.0.3-dev.d34b19a → 0.0.3-dev.e927a09

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.d34b19a",
3
+ "version": "0.0.3-dev.e927a09",
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";
12
+ import {
13
+ getErrorExitCode,
14
+ TlaConfigError,
15
+ TlaEvaluationError,
16
+ TlaModuleError,
17
+ UNEXPECTED_EXCEPTION,
18
+ } from "./errors";
6
19
  import { EXIT_STATUS, setExitCode, setNextStatePhase, 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;
@@ -828,8 +839,7 @@ export const createSearch = (
828
839
  holdsLikeTlc(
829
840
  constraint.expression,
830
841
  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)}`,
842
+ (expression) => `${UNEXPECTED_EXCEPTION}${getExpectedBoolean(expression, environment)}`,
833
843
  ),
834
844
  ),
835
845
  trackStatePossible:
@@ -962,8 +972,36 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
962
972
  const getFingerprintState = search.getFingerprintState;
963
973
  const nextActions = { value: undefined as SpecAction[] | undefined };
964
974
  const isReducing = config.view !== undefined || config.symmetry !== undefined;
975
+ const tlcFingerprints: number[] = [];
965
976
  const liveness = withLivenessExitCode(() =>
966
- createLivenessChecker(search.properties.liveness, spec.temporals, environment),
977
+ createLivenessChecker(search.properties.liveness, spec.temporals, environment, {
978
+ getFingerprint: (index) =>
979
+ (tlcFingerprints[index] ??= Number(
980
+ BigInt.asIntN(32, runtime.getFingerprint(states[index])),
981
+ )),
982
+ getSuccessors: (state) => {
983
+ const successors: LiveSuccessor[] = [];
984
+ if (spec.next === undefined) return successors;
985
+ forEachSuccessor(
986
+ spec.next,
987
+ state,
988
+ environment,
989
+ (successor) => {
990
+ canonicalizeState(successor.state);
991
+ const isInModel =
992
+ search.satisfiesConstraints(successor.state, state) &&
993
+ search.satisfiesActionConstraints(state, successor.state);
994
+ if (!isInModel) return false;
995
+ const fingerprintState = getFingerprintState(successor.state);
996
+ const index = findStateIndex(getStateHash(fingerprintState), fingerprintState);
997
+ successors.push({ index, state: successor.state });
998
+ return false;
999
+ },
1000
+ spec.scope,
1001
+ );
1002
+ return successors;
1003
+ },
1004
+ }),
967
1005
  );
968
1006
  const isCanonicalizedFirst = search.isSymmetric || liveness !== undefined;
969
1007
 
@@ -1104,7 +1142,7 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1104
1142
  outDegrees: failureOutDegrees,
1105
1143
  };
1106
1144
  };
1107
- const getPathTrace = (path: number[], loopStart?: number) => {
1145
+ const getPathSteps = (path: number[], loopStart?: number) => {
1108
1146
  const steps = getPathStates(path, NEXT_RECOVERY_FAILURE);
1109
1147
  const last = steps[steps.length - 1].state;
1110
1148
  const isClosed =
@@ -1113,7 +1151,7 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1113
1151
  loopStart === path.length - 1 ||
1114
1152
  findSuccessorWithFingerprint(last, path[loopStart]) !== undefined;
1115
1153
  if (!isClosed) throw new TlaEvaluationError(NEXT_RECOVERY_FAILURE);
1116
- return toTrace(steps, path, loopStart);
1154
+ return steps;
1117
1155
  };
1118
1156
  const getStateHash = (state: Value[]) => {
1119
1157
  let hash = 0x811c9dc5;
@@ -1179,7 +1217,7 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1179
1217
  };
1180
1218
  runtime.getCurrentState = () => (current.index === -1 ? undefined : states[current.index]);
1181
1219
  runtime.setLivenessSource = (index) => {
1182
- current.livenessSource = index;
1220
+ current.livenessSource = index ?? -1;
1183
1221
  };
1184
1222
  runtime.getLevel = (state) => {
1185
1223
  const source = current.livenessSource;
@@ -1335,32 +1373,43 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1335
1373
  }
1336
1374
  try {
1337
1375
  const accepted = liveness?.addState(index, state, liveSuccessors);
1338
- current.livenessSource = -1;
1339
- if (!accepted) return undefined;
1376
+ if (!liveness || !accepted) return undefined;
1377
+ const steps = getPathSteps(accepted);
1378
+ const properties = liveness.getViolatedProperties(
1379
+ steps.map((step) => step.state),
1380
+ steps.length - 1,
1381
+ );
1340
1382
  return reportViolation("property-violation", {
1341
- name: accepted.name,
1342
- trace: getPathTrace(accepted.path),
1383
+ name: properties[0],
1384
+ properties,
1385
+ trace: toTrace(steps, accepted),
1343
1386
  });
1344
1387
  } catch (error) {
1345
1388
  return toFailure(error, getStateTrace(index), undefined, getPartialOutDegrees());
1346
1389
  }
1347
1390
  };
1348
- const reportLasso = (lasso: Lasso) => {
1391
+ // TLC names the properties and the step back into the cycle from the states it prints.
1392
+ const reportLasso = (checker: LivenessChecker, lasso: Lasso) => {
1349
1393
  const path = [...lasso.prefix, ...lasso.cycle];
1350
- const trace = getPathTrace(path, lasso.prefix.length);
1351
- const back = path[lasso.prefix.length];
1394
+ const loopStart = lasso.prefix.length;
1395
+ const steps = getPathSteps(path, loopStart);
1396
+ const trace = toTrace(steps, path, loopStart);
1397
+ const properties = checker.getViolatedProperties(
1398
+ steps.map((step) => step.state),
1399
+ loopStart,
1400
+ );
1401
+ const back = path[loopStart];
1352
1402
  const last = path[path.length - 1];
1403
+ const lastState = steps[steps.length - 1].state;
1353
1404
  const loopLabel =
1354
- back === last ? undefined : withoutOutput(() => getLabel(last, states[last], states[back]));
1405
+ back === last ? undefined : withoutOutput(() => getLabel(last, lastState, states[back]));
1355
1406
  return reportViolation(
1356
1407
  "liveness-violation",
1357
- { name: lasso.name, trace, loopStart: lasso.prefix.length, loopLabel },
1408
+ { name: properties[0], properties, trace, loopStart, loopLabel },
1358
1409
  () =>
1359
1410
  back === last
1360
1411
  ? trace[trace.length - 1].action
1361
- : getTraceSuccessors(states[last]).find((successor) =>
1362
- isSameState(successor.state, states[back]),
1363
- )?.action,
1412
+ : findSuccessorWithFingerprint(lastState, back)?.action,
1364
1413
  );
1365
1414
  };
1366
1415
  const isPeriodic = liveness !== undefined && options.livenessCheck !== "final";
@@ -1373,7 +1422,6 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1373
1422
  if (!isGrown || periodic.time > (now - startedAt) * LIVENESS_RATIO) return undefined;
1374
1423
  periodic.size = expanded;
1375
1424
  const lasso = liveness?.findViolation();
1376
- current.livenessSource = -1;
1377
1425
  periodic.time += performance.now() - now;
1378
1426
  return lasso;
1379
1427
  };
@@ -1393,15 +1441,14 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1393
1441
  expansion.newStates = 0;
1394
1442
  if (isPeriodic && performance.now() >= periodic.at) {
1395
1443
  const lasso = findPeriodicViolation(index + 1);
1396
- if (lasso) return reportLasso(lasso);
1444
+ if (liveness && lasso) return reportLasso(liveness, lasso);
1397
1445
  }
1398
1446
  }
1399
1447
 
1400
1448
  current.index = -1;
1401
1449
  current.candidate = undefined;
1402
1450
  const lasso = liveness?.findViolation();
1403
- current.livenessSource = -1;
1404
- if (lasso) return reportLasso(lasso);
1451
+ if (liveness && lasso) return reportLasso(liveness, lasso);
1405
1452
 
1406
1453
  const postconditionViolation = search.findPostconditionViolation();
1407
1454
  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,5 +1,10 @@
1
1
  import { EXIT_STATUS, getExitCode, setModuleExitCode } from "./exit-codes";
2
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: ";
7
+
3
8
  export class TlaError extends Error {
4
9
  constructor(message: string, cause?: unknown) {
5
10
  super(message, { cause });