tla-ts 0.0.8-dev.d9bffda → 0.0.9-dev.0dd11f695

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 (119) hide show
  1. package/README.md +30 -0
  2. package/dist/compile.cjs +23 -0
  3. package/dist/compile.js +23 -0
  4. package/dist/deciders.cjs +15 -15
  5. package/dist/deciders.js +40 -40
  6. package/dist/index.cjs +1 -1
  7. package/dist/index.d.cts +80 -10
  8. package/dist/index.d.ts +80 -10
  9. package/dist/index.js +1 -1
  10. package/dist/parallel-worker.cjs +1 -1
  11. package/dist/parallel-worker.js +1 -1
  12. package/dist/prove-worker.cjs +1 -1
  13. package/dist/prove-worker.js +1 -1
  14. package/dist/prove.cjs +116 -36
  15. package/dist/prove.js +116 -36
  16. package/dist/run.cjs +143 -31
  17. package/dist/run.js +143 -31
  18. package/dist/tlapm.cjs +2 -2
  19. package/dist/tlapm.js +1 -1
  20. package/dist/transfer.cjs +128 -103
  21. package/dist/transfer.js +128 -103
  22. package/dist/worker.cjs +7 -7
  23. package/dist/worker.js +7 -7
  24. package/package.json +3 -1
  25. package/src/ast.ts +7 -21
  26. package/src/bags.ts +99 -99
  27. package/src/builtins.ts +44 -75
  28. package/src/bundled-modules.ts +1 -8
  29. package/src/check.ts +605 -311
  30. package/src/cli/options.ts +12 -3
  31. package/src/cli/run.ts +2 -2
  32. package/src/cli/runtime-invariants.ts +135 -0
  33. package/src/cli/shared.ts +20 -9
  34. package/src/cli/tlc-arguments.ts +646 -0
  35. package/src/cli/tlc-usage.ts +362 -0
  36. package/src/cli/tlc.ts +571 -185
  37. package/src/cli/typescript.ts +26 -0
  38. package/src/cli/xml-exporter.ts +4 -10
  39. package/src/codegen.ts +190 -46
  40. package/src/config.ts +101 -68
  41. package/src/coverage.ts +855 -0
  42. package/src/dependencies.ts +20 -28
  43. package/src/dfid.ts +636 -0
  44. package/src/environment.ts +266 -98
  45. package/src/errors.ts +142 -45
  46. package/src/evaluate.ts +632 -298
  47. package/src/exit-codes.ts +37 -1
  48. package/src/index.ts +3 -0
  49. package/src/instances.ts +85 -9
  50. package/src/java-overrides.ts +2 -12
  51. package/src/json-reader.ts +456 -0
  52. package/src/json.ts +262 -139
  53. package/src/levels.ts +2 -3
  54. package/src/lexer.ts +17 -26
  55. package/src/liveness-checker.ts +10 -18
  56. package/src/liveness.ts +121 -49
  57. package/src/parallel-worker.ts +14 -10
  58. package/src/parallel.ts +41 -17
  59. package/src/parser.ts +436 -90
  60. package/src/pcal/ast.ts +7 -28
  61. package/src/pcal/parse.ts +11 -39
  62. package/src/pcal/tokenize.ts +4 -20
  63. package/src/pcal/translate.ts +10 -42
  64. package/src/pcal/validate.ts +3 -21
  65. package/src/pretty-print.ts +1 -2
  66. package/src/prover/smt/solver/solver.ts +31 -27
  67. package/src/randomization.ts +84 -35
  68. package/src/resolve.ts +18 -60
  69. package/src/runtime.ts +11 -4
  70. package/src/sany/builtins.ts +3 -4
  71. package/src/sany/generator.ts +128 -176
  72. package/src/sany/levels.ts +6 -30
  73. package/src/sany/lexer.ts +7 -23
  74. package/src/sany/linter.ts +31 -29
  75. package/src/sany/modules.ts +1 -5
  76. package/src/sany/nodes.ts +4 -28
  77. package/src/sany/parse-error.ts +44 -100
  78. package/src/sany/report.ts +25 -40
  79. package/src/sany/selectors.ts +8 -22
  80. package/src/sany/source.ts +8 -15
  81. package/src/sany/xml.ts +11 -42
  82. package/src/search.ts +547 -144
  83. package/src/simulate.ts +694 -0
  84. package/src/spec-description.ts +166 -48
  85. package/src/standard-definitions.ts +2 -3
  86. package/src/standard-modules.ts +264 -68
  87. package/src/state-graph.ts +51 -18
  88. package/src/subexpressions.ts +31 -5
  89. package/src/successors.ts +267 -77
  90. package/src/symmetry.ts +31 -8
  91. package/src/tableau.ts +1 -2
  92. package/src/tlc/fingerprint.ts +183 -61
  93. package/src/tlc/jar-data.ts +113 -6
  94. package/src/tlc/messages.ts +122 -37
  95. package/src/tlc/order.ts +33 -38
  96. package/src/tlc/random.ts +16 -16
  97. package/src/tlc/replay.ts +563 -211
  98. package/src/tlc/summary.ts +2 -4
  99. package/src/tlc/tlc-operators.ts +81 -36
  100. package/src/tlc/tlcext-operators.ts +138 -117
  101. package/src/tlc/trace-spec.ts +273 -0
  102. package/src/tlc/value-stream.ts +143 -0
  103. package/src/tlc/version.ts +2 -4
  104. package/src/typescript/actions.ts +494 -0
  105. package/src/typescript/collections.ts +615 -0
  106. package/src/typescript/compile.ts +70 -0
  107. package/src/typescript/context.ts +106 -0
  108. package/src/typescript/emit.ts +122 -0
  109. package/src/typescript/expressions.ts +508 -0
  110. package/src/typescript/formula.ts +160 -0
  111. package/src/typescript/functions.ts +295 -0
  112. package/src/typescript/model.ts +164 -0
  113. package/src/typescript/names.ts +116 -0
  114. package/src/typescript/program.ts +51 -0
  115. package/src/typescript/properties.ts +148 -0
  116. package/src/typescript/scope.ts +117 -0
  117. package/src/typescript/steps.ts +175 -0
  118. package/src/typescript/types.ts +178 -0
  119. package/src/values.ts +832 -255
package/src/cli/tlc.ts CHANGED
@@ -1,9 +1,13 @@
1
1
  import {
2
+ appendFileSync,
3
+ closeSync,
2
4
  existsSync,
3
5
  mkdirSync,
6
+ openSync,
4
7
  readFileSync,
5
8
  readSync,
6
9
  realpathSync,
10
+ statSync,
7
11
  writeFileSync,
8
12
  } from "node:fs";
9
13
  import { basename, dirname, isAbsolute, join, resolve } from "node:path";
@@ -12,10 +16,13 @@ import { pathToFileURL } from "node:url";
12
16
  import { getHeapStatistics } from "node:v8";
13
17
  import { version } from "../../package.json";
14
18
  import type { Expression } from "../ast";
19
+ import type { CoverageReport } from "../coverage";
15
20
  import { describeRange } from "../evaluate";
