tla-ts 0.0.3-dev.79f7ed7 → 0.0.3-dev.852fbc8

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 (50) hide show
  1. package/README.md +16 -2
  2. package/dist/index.cjs +1 -1
  3. package/dist/index.d.cts +55 -22
  4. package/dist/index.d.ts +55 -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 +37 -16
  13. package/dist/transfer.js +37 -16
  14. package/package.json +1 -1
  15. package/src/ast.ts +93 -0
  16. package/src/check.ts +511 -99
  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 +87 -3
  23. package/src/evaluate.ts +252 -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/lexer.ts +5 -1
  28. package/src/live-check.ts +772 -0
  29. package/src/liveness.ts +120 -543
  30. package/src/parallel-worker.ts +7 -3
  31. package/src/parallel.ts +20 -4
  32. package/src/parser.ts +33 -11
  33. package/src/resolve.ts +122 -44
  34. package/src/run-cli.ts +112 -20
  35. package/src/runtime.ts +3 -1
  36. package/src/spec-description.ts +19 -8
  37. package/src/standard-modules.ts +10 -9
  38. package/src/state-graph.ts +157 -0
  39. package/src/subexpressions.ts +10 -10
  40. package/src/successors.ts +183 -39
  41. package/src/symmetry.ts +30 -8
  42. package/src/tableau.ts +51 -24
  43. package/src/tlc-ext.ts +29 -12
  44. package/src/tlc-module.ts +14 -33
  45. package/src/tlc-modules.ts +4 -0
  46. package/src/tlc-order.ts +25 -7
  47. package/src/tlc-random.ts +9 -6
  48. package/src/tlc-summary.ts +20 -5
  49. package/src/value-sources.ts +29 -0
  50. package/src/values.ts +179 -57
@@ -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
@@ -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:") => {
@@ -113,14 +132,47 @@ 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
+
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
+
116
164
  const printResult = (result: CheckResult) => {
117
165
  if (result.failure) {
166
+ const replay = result.failure.replay;
167
+ if (replay?.isBeforeError) printReplay(replay);
118
168
  console.log(`Error: ${result.failure.message}`);
119
169
  if (result.failure.initialState) {
120
170
  console.log("While working on the initial state:");
121
171
  printState(result.failure.initialState);
122
172
  }
123
173
  printTrace(result.failure.trace);
174
+ if (replay && !replay.isBeforeError) printReplay(replay);
175
+ if (result.failure.isWithoutStatistics) return;
124
176
  } else if (result.violation) {
125
177
  const violation = result.violation;
126
178
  const name = violation.name;
@@ -140,10 +192,10 @@ const printResult = (result: CheckResult) => {
140
192
  "invariant-violation": isInitial
141
193
  ? `Error: Invariant ${name} is violated by the initial state:`
142
194
  : `Error: Invariant ${name} is violated.`,
143
- "property-violation": `Error: Property ${name} is violated.`,
195
+ "property-violation": getTemporalHeadline(violation.properties ?? [name]),
144
196
  "liveness-violation":
145
197
  loopStart !== undefined
146
- ? `Error: Temporal property ${name} was violated.\n`
198
+ ? getTemporalHeadline(violation.properties ?? [name])
147
199
  : isInitial
148
200
  ? `Error: Property ${name} is violated by the initial state:`
149
201
  : `Error: Action property ${name} is violated.`,
@@ -152,6 +204,8 @@ const printResult = (result: CheckResult) => {
152
204
  if (violation.counts) console.log(violation.counts);
153
205
  console.log(headline);
154
206
  if (isInitial) printState(violation.trace[0].state);
207
+ else if (result.status === "property-violation")
208
+ printTrace(violation.trace, "Error: The following behavior constitutes a counter-example:\n");
155
209
  else if (loopStart === undefined) printTrace(violation.trace);
156
210
  else {
157
211
  printTrace(violation.trace, "Error: The following behavior constitutes a counter-example:\n");
@@ -191,6 +245,20 @@ const checkSpec = async (specPath: string, args: ParsedArgs) => {
191
245
  console.error(`Cannot find the specification file ${specPath}`);
192
246
  return EXIT_STATUS.configParseError;
193
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
+ }
194
262
  const configPath =
195
263
  args.get("-config")?.[0] ??
196
264
  (args.has("-config") ? undefined : specPath.replace(/\.tla$/, ".cfg"));
@@ -214,13 +282,26 @@ const checkSpec = async (specPath: string, args: ParsedArgs) => {
214
282
  console.error("Error: expect a strategy such as final for -lncheck option.");
215
283
  return 1;
216
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
+ }
217
297
  const directory = dirname(specPath);
218
298
  console.log(`Checking ${basename(specPath)} with ${basename(configPath)}`);
219
299
  const result = await check({
220
300
  workers: getWorkerCount(args.get("-workers")),
221
301
  livenessCheck: ["final", "seqfinal", "off"].includes(livenessCheck) ? "final" : "default",
222
302
  seed: BigInt(seed),
223
- source: readFileSync(specPath, "utf8"),
303
+ dump: dumpValues && getDump(dumpValues),
304
+ source,
224
305
  config,
225
306
  onPause: () => readSync(0, Buffer.alloc(1)),
226
307
  loadModule: (name) => {
@@ -241,21 +322,32 @@ const checkSpec = async (specPath: string, args: ParsedArgs) => {
241
322
  return result.failure?.exitCode ?? EXIT_CODES[result.status];
242
323
  };
243
324
 
244
- // TLC prints the errors it raises itself. tla-ts names the others, such as a module SANY rejects.
245
- 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) => {
246
331
  if (error instanceof TlaConfigError || error instanceof TlaEvaluationError) {
247
332
  return console.log(`Error: ${error.message}`);
248
333
  }
249
- 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.");
250
342
  };
251
343
 
252
344
  // Prints a TlaError and returns its exit code.
253
- const reportErrors = async (run: () => number | Promise<number>) => {
345
+ const reportErrors = async (run: () => number | Promise<number>, path?: string) => {
254
346
  try {
255
347
  return await run();
256
348
  } catch (error) {
257
349
  if (!(error instanceof TlaError)) throw error;
258
- printError(error);
350
+ printError(error, path);
259
351
  return getErrorExitCode(error);
260
352
  }
261
353
  };
@@ -266,7 +358,7 @@ const runEach = async (paths: string[], runPath: (path: string) => number | Prom
266
358
  const exitCodes: number[] = [];
267
359
  for (const [index, path] of paths.entries()) {
268
360
  if (index > 0) console.log("");
269
- exitCodes.push(await reportErrors(() => runPath(path)));
361
+ exitCodes.push(await reportErrors(() => runPath(path), path));
270
362
  }
271
363
  return exitCodes.find((exitCode) => exitCode !== EXIT_STATUS.success) ?? EXIT_STATUS.success;
272
364
  };