tla-ts 0.0.3-dev.366c320 → 0.0.3-dev.367c92f

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 (49) hide show
  1. package/README.md +5 -1
  2. package/dist/index.cjs +1 -1
  3. package/dist/index.d.cts +53 -22
  4. package/dist/index.d.ts +53 -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 -17
  11. package/dist/run-cli.js +20 -18
  12. package/dist/transfer.cjs +33 -17
  13. package/dist/transfer.js +33 -17
  14. package/package.json +1 -1
  15. package/src/ast.ts +3 -0
  16. package/src/builtins.ts +9 -3
  17. package/src/check.ts +455 -93
  18. package/src/cli-options.ts +11 -5
  19. package/src/codegen.ts +6 -3
  20. package/src/config.ts +224 -170
  21. package/src/environment.ts +114 -19
  22. package/src/errors.ts +78 -1
  23. package/src/evaluate.ts +182 -26
  24. package/src/exit-codes.ts +22 -3
  25. package/src/fingerprints.ts +2 -1
  26. package/src/instances.ts +4 -4
  27. package/src/levels.ts +63 -28
  28. package/src/live-check.ts +132 -70
  29. package/src/liveness.ts +117 -22
  30. package/src/parallel-worker.ts +2 -2
  31. package/src/parallel.ts +5 -2
  32. package/src/parser.ts +57 -16
  33. package/src/resolve.ts +106 -29
  34. package/src/run-cli.ts +103 -18
  35. package/src/runtime.ts +2 -0
  36. package/src/spec-description.ts +12 -6
  37. package/src/standard-modules.ts +54 -45
  38. package/src/state-graph.ts +157 -0
  39. package/src/substitution-levels.ts +17 -9
  40. package/src/successors.ts +169 -33
  41. package/src/symmetry.ts +16 -6
  42. package/src/tableau.ts +51 -24
  43. package/src/tlc-module.ts +11 -5
  44. package/src/tlc-modules.ts +4 -0
  45. package/src/tlc-order.ts +8 -4
  46. package/src/tlc-random.ts +9 -6
  47. package/src/tlc-summary.ts +20 -5
  48. package/src/value-sources.ts +29 -0
  49. package/src/values.ts +242 -61
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 {
@@ -628,14 +628,24 @@ const parse = (source: string, isTlapm: boolean): Module => {
628
628
  const body = parseExpression();
629
629
  return withRange({ kind: "Lambda", params, body, location: getLocation(token) }, start);
630
630
  }
631
- return parseExpression();
631
+ const argument = parseExpression();
632
+ // SANY reads an argument that only names an operator of a parameterized instance, such as
633
+ // I!Op, as that operator, which takes the arguments of the instance too.
634
+ if (argument.kind === "Identifier") missingArguments.delete(argument);
635
+ return argument;
632
636
  };
633
637
 
638
+ const missingArguments = new Map<Expression, { location: string; message: string }>();
639
+
640
+ const lastArguments: { range: SourceRange | undefined } = { range: undefined };
641
+
634
642
  const parseArguments = () =>
635
643
  withoutOffside(() => {
644
+ const start = cursor.index;
636
645
  expect("(");
637
646
  const args = parseSeparated(parseArgument);
638
647
  expect(")");
648
+ lastArguments.range = getRange(start);
639
649
  return args;
640
650
  });
641
651
 
