tla-ts 0.0.3-dev.79f7ed7 → 0.0.3-dev.91b9cf4

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.79f7ed7",
3
+ "version": "0.0.3-dev.91b9cf4",
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 {
@@ -38,10 +47,17 @@ import {
38
47
  } from "./successors";
39
48
  import {
40
49
  getActionLabel,
50
+ getActionSignature,
41
51
  getNextActions,
42
52
  getSpecificationValue,
43
53
  type SpecAction,
44
54
  } from "./spec-description";
55
+ import {
56
+ createStateWriter,
57
+ type GraphState,
58
+ type StateDump,
59
+ type StateWriter,
60
+ } from "./state-graph";
45
61
  import { getRepresentative, getSymmetryGroup } from "./symmetry";
46
62
  import { getTlcStringOrder, getTlcVariableOrder } from "./tlc-order";
47
63
  import { createTlcFingerprinter, getTlcFingerprint } from "./tlc-random";
@@ -51,6 +67,7 @@ import { createCounterExample } from "./tlc-ext";
51
67
  import { getFingerprintDistance, OUT_DEGREE_BUCKETS } from "./tlc-summary";
52
68
  import {
53
69
  combineHash,
70
+ formatState,
54
71
  formatValue,
55
72
  getValueHash,
56
73
  isFunctionValue,
@@ -74,6 +91,8 @@ export interface CheckOptions {
74
91
  workers?: number;
75
92
  // TLC's -lncheck: "final" checks liveness only on the complete state graph.
76
93
  livenessCheck?: "default" | "final";
94
+ // TLC's -dump: writes the reachable states, or with `dot` the state graph, through writeFile.
95
+ dump?: StateDump;
77
96
  }
78
97
 
79
98
  export type CheckStatus =
@@ -95,6 +114,8 @@ export interface TraceStep {
95
114
 
96
115
  export interface Violation {
97
116
  name: string;
117
+ // Every temporal property that a liveness counterexample violates, in the configuration's order.
118
+ properties?: string[];
98
119
  trace: TraceStep[];
99
120
  loopStart: number | undefined;
100
121
  loopLabel?: string;
@@ -507,7 +528,9 @@ const getMembership = (
507
528
  const getStateChecks = (named: NamedExpression[], environment: Environment): StateCheck[] =>
508
529
  named.flatMap((item) =>
509
530
  getConjuncts(item.expression, environment).map((expression) => {
510
- const variables = getReadVariables(expression, environment);
531
+ // A LET or an argument in the scope can read variables the expression doesn't name.
532
+ const variables =
533
+ item.scope === undefined ? getReadVariables(expression, environment) : undefined;
511
534
  return {
512
535
  name: item.name,
513
536
  expression,
@@ -820,7 +843,10 @@ export const createSearch = (
820
843
  )
821
844
  );
822
845
  } catch (error) {
823
- throw withHeadline(error, `Evaluating action property ${property.name} failed.`);
846
+ throw withHeadline(
847
+ withNextStateExitCode(error),
848
+ `Evaluating action property ${property.name} failed.`,
849
+ );
824
850
  }
825
851
  }),
826
852
  satisfiesActionConstraints: (state, next) =>
@@ -828,8 +854,7 @@ export const createSearch = (
828
854
  holdsLikeTlc(
829
855
  constraint.expression,
830
856
  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)}`,
857
+ (expression) => `${UNEXPECTED_EXCEPTION}${getExpectedBoolean(expression, environment)}`,
833
858
  ),
834
859
  ),
835
860
  trackStatePossible:
@@ -857,6 +882,11 @@ export const createSearch = (
857
882
  };
858
883
  };
859
884
 
885
+ // TLC exits with the code of a standard module's failure only when the failure escapes the
886
+ // computation of next states. In every other phase, the phase decides the code.
887
+ const withNextStateExitCode = (error: unknown) =>
888
+ error instanceof TlaModuleError ? setExitCode(error, error.exitCode) : error;
889
+
860
890
  const withHeadline = (error: unknown, headline: string) =>
861
891
  error instanceof TlaEvaluationError
862
892
  ? setExitCode(
@@ -865,8 +895,15 @@ const withHeadline = (error: unknown, headline: string) =>
865
895
  )
866
896
  : error;
867
897
 
898
+ // TLC finishes the -dump file whether or not the search finds a violation.
868
899
  export const checkSequentially = (options: CheckOptions): CheckResult => {
869
- setNextStatePhase(false);
900
+ const stateWriter = options.dump && createStateWriter(options.dump, options.writeFile);
901
+ const result = searchStates(options, stateWriter);
902
+ stateWriter?.close();
903
+ return result;
904
+ };
905
+
906
+ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefined): CheckResult => {
870
907
  const config = typeof options.config === "string" ? parseConfig(options.config) : options.config;
871
908
  const onPrint = options.onPrint ?? console.log;
872
909
  // TLC prints again while it rebuilds a trace, between the states it prints. Printing those lines
@@ -962,8 +999,36 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
962
999
  const getFingerprintState = search.getFingerprintState;
963
1000
  const nextActions = { value: undefined as SpecAction[] | undefined };
964
1001
  const isReducing = config.view !== undefined || config.symmetry !== undefined;
1002
+ const tlcFingerprints: number[] = [];
965
1003
  const liveness = withLivenessExitCode(() =>
966
- createLivenessChecker(search.properties.liveness, spec.temporals, environment),
1004
+ createLivenessChecker(search.properties.liveness, spec.temporals, environment, {
1005
+ getFingerprint: (index) =>
1006
+ (tlcFingerprints[index] ??= Number(
1007
+ BigInt.asIntN(32, runtime.getFingerprint(states[index])),
1008
+ )),
1009
+ getSuccessors: (state) => {
1010
+ const successors: LiveSuccessor[] = [];
1011
+ if (spec.next === undefined) return successors;
1012
+ forEachSuccessor(
1013
+ spec.next,
1014
+ state,
1015
+ environment,
1016
+ (successor) => {
1017
+ canonicalizeState(successor.state);
1018
+ const isInModel =
1019
+ search.satisfiesConstraints(successor.state, state) &&
1020
+ search.satisfiesActionConstraints(state, successor.state);
1021
+ if (!isInModel) return false;
1022
+ const fingerprintState = getFingerprintState(successor.state);
1023
+ const index = findStateIndex(getStateHash(fingerprintState), fingerprintState);
1024
+ successors.push({ index, state: successor.state });
1025
+ return false;
1026
+ },
1027
+ spec.scope,
1028
+ );
1029
+ return successors;
1030
+ },
1031
+ }),
967
1032
  );
968
1033
  const isCanonicalizedFirst = search.isSymmetric || liveness !== undefined;
969
1034
 
@@ -985,11 +1050,16 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
985
1050
  position: number,
986
1051
  loopStart: number | undefined,
987
1052
  ) => {
988
- const state = steps[position].state;
989
- const next = (steps[position + 1] ?? steps[loopStart ?? position]).state;
990
1053
  // TLC evaluates TLCGet("level") and Trace in an alias at the state's position in the trace.
991
1054
  runtime.getLevel = () => position + 1;
992
1055
  runtime.getBehavior = () => steps.slice(0, position + 1).map((step) => step.state);
1056
+ return evaluateAlias(
1057
+ alias,
1058
+ steps[position].state,
1059
+ (steps[position + 1] ?? steps[loopStart ?? position]).state,
1060
+ );
1061
+ };
1062
+ const evaluateAlias = (alias: string, state: Value[], next: Value[] | undefined) => {
993
1063
  try {
994
1064
  const body = getConfigDefinition("alias", alias, environment).body;
995
1065
  const value = evaluate(createIdentifier(alias), getContext(environment, state, next));
@@ -1104,7 +1174,7 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1104
1174
  outDegrees: failureOutDegrees,
1105
1175
  };
1106
1176
  };
1107
- const getPathTrace = (path: number[], loopStart?: number) => {
1177
+ const getPathSteps = (path: number[], loopStart?: number) => {
1108
1178
  const steps = getPathStates(path, NEXT_RECOVERY_FAILURE);
1109
1179
  const last = steps[steps.length - 1].state;
1110
1180
  const isClosed =
@@ -1113,7 +1183,7 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1113
1183
  loopStart === path.length - 1 ||
1114
1184
  findSuccessorWithFingerprint(last, path[loopStart]) !== undefined;
1115
1185
  if (!isClosed) throw new TlaEvaluationError(NEXT_RECOVERY_FAILURE);
1116
- return toTrace(steps, path, loopStart);
1186
+ return steps;
1117
1187
  };
1118
1188
  const getStateHash = (state: Value[]) => {
1119
1189
  let hash = 0x811c9dc5;
@@ -1179,7 +1249,7 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1179
1249
  };
1180
1250
  runtime.getCurrentState = () => (current.index === -1 ? undefined : states[current.index]);
1181
1251
  runtime.setLivenessSource = (index) => {
1182
- current.livenessSource = index;
1252
+ current.livenessSource = index ?? -1;
1183
1253
  };
1184
1254
  runtime.getLevel = (state) => {
1185
1255
  const source = current.livenessSource;
@@ -1190,6 +1260,18 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1190
1260
  return current.isExpanding ? depths[current.index] + 1 : 0;
1191
1261
  };
1192
1262
 
1263
+ const getGraphState = (state: Value[], level: number): GraphState => ({
1264
+ fingerprint: BigInt.asIntN(64, runtime.getFingerprint(state)),
1265
+ level,
1266
+ getLabel: () =>
1267
+ formatState(
1268
+ config.alias === undefined
1269
+ ? toRecord(state)
1270
+ : evaluateAlias(config.alias, state, undefined),
1271
+ ),
1272
+ getText: () => formatState(toRecord(state)),
1273
+ });
1274
+
1193
1275
  const visitInitialState = (state: Value[]) => {
1194
1276
  canonicalizeState(state);
1195
1277
  runtime.generatedStates++;
@@ -1206,6 +1288,7 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1206
1288
  countDistinctState(1);
1207
1289
  runtime.queueSize++;
1208
1290
  liveness?.addInitialState(states.length, state);
1291
+ stateWriter?.writeInitialState(getGraphState(state, 1));
1209
1292
  }
1210
1293
  const violated = search.findViolatedInvariant(state);
1211
1294
  if (violated) {
@@ -1226,7 +1309,13 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1226
1309
  addState(state, fingerprintState, -1, undefined);
1227
1310
  return undefined;
1228
1311
  };
1229
- const visitSuccessor = (index: number, successor: Successor, liveSuccessors: LiveSuccessor[]) => {
1312
+ const visitSuccessor = (
1313
+ index: number,
1314
+ successor: Successor,
1315
+ liveSuccessors: LiveSuccessor[],
1316
+ source: GraphState | undefined,
1317
+ action: SpecAction | undefined,
1318
+ ) => {
1230
1319
  const state = states[index];
1231
1320
  runtime.generatedStates++;
1232
1321
  current.candidate = successor.state;
@@ -1240,6 +1329,14 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1240
1329
  const isInModel = isStateInModel && search.satisfiesActionConstraints(state, successor.state);
1241
1330
  if (isInModel) search.trackActionPossible(state, successor.state);
1242
1331
  const existing = isInModel ? found : -1;
1332
+ if (source && isInModel) {
1333
+ stateWriter?.writeSuccessor(
1334
+ source,
1335
+ getGraphState(successor.state, depths[index] + 1),
1336
+ existing !== -1,
1337
+ action && { name: action.name, signature: getActionSignature(action) },
1338
+ );
1339
+ }
1243
1340
  if (existing !== -1 && liveness) {
1244
1341
  const stored = states[existing];
1245
1342
  const isStored = stored.every((value, position) => value === successor.state[position]);
@@ -1311,23 +1408,55 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1311
1408
  }
1312
1409
  return createSuccess();
1313
1410
  }
1411
+ // TLC labels and colors an edge of the -dump state graph by the action that generated it. When
1412
+ // the graph names its edges, the search generates successors action by action, as TLC does.
1413
+ const isNamingEdges = Boolean(
1414
+ options.dump?.dot && (options.dump.actionLabels || options.dump.colorize),
1415
+ );
1416
+ const forEachActionSuccessor = (
1417
+ state: Value[],
1418
+ onSuccessor: (successor: Successor, action: SpecAction | undefined) => boolean,
1419
+ ) => {
1420
+ if (!isNamingEdges) {
1421
+ return forEachSuccessor(
1422
+ next,
1423
+ state,
1424
+ environment,
1425
+ (successor) => onSuccessor(successor, undefined),
1426
+ spec.scope,
1427
+ );
1428
+ }
1429
+ nextActions.value ??= getNextActions(config, environment, specification.instanceActions);
1430
+ const progress = { isStopped: false };
1431
+ return nextActions.value.reduce((count, action) => {
1432
+ if (progress.isStopped) return count;
1433
+ return (
1434
+ count +
1435
+ forEachSuccessor(
1436
+ action.expression,
1437
+ state,
1438
+ environment,
1439
+ (successor) => {
1440
+ progress.isStopped = onSuccessor(successor, action);
1441
+ return progress.isStopped;
1442
+ },
1443
+ action.scope,
1444
+ )
1445
+ );
1446
+ }, 0);
1447
+ };
1314
1448
  const expandState = (index: number) => {
1315
1449
  const state = states[index];
1316
1450
  const liveSuccessors: LiveSuccessor[] = [];
1317
- const successorCount = forEachSuccessor(
1318
- next,
1319
- state,
1320
- environment,
1321
- (successor) => {
1322
- try {
1323
- outcome.result = visitSuccessor(index, successor, liveSuccessors);
1324
- } catch (error) {
1325
- outcome.result = toFailure(error, getTrace(index, successor));
1326
- }
1327
- return outcome.result !== undefined;
1328
- },
1329
- spec.scope,
1330
- );
1451
+ const source = stateWriter && getGraphState(state, depths[index]);
1452
+ const successorCount = forEachActionSuccessor(state, (successor, action) => {
1453
+ try {
1454
+ outcome.result = visitSuccessor(index, successor, liveSuccessors, source, action);
1455
+ } catch (error) {
1456
+ outcome.result = toFailure(error, getTrace(index, successor));
1457
+ }
1458
+ return outcome.result !== undefined;
1459
+ });
1331
1460
  current.isExpanding = false;
1332
1461
  if (outcome.result) return outcome.result;
1333
1462
  if (successorCount === 0 && config.checkDeadlock) {
@@ -1335,32 +1464,43 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1335
1464
  }
1336
1465
  try {
1337
1466
  const accepted = liveness?.addState(index, state, liveSuccessors);
1338
- current.livenessSource = -1;
1339
- if (!accepted) return undefined;
1467
+ if (!liveness || !accepted) return undefined;
1468
+ const steps = getPathSteps(accepted);
1469
+ const properties = liveness.getViolatedProperties(
1470
+ steps.map((step) => step.state),
1471
+ steps.length - 1,
1472
+ );
1340
1473
  return reportViolation("property-violation", {
1341
- name: accepted.name,
1342
- trace: getPathTrace(accepted.path),
1474
+ name: properties[0],
1475
+ properties,
1476
+ trace: toTrace(steps, accepted),
1343
1477
  });
1344
1478
  } catch (error) {
1345
1479
  return toFailure(error, getStateTrace(index), undefined, getPartialOutDegrees());
1346
1480
  }
1347
1481
  };
1348
- const reportLasso = (lasso: Lasso) => {
1482
+ // TLC names the properties and the step back into the cycle from the states it prints.
1483
+ const reportLasso = (checker: LivenessChecker, lasso: Lasso) => {
1349
1484
  const path = [...lasso.prefix, ...lasso.cycle];
1350
- const trace = getPathTrace(path, lasso.prefix.length);
1351
- const back = path[lasso.prefix.length];
1485
+ const loopStart = lasso.prefix.length;
1486
+ const steps = getPathSteps(path, loopStart);
1487
+ const trace = toTrace(steps, path, loopStart);
1488
+ const properties = checker.getViolatedProperties(
1489
+ steps.map((step) => step.state),
1490
+ loopStart,
1491
+ );
1492
+ const back = path[loopStart];
1352
1493
  const last = path[path.length - 1];
1494
+ const lastState = steps[steps.length - 1].state;
1353
1495
  const loopLabel =
1354
- back === last ? undefined : withoutOutput(() => getLabel(last, states[last], states[back]));
1496
+ back === last ? undefined : withoutOutput(() => getLabel(last, lastState, states[back]));
1355
1497
  return reportViolation(
1356
1498
  "liveness-violation",
1357
- { name: lasso.name, trace, loopStart: lasso.prefix.length, loopLabel },
1499
+ { name: properties[0], properties, trace, loopStart, loopLabel },
1358
1500
  () =>
1359
1501
  back === last
1360
1502
  ? trace[trace.length - 1].action
1361
- : getTraceSuccessors(states[last]).find((successor) =>
1362
- isSameState(successor.state, states[back]),
1363
- )?.action,
1503
+ : findSuccessorWithFingerprint(lastState, back)?.action,
1364
1504
  );
1365
1505
  };
1366
1506
  const isPeriodic = liveness !== undefined && options.livenessCheck !== "final";
@@ -1373,11 +1513,9 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1373
1513
  if (!isGrown || periodic.time > (now - startedAt) * LIVENESS_RATIO) return undefined;
1374
1514
  periodic.size = expanded;
1375
1515
  const lasso = liveness?.findViolation();
1376
- current.livenessSource = -1;
1377
1516
  periodic.time += performance.now() - now;
1378
1517
  return lasso;
1379
1518
  };
1380
- setNextStatePhase(true);
1381
1519
  for (let index = 0; index < states.length && !runtime.isStopped; index++) {
1382
1520
  current.index = index;
1383
1521
  current.candidate = undefined;
@@ -1386,22 +1524,21 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1386
1524
  try {
1387
1525
  outcome.result = expandState(index);
1388
1526
  } catch (error) {
1389
- outcome.result = toFailure(error, getStateTrace(index));
1527
+ outcome.result = toFailure(withNextStateExitCode(error), getStateTrace(index));
1390
1528
  }
1391
1529
  if (outcome.result) return outcome.result;
1392
1530
  outDegrees[getOutDegreeBucket()]++;
1393
1531
  expansion.newStates = 0;
1394
1532
  if (isPeriodic && performance.now() >= periodic.at) {
1395
1533
  const lasso = findPeriodicViolation(index + 1);
1396
- if (lasso) return reportLasso(lasso);
1534
+ if (liveness && lasso) return reportLasso(liveness, lasso);
1397
1535
  }
1398
1536
  }
1399
1537
 
1400
1538
  current.index = -1;
1401
1539
  current.candidate = undefined;
1402
1540
  const lasso = liveness?.findViolation();
1403
- current.livenessSource = -1;
1404
- if (lasso) return reportLasso(lasso);
1541
+ if (liveness && lasso) return reportLasso(liveness, lasso);
1405
1542
 
1406
1543
  const postconditionViolation = search.findPostconditionViolation();
1407
1544
  if (postconditionViolation) {
@@ -2,6 +2,8 @@ export interface OptionSpec {
2
2
  flag: string;
3
3
  isRequired?: boolean;
4
4
  isRepeatable?: boolean;
5
+ // How many of the arguments after the flag the option takes, when that depends on them.
6
+ getArity?: (rest: string[]) => number;
5
7
  }
6
8
 
7
9
  export interface ParsedOption {
@@ -29,27 +31,31 @@ export const defineCommand = (usage: string, specs: OptionSpec[]) => {
29
31
  const arities = new Map(
30
32
  specs.map((spec) => {
31
33
  const [name, ...values] = spec.flag.split(" ");
32
- return [name, values.length];
34
+ return [name, spec.getArity ?? (() => values.length)];
33
35
  }),
34
36
  );
35
37
  const parse = (args: string[]): ParsedArgs => {
36
38
  const options: ParsedOption[] = [];
37
39
  const positionals: string[] = [];
38
40
  const unknown: string[] = [];
41
+ const incomplete: ParsedOption[] = [];
39
42
  for (let index = 0; index < args.length; index++) {
40
- const arity = arities.get(args[index]);
41
- if (arity === undefined) {
43
+ const getArity = arities.get(args[index]);
44
+ if (getArity === undefined) {
42
45
  (args[index].startsWith("-") ? unknown : positionals).push(args[index]);
43
46
  continue;
44
47
  }
45
- options.push({ name: args[index], values: args.slice(index + 1, index + 1 + arity) });
48
+ const arity = getArity(args.slice(index + 1));
49
+ const option = { name: args[index], values: args.slice(index + 1, index + 1 + arity) };
50
+ options.push(option);
51
+ if (option.values.length < arity) incomplete.push(option);
46
52
  index += arity;
47
53
  }
48
54
  return {
49
55
  options,
50
56
  positionals,
51
57
  unknown,
52
- incomplete: options.find((option) => option.values.length < (arities.get(option.name) ?? 0)),
58
+ incomplete: incomplete[0],
53
59
  has: (name) => options.some((option) => option.name === name),
54
60
  get: (name) => options.findLast((option) => option.name === name)?.values,
55
61
  };
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",