tla-ts 0.0.3-dev.4c8c06c → 0.0.3-dev.4cf9a33

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.
Files changed (48) hide show
  1. package/README.md +16 -2
  2. package/dist/index.cjs +1 -1
  3. package/dist/index.d.cts +47 -22
  4. package/dist/index.d.ts +47 -22
  5. package/dist/index.js +1 -1
  6. package/dist/parallel-worker.cjs +1 -1
  7. package/dist/parallel-worker.js +2 -2
  8. package/dist/parallel.cjs +1 -1
  9. package/dist/parallel.js +2 -2
  10. package/dist/run-cli.cjs +19 -16
  11. package/dist/run-cli.js +20 -17
  12. package/dist/transfer.cjs +36 -15
  13. package/dist/transfer.js +36 -15
  14. package/package.json +1 -1
  15. package/src/ast.ts +93 -0
  16. package/src/check.ts +438 -98
  17. package/src/cli-options.ts +11 -5
  18. package/src/codegen.ts +15 -22
  19. package/src/config.ts +224 -170
  20. package/src/dependencies.ts +2 -2
  21. package/src/environment.ts +116 -28
  22. package/src/errors.ts +65 -3
  23. package/src/evaluate.ts +163 -156
  24. package/src/exit-codes.ts +39 -42
  25. package/src/instances.ts +16 -15
  26. package/src/levels.ts +62 -34
  27. package/src/live-check.ts +772 -0
  28. package/src/liveness.ts +120 -543
  29. package/src/parallel-worker.ts +7 -3
  30. package/src/parallel.ts +20 -4
  31. package/src/parser.ts +33 -11
  32. package/src/resolve.ts +122 -44
  33. package/src/run-cli.ts +91 -19
  34. package/src/runtime.ts +3 -1
  35. package/src/spec-description.ts +19 -8
  36. package/src/standard-modules.ts +2 -7
  37. package/src/state-graph.ts +157 -0
  38. package/src/subexpressions.ts +10 -10
  39. package/src/successors.ts +145 -27
  40. package/src/symmetry.ts +16 -6
  41. package/src/tableau.ts +51 -24
  42. package/src/tlc-ext.ts +29 -12
  43. package/src/tlc-module.ts +14 -33
  44. package/src/tlc-modules.ts +4 -0
  45. package/src/tlc-order.ts +25 -7
  46. package/src/tlc-random.ts +9 -6
  47. package/src/tlc-summary.ts +20 -5
  48. package/src/values.ts +121 -20
@@ -15,7 +15,7 @@ import type {
15
15
  WorkerMessage,
16
16
  } from "./parallel";
17
17
  import { getSuccessors, type Successor } from "./successors";
18
- import { getTlcStringOrder, getTlcVariableOrder } from "./tlc-order";
18
+ import { getTlcStringOrder, getTlcDeclarationOrder } from "./tlc-order";
19
19
  import { OUT_DEGREE_BUCKETS } from "./tlc-summary";
20
20
  import { createStateDecoder, createStateEncoder, type EncodedStates } from "./transfer";
21
21
  import { getRankedStringCount, setStringOrder, type Value } from "./values";
@@ -61,7 +61,7 @@ const run = (start: StartMessage, parent: Port) => {
61
61
  });
62
62
  const environment = specification.environment;
63
63
  const search = createSearch(start.config, environment, () =>
64
- getTlcVariableOrder(start.source, loadModule),
64
+ getTlcDeclarationOrder(start.source, loadModule, "variable"),
65
65
  );
66
66
  const nextAction = search?.spec.next;
67
67
  if (!search || nextAction === undefined)
