tla-ts 0.0.3-dev.252cf06 → 0.0.3-dev.31e0776

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.252cf06",
3
+ "version": "0.0.3-dev.31e0776",
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
@@ -16,7 +16,7 @@ import {
16
16
  TlaModuleError,
17
17
  UNEXPECTED_EXCEPTION,
18
18
  } from "./errors";
19
- import { EXIT_STATUS, setExitCode, setNextStatePhase, withLivenessExitCode } from "./exit-codes";
19
+ import { EXIT_STATUS, setExitCode, withLivenessExitCode } from "./exit-codes";
20
20
  import {
21
21
  describeRange,
22
22
  evaluate,
@@ -47,10 +47,17 @@ import {
47
47
  } from "./successors";
48
48
  import {
49
49
  getActionLabel,
50
+ getActionSignature,
50
51
  getNextActions,
51
52
  getSpecificationValue,
52
53
  type SpecAction,
53
54
  } from "./spec-description";
55
+ import {
56
+ createStateWriter,
57
+ type GraphState,
58
+ type StateDump,
59
+ type StateWriter,
60
+ } from "./state-graph";
54
61
  import { getRepresentative, getSymmetryGroup } from "./symmetry";
55
62
  import { getTlcStringOrder, getTlcVariableOrder } from "./tlc-order";
56
63
  import { createTlcFingerprinter, getTlcFingerprint } from "./tlc-random";
@@ -60,6 +67,7 @@ import { createCounterExample } from "./tlc-ext";
60
67
  import { getFingerprintDistance, OUT_DEGREE_BUCKETS } from "./tlc-summary";
61
68
  import {
62
69
  combineHash,
70
+ formatState,
63
71
  formatValue,
64
72
  getValueHash,
65
73
  isFunctionValue,
@@ -83,6 +91,8 @@ export interface CheckOptions {
83
91
  workers?: number;
84
92
  // TLC's -lncheck: "final" checks liveness only on the complete state graph.
85
93
  livenessCheck?: "default" | "final";
94
+ // TLC's -dump: writes the reachable states, or with `dot` the state graph, through writeFile.
95
+ dump?: StateDump;
86
96
  }
87
97
 
88
98
  export type CheckStatus =
@@ -518,7 +528,9 @@ const getMembership = (
518
528
  const getStateChecks = (named: NamedExpression[], environment: Environment): StateCheck[] =>
519
529
  named.flatMap((item) =>
520
530
  getConjuncts(item.expression, environment).map((expression) => {
521
- 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;
522
534
  return {
523
535
  name: item.name,
524
536
  expression,
@@ -831,7 +843,10 @@ export const createSearch = (
831
843
  )
832
844
  );
833
845
  } catch (error) {
834
- throw withHeadline(error, `Evaluating action property ${property.name} failed.`);
846
+ throw withHeadline(
847
+ withNextStateExitCode(error),
848
+ `Evaluating action property ${property.name} failed.`,
849
+ );
835
850
  }
836
851
  }),
837
852
  satisfiesActionConstraints: (state, next) =>
@@ -867,6 +882,11 @@ export const createSearch = (
867
882
  };
868
883
  };
869
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
+
870
890
  const withHeadline = (error: unknown, headline: string) =>
871
891
  error instanceof TlaEvaluationError
872
892
  ? setExitCode(
@@ -875,8 +895,15 @@ const withHeadline = (error: unknown, headline: string) =>
875
895
  )
876
896
  : error;
877
897
 
898
+ // TLC finishes the -dump file whether or not the search finds a violation.
878
899
  export const checkSequentially = (options: CheckOptions): CheckResult => {
879
- 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 => {
880
907
  const config = typeof options.config === "string" ? parseConfig(options.config) : options.config;
881
908
  const onPrint = options.onPrint ?? console.log;
882
909
  // TLC prints again while it rebuilds a trace, between the states it prints. Printing those lines
@@ -1023,11 +1050,16 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1023
1050
  position: number,
1024
1051
  loopStart: number | undefined,
1025
1052
  ) => {
1026
- const state = steps[position].state;
1027
- const next = (steps[position + 1] ?? steps[loopStart ?? position]).state;
1028
1053
  // TLC evaluates TLCGet("level") and Trace in an alias at the state's position in the trace.
1029
1054
  runtime.getLevel = () => position + 1;
1030
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) => {
1031
1063
  try {
1032
1064
  const body = getConfigDefinition("alias", alias, environment).body;
1033
1065
  const value = evaluate(createIdentifier(alias), getContext(environment, state, next));
@@ -1228,6 +1260,18 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1228
1260
  return current.isExpanding ? depths[current.index] + 1 : 0;
1229
1261
  };
1230
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
+
1231
1275
  const visitInitialState = (state: Value[]) => {
1232
1276
  canonicalizeState(state);
1233
1277
  runtime.generatedStates++;
@@ -1244,6 +1288,7 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1244
1288
  countDistinctState(1);
1245
1289
  runtime.queueSize++;
1246
1290
  liveness?.addInitialState(states.length, state);
1291
+ stateWriter?.writeInitialState(getGraphState(state, 1));
1247
1292
  }
1248
1293
  const violated = search.findViolatedInvariant(state);
1249
1294
  if (violated) {
@@ -1264,7 +1309,13 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1264
1309
  addState(state, fingerprintState, -1, undefined);
1265
1310
  return undefined;
1266
1311
  };
1267
- 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
+ ) => {
1268
1319
  const state = states[index];
1269
1320
  runtime.generatedStates++;
1270
1321
  current.candidate = successor.state;
@@ -1278,6 +1329,14 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1278
1329
  const isInModel = isStateInModel && search.satisfiesActionConstraints(state, successor.state);
1279
1330
  if (isInModel) search.trackActionPossible(state, successor.state);
1280
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
+ }
1281
1340
  if (existing !== -1 && liveness) {
1282
1341
  const stored = states[existing];
1283
1342
  const isStored = stored.every((value, position) => value === successor.state[position]);
@@ -1349,23 +1408,55 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1349
1408
  }
1350
1409
  return createSuccess();
1351
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
+ };
1352
1448
  const expandState = (index: number) => {
1353
1449
  const state = states[index];
1354
1450
  const liveSuccessors: LiveSuccessor[] = [];
1355
- const successorCount = forEachSuccessor(
1356
- next,
1357
- state,
1358
- environment,
1359
- (successor) => {
1360
- try {
1361
- outcome.result = visitSuccessor(index, successor, liveSuccessors);
1362
- } catch (error) {
1363
- outcome.result = toFailure(error, getTrace(index, successor));
1364
- }
1365
- return outcome.result !== undefined;
1366
- },
1367
- spec.scope,
1368
- );
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
+ });
1369
1460
  current.isExpanding = false;
1370
1461
  if (outcome.result) return outcome.result;
1371
1462
  if (successorCount === 0 && config.checkDeadlock) {
@@ -1425,7 +1516,6 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1425
1516
  periodic.time += performance.now() - now;
1426
1517
  return lasso;
1427
1518
  };
1428
- setNextStatePhase(true);
1429
1519
  for (let index = 0; index < states.length && !runtime.isStopped; index++) {
1430
1520
  current.index = index;
1431
1521
  current.candidate = undefined;
@@ -1434,7 +1524,7 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1434
1524
  try {
1435
1525
  outcome.result = expandState(index);
1436
1526
  } catch (error) {
1437
- outcome.result = toFailure(error, getStateTrace(index));
1527
+ outcome.result = toFailure(withNextStateExitCode(error), getStateTrace(index));
1438
1528
  }
1439
1529
  if (outcome.result) return outcome.result;
1440
1530
  outDegrees[getOutDegreeBucket()]++;
@@ -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,7 +1,5 @@
1
1
  import { getChildren, isLocallyResolved, type Expression } from "./ast";
2
- import { TlaEvaluationError } from "./errors";
3
2
  import {
4
- describeLocation,
5
3
  bindValue,
6
4
  expectBoolean,
7
5
  findGlobalName,
@@ -18,13 +16,16 @@ import {
18
16
  isWorthCaching,
19
17
  keepLazy,
20
18
  resolveGlobalOperator,
19
+ createPrimeOutsideActionError,
20
+ createUnassignedError,
21
+ getSortedFields,
22
+ hasDuplicateFields,
21
23
  type Context,
22
24
  type Environment,
23
25
  type Evaluator,
24
26
  } from "./evaluate";
25
27
  import {
26
28
  applyFunction,
27
- compareValues,
28
29
  createEnumeratedSet,
29
30
  createSortedFunction,
30
31
  createTuple,
@@ -82,14 +83,10 @@ const createRuntime = () => ({
82
83
  equal: valuesEqual,
83
84
  enumerate: getEnumeratedElements,
84
85
  unassigned: (name: string, expression: Expression): never => {
85
- throw new TlaEvaluationError(
86
- `The variable ${name} is not assigned at ${describeLocation(expression)}`,
87
- );
86
+ throw createUnassignedError(name, expression);
88
87
  },
89
88
  primeOutsideAction: (expression: Expression): never => {
90
- throw new TlaEvaluationError(
91
- `A primed expression appears outside an action at ${describeLocation(expression)}`,
92
- );
89
+ throw createPrimeOutsideActionError(expression);
93
90
  },
94
91
  prime: (context: Context): Context => ({
95
92
  environment: context.environment,
@@ -260,13 +257,8 @@ const generateExpression = (generator: Generator, expression: Expression, frame:
260
257
  case "FieldAccess":
261
258
  return `apply(${generate(expression.record)}, ${JSON.stringify(expression.field)}, ${addReference(generator, getFieldError(expression))})`;
262
259
  case "Record": {
263
- const fields = [...expression.fields].sort((left, right) =>
264
- compareValues(left.name, right.name),
265
- );
266
- const hasDuplicates = fields.some(
267
- (field, index) => index > 0 && fields[index - 1].name === field.name,
268
- );
269
- if (hasDuplicates) return generateDelegate(generator, expression, frame);
260
+ const fields = getSortedFields(expression.fields);
261
+ if (hasDuplicateFields(fields)) return generateDelegate(generator, expression, frame);
270
262
  const names = addReference(
271
263
  generator,
272
264
  fields.map((field) => field.name),
@@ -17,7 +17,8 @@ import { EXIT_STATUS, setExitCode } from "./exit-codes";
17
17
  import {
18
18
  createBigNumberError,
19
19
  createRealNumberError,
20
- isConstantLevel,
20
+ evaluate,
21
+ getDefinition,
21
22
  isTlcInteger,
22
23
  type Builtin,
23
24
  type Environment,
@@ -44,7 +45,7 @@ import {
44
45
  import { createRuntime } from "./runtime";
45
46
  import { CORE_OPERATORS, getStandardModule, STANDARD_DEPENDENCIES } from "./standard-modules";
46
47
  import { resolveInstanceSubexpressions, resolveModuleSubexpressions } from "./subexpressions";
47
- import { checkModuleLevels } from "./levels";
48
+ import { checkModuleLevels, createLevelAnalyzer } from "./levels";
48
49
  import { checkInstances, type InstanceCheck } from "./substitution-levels";
49
50
  import {
50
51
  checkInteger,
@@ -212,6 +213,8 @@ export const createEnvironment = (
212
213
  const root = parseModule(options.source);
213
214
  const definitions = new Map<string, Definition>();
214
215
  const parameterized = new Map<string, boolean>();
216
+ // The definition each instance copy came from, and the instance parameters the copy adds.
217
+ const copySources = new Map<string, { source: string; prefix: number }>();
215
218
  const builtins = new Map<string, Builtin>(
216
219
  CORE_OPERATORS.map((operator) => [operator.name, operator]),
217
220
  );
@@ -379,10 +382,11 @@ export const createEnvironment = (
379
382
  variables: new Set(linked.variables),
380
383
  getDefinition: (key) => definitions.get(key),
381
384
  isParameterized: (key) => parameterized.get(key) === true,
382
- addDefinition: (name, create) => {
385
+ addDefinition: (source, name, create) => {
383
386
  const key = createName(`${name}@${module.name}`);
384
387
  definitions.set(key, create(key));
385
388
  parameterized.set(key, !isParameterFree);
389
+ copySources.set(key, { source, prefix: instance.params.length });
386
390
  return key;
387
391
  },
388
392
  createName,
@@ -544,7 +548,7 @@ export const createEnvironment = (
544
548
  variables: new Set(linked.variables),
545
549
  getDefinition: (key) => definitions.get(key),
546
550
  isParameterized: (key) => parameterized.get(key) === true,
547
- addDefinition: (name, create) => {
551
+ addDefinition: (_source, name, create) => {
548
552
  const key = `${name}${KEY_SEPARATOR}${instance.module}${suffix}.${copies.length}`;
549
553
  const definition = create(key);
550
554
  copies.push(
@@ -872,6 +876,38 @@ export const createEnvironment = (
872
876
  );
873
877
  }
874
878
  });
879
+ // TLC sets a module-scoped entry on the body of the module's definition, which every instance of
880
+ // the module shares.
881
+ const scopedKeys = new Set(
882
+ [...config.constants, ...config.substitutions]
883
+ .filter((item) => item.module !== undefined)
884
+ .flatMap(getScopedKeys),
885
+ );
886
+ const getOverride = (
887
+ key: string,
888
+ prefix: number,
889
+ ): { key: string; prefix: number } | undefined => {
890
+ if (scopedKeys.has(key)) return { key, prefix };
891
+ const copy = copySources.get(key);
892
+ return copy && getOverride(copy.source, prefix + copy.prefix);
893
+ };
894
+ copySources.forEach((copy, key) => {
895
+ const override = getOverride(copy.source, copy.prefix);
896
+ const definition = definitions.get(key);
897
+ if (!override || !definition) return;
898
+ const params = definition.kind === "Operator" ? definition.params : [];
899
+ const alias = createLocalAlias(
900
+ key,
901
+ override.key,
902
+ params,
903
+ params.slice(override.prefix),
904
+ definition.location,
905
+ );
906
+ definitions.set(key, alias);
907
+ linkedRoot.visible.forEach((symbol, name) => {
908
+ if (symbol.key === key && name !== key) definitions.set(name, alias);
909
+ });
910
+ });
875
911
  declaredConstants.forEach((name) => {
876
912
  if (!constants.has(name) && !substitutions.has(name) && !operatorKeys.has(name)) {
877
913
  throw new TlaConfigError(`The constant ${name} is not assigned a value by the configuration`);
@@ -907,18 +943,41 @@ export const createEnvironment = (
907
943
  getDefinition: (symbol) => definitions.get(linked.visible.get(symbol)?.key ?? symbol),
908
944
  };
909
945
  });
946
+ // TLC evaluates a substitute at startup and rejects it only when that fails and the level bound it
947
+ // computes is above constant. The bound counts the operators that TLC's Java code overrides with
948
+ // a minimum level as state-level, so the analyzer takes them for variables.
949
+ const analyzer = createLevelAnalyzer({
950
+ constants: new Set(constants.keys()),
951
+ variables: new Set([
952
+ ...variables,
953
+ ...["TLCGet", "Trace", "CounterExample"].filter((name) => builtins.has(name)),
954
+ ]),
955
+ getDefinition: (name) => getDefinition(name, environment),
956
+ });
957
+ const isEvaluable = (body: Expression) => {
958
+ try {
959
+ evaluate(body, { environment, scope: undefined, state: undefined, next: undefined });
960
+ return true;
961
+ } catch (error) {
962
+ if (error instanceof TlaEvaluationError) return false;
963
+ throw error;
964
+ }
965
+ };
910
966
  substitutions.forEach((target, name) => {
911
967
  const definition = definitions.get(target);
912
968
  if (
913
969
  declaredConstants.includes(name) &&
914
- definition &&
915
- !isConstantLevel(definition, environment)
970
+ definition?.kind === "Operator" &&
971
+ definition.params.length === 0 &&
972
+ analyzer.analyzeDefinition(definition, new Map()).level > 0 &&
973
+ !isEvaluable(definition.body)
916
974
  ) {
917
975
  throw new TlaConfigError(
918
976
  `The configuration file substitutes constant ${name} with non-constant ${target}`,
919
977
  );
920
978
  }
921
979
  });
980
+ runtime.isStarted = true;
922
981
  return {
923
982
  environment,
924
983
  assumptions,
package/src/errors.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { EXIT_STATUS, getExitCode, setModuleExitCode } from "./exit-codes";
1
+ import { EXIT_STATUS, getExitCode } from "./exit-codes";
2
2
 
3
3
  // How TLC reports a RuntimeException it did not expect, such as one raised while computing next
4
4
  // states.
@@ -46,10 +46,12 @@ export class TlaEvaluationError extends TlaError {
46
46
  // An evaluation error that TLC raises as an EvalException from a standard module's Java code. It
47
47
  // keeps the name TlaEvaluationError, and index.ts doesn't export it.
48
48
  export class TlaModuleError extends TlaEvaluationError {
49
+ exitCode: number;
50
+
49
51
  constructor(message: string, exitCode: number = EXIT_STATUS.error) {
50
52
  super(message);
51
53
  this.name = "TlaEvaluationError";
52
- setModuleExitCode(this, exitCode);
54
+ this.exitCode = exitCode;
53
55
  }
54
56
  }
55
57
 
package/src/evaluate.ts CHANGED
@@ -771,11 +771,7 @@ const evaluateLocalIdentifier = (name: string, expression: Expression, context:
771
771
  const global = findGlobalName(name, context.environment);
772
772
  if (global?.kind === "Variable") {
773
773
  const value = context.state?.[global.index];
774
- if (value === undefined) {
775
- throw new TlaEvaluationError(
776
- `The variable ${name} is not assigned at ${describeLocation(expression)}`,
777
- );
778
- }
774
+ if (value === undefined) throw createUnassignedError(name, expression);
779
775
  return value;
780
776
  }
781
777
  if (global?.kind === "Value") return global.value;
@@ -1055,11 +1051,7 @@ const compileIdentifier = (
1055
1051
  const index = global.index;
1056
1052
  return (context) => {
1057
1053
  const value = context.state?.[index];
1058
- if (value === undefined) {
1059
- throw new TlaEvaluationError(
1060
- `The variable ${name} is not assigned at ${describeLocation(expression)}`,
1061
- );
1062
- }
1054
+ if (value === undefined) throw createUnassignedError(name, expression);
1063
1055
  return value;
1064
1056
  };
1065
1057
  }
@@ -1571,11 +1563,24 @@ const compileSetComprehension = (
1571
1563
  };
1572
1564
  };
1573
1565
 
1574
- const compileRecord = (recordFields: RecordField[], environment: Environment): Evaluator => {
1575
- const fields = [...recordFields].sort((left, right) => compareValues(left.name, right.name));
1576
- const hasDuplicates = fields.some(
1577
- (field, index) => index > 0 && fields[index - 1].name === field.name,
1566
+ // TLC orders a record's fields by name.
1567
+ export const getSortedFields = (fields: RecordField[]) =>
1568
+ [...fields].sort((left, right) => compareValues(left.name, right.name));
1569
+
1570
+ export const hasDuplicateFields = (sortedFields: RecordField[]) =>
1571
+ sortedFields.some((field, index) => index > 0 && sortedFields[index - 1].name === field.name);
1572
+
1573
+ export const createUnassignedError = (name: string, expression: Expression) =>
1574
+ new TlaEvaluationError(`The variable ${name} is not assigned at ${describeLocation(expression)}`);
1575
+
1576
+ export const createPrimeOutsideActionError = (expression: Expression) =>
1577
+ new TlaEvaluationError(
1578
+ `A primed expression appears outside an action at ${describeLocation(expression)}`,
1578
1579
  );
1580
+
1581
+ const compileRecord = (recordFields: RecordField[], environment: Environment): Evaluator => {
1582
+ const fields = getSortedFields(recordFields);
1583
+ const hasDuplicates = hasDuplicateFields(fields);
1579
1584
  const values = fields.map((field) => getEvaluator(field.value, environment));
1580
1585
  if (hasDuplicates) {
1581
1586
  return (context) =>
@@ -1653,11 +1658,7 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
1653
1658
  case "Prime": {
1654
1659
  const inner = child(expression.expression);
1655
1660
  return (context) => {
1656
- if (!context.next) {
1657
- throw new TlaEvaluationError(
1658
- `A primed expression appears outside an action at ${describeLocation(expression)}`,
1659
- );
1660
- }
1661
+ if (!context.next) throw createPrimeOutsideActionError(expression);
1661
1662
  return inner({
1662
1663
  environment: context.environment,
1663
1664
  scope: context.scope,
@@ -1737,9 +1738,7 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
1737
1738
  case "Record":
1738
1739
  return compileRecord(expression.fields, environment);
1739
1740
  case "RecordSet": {
1740
- const fields = [...expression.fields].sort((left, right) =>
1741
- compareValues(left.name, right.name),
1742
- );
1741
+ const fields = getSortedFields(expression.fields);
1743
1742
  const names = fields.map((field) => field.name);
1744
1743
  const sets = fields.map((field) => child(field.value));
1745
1744
  return (context) => ({ kind: "RecordSet", names, sets: sets.map((set) => set(context)) });
package/src/exit-codes.ts CHANGED
@@ -17,12 +17,6 @@ export const EXIT_STATUS = {
17
17
  } as const;
18
18
 
19
19
  const exitCodes = new WeakMap<Error, number>();
20
- const moduleExitCodes = new WeakMap<Error, number>();
21
- const phase = { isNextState: false };
22
-
23
- export const setNextStatePhase = (isNextState: boolean) => {
24
- phase.isNextState = isNextState;
25
- };
26
20
 
27
21
  // The innermost site that knows TLC's exit status for an error sets it first and wins.
28
22
  export const setExitCode = <Thrown>(error: Thrown, code: number) => {
@@ -30,13 +24,7 @@ export const setExitCode = <Thrown>(error: Thrown, code: number) => {
30
24
  return error;
31
25
  };
32
26
 
33
- // TLC exits with the code of an exception from a standard module's Java code only when the exception
34
- // escapes the computation of next states. In every other phase, the phase decides the code.
35
- export const setModuleExitCode = (error: Error, code: number) => {
36
- if (phase.isNextState) moduleExitCodes.set(error, code);
37
- };
38
-
39
- export const getExitCode = (error: Error) => exitCodes.get(error) ?? moduleExitCodes.get(error);
27
+ export const getExitCode = (error: Error) => exitCodes.get(error);
40
28
 
41
29
  // TLC exits with 255 when it fails to process or evaluate a liveness property, in any phase.
42
30
  const withErrorExitCode = <Result>(run: () => Result) => {
package/src/instances.ts CHANGED
@@ -219,7 +219,7 @@ interface Instantiation {
219
219
  variables: Set<string>;
220
220
  getDefinition: (key: string) => Definition | undefined;
221
221
  isParameterized: (key: string) => boolean;
222
- addDefinition: (name: string, create: (key: string) => Definition) => string;
222
+ addDefinition: (source: string, name: string, create: (key: string) => Definition) => string;
223
223
  createName: (name: string) => string;
224
224
  }
225
225
 
@@ -640,7 +640,7 @@ const copyDefinition = (rewrite: Rewrite, key: string): string => {
640
640
  const instantiation = rewrite.instantiation;
641
641
  const definition = instantiation.getDefinition(key);
642
642
  if (!definition) return key;
643
- return instantiation.addDefinition(definition.name, (copyKey) => {
643
+ return instantiation.addDefinition(key, definition.name, (copyKey) => {
644
644
  rewrite.copies.set(key, copyKey);
645
645
  const rename = createRenamer(rewrite);
646
646
  const mapped = renameParams(
@@ -679,7 +679,7 @@ export const createInstantiation = (instantiation: Instantiation) => {
679
679
  if (copy !== undefined) return copy;
680
680
  const definition = instantiation.getDefinition(key);
681
681
  if (!definition) return key;
682
- return instantiation.addDefinition(definition.name, () =>
682
+ return instantiation.addDefinition(key, definition.name, () =>
683
683
  withInstanceParams(definition, instantiation.params, definition.location),
684
684
  );
685
685
  },
package/src/parallel.ts CHANGED
@@ -114,9 +114,12 @@ export const check = async (options: CheckOptions): Promise<CheckResult> => {
114
114
  });
115
115
  };
116
116
  const count = options.workers ?? 1;
117
+ // TLC's workers write the -dump state graph in whichever order they find it, so one worker
118
+ // writes the graph a single TLC worker does.
117
119
  const isSequential =
118
120
  count < 2 ||
119
121
  typeof SharedArrayBuffer !== "function" ||
122
+ options.dump !== undefined ||
120
123
  config.view !== undefined ||
121
124
  config.postconditions.length > 0 ||
122
125
  config.possible.length > 0;