16
21
  import type {
22
+ CheckOptions,
17
23
  CheckProgress,
18
24
  InitialStateViolation,
25
+ ModuleOperator,
19
26
  OutputLine,
20
27
  CheckResult,
21
28
  CheckStatus,
@@ -25,11 +32,14 @@ import type {
25
32
  Violation,
26
33
  } from "../check";
27
34
  import { parseConfig } from "../config";
35
+ import { checkDepthFirst, type DepthFirstOutput } from "../dfid";
28
36
  import {
29
- getErrorExitCode,
37
+ TlaAliasFormatError,
30
38
  TlaConfigError,
31
39
  TlaError,
32
40
  TlaEvaluationError,
41
+ TlaFeatureUnsupportedError,
42
+ TlaMissingCheckpointError,
33
43
  TlaSyntaxError,
34
44
  getUnexpectedException,
35
45
  UNEXPECTED_EXCEPTION,
@@ -37,7 +47,8 @@ import {
37
47
  } from "../errors";
38
48
  import { EXIT_STATUS, setExitCode } from "../exit-codes";
39
49
  import { check } from "../parallel";
40
- import { parseModule } from "../parser";
50
+ import { extractModule, parseModule } from "../parser";
51
+ import { simulate, type SimulationOutput, type SimulationStatistics } from "../simulate";
41
52
  import type { StateDump } from "../state-graph";
42
53
  import {
43
54
  formatProbability,
@@ -45,7 +56,11 @@ import {
45
56
  getOptimisticProbability,
46
57
  getOutDegreeSummary,
47
58
  } from "../tlc/summary";
48
- import { SANY_174_STANDARD_MODULES, SANY_STANDARD_MODULES } from "../sany/modules";
59
+ import {
60
+ getSanyStandardModules,
61
+ SANY_174_STANDARD_MODULES,
62
+ SANY_STANDARD_MODULES,
63
+ } from "../sany/modules";
49
64
  import { getSanyReport, type SanyModuleOrigin } from "../sany/report";
50
65
  import { getTlcFingerprint } from "../tlc/fingerprint";
51
66
  import type { TlcVersion } from "../tlc/version";
@@ -60,13 +75,16 @@ import {
60
75
  type MessagePrinter,
61
76
  } from "../tlc/messages";
62
77
  import { formatState } from "../values";
63
- import { CHECK_COMMAND, USAGE, type ParsedArgs } from "./options";
78
+ import { addRuntimeInvariants } from "./runtime-invariants";
79
+ import { parseTlcArguments, type TlcArguments } from "./tlc-arguments";
80
+ import { getTlcUsage } from "./tlc-usage";
64
81
  import {
65
82
  createModuleLoader,
66
83
  findModuleFile,
67
84
  getInputPaths,
68
85
  getToolsJar,
69
86
  getStandardModulesUrl,
87
+ getTopLevelExitCode,
70
88
  printError,
71
89
  printMissingFile,
72
90
  printMissingFile174,
@@ -75,6 +93,7 @@ import {
75
93
  toLibraryPath,
76
94
  type JavaProperties,
77
95
  } from "./shared";
96
+ import { writeTypeScriptSpec } from "./typescript";
78
97
 
79
98
  const EXIT_CODES: Record<CheckStatus, number> = {
80
99
  success: EXIT_STATUS.success,
@@ -87,19 +106,12 @@ const EXIT_CODES: Record<CheckStatus, number> = {
87
106
  error: EXIT_STATUS.error,
88
107
  };
89
108
 
90
- const isJavaLong = (text: string) =>
91
- /^[+-]?\d+$/.test(text) && BigInt.asIntN(64, BigInt(text)) === BigInt(text);
92
-
93
- const getWorkerCount = (values: string[] | undefined) => {
94
- if (!values) return 1;
95
- return values[0] === "auto"
96
- ? availableParallelism()
97
- : Math.max(1, Number.parseInt(values[0], 10) || 1);
109
+ const checkNotDirectory = (path: string) => {
110
+ if (statSync(path, { throwIfNoEntry: false })?.isDirectory()) {
111
+ throw new TlaEvaluationError(`${path} (Is a directory)`);
112
+ }
98
113
  };
99
114
 
100
- const UNSUPPORTED_DUMP_FORMATS = ["constrained", "stuttering", "strict"];
101
-
102
- // TLC names the file of a -dump by its format unless the name already ends that way.
103
115
  const getDumpPath = (path: string, extension: string) =>
104
116
  path.endsWith(extension) ? path : `${path}${extension}`;
105
117
 
@@ -112,6 +124,9 @@ const getStateDump = (values: string[]): StateDump => {
112
124
  colorize: format.includes("colorize"),
113
125
  actionLabels: format.includes("actionlabels"),
114
126
  snapshot: format.includes("snapshot"),
127
+ constrained: format.includes("constrained"),
128
+ stuttering: format.includes("stuttering"),
129
+ strict: format.includes("strict"),
115
130
  };
116
131
  };
117
132
 
@@ -136,7 +151,6 @@ const getInitialViolationHeadline = (
136
151
  text: `Property ${name} is violated by the initial state:`,
137
152
  };
138
153
 
139
- // What the spec prints as TLC rebuilds a trace, before it prints the states or after.
140
154
  const printTraceOutput = (printer: MessagePrinter, lines: OutputLine[] | undefined) =>
141
155
  lines?.forEach((line) => {
142
156
  if (typeof line === "string") return console.log(line);
@@ -151,24 +165,40 @@ const printTraceOutput = (printer: MessagePrinter, lines: OutputLine[] | undefin
151
165
  );
152
166
  });
153
167
 
168
+ interface TlcPrinter extends MessagePrinter {
169
+ isDiffTrace: boolean;
170
+ }
171
+
172
+ const BEHAVIOR = {
173
+ code: MESSAGE_CODE.behaviorUpToThisPoint,
174
+ text: "The behavior up to this point is:",
175
+ };
176
+
177
+ // TLC's -difftrace prints in full the last state of a behavior it rebuilds from the state graph.
154
178
  const printTrace = (
155
- printer: MessagePrinter,
179
+ printer: TlcPrinter,
156
180
  trace: TraceStep[],
157
- heading: { code: number; text: string } = {
158
- code: MESSAGE_CODE.behaviorUpToThisPoint,
159
- text: "The behavior up to this point is:",
160
- },
181
+ heading: { code: number; text: string } = BEHAVIOR,
161
182
  isRebuiltAfterHeading = false,
183
+ isLastDiffed = heading !== BEHAVIOR,
162
184
  ) => {
163
185
  if (trace.length > 0) printer.print(heading.code, MESSAGE_LEVEL.error, heading.text);
164
- trace.forEach((step, index) => {
165
- if (index > 0 || isRebuiltAfterHeading) printTraceOutput(printer, step.output);
166
- printer.print(
167
- MESSAGE_CODE.statePrint2,
168
- MESSAGE_LEVEL.state,
169
- `${index + 1}: <${step.label ?? step.action ?? "Initial predicate"}>\n${formatState(step.state)}`,
170
- );
171
- });
186
+ // TLC reports an error in printing the trace and stops printing it.
187
+ try {
188
+ trace.forEach((step, index) => {
189
+ if (index > 0 || isRebuiltAfterHeading) printTraceOutput(printer, step.output);
190
+ const isDiffed =
191
+ printer.isDiffTrace && index > 0 && (isLastDiffed || index < trace.length - 1);
192
+ printer.print(
193
+ MESSAGE_CODE.statePrint2,
194
+ MESSAGE_LEVEL.state,
195
+ `${index + 1}: <${step.label ?? step.action ?? "Initial predicate"}>\n${formatState(step.state, isDiffed ? trace[index - 1].state : undefined)}`,
196
+ );
197
+ });
198
+ } catch (error) {
199
+ if (!(error instanceof TlaAliasFormatError)) throw error;
200
+ printer.print(MESSAGE_CODE.general, MESSAGE_LEVEL.error, error.message);
201
+ }
172
202
  };
173
203
 
174
204
  const COUNTER_EXAMPLE = {
@@ -184,8 +214,7 @@ const getTemporalHeadline = (names: string[], version: TlcVersion) =>
184
214
  ? `Temporal property ${names[0]} was violated.\n`
185
215
  : `Temporal properties ${names.slice(0, -1).join(", ")}${names.length > 2 ? "," : ""} and ${names[names.length - 1]} were violated.\n`;
186
216
 
187
- // TLC's FingerprintException#getTrace: the range of each source, innermost first, skipping a
188
- // source the same as the one inside it.
217
+ // Innermost first, skipping a source the same as the one inside it.
189
218
  const formatFingerprintTrace = (sources: Expression[]) =>
190
219
  sources
191
220
  .filter((source, index) => source !== sources[index - 1])
@@ -193,8 +222,7 @@ const formatFingerprintTrace = (sources: Expression[]) =>
193
222
  .toReversed()
194
223
  .join("");
195
224
 
196
- // TLC's CallStack.toString: the range of each expression, skipping an expression that it evaluates
197
- // again right inside itself.
225
+ // Skips an expression that TLC evaluates again right inside itself.
198
226
  const formatCallStack = (expressions: Expression[]) => {
199
227
  if (expressions.length === 0) return " The error call stack is empty.\n";
200
228
  const lines: string[] = [];
@@ -229,7 +257,6 @@ const printInitialStates = (printer: MessagePrinter, initialStates: InitialState
229
257
 
230
258
  interface Timing {
231
259
  startTime: number;
232
- // Whether TLC has printed that SANY finished.
233
260
  isParsed: boolean;
234
261
  livenessStartTime: number | undefined;
235
262
  }
@@ -252,10 +279,56 @@ const printProgress = (
252
279
  );
253
280
  };
254
281
 
282
+ const COVERAGE_CODES = {
283
+ init: MESSAGE_CODE.coverageInit,
284
+ next: MESSAGE_CODE.coverageNext,
285
+ invariant: MESSAGE_CODE.coverageProperty,
286
+ implied: MESSAGE_CODE.coverageProperty,
287
+ constraint: MESSAGE_CODE.coverageConstraint,
288
+ };
289
+
290
+ // TLC asks to turn coverage off once a check that reports it has run for five minutes.
291
+ const COVERAGE_OVERHEAD = 5 * 60_000;
292
+
293
+ const printCoverage = (printer: MessagePrinter, coverage: CoverageReport, startTime: number) => {
294
+ const print = (code: number, text: string) => printer.print(code, MESSAGE_LEVEL.none, text);
295
+ print(
296
+ MESSAGE_CODE.coverageStart,
297
+ `The coverage statistics at ${formatTlcDate(new Date())} (see https://explain.tlapl.us/module-coverage-statistics for how to interpret the following statistics).`,
298
+ );
299
+ coverage.variables.forEach((variable) =>
300
+ print(MESSAGE_CODE.coverageVariable, `<${variable.label}>: ${variable.distinct}`),
301
+ );
302
+ coverage.relations.forEach((relation) => {
303
+ const code = COVERAGE_CODES[relation.kind];
304
+ print(
305
+ code,
306
+ code === MESSAGE_CODE.coverageProperty
307
+ ? `<${relation.label}>`
308
+ : `<${relation.label}>: ${relation.distinct}:${relation.generated}`,
309
+ );
310
+ relation.expressions.forEach((expression) => {
311
+ const location = ` ${"|".repeat(expression.depth)}${expression.location}`;
312
+ if (expression.cost > 0) {
313
+ print(
314
+ MESSAGE_CODE.coverageValueCost,
315
+ `${location}: ${expression.count}:${expression.cost}`,
316
+ );
317
+ } else print(MESSAGE_CODE.coverageValue, `${location}: ${expression.count}`);
318
+ });
319
+ });
320
+ if (Date.now() - startTime > COVERAGE_OVERHEAD) {
321
+ print(
322
+ MESSAGE_CODE.coverageEndOverhead,
323
+ "End of statistics (please note that for performance reasons large models\nare best checked with coverage and cost statistics disabled).",
324
+ );
325
+ } else print(MESSAGE_CODE.coverageEnd, "End of statistics.");
326
+ };
327
+
255
328
  const getClassPath = (directory: string, module: string) => join(directory, `${module}.class`);
256
329
 
257
330
  const printCheckProgress = (
258
- printer: MessagePrinter,
331
+ printer: TlcPrinter,
259
332
  progress: CheckProgress,
260
333
  timing: Timing,
261
334
  directory: string,
@@ -333,6 +406,9 @@ const printCheckProgress = (
333
406
  return;
334
407
  case "progress":
335
408
  printProgress(printer, progress.statistics, timing.startTime);
409
+ if (progress.statistics.coverage) {
410
+ printCoverage(printer, progress.statistics.coverage, timing.startTime);
411
+ }
336
412
  return;
337
413
  case "liveness-started": {
338
414
  timing.livenessStartTime = Date.now();
@@ -351,8 +427,16 @@ const printCheckProgress = (
351
427
  case "liveness-finished":
352
428
  printLivenessEnd(printer, timing);
353
429
  return;
430
+ case "sequential-fallback":
431
+ process.stderr.write(
432
+ `Warning: the search ordered the string ${JSON.stringify(progress.string)} against another string it created, so tla-ts checks the model again with one worker. Workers don't agree on the order of strings the search creates.\n`,
433
+ );
434
+ return;
354
435
  case "warning":
355
436
  print(progress.code, MESSAGE_LEVEL.warning, progress.text);
437
+ return;
438
+ case "violation":
439
+ printViolation(progress.status, progress.violation, printer);
356
440
  }
357
441
  };
358
442
 
@@ -366,8 +450,8 @@ const printLivenessEnd = (printer: MessagePrinter, timing: Timing) => {
366
450
  timing.livenessStartTime = undefined;
367
451
  };
368
452
 
369
- // Prints a violation, and returns whether TLC goes on to print the statistics of the search.
370
- const printViolation = (status: CheckStatus, violation: Violation, printer: MessagePrinter) => {
453
+ // Returns whether TLC goes on to print the statistics of the search.
454
+ const printViolation = (status: CheckStatus, violation: Violation, printer: TlcPrinter) => {
371
455
  const print = printer.print;
372
456
  const name = violation.name;
373
457
  const loopStart = violation.loopStart;
@@ -409,15 +493,19 @@ const printViolation = (status: CheckStatus, violation: Violation, printer: Mess
409
493
  },
410
494
  "postcondition-violation": {
411
495
  code: violation.postcondition?.code ?? MESSAGE_CODE.general,
412
- text: violation.message ?? `Postcondition ${name} is false.`,
496
+ text: formatInnerMessage(
497
+ violation.postcondition?.code ?? MESSAGE_CODE.general,
498
+ violation.message ?? `Postcondition ${name} is false.`,
499
+ printer.isTool,
500
+ ),
413
501
  },
414
502
  }[status];
415
503
  // A safety property's counterexample ends where it breaks, and a liveness one loops back.
416
504
  const isProperty = status === "property-violation";
417
505
  const isLasso = loopStart !== undefined && !isProperty;
418
506
  const isCounterExample = isProperty || isLasso;
419
- // TLC rebuilds a liveness counterexample before it reports the violation, and 1.7.4's
420
- // LiveWorker#printTrace after it prints the heading of the counterexample.
507
+ // TLC rebuilds a liveness counterexample before it reports the violation, and 1.7.4 after it
508
+ // prints the counterexample's heading.
421
509
  const isRebuiltFirst = isCounterExample && printer.version !== "1.7.4";
422
510
  if (isRebuiltFirst) printTraceOutput(printer, violation.trace[0]?.output);
423
511
  if (violation.counts) console.log(violation.counts);
@@ -436,8 +524,8 @@ const printViolation = (status: CheckStatus, violation: Violation, printer: Mess
436
524
  isCounterExample ? COUNTER_EXAMPLE : undefined,
437
525
  isCounterExample && !isRebuiltFirst,
438
526
  );
439
- printTraceOutput(printer, violation.traceOutput);
440
527
  }
528
+ printTraceOutput(printer, violation.traceOutput);
441
529
  if (isLasso) {
442
530
  const label = violation.loopLabel;
443
531
  if (loopStart === violation.trace.length - 1)
@@ -457,8 +545,15 @@ const printViolation = (status: CheckStatus, violation: Violation, printer: Mess
457
545
  const postcondition =
458
546
  violation.unwitnessed ??
459
547
  (status === "postcondition-violation" ? undefined : violation.postcondition);
548
+ printTraceOutput(printer, violation.postconditionOutput);
460
549
  if (postcondition?.counts) console.log(postcondition.counts);
461
- if (postcondition) print(postcondition.code, MESSAGE_LEVEL.error, postcondition.message);
550
+ if (postcondition) {
551
+ print(
552
+ postcondition.code,
553
+ MESSAGE_LEVEL.error,
554
+ formatInnerMessage(postcondition.code, postcondition.message, printer.isTool),
555
+ );
556
+ }
462
557
  // TLC checks assumptions before it starts the search, so it has no statistics to print.
463
558
  return !isInitial && status !== "assumption-violation";
464
559
  };
@@ -470,7 +565,54 @@ const printNestedExpressions = (printer: MessagePrinter, callStack: Expression[]
470
565
  `The error occurred when TLC was evaluating the nested\nexpressions at the following positions:\n${formatCallStack(callStack)}`,
471
566
  );
472
567
 
473
- const printResult = (result: CheckResult, printer: MessagePrinter, timing: Timing) => {
568
+ const printSuccess = (printer: MessagePrinter, optimistic: number, actual: number | undefined) =>
569
+ printer.print(
570
+ MESSAGE_CODE.success,
571
+ MESSAGE_LEVEL.none,
572
+ [
573
+ "Model checking completed. No error has been found.",
574
+ " Estimates of the probability that TLC did not check all reachable states",
575
+ " because two distinct states had the same fingerprint:",
576
+ ` calculated (optimistic): val = ${formatProbability(optimistic)}`,
577
+ ...(actual === undefined
578
+ ? []
579
+ : [` based on the actual fingerprints: val = ${formatProbability(actual)}`]),
580
+ ].join("\n"),
581
+ );
582
+
583
+ const printDepthFirst = (printer: TlcPrinter, output: DepthFirstOutput) => {
584
+ switch (output.kind) {
585
+ case "message":
586
+ printer.print(
587
+ output.code,
588
+ output.isError ? MESSAGE_LEVEL.error : MESSAGE_LEVEL.none,
589
+ printer.isTool ? output.toolMessage : output.message,
590
+ );
591
+ return;
592
+ case "behavior":
593
+ output.states.forEach((state, index) =>
594
+ output.isInvariant
595
+ ? printer.print(
596
+ MESSAGE_CODE.statePrint2,
597
+ MESSAGE_LEVEL.state,
598
+ `${index + 1}: \n${formatState(state, printer.isDiffTrace ? output.states[index - 1] : undefined)}`,
599
+ )
600
+ : printer.print(
601
+ MESSAGE_CODE.statePrint1,
602
+ MESSAGE_LEVEL.state,
603
+ `${index + 1}:\n${formatState(state)}`,
604
+ ),
605
+ );
606
+ return;
607
+ case "nested-expressions":
608
+ printNestedExpressions(printer, output.callStack);
609
+ return;
610
+ case "success":
611
+ printSuccess(printer, output.optimistic, output.actual);
612
+ }
613
+ };
614
+
615
+ const printResult = (result: CheckResult, printer: TlcPrinter, timing: Timing) => {
474
616
  const print = printer.print;
475
617
  if (result.failure) {
476
618
  const failure = result.failure;
@@ -478,8 +620,8 @@ const printResult = (result: CheckResult, printer: MessagePrinter, timing: Timin
478
620
  const printCallStack = () => {
479
621
  const fingerprint = failure.fingerprint;
480
622
  if (fingerprint) {
481
- // TLC prints the call stack when the replay has one, and otherwise the sources of the
482
- // values it failed to fingerprint, innermost first. TLC 1.7.4 always prints the sources.
623
+ // TLC prints the call stack when the replay has one, and otherwise the sources of the values it
624
+ // failed to fingerprint. TLC 1.7.4 always prints the sources.
483
625
  const trace =
484
626
  failure.callStack?.length && printer.version !== "1.7.4"
485
627
  ? formatCallStack(failure.callStack)
@@ -495,7 +637,7 @@ const printResult = (result: CheckResult, printer: MessagePrinter, timing: Timin
495
637
  };
496
638
  if (failure.isCallStackFirst) printCallStack();
497
639
  // TLC prints the state as it reports the error, so a state it can't print fails outside the
498
- // checker, which TLC reports as an exception it did not expect.
640
+ // checker, as an exception TLC did not expect.
499
641
  const initialState =
500
642
  failure.initialState &&
501
643
  (() => {
@@ -528,7 +670,13 @@ const printResult = (result: CheckResult, printer: MessagePrinter, timing: Timin
528
670
  printTraceOutput(printer, failure.traceOutput);
529
671
  const postcondition = failure.postcondition;
530
672
  if (postcondition?.counts) console.log(postcondition.counts);
531
- if (postcondition) print(postcondition.code, MESSAGE_LEVEL.error, postcondition.message);
673
+ if (postcondition) {
674
+ print(
675
+ postcondition.code,
676
+ MESSAGE_LEVEL.error,
677
+ formatInnerMessage(postcondition.code, postcondition.message, printer.isTool),
678
+ );
679
+ }
532
680
  if (!failure.isCallStackFirst) printCallStack();
533
681
  } else if (result.violation) {
534
682
  if (!printViolation(result.status, result.violation, printer)) return;
@@ -537,37 +685,26 @@ const printResult = (result: CheckResult, printer: MessagePrinter, timing: Timin
537
685
  const additionalViolation = result.additionalViolation;
538
686
  if (additionalViolation) printViolation("property-violation", additionalViolation, printer);
539
687
  if (result.liveCallStack) printNestedExpressions(printer, result.liveCallStack);
540
- } else {
688
+ } else if (result.status === "success") {
541
689
  printLivenessEnd(printer, timing);
542
- const optimistic = getOptimisticProbability(result.distinctStates, result.generatedStates);
543
- const actual =
690
+ printSuccess(
691
+ printer,
692
+ getOptimisticProbability(result.distinctStates, result.generatedStates),
544
693
  result.fingerprintDistance === undefined
545
- ? []
546
- : [
547
- ` based on the actual fingerprints: val = ${formatProbability(getActualProbability(result.fingerprintDistance))}`,
548
- ];
549
- print(
550
- MESSAGE_CODE.success,
551
- MESSAGE_LEVEL.none,
552
- [
553
- "Model checking completed. No error has been found.",
554
- " Estimates of the probability that TLC did not check all reachable states",
555
- " because two distinct states had the same fingerprint:",
556
- ` calculated (optimistic): val = ${formatProbability(optimistic)}`,
557
- ...actual,
558
- ].join("\n"),
694
+ ? undefined
695
+ : getActualProbability(result.fingerprintDistance),
559
696
  );
560
697
  }
561
698
  if (result.failure?.isWithoutStatistics) return;
562
699
  if (result.status !== "success") printLivenessEnd(printer, timing);
700
+ if (result.coverage) printCoverage(printer, result.coverage, timing.startTime);
563
701
  if (printer.isTool) printProgress(printer, result, timing.startTime);
564
702
  print(
565
703
  MESSAGE_CODE.stats,
566
704
  MESSAGE_LEVEL.none,
567
705
  `${result.generatedStates} states generated, ${result.distinctStates} distinct states found, ${result.queuedStates} states left on queue.`,
568
706
  );
569
- // ModelChecker#printSummary prints the depth, which TLC 1.7.4 prints only after a search it
570
- // reports as successful, and as at least 1, and then the outdegree of a successful search.
707
+ // TLC 1.7.4 prints the depth only after a search it reports as successful, and as at least 1.
571
708
  const is174 = printer.version === "1.7.4";
572
709
  const outDegrees = is174 ? (result.outDegrees ?? result.violationOutDegrees) : result.outDegrees;
573
710
  if (!is174 || outDegrees) {
@@ -581,14 +718,10 @@ const printResult = (result: CheckResult, printer: MessagePrinter, timing: Timin
581
718
  if (outDegree) print(MESSAGE_CODE.stateGraphOutdegree, MESSAGE_LEVEL.none, outDegree);
582
719
  };
583
720
 
584
- // Java's Files.createTempDirectory names a directory by a random unsigned long. tla-ts derives it
585
- // from TLC's fingerprint of what the directory holds, so that each run of a spec prints the same
586
- // files.
721
+ // Java names the directory by a random unsigned long. tla-ts derives it from what the directory
722
+ // holds, so that each run of a spec prints the same files.
587
723
  const getTemporaryName = (contents: string) => getTlcFingerprint([contents]).toString();
588
724
 
589
- // The file TLC's SANY says it parses each module from: the real path of a module's own file, or a
590
- // copy in a temporary directory of a module from the root module's file or from the jar on the
591
- // class path, followed by where TLC copied it from.
592
725
  const createFileDescriber = (
593
726
  specPath: string,
594
727
  directories: string[],
@@ -619,7 +752,20 @@ const createFileDescriber = (
619
752
  const printWelcome = (printer: MessagePrinter) =>
620
753
  printer.print(MESSAGE_CODE.version, MESSAGE_LEVEL.none, `TLC2 Version ${version} (rev: tla-ts)`);
621
754
 
622
- // TLC.printErrorMsg: TLC says which version it is, then why it can't read its options.
755
+ // ModelConfig needs a final newline to end a trailing \* comment.
756
+ const getEmbeddedConfig = (contents: string, name: string) => {
757
+ const lines = contents.split(/\r?\n/);
758
+ const start = lines.findIndex(
759
+ (line) => line.match(/^-----*\s*CONFIG\s+(\S+?)\s*-----*$/)?.[1] === name,
760
+ );
761
+ if (start === -1) return "\n";
762
+ const end = lines.findIndex((line, index) => index > start && line.startsWith("===="));
763
+ return `${lines
764
+ .slice(start + 1, end === -1 ? undefined : end)
765
+ .join("\n")
766
+ .trim()}\n`;
767
+ };
768
+
623
769
  const printCommandLineError = (printer: MessagePrinter, message: string) => {
624
770
  printWelcome(printer);
625
771
  printer.print(
@@ -630,86 +776,195 @@ const printCommandLineError = (printer: MessagePrinter, message: string) => {
630
776
  return 1;
631
777
  };
632
778
 
633
- // TLC.printStartupBanner, with what runs tla-ts in place of the JVM. tla-ts keeps its fingerprints
634
- // and its queue of states in memory.
635
- const printStartupBanner = (printer: MessagePrinter, seed: string, workers: number) =>
779
+ // tla-ts keeps its fingerprints and its queue of states in memory.
780
+ const printStartupBanner = (printer: MessagePrinter, args: TlcArguments) => {
781
+ const workers = `${args.workers} worker${args.workers === 1 ? "" : "s"} on ${availableParallelism()} cores with ${Math.floor(getHeapStatistics().heap_size_limit / 1024 / 1024)}MB heap and 0MB offheap memory [pid: ${process.pid}] (${type()} ${release()} ${arch()}, Node.js ${process.versions.node} ${process.arch.endsWith("64") ? 64 : 32}bit`;
782
+ if (args.mode === "model-check" && args.dfidDepth !== undefined) {
783
+ printer.print(
784
+ MESSAGE_CODE.depthFirstModelChecking,
785
+ MESSAGE_LEVEL.none,
786
+ `Running depth-first search Model-Checking with fp ${args.fingerprintIndex} and seed ${args.seed} with ${workers}).`,
787
+ );
788
+ return;
789
+ }
790
+ if (args.mode === "model-check") {
791
+ printer.print(
792
+ MESSAGE_CODE.modelChecking,
793
+ MESSAGE_LEVEL.none,
794
+ `Running breadth-first search Model-Checking with fp ${args.fingerprintIndex} and seed ${args.seed} with ${workers}, MemFPSet, MemStateQueue).`,
795
+ );
796
+ return;
797
+ }
636
798
  printer.print(
637
- MESSAGE_CODE.modelChecking,
799
+ MESSAGE_CODE.simulating,
638
800
  MESSAGE_LEVEL.none,
639
- `Running breadth-first search Model-Checking with fp 0 and seed ${BigInt(seed)} with ${workers} worker${workers === 1 ? "" : "s"} on ${availableParallelism()} cores with ${Math.floor(getHeapStatistics().heap_size_limit / 1024 / 1024)}MB heap and 0MB offheap memory [pid: ${process.pid}] (${type()} ${release()} ${arch()}, Node.js ${process.versions.node} ${process.arch.endsWith("64") ? 64 : 32}bit, MemFPSet, MemStateQueue).`,
801
+ `Running ${args.scheduler === "rl" ? "RL" : "Random"} Simulation with seed ${args.seed} with ${workers}).`,
640
802
  );
803
+ };
641
804
 
642
- // TLC loads Integers for the binary trace that its trace exploration spec records. -generateSpecTE
643
- // turns the spec on, and -tool, -continue, -noGenerateSpecTE and -noTE turn it off, as
644
- // -noGenerateSpecTEBin and -noTEBin turn off the binary trace. TLC 1.7.4 records no such trace.
645
- const isTraceRecorded = (args: ParsedArgs, version: TlcVersion) => {
646
- const flags = [...args.unknown, ...args.options.map((option) => option.name)];
647
- const hasFlag = (name: string, alias = name) =>
648
- flags.some((flag) => flag === name || flag.toLowerCase() === alias.toLowerCase());
649
- const isSpecGenerated =
650
- hasFlag("-generateSpecTE") ||
651
- (!hasFlag("-noGenerateSpecTE", "-noTE") && !hasFlag("-tool") && !hasFlag("-continue"));
652
- return version !== "1.7.4" && isSpecGenerated && !hasFlag("-noGenerateSpecTEBin", "-noTEBin");
805
+ const printSimulation = (printer: TlcPrinter, output: SimulationOutput) => {
806
+ const print = printer.print;
807
+ switch (output.kind) {
808
+ case "message":
809
+ print(
810
+ output.code,
811
+ output.isError ? MESSAGE_LEVEL.error : MESSAGE_LEVEL.none,
812
+ printer.isTool ? output.toolMessage : output.message,
813
+ );
814
+ return;
815
+ case "behavior": {
816
+ const last = output.trace[output.trace.length - 1];
817
+ if (!output.isLastStateOnly) {
818
+ printTrace(printer, output.trace, BEHAVIOR, false, true);
819
+ return;
820
+ }
821
+ print(MESSAGE_CODE.errorState, MESSAGE_LEVEL.none, "The error state is:\n");
822
+ print(MESSAGE_CODE.statePrint1, MESSAGE_LEVEL.state, `:\n${formatState(last.state)}`);
823
+ return;
824
+ }
825
+ case "progress": {
826
+ const statistics = output.statistics;
827
+ if (printer.isTool) {
828
+ printSimulationProgress(printer, statistics);
829
+ return;
830
+ }
831
+ const variance = statistics.levelM2 / (statistics.traces + 1);
832
+ print(
833
+ MESSAGE_CODE.simulationProgress,
834
+ MESSAGE_LEVEL.none,
835
+ `Progress: ${statistics.generatedStates} states checked, ${statistics.traces} traces generated (trace length: mean=${statistics.levelMean}, var(x)=${Math.round(variance)}, sd=${Math.round(Math.sqrt(variance))})`,
836
+ );
837
+ return;
838
+ }
839
+ case "summary":
840
+ if (printer.isTool) printSimulationProgress(printer, output.statistics);
841
+ print(
842
+ MESSAGE_CODE.simulationStats,
843
+ MESSAGE_LEVEL.none,
844
+ `The number of states generated: ${output.statistics.generatedStates}\nSimulation using seed ${output.statistics.seed} and aril ${output.statistics.aril}`,
845
+ );
846
+ }
847
+ };
848
+
849
+ const printSimulationProgress = (printer: MessagePrinter, statistics: SimulationStatistics) =>
850
+ printer.print(
851
+ MESSAGE_CODE.simulationProgress,
852
+ MESSAGE_LEVEL.none,
853
+ `Progress(${statistics.traces}) at ${formatTlcDate(new Date())}: ${statistics.generatedStates} states generated, -1 distinct states found, -1 states left on queue.`,
854
+ );
855
+
856
+ // Java's Path drops repeated and trailing separators.
857
+ const getJavaPath = (path: string) => path.replace(/\/+/g, "/").replace(/(.)\/$/, "$1");
858
+
859
+ const getJavaParent = (path: string) => {
860
+ const normalized = getJavaPath(path);
861
+ const separator = normalized.lastIndexOf("/");
862
+ return separator === -1 ? "." : normalized.slice(0, Math.max(separator, 1));
863
+ };
864
+
865
+ const resolveJavaPath = (directory: string, name: string) =>
866
+ directory.endsWith("/") ? `${directory}${name}` : `${directory}/${name}`;
867
+
868
+ // -generateSpecTE turns the trace exploration spec on, and -tool, -continue, -noGenerateSpecTE,
869
+ // -noTE and a spec TLC named as a trace spec turn it off. TLC 1.7.4 writes no such spec.
870
+ const getTraceSpecLocation = (
871
+ args: TlcArguments,
872
+ version: TlcVersion,
873
+ mainFile: string,
874
+ startTime: number,
875
+ ) => {
876
+ const isGenerated =
877
+ version !== "1.7.4" &&
878
+ (args.isTraceSpecForced ||
879
+ (!args.isTraceSpecDisabled &&
880
+ !args.isTool &&
881
+ !args.isContinued &&
882
+ !basename(mainFile).includes("_TTrace")));
883
+ if (!isGenerated) return undefined;
884
+ const output = args.traceSpecPath;
885
+ const module = `${basename(mainFile)}_TTrace_${Math.floor(startTime / 1000)}`;
886
+ const location =
887
+ output === undefined
888
+ ? { directory: getJavaParent(mainFile), module }
889
+ : output.toLowerCase().endsWith(".tla")
890
+ ? { directory: getJavaParent(output), module: basename(output).replace(/\.tla$/, "") }
891
+ : { directory: getJavaPath(output), module };
892
+ return {
893
+ ...location,
894
+ traceFile: args.isTraceBinaryDisabled
895
+ ? undefined
896
+ : resolveJavaPath(location.directory, `${location.module}.bin`),
897
+ };
898
+ };
899
+
900
+ const JAVA_FILE_ERRORS: Record<string, string> = {
901
+ ENOENT: "No such file or directory",
902
+ ENOTDIR: "Not a directory",
903
+ EISDIR: "Is a directory",
904
+ EACCES: "Permission denied",
905
+ };
906
+
907
+ // TLC writes files with a FileOutputStream, which names the path and the system's error.
908
+ const writeJavaFile = (path: string, content: string | Uint8Array) => {
909
+ try {
910
+ writeFileSync(path, content);
911
+ } catch (error) {
912
+ const reason =
913
+ error instanceof Error && "code" in error ? JAVA_FILE_ERRORS[String(error.code)] : undefined;
914
+ if (reason === undefined) throw error;
915
+ throw new TlaEvaluationError(`${path} (${reason})`);
916
+ }
917
+ };
918
+
919
+ // Java's File#mkdirs reports a failure only through its result, which TLC ignores.
920
+ const makeJavaDirectory = (path: string) => {
921
+ try {
922
+ mkdirSync(path, { recursive: true });
923
+ } catch {}
924
+ };
925
+
926
+ const createMetadir = (args: TlcArguments) => {
927
+ const now = new Date();
928
+ const pad = (value: number, length = 2) => String(value).padStart(length, "0");
929
+ const name = `${pad(now.getFullYear() % 100)}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}-${pad(now.getHours())}-${pad(now.getMinutes())}-${pad(now.getSeconds())}.${pad(now.getMilliseconds(), 3)}`;
930
+ const directory = join(args.metadir ?? "states", name);
931
+ mkdirSync(directory, { recursive: true });
932
+ return directory;
653
933
  };
654
934
 
655
935
  const checkSpec = async (
656
936
  specPath: string,
657
- args: ParsedArgs,
937
+ args: TlcArguments,
938
+ dump: StateDump | undefined,
658
939
  java: JavaProperties,
659
- printer: MessagePrinter,
940
+ printer: TlcPrinter,
660
941
  ) => {
661
- // TLC.handleParameters: TLC reads its options before it says which version it is.
662
- const seed = args.has("-seed") ? args.get("-seed")?.[0] : "0";
663
- if (seed === undefined) return printCommandLineError(printer, "Error: seed required.");
664
- if (!isJavaLong(seed)) {
665
- return printCommandLineError(
666
- printer,
667
- `Error: An integer for seed required. But encountered ${seed}`,
668
- );
669
- }
670
- const livenessCheck = args.has("-lncheck") ? args.get("-lncheck")?.[0]?.toLowerCase() : "default";
671
- if (livenessCheck === undefined) {
672
- return printCommandLineError(
673
- printer,
674
- "Error: expect a strategy such as final for -lncheck option.",
675
- );
676
- }
677
- const dumpValues = args.get("-dump");
678
- if (dumpValues?.length === 0) {
679
- return printCommandLineError(printer, "Error: A file name for dumping states required.");
680
- }
681
- const unsupportedFormat =
682
- dumpValues?.length === 2 &&
683
- UNSUPPORTED_DUMP_FORMATS.find((format) => dumpValues[0].toLowerCase().includes(format));
684
- if (unsupportedFormat) {
685
- console.error(`Error: tla-ts does not support the -dump format ${unsupportedFormat}.`);
686
- return 1;
687
- }
688
- const fingerprintIndex = args.get("-fp")?.[0];
689
- if (fingerprintIndex !== undefined && Number(fingerprintIndex) !== 0) {
690
- console.error(
691
- `Error: tla-ts fingerprints states as TLC does with -fp 0, not -fp ${fingerprintIndex}.`,
692
- );
693
- return 1;
694
- }
695
- const workers = getWorkerCount(args.get("-workers"));
942
+ const workers = args.workers;
943
+ const livenessCheck = args.livenessCheck;
944
+ const seed = args.seed;
696
945
  const version = printer.version;
697
946
  printWelcome(printer);
698
- printStartupBanner(printer, seed, workers);
699
- const configPath =
700
- args.get("-config")?.[0] ??
701
- (args.has("-config") ? undefined : specPath.replace(/\.tla$/, ".cfg"));
702
- if (!configPath || !existsSync(configPath)) {
947
+ // TLC reads the checkpoint's table of names first.
948
+ const recoverDirectory = args.recoverDirectory;
949
+ if (recoverDirectory !== undefined) {
950
+ throw existsSync(join(recoverDirectory, "vars.chkpt"))
951
+ ? new TlaFeatureUnsupportedError(
952
+ `tla-ts can't recover a model check from the checkpoint in ${recoverDirectory}.`,
953
+ )
954
+ : new TlaMissingCheckpointError(recoverDirectory);
955
+ }
956
+ printStartupBanner(printer, args);
957
+ const configPath = args.configPath ?? specPath.replace(/\.tla$/, ".cfg");
958
+ if (!existsSync(configPath)) {
703
959
  printer.print(
704
960
  MESSAGE_CODE.configFileError,
705
961
  MESSAGE_LEVEL.error,
706
- `TLC encountered the following error when trying to read the configuration file ${configPath ?? ""}:\nFile not found.`,
962
+ `TLC encountered the following error when trying to read the configuration file ${configPath}:\nFile not found.`,
707
963
  );
708
964
  return EXIT_STATUS.configParseError;
709
965
  }
710
966
  const fileName = basename(specPath, ".tla");
711
967
  const timing: Timing = { startTime: Date.now(), livenessStartTime: undefined, isParsed: false };
712
- // Without -tool, TLC prints how long it ran for a person to read.
713
968
  const printFinished = () => {
714
969
  const runtime = Date.now() - timing.startTime;
715
970
  printer.print(
@@ -732,13 +987,19 @@ const checkSpec = async (
732
987
  printError(error, printer);
733
988
  }
734
989
  printFinished();
735
- return getErrorExitCode(error);
990
+ return getTopLevelExitCode(error);
736
991
  };
737
992
  // TLC reads the configuration file before it parses the spec, and prints how long it ran even
738
993
  // when it can't read it.
739
994
  const config = (() => {
740
995
  try {
741
- return parseConfig(readFileSync(configPath, "utf8"), version);
996
+ const contents = readFileSync(configPath, "utf8");
997
+ return parseConfig(
998
+ configPath.endsWith(".tla")
999
+ ? getEmbeddedConfig(contents, configPath.replaceAll(".tla", ""))
1000
+ : contents,
1001
+ version,
1002
+ );
742
1003
  } catch (error) {
743
1004
  if (!(error instanceof TlaConfigError)) throw error;
744
1005
  return error;
@@ -755,17 +1016,24 @@ const checkSpec = async (
755
1016
  return EXIT_STATUS.error;
756
1017
  }
757
1018
  if (config instanceof TlaConfigError) return printFailure(config);
758
- if (args.has("-deadlock")) config.checkDeadlock = false;
1019
+ if (!args.isDeadlockChecked) config.checkDeadlock = false;
759
1020
  const directory = dirname(specPath);
760
1021
  const directories = [directory, ...java.libraries];
761
1022
  const loadModule = createModuleLoader(directories);
762
- const isRecorded = isTraceRecorded(args, version);
1023
+ const traceSpec = getTraceSpecLocation(
1024
+ args,
1025
+ version,
1026
+ specPath.replace(/\.tla$/, ""),
1027
+ timing.startTime,
1028
+ );
1029
+ const getOperatorModules = (kind: ModuleOperator["kind"]) =>
1030
+ args.moduleOperators
1031
+ .filter((operator) => operator.kind === kind)
1032
+ .map((operator) => operator.module);
763
1033
  if (printer.isTool) {
764
1034
  printer.print(MESSAGE_CODE.startingSany, MESSAGE_LEVEL.none, "Starting SANY...");
765
1035
  }
766
- // TLC.handleParameters: SANY names the spec as TLC's arguments do, except that TLC runs from the
767
- // directory of a spec given by an absolute path, and names it by its file name. SANY looks for
768
- // the spec's modules in the spec's directory and the TLA-Library directories.
1036
+ // TLC runs from the directory of a spec given by an absolute path, and names it by its file name.
769
1037
  const isAbsoluteSpec = isAbsolute(specPath);
770
1038
  const specName = isAbsoluteSpec ? fileName : specPath.replace(/\.tla$/, "");
771
1039
  const jar = getToolsJar(java);
@@ -782,27 +1050,29 @@ const checkSpec = async (
782
1050
  [...(isAbsoluteSpec || directory === "." ? [] : [directory]), ...java.libraries],
783
1051
  );
784
1052
  }
785
- // TLC prints what SANY prints as it parses the spec, and the errors it rejects the spec for.
786
1053
  const sany = getSanyReport(
787
1054
  specPath,
788
1055
  reportMissingFile ? reportMissingModules174(loadModule, reportMissingFile) : loadModule,
789
1056
  {
790
1057
  fileName: specName,
791
- describeFile: createFileDescriber(
792
- specPath,
793
- directories,
794
- java,
795
- args.get("-metadir")?.[0],
796
- version,
797
- ),
1058
+ describeFile: createFileDescriber(specPath, directories, java, args.metadir, version),
798
1059
  version,
799
1060
  // TLC's trace exploration spec records the trace with the post condition of _TLCTrace.
800
- rootExtendees: isRecorded ? ["_TLCTrace"] : undefined,
1061
+ rootExtendees: [
1062
+ ...getOperatorModules("postcondition"),
1063
+ ...(traceSpec?.traceFile === undefined ? [] : ["_TLCTrace"]),
1064
+ ...args.invariants.flatMap((invariant) => invariant.modules),
1065
+ ...getOperatorModules("constraint"),
1066
+ ...getOperatorModules("view").slice(0, 1),
1067
+ ],
1068
+ suppressedCodes: args.suppressedCodes,
1069
+ errorCodes: args.errorCodes,
801
1070
  onPrint: (text) => process.stdout.write(text),
802
1071
  onPrintError: (text) => process.stderr.write(text),
803
1072
  },
804
1073
  );
805
- if (sany.isFailed) {
1074
+ const specification = sany.specification;
1075
+ if (sany.isFailed || specification === undefined) {
806
1076
  printCheckProgress(printer, { kind: "parsed" }, timing, directory);
807
1077
  printParsingFailed();
808
1078
  printFinished();
@@ -817,18 +1087,41 @@ const checkSpec = async (
817
1087
  undefined,
818
1088
  );
819
1089
  }
820
- const result = await check({
1090
+ const userFile = args.userFile;
1091
+ const standardModules = getSanyStandardModules(version);
1092
+ const invariants = addRuntimeInvariants(
1093
+ source,
1094
+ specification.root,
1095
+ args.invariants,
1096
+ (name) => loadModule(name) ?? standardModules.get(name) ?? extractModule(source, name),
1097
+ version,
1098
+ );
1099
+ config.invariants.push(...invariants.names);
1100
+ const options: CheckOptions = {
821
1101
  workers,
822
- livenessCheck: ["final", "seqfinal", "off"].includes(livenessCheck) ? "final" : "default",
823
- seed: BigInt(seed),
824
- dump: dumpValues && getStateDump(dumpValues),
1102
+ livenessCheck:
1103
+ livenessCheck === "off"
1104
+ ? "off"
1105
+ : ["final", "seqfinal"].includes(livenessCheck)
1106
+ ? "final"
1107
+ : "default",
1108
+ seed,
1109
+ fingerprintPolynomial: args.fingerprintIndex,
1110
+ maxSetSize: args.maxSetSize,
1111
+ isLazyValueExpanded: args.isLazyValueExpanded,
1112
+ isViewPrinted: args.isViewPrinted,
1113
+ dump,
825
1114
  isTool: printer.isTool,
826
- isTraceRecorded: isRecorded,
1115
+ isContinued: args.isContinued,
1116
+ moduleOperators: args.moduleOperators,
1117
+ traceSpec,
1118
+ coverage: args.coverage,
827
1119
  isSanyReported: true,
828
- isWarningEnabled: !args.has("-nowarning"),
1120
+ isWarningEnabled: args.isWarningEnabled,
829
1121
  version,
830
1122
  onProgress: (progress) => printCheckProgress(printer, progress, timing, directory),
831
- source,
1123
+ onPrint: userFile === undefined ? undefined : (text) => appendFileSync(userFile, `${text}\n`),
1124
+ source: invariants.source,
832
1125
  config,
833
1126
  onPause: () => readSync(0, Buffer.alloc(1)),
834
1127
  loadModule,
@@ -836,14 +1129,58 @@ const checkSpec = async (
836
1129
  const classPath = getClassPath(directory, name);
837
1130
  return existsSync(classPath) ? readFileSync(classPath) : undefined;
838
1131
  },
839
- readFile: (path) => (existsSync(path) ? readFileSync(path, "utf8") : undefined),
840
- writeFile: (path, content) => {
841
- mkdirSync(dirname(resolve(path)), { recursive: true });
842
- writeFileSync(path, content);
1132
+ readFile: (path) => {
1133
+ checkNotDirectory(path);
1134
+ return existsSync(path) ? readFileSync(path, "utf8") : undefined;
843
1135
  },
844
- });
1136
+ writeFile: writeJavaFile,
1137
+ makeDirectory: makeJavaDirectory,
1138
+ };
1139
+ if (args.mode !== "model-check") {
1140
+ const status = simulate({
1141
+ ...options,
1142
+ traceDepth: args.traceDepth,
1143
+ traceCount: args.traceCount,
1144
+ aril: args.aril,
1145
+ isGenerating: args.mode === "generate",
1146
+ scheduler: args.scheduler,
1147
+ onSimulation: (output) => printSimulation(printer, output),
1148
+ });
1149
+ printFinished();
1150
+ return status;
1151
+ }
1152
+ if (args.dfidDepth !== undefined) {
1153
+ const status = checkDepthFirst({
1154
+ ...options,
1155
+ maxDepth: args.dfidDepth,
1156
+ onOutput: (output) => printDepthFirst(printer, output),
1157
+ });
1158
+ printFinished();
1159
+ return status;
1160
+ }
1161
+ const result = await check(options);
845
1162
  printResult(result, printer, timing);
846
1163
  printFinished();
1164
+ if (traceSpec && result.traceSpec !== undefined) {
1165
+ const path = resolveJavaPath(traceSpec.directory, `${traceSpec.module}.tla`);
1166
+ makeJavaDirectory(traceSpec.directory);
1167
+ const failure = (() => {
1168
+ try {
1169
+ writeJavaFile(path, result.traceSpec);
1170
+ return undefined;
1171
+ } catch (error) {
1172
+ if (!(error instanceof TlaEvaluationError)) throw error;
1173
+ return error;
1174
+ }
1175
+ })();
1176
+ printer.print(
1177
+ failure ? MESSAGE_CODE.traceSpecFailed : MESSAGE_CODE.traceSpecWritten,
1178
+ MESSAGE_LEVEL.none,
1179
+ failure
1180
+ ? `Failed to generate trace exploration spec; error message: ${failure.message}`
1181
+ : `Trace exploration spec path: ${path}`,
1182
+ );
1183
+ }
847
1184
  return result.failure?.exitCode ?? EXIT_CODES[result.status];
848
1185
  } catch (error) {
849
1186
  if (!(error instanceof TlaError)) throw error;
@@ -853,8 +1190,6 @@ const checkSpec = async (
853
1190
  }
854
1191
  };
855
1192
 
856
- // What SANY prints about a spec it rejects: a module it can't find or parse is a fatal error, and
857
- // it reports the other errors as semantic errors.
858
1193
  const formatSanyErrors = (error: TlaSyntaxError, specName: string) => {
859
1194
  const isFatal = error instanceof TlaSanyFatalError;
860
1195
  if (!isFatal && !error.failure)
@@ -869,28 +1204,69 @@ const formatSanyErrors = (error: TlaSyntaxError, specName: string) => {
869
1204
  };
870
1205
 
871
1206
  export const checkSpecs = async (args: string[], java: JavaProperties) => {
872
- const parsed = CHECK_COMMAND.parse(args);
873
- const inputs = getInputPaths(parsed.positionals);
874
- const isConfigured = parsed.has("-config");
875
- // Like TLC, a spec named without an extension is the .tla file of that name. A glob also matches
876
- // modules that only other specs import, which have no configuration.
1207
+ const version = java.tlcVersion ?? "master";
1208
+ const parsed = parseTlcArguments(args);
1209
+ if ("error" in parsed) {
1210
+ if (parsed.isUncaught) {
1211
+ console.error(`Exception in thread "main" ${parsed.error}`);
1212
+ return 1;
1213
+ }
1214
+ return printCommandLineError(createMessagePrinter(parsed.isTool, true, version), parsed.error);
1215
+ }
1216
+ if (parsed.isUsage) {
1217
+ console.log(getTlcUsage());
1218
+ return 1;
1219
+ }
1220
+ // TLC opens the file of a -dump as it reads its arguments, in the meta directory it creates.
1221
+ const dump =
1222
+ parsed.dump &&
1223
+ getStateDump(
1224
+ parsed.dump.map((value) =>
1225
+ value.includes("${metadir}") ? value.replace("${metadir}", createMetadir(parsed)) : value,
1226
+ ),
1227
+ );
1228
+ const dumpPath = dump?.path;
1229
+ if (dumpPath !== undefined) {
1230
+ try {
1231
+ closeSync(openSync(dumpPath, "w"));
1232
+ } catch {
1233
+ console.log(`Error: Unable to write to file ${dumpPath}`);
1234
+ return printCommandLineError(
1235
+ createMessagePrinter(parsed.isTool, true, version),
1236
+ `Error: Given file name ${dumpPath} for dumping states invalid.`,
1237
+ );
1238
+ }
1239
+ }
1240
+ const isConfigured = parsed.configPath !== undefined;
1241
+ if (isConfigured && parsed.specs.length > 1) {
1242
+ return printCommandLineError(
1243
+ createMessagePrinter(parsed.isTool, true, version),
1244
+ `Error: more than one input files: ${parsed.specs[0].replace(/\.tla$/, "")} and ${parsed.specs[1]}`,
1245
+ );
1246
+ }
1247
+ const inputs = getInputPaths(parsed.specs);
1248
+ // A spec named without an extension is the .tla file of that name. A glob also matches modules
1249
+ // that only other specs import, which have no configuration. A TypeScript file compiles to a spec.
877
1250
  const specPaths = inputs
878
1251
  .map((input) => ({
879
1252
  ...input,
880
1253
  path:
881
- input.isGlobbed || /\.(tla|cfg)$/.test(input.path)
1254
+ input.isGlobbed || /\.(tla|cfg|ts)$/.test(input.path)
882
1255
  ? input.path.replace(/\.cfg$/, ".tla")
883
1256
  : `${input.path}.tla`,
884
1257
  }))
885
1258
  .filter(
886
1259
  (input) =>
887
- input.path.endsWith(".tla") &&
888
- (!input.isGlobbed || isConfigured || existsSync(input.path.replace(/\.tla$/, ".cfg"))),
1260
+ input.path.endsWith(".ts") ||
1261
+ (input.path.endsWith(".tla") &&
1262
+ (!input.isGlobbed || isConfigured || existsSync(input.path.replace(/\.tla$/, ".cfg")))),
889
1263
  )
890
1264
  .map((input) => input.path);
891
1265
  if (specPaths.length === 0) {
892
- console.error(USAGE);
893
- return 1;
1266
+ return printCommandLineError(
1267
+ createMessagePrinter(parsed.isTool, true, version),
1268
+ "Error: Missing input TLA+ module.",
1269
+ );
894
1270
  }
895
1271
  if (isConfigured && specPaths.length > 1) {
896
1272
  console.error("Error: -config applies to one specification, but several were given.");
@@ -907,22 +1283,32 @@ export const checkSpecs = async (args: string[], java: JavaProperties) => {
907
1283
  const exitCodes: number[] = [];
908
1284
  for (const [index, path] of paths.entries()) {
909
1285
  if (index > 0) console.log("");
910
- // TLC checks one spec, so tla-ts names each of several it checks.
911
- if (paths.length > 1)
912
- console.log(`Checking ${basename(path)} with ${basename(path, ".tla")}.cfg`);
913
- const printer = createMessagePrinter(
914
- parsed.has("-tool"),
915
- !parsed.has("-nowarning"),
916
- java.tlcVersion ?? "master",
1286
+ const printer = {
1287
+ ...createMessagePrinter(
1288
+ parsed.isTool,
1289
+ parsed.isWarningEnabled,
1290
+ version,
1291
+ parsed.suppressedCodes,
1292
+ parsed.errorCodes,
1293
+ ),
1294
+ isDiffTrace: parsed.isDiffTrace,
1295
+ };
1296
+ exitCodes.push(
1297
+ await reportErrors(async () => {
1298
+ const specPath = path.endsWith(".ts") ? await writeTypeScriptSpec(path) : path;
1299
+ // TLC checks one spec, so tla-ts names each of several it checks.
1300
+ if (paths.length > 1) {
1301
+ console.log(`Checking ${basename(specPath)} with ${basename(specPath, ".tla")}.cfg`);
1302
+ }
1303
+ return checkSpec(specPath, parsed, dump, java, printer);
1304
+ }, printer),
917
1305
  );
918
- exitCodes.push(await reportErrors(() => checkSpec(path, parsed, java, printer), printer));
919
1306
  }
920
1307
  return exitCodes.find((exitCode) => exitCode !== EXIT_STATUS.success) ?? EXIT_STATUS.success;
921
1308
  };
922
1309
 
923
- // TLC 1.7.4's SimpleFilenameToStream looks for a module in the directory of a spec that TLC is
924
- // given by an absolute path, then in the directory that a relative path names, or else in the
925
- // TLA-Library directories.
1310
+ // TLC 1.7.4 looks in the directory of a spec given by an absolute path, then in the directory a
1311
+ // relative path names, or else in the TLA-Library directories.
926
1312
  const createMissingFilePrinter174 = (
927
1313
  specPath: string,
928
1314
  java: JavaProperties,