@@ -128,7 +128,11 @@ const run = (start: StartMessage, parent: Port) => {
128
128
  if (isSharedFingerprintsFull(shared.fingerprints)) return "paused";
129
129
  const successor = successors[expansion.index];
130
130
  if (search.findViolatedActionProperty(state, successor.state)) return undefined;
131
- if (!search.satisfiesActionConstraints(state, successor.state)) continue;
131
+ if (!search.satisfiesActionConstraints(state, successor.state)) {
132
+ // TLC checks the invariants of every successor it has not seen, even outside the model.
133
+ if (search.findViolatedInvariant(successor.state, state)) return undefined;
134
+ continue;
135
+ }
132
136
  if (generatedStates) {
133
137
  writeStateFingerprint(successor.state, fingerprint);
134
138
  if (!generatedStates.insert(fingerprint[0], fingerprint[1])) continue;
package/src/parallel.ts CHANGED
@@ -20,7 +20,7 @@ import {
20
20
  type SharedFingerprints,
21
21
  } from "./fingerprints";
22
22
  import { getInitialStates } from "./successors";
23
- import { getTlcStringOrder, getTlcVariableOrder } from "./tlc-order";
23
+ import { getTlcStringOrder, getTlcDeclarationOrder } from "./tlc-order";
24
24
  import { getFingerprintDistance, OUT_DEGREE_BUCKETS } from "./tlc-summary";
25
25
  import { createStateEncoder, type EncodedStates } from "./transfer";
26
26
  import { getRankedStringCount, setStringOrder, type Value } from "./values";
@@ -102,11 +102,24 @@ const spawnWorker = async (onMessage: (message: WorkerMessage) => void): Promise
102
102
 
103
103
  export const check = async (options: CheckOptions): Promise<CheckResult> => {
104
104
  const config = typeof options.config === "string" ? parseConfig(options.config) : options.config;
105
- const fallBack = () => checkSequentially({ ...options, config });
105
+ const print = options.onPrint ?? console.log;
106
+ const printed = { count: 0 };
107
+ // The search on the calling thread prints what this one printed while it started, so it skips that.
108
+ const fallBack = () => {
109
+ const skipped = { count: printed.count };
110
+ return checkSequentially({
111
+ ...options,
112
+ config,
113
+ onPrint: (text) => (skipped.count-- > 0 ? undefined : print(text)),
114
+ });
115
+ };
106
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.
107
119
  const isSequential =
108
120
  count < 2 ||
109
121
  typeof SharedArrayBuffer !== "function" ||
122
+ options.dump !== undefined ||
110
123
  config.view !== undefined ||
111
124
  config.postconditions.length > 0 ||
112
125
  config.possible.length > 0;
@@ -129,12 +142,15 @@ export const check = async (options: CheckOptions): Promise<CheckResult> => {
129
142
  source: options.source,
130
143
  loadModule,
131
144
  loadClass,
132
- print: options.onPrint ?? console.log,
145
+ print: (text) => {
146
+ printed.count++;
147
+ print(text);
148
+ },
133
149
  files: { readFile: options.readFile, writeFile: options.writeFile },
134
150
  });
135
151
  const environment = specification.environment;
136
152
  const search = createSearch(config, environment, () =>
137
- getTlcVariableOrder(options.source, loadModule),
153
+ getTlcDeclarationOrder(options.source, loadModule, "variable"),
138
154
  );
139
155
  if (findAssumptionViolation(specification.assumptions, environment)) return fallBack();
140
156
  if (
package/src/parser.ts CHANGED
@@ -22,7 +22,7 @@ import type {
22
22
  StepBody,
23
23
  UseOrHide,
24
24
  } from "./ast";
25
- import { TlaSyntaxError } from "./errors";
25
+ import { createSanyError, formatRange, TlaSyntaxError } from "./errors";
26
26
  import { getNumeralValue, tokenize, type Token } from "./lexer";
27
27
 
28
28
  interface InfixOperator {
@@ -135,6 +135,8 @@ const INFIX_OPERATORS = new Map<string, InfixOperator>([
135
135
  ["^^", createInfix(14, 14, false)],
136
136
  ]);
137
137
 
138
+ const NEGATION_PRECEDENCE = 12;
139
+
138
140
  const POSTFIX_OPERATORS = new Set(["^+", "^*", "^#"]);
139
141
 
140
142
  const PREFIX_OPERATOR_REFERENCES = new Set(["-", "~", "-."]);
@@ -629,11 +631,15 @@ const parse = (source: string, isTlapm: boolean): Module => {
629
631
  return parseExpression();
630
632
  };
631
633
 
634
+ const lastArguments: { range: SourceRange | undefined } = { range: undefined };
635
+
632
636
  const parseArguments = () =>
633
637
  withoutOffside(() => {
638
+ const start = cursor.index;
634
639
  expect("(");
635
640
  const args = parseSeparated(parseArgument);
636
641
  expect(")");
642
+ lastArguments.range = getRange(start);
637
643
  return args;
638
644
  });
639
645
 
@@ -660,9 +666,12 @@ const parse = (source: string, isTlapm: boolean): Module => {
660
666
  if (peek().kind === "Identifier" && (isAt("|->", 1) || isAt(":", 1))) {
661
667
  const kind = isAt("|->", 1) ? "Record" : "RecordSet";
662
668
  const fields = parseSeparated(() => {
669
+ const fieldStart = cursor.index;
670
+ const fieldLocation = getLocation(peek());
663
671
  const name = expectIdentifier();
672
+ fieldLocation.range = getRange(fieldStart);
664
673
  expect(kind === "Record" ? "|->" : ":");
665
- return { name, value: parseExpression() };
674
+ return { name, value: parseExpression(), location: fieldLocation };
666
675
  });
667
676
  expect("]");
668
677
  return { kind, fields, location };
@@ -854,7 +863,7 @@ const parse = (source: string, isTlapm: boolean): Module => {
854
863
  const args = hasArguments ? parseArguments() : [];
855
864
  if (!isSelectorAhead()) {
856
865
  return hasArguments
857
- ? { kind: "Apply", operator: name, args, location }
866
+ ? { kind: "Apply", operator: name, args, argumentsRange: lastArguments.range, location }
858
867
  : { kind: "Identifier", name, location };
859
868
  }
860
869
  const instance = openModules
@@ -883,9 +892,10 @@ const parse = (source: string, isTlapm: boolean): Module => {
883
892
  const argumentCounts = selectors.map((selector) =>
884
893
  "args" in selector ? selector.args.length : 0,
885
894
  );
895
+ const argumentsRange = lastArguments.range;
886
896
  return argumentCounts.slice(0, -1).some((count) => count > 0)
887
- ? { kind: "Apply", operator, args: qualifiedArgs, argumentCounts, location }
888
- : { kind: "Apply", operator, args: qualifiedArgs, location };
897
+ ? { kind: "Apply", operator, args: qualifiedArgs, argumentCounts, argumentsRange, location }
898
+ : { kind: "Apply", operator, args: qualifiedArgs, argumentsRange, location };
889
899
  }
890
900
  if (token.kind === "Operator" && isOperatorName(token.text) && isAt("("))
891
901
  return { kind: "Apply", operator: token.text, args: parseArguments(), location };
@@ -977,7 +987,12 @@ const parse = (source: string, isTlapm: boolean): Module => {
977
987
  return { kind: "Apply", operator: "~", args: [parseExpression(5)], location };
978
988
  case "-":
979
989
  advance();
980
- return { kind: "Apply", operator: "-.", args: [parseExpression(13)], location };
990
+ return {
991
+ kind: "Apply",
992
+ operator: "-.",
993
+ args: [parseExpression(NEGATION_PRECEDENCE + 1)],
994
+ location,
995
+ };
981
996
  case "[]":
982
997
  advance();
983
998
  return { kind: "Always", expression: parseExpression(16), location };
@@ -1054,6 +1069,10 @@ const parse = (source: string, isTlapm: boolean): Module => {
1054
1069
  }
1055
1070
  }
1056
1071
  advance();
1072
+ // SANY reads - after an infix operator as prefix -, and rejects it after one that binds tighter.
1073
+ if (infix.low > NEGATION_PRECEDENCE && isAt("-")) {
1074
+ throw createError(`Precedence conflict between ${token.text} and -`, peek());
1075
+ }
1057
1076
  const right = parseExpression(infix.high + 1);
1058
1077
  const left = state.left;
1059
1078
  if (token.text === "/\\" || token.text === "\\/") {
@@ -1412,11 +1431,14 @@ const parse = (source: string, isTlapm: boolean): Module => {
1412
1431
  location: getLocation(keyword),
1413
1432
  };
1414
1433
  const invalid =
1415
- use.kind === "Hide" && !isTlapm ? use.facts.find((fact) => !isHideFact(fact)) : undefined;
1416
- if (invalid) {
1417
- throw createError(
1418
- "The only expression allowed as a fact in a HIDE is the name of a theorem, assumption, or step",
1419
- invalid.location,
1434
+ use.kind === "Hide" && !isTlapm ? use.facts.filter((fact) => !isHideFact(fact)) : [];
1435
+ if (invalid.length > 0) {
1436
+ throw createSanyError(
1437
+ invalid.map((fact) => ({
1438
+ location: formatRange(fact.location.range ?? getRange(start)),
1439
+ message:
1440
+ "The only expression allowed as a fact in a HIDE is \nthe name of a theorem, assumption, or step.",
1441
+ })),
1420
1442
  );
1421
1443
  }
1422
1444
  return withRange(use, start);
package/src/resolve.ts CHANGED
@@ -1,20 +1,28 @@
1
- import type {
2
- AssumeProve,
3
- Bound,
4
- BoundPattern,
5
- Definition,
6
- Expression,
7
- Instance,
8
- Module,
9
- NewSymbol,
10
- OperatorParam,
11
- Proof,
12
- ProofStep,
13
- SourceLocation,
14
- Theorem,
1
+ import {
2
+ getChildren,
3
+ isLocallyResolved,
4
+ type AssumeProve,
5
+ type Bound,
6
+ type BoundPattern,
7
+ type Definition,
8
+ type Expression,
9
+ type Instance,
10
+ type Module,
11
+ type NewSymbol,
12
+ type OperatorParam,
13
+ type Proof,
14
+ type ProofStep,
15
+ type SourceLocation,
16
+ type SourceRange,
17
+ type Theorem,
15
18
  } from "./ast";
16
- import { TlaSyntaxError } from "./errors";
17
- import { getChildren, isLocallyResolved } from "./evaluate";
19
+ import {
20
+ createSanyError,
21
+ createSemanticError,
22
+ formatRange,
23
+ TlaSyntaxError,
24
+ type SanyError,
25
+ } from "./errors";
18
26
 
19
27
  export interface ModuleSymbol {
20
28
  key: string;
@@ -102,6 +110,21 @@ const findSymbol = (name: string, unit: Unit): ModuleSymbol | undefined => {
102
110
  : unit.imported.get(name);
103
111
  };
104
112
 
113
+ // SANY reports a name at the range of its text.
114
+ const getNameRange = (location: SourceLocation, name: string): SourceRange => ({
115
+ module: location.range?.module ?? "",
116
+ start: location,
117
+ end: { line: location.line, column: location.column + name.length - 1 },
118
+ });
119
+
120
+ // SANY reports an operator symbol applied to operands as one it cannot resolve.
121
+ const getFixity = (expression: Expression) => {
122
+ if (expression.kind !== "Apply") return undefined;
123
+ if (expression.args.length === 2) return "infix";
124
+ if (expression.args.length !== 1) return undefined;
125
+ return isBefore(expression.location, expression.args[0].location) ? "prefix" : "postfix";
126
+ };
127
+
105
128
  // SANY names an undefined operator symbol such as + differently from an undefined identifier.
106
129
  const isOperatorSymbol = (name: string) =>
107
130
  name[0].toLowerCase() === name[0].toUpperCase() &&
@@ -134,7 +157,7 @@ const getSymbolArity = (
134
157
  }
135
158
  // A name such as Inv!P1 selects the label P1 of a definition or theorem, which takes its own
136
159
  // arguments.
137
- const prefix = name.slice(0, name.indexOf("!"));
160
+ const prefix = name.includes("!") ? name.slice(0, name.indexOf("!")) : "";
138
161
  const isSelected =
139
162
  prefix !== "" &&
140
163
  (lookupLocal(scope, prefix) !== undefined ||
@@ -143,11 +166,23 @@ const getSymbolArity = (
143
166
  if (isSelected) {
144
167
  return expression.kind === "Apply" ? expression.args.length : 0;
145
168
  }
146
- const position = `at line ${location.line}, column ${location.column}`;
147
- throw new TlaSyntaxError(
148
- isOperatorSymbol(name)
149
- ? `Could not find declaration or definition of symbol '${name}' ${position}`
150
- : `Unknown operator: \`${name}' ${position}`,
169
+ const range = getNameRange(location, name === "-." ? "-" : name);
170
+ if (!isOperatorSymbol(name)) throw createSemanticError(`Unknown operator: \`${name}'.`, range);
171
+ const missing = {
172
+ location: formatRange(range),
173
+ message: `Could not find declaration or definition of symbol '${name}'.`,
174
+ };
175
+ const fixity = getFixity(expression);
176
+ throw createSanyError(
177
+ fixity && location.range
178
+ ? [
179
+ missing,
180
+ {
181
+ location: formatRange(location.range),
182
+ message: `Couldn't resolve ${fixity} operator symbol \`${name}'.`,
183
+ },
184
+ ]
185
+ : [missing],
151
186
  );
152
187
  };
153
188
 
@@ -234,13 +269,13 @@ const resolveApply = (
234
269
  scope: LocalName | undefined,
235
270
  unit: Unit,
236
271
  ) => {
237
- const callee = lookupLocal(scope, expression.operator)
238
- ? undefined
239
- : getVisibleDefinition(expression.operator, unit);
240
- const arity = getSymbolArity(expression, expression.operator, scope, unit);
272
+ const operator = expression.operator;
273
+ const callee = lookupLocal(scope, operator) ? undefined : getVisibleDefinition(operator, unit);
274
+ const arity = getSymbolArity(expression, operator, scope, unit);
241
275
  if (arity !== expression.args.length) {
242
- throw new TlaSyntaxError(
243
- `The operator ${expression.operator} requires ${arity} arguments at line ${expression.location.line}, column ${expression.location.column}`,
276
+ throw createSemanticError(
277
+ `The operator ${operator} requires ${arity} arguments.`,
278
+ expression.argumentsRange ?? getNameRange(expression.location, operator),
244
279
  );
245
280
  }
246
281
  expression.args.forEach((arg, index) => {
@@ -274,10 +309,12 @@ const resolveExpression = (
274
309
  case "ExceptAt":
275
310
  return;
276
311
  case "Identifier": {
277
- const arity = getSymbolArity(expression, expression.name, scope, unit);
312
+ const name = expression.name;
313
+ const arity = getSymbolArity(expression, name, scope, unit);
278
314
  if (arity > 0) {
279
- throw new TlaSyntaxError(
280
- `The operator ${expression.name} requires ${arity} arguments at line ${expression.location.line}, column ${expression.location.column}`,
315
+ throw createSemanticError(
316
+ `The operator ${name} requires ${arity} arguments.`,
317
+ getNameRange(expression.location, name),
281
318
  );
282
319
  }
283
320
  return;
@@ -346,14 +383,21 @@ const resolveExpression = (
346
383
  resolveAll([expression.domain, expression.range]);
347
384
  return;
348
385
  case "Record":
349
- case "RecordSet":
350
- if (new Set(expression.fields.map((field) => field.name)).size < expression.fields.length) {
351
- throw new TlaSyntaxError(
352
- `Non-unique fields in constructor at line ${expression.location.line}, column ${expression.location.column}`,
386
+ case "RecordSet": {
387
+ const repeated = expression.fields.filter((field, index) =>
388
+ expression.fields.slice(0, index).some((earlier) => earlier.name === field.name),
389
+ );
390
+ if (repeated.length > 0) {
391
+ throw createSanyError(
392
+ repeated.map((field) => ({
393
+ location: formatRange(field.location.range ?? getNameRange(field.location, field.name)),
394
+ message: "Non-unique fields in constructor.",
395
+ })),
353
396
  );
354
397
  }
355
398
  resolveAll(expression.fields.map((field) => field.value));
356
399
  return;
400
+ }
357
401
  case "Except":
358
402
  resolveAll([
359
403
  expression.function,
@@ -768,6 +812,29 @@ export const resolveSubstitutions = (
768
812
  );
769
813
  };
770
814
 
815
+ // SANY reports the errors of every unit it checks, in the order of the units in the module.
816
+ export const collectSemanticErrors = (units: { location: SourceLocation; check: () => void }[]) => {
817
+ const errors: SanyError[] = [];
818
+ units
819
+ .toSorted((left, right) => (isBefore(left.location, right.location) ? -1 : 1))
820
+ .forEach((unit) => {
821
+ try {
822
+ unit.check();
823
+ } catch (error) {
824
+ if (!(error instanceof TlaSyntaxError) || !error.sany) throw error;
825
+ error.sany.errors
826
+ .filter((item) =>
827
+ errors.every(
828
+ (existing) =>
829
+ existing.location !== item.location || existing.message !== item.message,
830
+ ),
831
+ )
832
+ .forEach((item) => errors.push(item));
833
+ }
834
+ });
835
+ if (errors.length > 0) throw createSanyError(errors);
836
+ };
837
+
771
838
  export const resolveModule = (module: Module, unit: ModuleUnit) => {
772
839
  const symbols = createSymbols(module, unit.imported);
773
840
  const facts = new Set(
@@ -781,13 +848,24 @@ export const resolveModule = (module: Module, unit: ModuleUnit) => {
781
848
  self,
782
849
  facts,
783
850
  });
784
- module.definitions.forEach((definition) =>
785
- resolveDefinition(definition, undefined, createUnit(definition.location, definition)),
786
- );
787
- module.assumptions.forEach((assumption) =>
788
- resolveExpression(assumption.expression, undefined, createUnit(assumption.location, undefined)),
789
- );
790
- module.theorems.forEach((theorem) =>
791
- resolveTheorem(theorem, createUnit(theorem.location, undefined)),
792
- );
851
+ collectSemanticErrors([
852
+ ...module.definitions.map((definition) => ({
853
+ location: definition.location,
854
+ check: () =>
855
+ resolveDefinition(definition, undefined, createUnit(definition.location, definition)),
856
+ })),
857
+ ...module.assumptions.map((assumption) => ({
858
+ location: assumption.location,
859
+ check: () =>
860
+ resolveExpression(
861
+ assumption.expression,
862
+ undefined,
863
+ createUnit(assumption.location, undefined),
864
+ ),
865
+ })),
866
+ ...module.theorems.map((theorem) => ({
867
+ location: theorem.location,
868
+ check: () => resolveTheorem(theorem, createUnit(theorem.location, undefined)),
869
+ })),
870
+ ]);
793
871
  };
package/src/run-cli.ts CHANGED
@@ -14,25 +14,29 @@ import type { CheckResult, CheckStatus, TraceStep } from "./check";
14
14
  import { defineCommand, type ParsedArgs } from "./cli-options";
15
15
  import { parseConfig } from "./config";
16
16
  import {
17
+ createSanyError,
17
18
  getErrorExitCode,
18
19
  TlaConfigError,
19
20
  TlaError,
20
21
  TlaEvaluationError,
21
22
  TlaProofError,
23
+ TlaSyntaxError,
24
+ type SanyReport,
22
25
  } from "./errors";
23
26
  import { EXIT_STATUS } from "./exit-codes";
24
27
  import type { LineRange } from "./obligation-generate";
25
28
  import { getAtPrefix, getLocusText } from "./obligation-expression";
26
29
  import { formatSummary, getObligations, WHOLE_MODULE, type ModuleObligations } from "./obligations";
27
30
  import { check } from "./parallel";
28
- import { prettyPrint } from "./pretty-print";
31
+ import { parseModule } from "./parser";
32
+ import type { StateDump } from "./state-graph";
29
33
  import {
30
34
  formatProbability,
31
35
  getActualProbability,
32
36
  getOptimisticProbability,
33
37
  getOutDegreeSummary,
34
38
  } from "./tlc-summary";
35
- import { formatValue, type Value } from "./values";
39
+ import { formatState, type Value } from "./values";
36
40
 
37
41
  const EXIT_CODES: Record<CheckStatus, number> = {
38
42
  success: EXIT_STATUS.success,
@@ -48,6 +52,11 @@ const EXIT_CODES: Record<CheckStatus, number> = {
48
52
  const CHECK_COMMAND = defineCommand("tla-ts <Spec.tla|Spec.cfg|glob>... {options}", [
49
53
  { flag: "-config <Spec.cfg>" },
50
54
  { flag: "-deadlock" },
55
+ // Like TLC, -dump takes a format only when the next argument starts with dot and a file follows.
56
+ {
57
+ flag: "-dump [<format>] <file>",
58
+ getArity: (rest) => (rest.length > 1 && rest[0].startsWith("dot") ? 2 : 1),
59
+ },
51
60
  { flag: "-lncheck <final|default>" },
52
61
  { flag: "-seed <num>" },
53
62
  { flag: "-workers <count|auto>" },
@@ -95,14 +104,24 @@ const getWorkerCount = (values: string[] | undefined) => {
95
104
  : Math.max(1, Number.parseInt(values[0], 10) || 1);
96
105
  };
97
106
 
98
- const printState = (state: Record<string, Value>) => {
99
- const entries = Object.entries(state);
100
- entries.forEach(([name, value]) =>
101
- console.log(
102
- `${entries.length === 1 ? "" : "/\\ "}${name} = ${prettyPrint(formatValue(value))}`,
103
- ),
104
- );
105
- console.log("");
107
+ const printState = (state: Record<string, Value>) => console.log(formatState(state));
108
+
109
+ const UNSUPPORTED_DUMP_FORMATS = ["constrained", "stuttering", "strict"];
110
+
111
+ // TLC names the file of a -dump by its format unless the name already ends that way.
112
+ const getDumpPath = (path: string, extension: string) =>
113
+ path.endsWith(extension) ? path : `${path}${extension}`;
114
+
115
+ const getDump = (values: string[]): StateDump => {
116
+ if (values.length === 1) return { path: getDumpPath(values[0], ".dump") };
117
+ const format = values[0].toLowerCase();
118
+ return {
119
+ path: getDumpPath(values[1], ".dot"),
120
+ dot: true,
121
+ colorize: format.includes("colorize"),
122
+ actionLabels: format.includes("actionlabels"),
123
+ snapshot: format.includes("snapshot"),
124
+ };
106
125
  };
107
126
 
108
127
  const printTrace = (trace: TraceStep[], heading = "Error: The behavior up to this point is:") => {
@@ -113,6 +132,11 @@ const printTrace = (trace: TraceStep[], heading = "Error: The behavior up to thi
113
132
  });
114
133
  };
115
134
 
135
+ const getTemporalHeadline = (names: string[]) =>
136
+ names.length === 1
137
+ ? `Error: Temporal property ${names[0]} was violated.\n`
138
+ : `Error: Temporal properties ${names.slice(0, -1).join(", ")}${names.length > 2 ? "," : ""} and ${names[names.length - 1]} were violated.\n`;
139
+
116
140
  const printResult = (result: CheckResult) => {
117
141
  if (result.failure) {
118
142
  console.log(`Error: ${result.failure.message}`);
@@ -121,6 +145,14 @@ const printResult = (result: CheckResult) => {
121
145
  printState(result.failure.initialState);
122
146
  }
123
147
  printTrace(result.failure.trace);
148
+ const replay = result.failure.replay;
149
+ replay?.output.forEach((line) => console.log(line));
150
+ if (replay?.callStack) {
151
+ const frames = replay.callStack.map((frame, index) => `${index}. ${frame}\n`).join("");
152
+ console.log(
153
+ `Error: The error occurred when TLC was evaluating the nested\nexpressions at the following positions:\n${frames ? `${frames}\n` : " The error call stack is empty.\n"}`,
154
+ );
155
+ }
124
156
  } else if (result.violation) {
125
157
  const violation = result.violation;
126
158
  const name = violation.name;
@@ -140,10 +172,10 @@ const printResult = (result: CheckResult) => {
140
172
  "invariant-violation": isInitial
141
173
  ? `Error: Invariant ${name} is violated by the initial state:`
142
174
  : `Error: Invariant ${name} is violated.`,
143
- "property-violation": `Error: Property ${name} is violated.`,
175
+ "property-violation": getTemporalHeadline(violation.properties ?? [name]),
144
176
  "liveness-violation":
145
177
  loopStart !== undefined
146
- ? `Error: Temporal property ${name} was violated.\n`
178
+ ? getTemporalHeadline(violation.properties ?? [name])
147
179
  : isInitial
148
180
  ? `Error: Property ${name} is violated by the initial state:`
149
181
  : `Error: Action property ${name} is violated.`,
@@ -152,6 +184,8 @@ const printResult = (result: CheckResult) => {
152
184
  if (violation.counts) console.log(violation.counts);
153
185
  console.log(headline);
154
186
  if (isInitial) printState(violation.trace[0].state);
187
+ else if (result.status === "property-violation")
188
+ printTrace(violation.trace, "Error: The following behavior constitutes a counter-example:\n");
155
189
  else if (loopStart === undefined) printTrace(violation.trace);
156
190
  else {
157
191
  printTrace(violation.trace, "Error: The following behavior constitutes a counter-example:\n");
@@ -191,6 +225,20 @@ const checkSpec = async (specPath: string, args: ParsedArgs) => {
191
225
  console.error(`Cannot find the specification file ${specPath}`);
192
226
  return EXIT_STATUS.configParseError;
193
227
  }
228
+ const source = readFileSync(specPath, "utf8");
229
+ const fileName = basename(specPath, ".tla");
230
+ const moduleName = parseModule(source).name;
231
+ if (moduleName !== fileName) {
232
+ throw createSanyError(
233
+ [
234
+ {
235
+ location: "Unknown location",
236
+ message: `File name '${fileName}' does not match the name '${moduleName}' of the top level module it contains.`,
237
+ },
238
+ ],
239
+ true,
240
+ );
241
+ }
194
242
  const configPath =
195
243
  args.get("-config")?.[0] ??
196
244
  (args.has("-config") ? undefined : specPath.replace(/\.tla$/, ".cfg"));
@@ -214,13 +262,26 @@ const checkSpec = async (specPath: string, args: ParsedArgs) => {
214
262
  console.error("Error: expect a strategy such as final for -lncheck option.");
215
263
  return 1;
216
264
  }
265
+ const dumpValues = args.get("-dump");
266
+ if (dumpValues?.length === 0) {
267
+ console.error("Error: A file name for dumping states required.");
268
+ return 1;
269
+ }
270
+ const unsupportedFormat =
271
+ dumpValues?.length === 2 &&
272
+ UNSUPPORTED_DUMP_FORMATS.find((format) => dumpValues[0].toLowerCase().includes(format));
273
+ if (unsupportedFormat) {
274
+ console.error(`Error: tla-ts does not support the -dump format ${unsupportedFormat}.`);
275
+ return 1;
276
+ }
217
277
  const directory = dirname(specPath);
218
278
  console.log(`Checking ${basename(specPath)} with ${basename(configPath)}`);
219
279
  const result = await check({
220
280
  workers: getWorkerCount(args.get("-workers")),
221
281
  livenessCheck: ["final", "seqfinal", "off"].includes(livenessCheck) ? "final" : "default",
222
282
  seed: BigInt(seed),
223
- source: readFileSync(specPath, "utf8"),
283
+ dump: dumpValues && getDump(dumpValues),
284
+ source,
224
285
  config,
225
286
  onPause: () => readSync(0, Buffer.alloc(1)),
226
287
  loadModule: (name) => {
@@ -241,21 +302,32 @@ const checkSpec = async (specPath: string, args: ParsedArgs) => {
241
302
  return result.failure?.exitCode ?? EXIT_CODES[result.status];
242
303
  };
243
304
 
244
- // TLC prints the errors it raises itself. tla-ts names the others, such as a module SANY rejects.
245
- const printError = (error: TlaError) => {
305
+ const formatSanyErrors = (report: SanyReport) =>
306
+ `*** Errors: ${report.errors.length}\n\n${report.errors.map((error) => `${error.location}\n\n${error.message}\n\n`).join("\n")}`;
307
+
308
+ // TLC prints the errors it raises itself, and SANY's report of a spec it rejects. tla-ts names the
309
+ // others, such as a module it cannot parse.
310
+ const printError = (error: TlaError, path?: string) => {
246
311
  if (error instanceof TlaConfigError || error instanceof TlaEvaluationError) {
247
312
  return console.log(`Error: ${error.message}`);
248
313
  }
249
- console.error(`${error.name}: ${error.message}`);
314
+ const report = error instanceof TlaSyntaxError ? error.sany : undefined;
315
+ if (!report || path === undefined) return console.error(`${error.name}: ${error.message}`);
316
+ console.log(
317
+ report.isFatal
318
+ ? `\nFatal errors while parsing TLA+ spec in file ${basename(path, ".tla")}\n\n${report.errors.map((item) => `${item.location}\n\n${item.message}\n`).join("")}${formatSanyErrors(report)}\n`
319
+ : `Semantic errors:\n\n${formatSanyErrors(report)}`,
320
+ );
321
+ console.log("Error: Parsing or semantic analysis failed.");
250
322
  };
251
323
 
252
324
  // Prints a TlaError and returns its exit code.
253
- const reportErrors = async (run: () => number | Promise<number>) => {
325
+ const reportErrors = async (run: () => number | Promise<number>, path?: string) => {
254
326
  try {
255
327
  return await run();
256
328
  } catch (error) {
257
329
  if (!(error instanceof TlaError)) throw error;
258
- printError(error);
330
+ printError(error, path);
259
331
  return getErrorExitCode(error);
260
332
  }
261
333
  };
@@ -266,7 +338,7 @@ const runEach = async (paths: string[], runPath: (path: string) => number | Prom
266
338
  const exitCodes: number[] = [];
267
339
  for (const [index, path] of paths.entries()) {
268
340
  if (index > 0) console.log("");
269
- exitCodes.push(await reportErrors(() => runPath(path)));
341
+ exitCodes.push(await reportErrors(() => runPath(path), path));
270
342
  }
271
343
  return exitCodes.find((exitCode) => exitCode !== EXIT_STATUS.success) ?? EXIT_STATUS.success;
272
344
  };
package/src/runtime.ts CHANGED
@@ -6,7 +6,7 @@ export interface CheckerRuntime {
6
6
  getBehavior: (state: Value[]) => Value[][];
7
7
  getSpecification: () => Value;
8
8
  counterExample: Value | undefined;
9
- setLivenessSource: (index: number) => void;
9
+ setLivenessSource: (index: number | undefined) => void;
10
10
  getCurrentState: () => Value[] | undefined;
11
11
  getFingerprint: (state: Value[]) => bigint;
12
12
  getRandom: () => JavaRandom;
@@ -24,6 +24,7 @@ export interface CheckerRuntime {
24
24
  properties: Map<string, string>;
25
25
  possibleCounts: Map<string, number>;
26
26
  isStopped: boolean;
27
+ isStarted: boolean;
27
28
  checkDeadlock: boolean;
28
29
  startedAt: number;
29
30
  }
@@ -75,6 +76,7 @@ export const createRuntime = (checkDeadlock: boolean, seed = 0n): CheckerRuntime
75
76
  properties: new Map(),
76
77
  possibleCounts: new Map(),
77
78
  isStopped: false,
79
+ isStarted: false,
78
80
  checkDeadlock,
79
81
  startedAt: Date.now(),
80
82
  };