@@ -662,9 +672,12 @@ const parse = (source: string, isTlapm: boolean): Module => {
662
672
  if (peek().kind === "Identifier" && (isAt("|->", 1) || isAt(":", 1))) {
663
673
  const kind = isAt("|->", 1) ? "Record" : "RecordSet";
664
674
  const fields = parseSeparated(() => {
675
+ const fieldStart = cursor.index;
676
+ const fieldLocation = getLocation(peek());
665
677
  const name = expectIdentifier();
678
+ fieldLocation.range = getRange(fieldStart);
666
679
  expect(kind === "Record" ? "|->" : ":");
667
- return { name, value: parseExpression() };
680
+ return { name, value: parseExpression(), location: fieldLocation };
668
681
  });
669
682
  expect("]");
670
683
  return { kind, fields, location };
@@ -823,7 +836,8 @@ const parse = (source: string, isTlapm: boolean): Module => {
823
836
  };
824
837
 
825
838
  const parsePrimary = (): Expression => {
826
- const isFactStart = cursor.index === factStart.index;
839
+ const start = cursor.index;
840
+ const isFactStart = start === factStart.index;
827
841
  const token = advance();
828
842
  const location = getLocation(token);
829
843
  if (isTlapm && token.kind === "Keyword" && token.text === "LAMBDA") {
@@ -856,13 +870,18 @@ const parse = (source: string, isTlapm: boolean): Module => {
856
870
  const args = hasArguments ? parseArguments() : [];
857
871
  if (!isSelectorAhead()) {
858
872
  return hasArguments
859
- ? { kind: "Apply", operator: name, args, location }
873
+ ? { kind: "Apply", operator: name, args, argumentsRange: lastArguments.range, location }
860
874
  : { kind: "Identifier", name, location };
861
875
  }
862
876
  const instance = openModules
863
877
  .flatMap((module) => module.instances)
864
878
  .find((candidate) => candidate.name === name);
865
- if (instance && !isFactStart && !isTlapm && instance.params.length !== args.length) {
879
+ const isMissingArguments =
880
+ instance !== undefined &&
881
+ !isFactStart &&
882
+ !isTlapm &&
883
+ instance.params.length !== args.length;
884
+ if (isMissingArguments && args.length > 0) {
866
885
  throw createError(
867
886
  `The operator ${name} requires ${instance.params.length} arguments`,
868
887
  token,
@@ -876,18 +895,36 @@ const parse = (source: string, isTlapm: boolean): Module => {
876
895
  const names = selectors.flatMap((selector) =>
877
896
  selector.kind === "Name" ? [selector.name] : [],
878
897
  );
879
- if (names.length < selectors.length) return { kind: "Subexpression", selectors, location };
880
898
  const operator = names.join("!");
881
899
  const qualifiedArgs = selectors.flatMap((selector) =>
882
900
  "args" in selector ? selector.args : [],
883
901
  );
884
- if (qualifiedArgs.length === 0) return { kind: "Identifier", name: operator, location };
885
902
  const argumentCounts = selectors.map((selector) =>
886
903
  "args" in selector ? selector.args.length : 0,
887
904
  );
888
- return argumentCounts.slice(0, -1).some((count) => count > 0)
889
- ? { kind: "Apply", operator, args: qualifiedArgs, argumentCounts, location }
890
- : { kind: "Apply", operator, args: qualifiedArgs, location };
905
+ const argumentsRange = lastArguments.range;
906
+ const reference: Expression =
907
+ names.length < selectors.length
908
+ ? { kind: "Subexpression", selectors, location }
909
+ : qualifiedArgs.length === 0
910
+ ? { kind: "Identifier", name: operator, location }
911
+ : argumentCounts.slice(0, -1).some((count) => count > 0)
912
+ ? {
913
+ kind: "Apply",
914
+ operator,
915
+ args: qualifiedArgs,
916
+ argumentCounts,
917
+ argumentsRange,
918
+ location,
919
+ }
920
+ : { kind: "Apply", operator, args: qualifiedArgs, argumentsRange, location };
921
+ if (isMissingArguments) {
922
+ missingArguments.set(reference, {
923
+ location: formatRange(getRange(start)),
924
+ message: `The operator ${name} requires ${instance.params.length} arguments.`,
925
+ });
926
+ }
927
+ return reference;
891
928
  }
892
929
  if (token.kind === "Operator" && isOperatorName(token.text) && isAt("("))
893
930
  return { kind: "Apply", operator: token.text, args: parseArguments(), location };
@@ -1423,11 +1460,14 @@ const parse = (source: string, isTlapm: boolean): Module => {
1423
1460
  location: getLocation(keyword),
1424
1461
  };
1425
1462
  const invalid =
1426
- use.kind === "Hide" && !isTlapm ? use.facts.find((fact) => !isHideFact(fact)) : undefined;
1427
- if (invalid) {
1428
- throw createError(
1429
- "The only expression allowed as a fact in a HIDE is the name of a theorem, assumption, or step",
1430
- invalid.location,
1463
+ use.kind === "Hide" && !isTlapm ? use.facts.filter((fact) => !isHideFact(fact)) : [];
1464
+ if (invalid.length > 0) {
1465
+ throw createSanyError(
1466
+ invalid.map((fact) => ({
1467
+ location: formatRange(fact.location.range ?? getRange(start)),
1468
+ message:
1469
+ "The only expression allowed as a fact in a HIDE is \nthe name of a theorem, assumption, or step.",
1470
+ })),
1431
1471
  );
1432
1472
  }
1433
1473
  return withRange(use, start);
@@ -1705,6 +1745,7 @@ const parse = (source: string, isTlapm: boolean): Module => {
1705
1745
  end: { line: token.line, column: token.endColumn },
1706
1746
  };
1707
1747
  }
1748
+ if (missingArguments.size > 0) throw createSanyError([...missingArguments.values()]);
1708
1749
  openModules.pop();
1709
1750
  recursiveScopes.pop();
1710
1751
  return module;
package/src/resolve.ts CHANGED
@@ -13,9 +13,16 @@ import {
13
13
  type Proof,
14
14
  type ProofStep,
15
15
  type SourceLocation,
16
+ type SourceRange,
16
17
  type Theorem,
17
18
  } from "./ast";
18
- import { TlaSyntaxError } from "./errors";
19
+ import {
20
+ createSanyError,
21
+ createSemanticError,
22
+ formatRange,
23
+ TlaSyntaxError,
24
+ type SanyError,
25
+ } from "./errors";
19
26
 
20
27
  export interface ModuleSymbol {
21
28
  key: string;
@@ -103,6 +110,21 @@ const findSymbol = (name: string, unit: Unit): ModuleSymbol | undefined => {
103
110
  : unit.imported.get(name);
104
111
  };
105
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
+
106
128
  // SANY names an undefined operator symbol such as + differently from an undefined identifier.
107
129
  const isOperatorSymbol = (name: string) =>
108
130
  name[0].toLowerCase() === name[0].toUpperCase() &&
@@ -135,7 +157,7 @@ const getSymbolArity = (
135
157
  }
136
158
  // A name such as Inv!P1 selects the label P1 of a definition or theorem, which takes its own
137
159
  // arguments.
138
- const prefix = name.slice(0, name.indexOf("!"));
160
+ const prefix = name.includes("!") ? name.slice(0, name.indexOf("!")) : "";
139
161
  const isSelected =
140
162
  prefix !== "" &&
141
163
  (lookupLocal(scope, prefix) !== undefined ||
@@ -144,11 +166,23 @@ const getSymbolArity = (
144
166
  if (isSelected) {
145
167
  return expression.kind === "Apply" ? expression.args.length : 0;
146
168
  }
147
- const position = `at line ${location.line}, column ${location.column}`;
148
- throw new TlaSyntaxError(
149
- isOperatorSymbol(name)
150
- ? `Could not find declaration or definition of symbol '${name}' ${position}`
151
- : `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],
152
186
  );
153
187
  };
154
188
 
@@ -235,13 +269,13 @@ const resolveApply = (
235
269
  scope: LocalName | undefined,
236
270
  unit: Unit,
237
271
  ) => {
238
- const callee = lookupLocal(scope, expression.operator)
239
- ? undefined
240
- : getVisibleDefinition(expression.operator, unit);
241
- 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);
242
275
  if (arity !== expression.args.length) {
243
- throw new TlaSyntaxError(
244
- `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),
245
279
  );
246
280
  }
247
281
  expression.args.forEach((arg, index) => {
@@ -275,10 +309,12 @@ const resolveExpression = (
275
309
  case "ExceptAt":
276
310
  return;
277
311
  case "Identifier": {
278
- const arity = getSymbolArity(expression, expression.name, scope, unit);
312
+ const name = expression.name;
313
+ const arity = getSymbolArity(expression, name, scope, unit);
279
314
  if (arity > 0) {
280
- throw new TlaSyntaxError(
281
- `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),
282
318
  );
283
319
  }
284
320
  return;
@@ -347,14 +383,21 @@ const resolveExpression = (
347
383
  resolveAll([expression.domain, expression.range]);
348
384
  return;
349
385
  case "Record":
350
- case "RecordSet":
351
- if (new Set(expression.fields.map((field) => field.name)).size < expression.fields.length) {
352
- throw new TlaSyntaxError(
353
- `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
+ })),
354
396
  );
355
397
  }
356
398
  resolveAll(expression.fields.map((field) => field.value));
357
399
  return;
400
+ }
358
401
  case "Except":
359
402
  resolveAll([
360
403
  expression.function,
@@ -769,6 +812,29 @@ export const resolveSubstitutions = (
769
812
  );
770
813
  };
771
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
+
772
838
  export const resolveModule = (module: Module, unit: ModuleUnit) => {
773
839
  const symbols = createSymbols(module, unit.imported);
774
840
  const facts = new Set(
@@ -782,13 +848,24 @@ export const resolveModule = (module: Module, unit: ModuleUnit) => {
782
848
  self,
783
849
  facts,
784
850
  });
785
- module.definitions.forEach((definition) =>
786
- resolveDefinition(definition, undefined, createUnit(definition.location, definition)),
787
- );
788
- module.assumptions.forEach((assumption) =>
789
- resolveExpression(assumption.expression, undefined, createUnit(assumption.location, undefined)),
790
- );
791
- module.theorems.forEach((theorem) =>
792
- resolveTheorem(theorem, createUnit(theorem.location, undefined)),
793
- );
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
+ ]);
794
871
  };
package/src/run-cli.ts CHANGED
@@ -10,29 +10,33 @@ import {
10
10
  import { spawnSync } from "node:child_process";
11
11
  import { basename, delimiter, dirname, join, resolve } from "node:path";
12
12
  import { availableParallelism } from "node:os";
13
- import type { CheckResult, CheckStatus, TraceStep } from "./check";
13
+ import type { CheckResult, CheckStatus, Replay, 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:") => {
@@ -118,14 +137,42 @@ const getTemporalHeadline = (names: string[]) =>
118
137
  ? `Error: Temporal property ${names[0]} was violated.\n`
119
138
  : `Error: Temporal properties ${names.slice(0, -1).join(", ")}${names.length > 2 ? "," : ""} and ${names[names.length - 1]} were violated.\n`;
120
139
 
140
+ const getFrames = (callStack: string[]) =>
141
+ callStack.map((frame, index) => `${index}. ${frame}\n`).join("");
142
+
143
+ const printCallStack = (frames: string) =>
144
+ console.log(
145
+ `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"}`,
146
+ );
147
+
148
+ const printReplay = (replay: Replay) => {
149
+ replay.output.forEach((line) => console.log(line));
150
+ const frames = getFrames(replay.callStack ?? []);
151
+ const fingerprint = replay.fingerprint;
152
+ if (replay.isBeforeError) {
153
+ if (frames) printCallStack(frames);
154
+ } else if (replay.callStack && fingerprint) {
155
+ const sources = fingerprint.sources.map((source) => `${source}\n`).join("");
156
+ console.log(
157
+ `Error: TLC was unable to fingerprint.\n\nFingerprint Stack Trace:\n${frames ? `${frames}\n` : sources}\nReason:\n${fingerprint.reason}`,
158
+ );
159
+ } else if (replay.callStack) {
160
+ printCallStack(frames);
161
+ }
162
+ };
163
+
121
164
  const printResult = (result: CheckResult) => {
122
165
  if (result.failure) {
166
+ const replay = result.failure.replay;
167
+ if (replay?.isBeforeError) printReplay(replay);
123
168
  console.log(`Error: ${result.failure.message}`);
124
169
  if (result.failure.initialState) {
125
170
  console.log("While working on the initial state:");
126
171
  printState(result.failure.initialState);
127
172
  }
128
173
  printTrace(result.failure.trace);
174
+ if (replay && !replay.isBeforeError) printReplay(replay);
175
+ if (result.failure.isWithoutStatistics) return;
129
176
  } else if (result.violation) {
130
177
  const violation = result.violation;
131
178
  const name = violation.name;
@@ -198,6 +245,20 @@ const checkSpec = async (specPath: string, args: ParsedArgs) => {
198
245
  console.error(`Cannot find the specification file ${specPath}`);
199
246
  return EXIT_STATUS.configParseError;
200
247
  }
248
+ const source = readFileSync(specPath, "utf8");
249
+ const fileName = basename(specPath, ".tla");
250
+ const moduleName = parseModule(source).name;
251
+ if (moduleName !== fileName) {
252
+ throw createSanyError(
253
+ [
254
+ {
255
+ location: "Unknown location",
256
+ message: `File name '${fileName}' does not match the name '${moduleName}' of the top level module it contains.`,
257
+ },
258
+ ],
259
+ true,
260
+ );
261
+ }
201
262
  const configPath =
202
263
  args.get("-config")?.[0] ??
203
264
  (args.has("-config") ? undefined : specPath.replace(/\.tla$/, ".cfg"));
@@ -221,13 +282,26 @@ const checkSpec = async (specPath: string, args: ParsedArgs) => {
221
282
  console.error("Error: expect a strategy such as final for -lncheck option.");
222
283
  return 1;
223
284
  }
285
+ const dumpValues = args.get("-dump");
286
+ if (dumpValues?.length === 0) {
287
+ console.error("Error: A file name for dumping states required.");
288
+ return 1;
289
+ }
290
+ const unsupportedFormat =
291
+ dumpValues?.length === 2 &&
292
+ UNSUPPORTED_DUMP_FORMATS.find((format) => dumpValues[0].toLowerCase().includes(format));
293
+ if (unsupportedFormat) {
294
+ console.error(`Error: tla-ts does not support the -dump format ${unsupportedFormat}.`);
295
+ return 1;
296
+ }
224
297
  const directory = dirname(specPath);
225
298
  console.log(`Checking ${basename(specPath)} with ${basename(configPath)}`);
226
299
  const result = await check({
227
300
  workers: getWorkerCount(args.get("-workers")),
228
301
  livenessCheck: ["final", "seqfinal", "off"].includes(livenessCheck) ? "final" : "default",
229
302
  seed: BigInt(seed),
230
- source: readFileSync(specPath, "utf8"),
303
+ dump: dumpValues && getDump(dumpValues),
304
+ source,
231
305
  config,
232
306
  onPause: () => readSync(0, Buffer.alloc(1)),
233
307
  loadModule: (name) => {
@@ -248,21 +322,32 @@ const checkSpec = async (specPath: string, args: ParsedArgs) => {
248
322
  return result.failure?.exitCode ?? EXIT_CODES[result.status];
249
323
  };
250
324
 
251
- // TLC prints the errors it raises itself. tla-ts names the others, such as a module SANY rejects.
252
- const printError = (error: TlaError) => {
325
+ const formatSanyErrors = (report: SanyReport) =>
326
+ `*** Errors: ${report.errors.length}\n\n${report.errors.map((error) => `${error.location}\n\n${error.message}\n\n`).join("\n")}`;
327
+
328
+ // TLC prints the errors it raises itself, and SANY's report of a spec it rejects. tla-ts names the
329
+ // others, such as a module it cannot parse.
330
+ const printError = (error: TlaError, path?: string) => {
253
331
  if (error instanceof TlaConfigError || error instanceof TlaEvaluationError) {
254
332
  return console.log(`Error: ${error.message}`);
255
333
  }
256
- console.error(`${error.name}: ${error.message}`);
334
+ const report = error instanceof TlaSyntaxError ? error.sany : undefined;
335
+ if (!report || path === undefined) return console.error(`${error.name}: ${error.message}`);
336
+ console.log(
337
+ report.isFatal
338
+ ? `\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`
339
+ : `Semantic errors:\n\n${formatSanyErrors(report)}`,
340
+ );
341
+ console.log("Error: Parsing or semantic analysis failed.");
257
342
  };
258
343
 
259
344
  // Prints a TlaError and returns its exit code.
260
- const reportErrors = async (run: () => number | Promise<number>) => {
345
+ const reportErrors = async (run: () => number | Promise<number>, path?: string) => {
261
346
  try {
262
347
  return await run();
263
348
  } catch (error) {
264
349
  if (!(error instanceof TlaError)) throw error;
265
- printError(error);
350
+ printError(error, path);
266
351
  return getErrorExitCode(error);
267
352
  }
268
353
  };
@@ -273,7 +358,7 @@ const runEach = async (paths: string[], runPath: (path: string) => number | Prom
273
358
  const exitCodes: number[] = [];
274
359
  for (const [index, path] of paths.entries()) {
275
360
  if (index > 0) console.log("");
276
- exitCodes.push(await reportErrors(() => runPath(path)));
361
+ exitCodes.push(await reportErrors(() => runPath(path), path));
277
362
  }
278
363
  return exitCodes.find((exitCode) => exitCode !== EXIT_STATUS.success) ?? EXIT_STATUS.success;
279
364
  };
package/src/runtime.ts CHANGED
@@ -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
  };
@@ -7,13 +7,12 @@ import {
7
7
  } from "./ast";
8
8
  import type { ModelConfig } from "./config";
9
9
  import type { InstanceAction } from "./environment";
10
- import { TlaError } from "./errors";
10
+ import { formatRange, TlaError } from "./errors";
11
11
  import {
12
12
  bindDefinitions,
13
13
  bindOperatorArguments,
14
14
  evaluate,
15
15
  forEachBinding,
16
- formatRange,
17
16
  getDefinition,
18
17
  isConstantLevel,
19
18
  lookupScope,
@@ -469,10 +468,17 @@ export const getNextActions = (
469
468
  instanceActions: Map<string, InstanceAction>,
470
469
  ) => describe(config, environment, instanceActions).actions;
471
470
 
472
- export const getActionLabel = (action: SpecAction) => {
473
- const parameters = action.parameters.map((parameter) => formatValue(parameter[1]));
474
- return `${action.name === UNNAMED_ACTION ? "Action" : action.name}${parameters.length === 0 ? "" : `(${parameters.join(",")})`} ${formatRange(action.location.range ?? BUILTIN_RANGE)}`;
475
- };
471
+ const formatParameters = (action: SpecAction) =>
472
+ action.parameters.length === 0
473
+ ? ""
474
+ : `(${action.parameters.map((parameter) => formatValue(parameter[1])).join(",")})`;
475
+
476
+ export const getActionLabel = (action: SpecAction) =>
477
+ `${action.name === UNNAMED_ACTION ? "Action" : action.name}${formatParameters(action)} ${formatRange(action.location.range ?? BUILTIN_RANGE)}`;
478
+
479
+ // TLC's Action.getInvocationSignature, which names the action and the values of its parameters.
480
+ export const getActionSignature = (action: SpecAction) =>
481
+ `${action.name}${formatParameters(action)}`;
476
482
 
477
483
  export const getSpecificationValue = (
478
484
  config: ModelConfig,