tla-ts 0.0.3 → 0.0.4-dev.2be6058

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 (86) hide show
  1. package/README.md +32 -12
  2. package/dist/cli.cjs +1 -1
  3. package/dist/cli.js +1 -1
  4. package/dist/index.cjs +1 -1
  5. package/dist/index.d.cts +160 -8
  6. package/dist/index.d.ts +160 -8
  7. package/dist/index.js +1 -1
  8. package/dist/parallel-worker.cjs +2 -2
  9. package/dist/parallel-worker.js +2 -2
  10. package/dist/parallel.cjs +1 -1
  11. package/dist/parallel.js +2 -2
  12. package/dist/run-cli.cjs +45 -18
  13. package/dist/run-cli.js +45 -18
  14. package/dist/transfer.cjs +1393 -18
  15. package/dist/transfer.js +1393 -18
  16. package/package.json +5 -1
  17. package/src/ast.ts +147 -6
  18. package/src/bags.ts +4 -7
  19. package/src/builtins.ts +29 -11
  20. package/src/bundled-modules.ts +3 -3
  21. package/src/canonical.ts +4 -3
  22. package/src/check.ts +1539 -235
  23. package/src/cli-options.ts +11 -5
  24. package/src/cli.ts +8 -1
  25. package/src/codegen.ts +77 -37
  26. package/src/config.ts +254 -181
  27. package/src/dependencies.ts +2 -2
  28. package/src/environment.ts +540 -140
  29. package/src/errors.ts +224 -3
  30. package/src/evaluate.ts +797 -246
  31. package/src/exit-codes.ts +22 -43
  32. package/src/fingerprints.ts +46 -11
  33. package/src/index.ts +1 -0
  34. package/src/instances.ts +19 -16
  35. package/src/java-overrides.ts +104 -25
  36. package/src/levels.ts +191 -45
  37. package/src/lexer.ts +127 -30
  38. package/src/live-check.ts +867 -0
  39. package/src/liveness.ts +218 -572
  40. package/src/obligation-expression.ts +2 -2
  41. package/src/obligation-source.ts +2 -0
  42. package/src/parallel-worker.ts +174 -213
  43. package/src/parallel.ts +131 -39
  44. package/src/parser.ts +456 -147
  45. package/src/pcal-ast.ts +770 -0
  46. package/src/pcal-parse.ts +1523 -0
  47. package/src/pcal-tokenize.ts +516 -0
  48. package/src/pcal-translate.ts +1230 -0
  49. package/src/pcal-validate.ts +454 -0
  50. package/src/randomization.ts +24 -7
  51. package/src/resolve.ts +1481 -426
  52. package/src/run-cli.ts +1212 -143
  53. package/src/runtime.ts +19 -1
  54. package/src/sany-builtins.ts +147 -0
  55. package/src/sany-generator.ts +3128 -0
  56. package/src/sany-levels.ts +1208 -0
  57. package/src/sany-lexer.ts +545 -0
  58. package/src/sany-linter.ts +122 -0
  59. package/src/sany-modules.ts +1398 -0
  60. package/src/sany-nodes.ts +463 -0
  61. package/src/sany-parse-error.ts +2161 -0
  62. package/src/sany-report.ts +356 -0
  63. package/src/sany-selectors.ts +738 -0
  64. package/src/sany-source.ts +248 -0
  65. package/src/sany-xml.ts +1017 -0
  66. package/src/spec-description.ts +42 -11
  67. package/src/standard-modules.ts +200 -148
  68. package/src/standard-ranges.ts +116 -0
  69. package/src/state-graph.ts +180 -0
  70. package/src/subexpressions.ts +231 -171
  71. package/src/substitution-levels.ts +38 -17
  72. package/src/successors.ts +219 -107
  73. package/src/symmetry.ts +194 -54
  74. package/src/tableau.ts +54 -25
  75. package/src/tlc-ext.ts +42 -29
  76. package/src/tlc-messages.ts +329 -0
  77. package/src/tlc-module.ts +52 -43
  78. package/src/tlc-modules.ts +4 -0
  79. package/src/tlc-order.ts +78 -10
  80. package/src/tlc-random.ts +37 -9
  81. package/src/tlc-replay.ts +655 -0
  82. package/src/tlc-summary.ts +20 -5
  83. package/src/tlc-version.ts +18 -0
  84. package/src/transfer.ts +15 -3
  85. package/src/value-sources.ts +29 -0
  86. package/src/values.ts +731 -184
package/src/run-cli.ts CHANGED
@@ -8,9 +8,25 @@ import {
8
8
  writeFileSync,
9
9
  } from "node:fs";
10
10
  import { spawnSync } from "node:child_process";
11
- import { basename, delimiter, dirname, join, resolve } from "node:path";
12
- import { availableParallelism } from "node:os";
13
- import type { CheckResult, CheckStatus, TraceStep } from "./check";
11
+ import { createHash } from "node:crypto";
12
+ import { basename, delimiter, dirname, isAbsolute, join, resolve } from "node:path";
13
+ import { arch, availableParallelism, release, tmpdir, type } from "node:os";
14
+ import { pathToFileURL } from "node:url";
15
+ import { getHeapStatistics } from "node:v8";
16
+ import { version } from "../package.json";
17
+ import type { Expression } from "./ast";
18
+ import { describeRange } from "./evaluate";
19
+ import type {
20
+ CheckProgress,
21
+ InitialStateViolation,
22
+ OutputLine,
23
+ CheckResult,
24
+ CheckStatus,
25
+ InitialStates,
26
+ SearchStatistics,
27
+ TraceStep,
28
+ Violation,
29
+ } from "./check";
14
30
  import { defineCommand, type ParsedArgs } from "./cli-options";
15
31
  import { parseConfig } from "./config";
16
32
  import {
@@ -19,20 +35,43 @@ import {
19
35
  TlaError,
20
36
  TlaEvaluationError,
21
37
  TlaProofError,
38
+ TlaSyntaxError,
39
+ getUnexpectedException,
40
+ TlaJavaException,
41
+ UNEXPECTED_EXCEPTION,
42
+ TlaSanyFatalError,
43
+ TlaUnsupportedError,
22
44
  } from "./errors";
23
- import { EXIT_STATUS } from "./exit-codes";
45
+ import { EXIT_STATUS, setExitCode } from "./exit-codes";
24
46
  import type { LineRange } from "./obligation-generate";
25
47
  import { getAtPrefix, getLocusText } from "./obligation-expression";
26
48
  import { formatSummary, getObligations, WHOLE_MODULE, type ModuleObligations } from "./obligations";
27
49
  import { check } from "./parallel";
28
- import { prettyPrint } from "./pretty-print";
50
+ import { parseModule } from "./parser";
51
+ import type { StateDump } from "./state-graph";
29
52
  import {
30
53
  formatProbability,
31
54
  getActualProbability,
32
55
  getOptimisticProbability,
33
56
  getOutDegreeSummary,
34
57
  } from "./tlc-summary";
35
- import { formatValue, type Value } from "./values";
58
+ import type { SanySpecification } from "./sany-generator";
59
+ import { SANY_174_STANDARD_MODULES, SANY_STANDARD_MODULES } from "./sany-modules";
60
+ import { getSanyModuleName, getSanyReport, type SanyModuleOrigin } from "./sany-report";
61
+ import { exportSanyXml, XML_EXPORT_EXIT_CODE, type XmlExportOptions } from "./sany-xml";
62
+ import { getTlcVersion, type TlcVersion } from "./tlc-version";
63
+ import {
64
+ createMessagePrinter,
65
+ formatTlcDate,
66
+ formatInnerMessage,
67
+ formatNestedMessage,
68
+ formatTlcDuration,
69
+ getCodedMessage,
70
+ MESSAGE_CODE,
71
+ MESSAGE_LEVEL,
72
+ type MessagePrinter,
73
+ } from "./tlc-messages";
74
+ import { formatState } from "./values";
36
75
 
37
76
  const EXIT_CODES: Record<CheckStatus, number> = {
38
77
  success: EXIT_STATUS.success,
@@ -48,8 +87,17 @@ const EXIT_CODES: Record<CheckStatus, number> = {
48
87
  const CHECK_COMMAND = defineCommand("tla-ts <Spec.tla|Spec.cfg|glob>... {options}", [
49
88
  { flag: "-config <Spec.cfg>" },
50
89
  { flag: "-deadlock" },
90
+ // Like TLC, -dump takes a format only when the next argument starts with dot and a file follows.
91
+ {
92
+ flag: "-dump [<format>] <file>",
93
+ getArity: (rest) => (rest.length > 1 && rest[0].startsWith("dot") ? 2 : 1),
94
+ },
95
+ { flag: "-fp <num>" },
51
96
  { flag: "-lncheck <final|default>" },
97
+ { flag: "-metadir <directory>" },
98
+ { flag: "-nowarning" },
52
99
  { flag: "-seed <num>" },
100
+ { flag: "-tool" },
53
101
  { flag: "-workers <count|auto>" },
54
102
  ]);
55
103
 
@@ -63,10 +111,65 @@ const PROVE_COMMAND = defineCommand("tla-ts prove {options} <Module.tla|glob>...
63
111
  { flag: "-I <directory>", isRepeatable: true },
64
112
  ]);
65
113
 
114
+ const XML_EXPORT_FLAGS = new Set(["-o", "-t", "-r", "-u"]);
115
+
116
+ const XML_EXPORT_174_FLAGS = new Set(["-o"]);
117
+
118
+ // The usage that XMLExporter.printUsage prints with UsageGenerator.
119
+ const XML_EXPORT_USAGE = (() => {
120
+ const bold = (text: string) => `\x1b[1m${text}\x1b[0m`;
121
+ const options = [
122
+ ["-I", "Include; use given directory path to resolve module dependencies."],
123
+ ["-help", "Print this usage information."],
124
+ ["-o", "Offline mode; skip XML schema validation step."],
125
+ [
126
+ "-r",
127
+ "Restrict mode; include only declarations and definitions of the specified module, excluding extended or instantiated modules.",
128
+ ],
129
+ ["-t", "Terse; format XML output without tabs or newlines."],
130
+ [
131
+ "-u",
132
+ "Uncomment; process boxed comments and single-line comments (\\*) in pre-comments to extract their content.",
133
+ ],
134
+ ];
135
+ const tips = [
136
+ "Only one root TLA+ file can be parsed per run.",
137
+ "Multiple directory search paths can be given by providing multiple -I arguments.",
138
+ "XML schema validation does not require network access.",
139
+ ];
140
+ return [
141
+ "",
142
+ bold("NAME"),
143
+ "",
144
+ "\ttla2sany.xml.XMLExporter - Emit SANY's parse tree as XML - Version 2.2 created 08 July 2020",
145
+ "",
146
+ "",
147
+ bold("SYNOPSIS"),
148
+ "",
149
+ `\t${bold("tla2sany.xml.XMLExporter")} [${bold("-Iortu")}] [${bold("-help")}] FILE`,
150
+ "",
151
+ bold("DESCRIPTION"),
152
+ "",
153
+ "\tGiven a TLA+ file, parse that file with SANY then translate the module's semantic parse tree to XML, including all the modules depended on. The XML is printed to stdout and its output format is given by an XML Schema file (.xsd) found at https://proofs.tlapl.us/doc/web/sany.xsd.",
154
+ "",
155
+ bold("OPTIONS"),
156
+ "",
157
+ ...options.map(([flag, description]) => `\t${bold(flag)}\n\t\t${description}`),
158
+ "",
159
+ bold("TIPS"),
160
+ "",
161
+ ...tips.flatMap((tip) => [`\t${tip}`, ""]),
162
+ "",
163
+ ].join("\n");
164
+ })();
165
+
66
166
  const USAGE = [
67
167
  `Usage: ${CHECK_COMMAND.usage}`,
68
168
  ` ${PROVE_COMMAND.usage}`,
69
169
  " tla-ts prove [<tlapm option>]... <Module.tla|glob>...",
170
+ " tla-ts [<JVM option>]... tlc2.TLC <TLC option>... <Spec>",
171
+ " (-cp tla2tools.jar or -Dtla-ts.tlc=1.7.4 picks the TLC to reproduce)",
172
+ " tla-ts [<JVM option>]... tla2sany.xml.XMLExporter [-I <directory>]... [-o] [-t] [-r] [-u] <Module.tla>",
70
173
  ].join("\n");
71
174
 
72
175
  const GLOB_CHARACTERS = /[*?[{]/;
@@ -95,178 +198,845 @@ const getWorkerCount = (values: string[] | undefined) => {
95
198
  : Math.max(1, Number.parseInt(values[0], 10) || 1);
96
199
  };
97
200
 
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("");
201
+ const UNSUPPORTED_DUMP_FORMATS = ["constrained", "stuttering", "strict"];
202
+
203
+ // TLC names the file of a -dump by its format unless the name already ends that way.
204
+ const getDumpPath = (path: string, extension: string) =>
205
+ path.endsWith(extension) ? path : `${path}${extension}`;
206
+
207
+ const getDump = (values: string[]): StateDump => {
208
+ if (values.length === 1) return { path: getDumpPath(values[0], ".dump") };
209
+ const format = values[0].toLowerCase();
210
+ return {
211
+ path: getDumpPath(values[1], ".dot"),
212
+ dot: true,
213
+ colorize: format.includes("colorize"),
214
+ actionLabels: format.includes("actionlabels"),
215
+ snapshot: format.includes("snapshot"),
216
+ };
106
217
  };
107
218
 
108
- const printTrace = (trace: TraceStep[], heading = "Error: The behavior up to this point is:") => {
109
- if (trace.length > 0) console.log(heading);
219
+ // What the spec prints as TLC rebuilds a trace, before it prints the states or after.
220
+ const printInitialStatesProgress = (printer: MessagePrinter, count: number) =>
221
+ printer.print(
222
+ MESSAGE_CODE.computingInitProgress,
223
+ MESSAGE_LEVEL.none,
224
+ `Computed ${count} initial states...`,
225
+ );
226
+
227
+ const getInitialViolationHeadline = (
228
+ status: InitialStateViolation["status"],
229
+ name: string | undefined,
230
+ ) =>
231
+ status === "invariant-violation"
232
+ ? {
233
+ code: MESSAGE_CODE.invariantViolatedInitial,
234
+ text: `Invariant ${name} is violated by the initial state:`,
235
+ }
236
+ : {
237
+ code: MESSAGE_CODE.propertyViolatedInitial,
238
+ text: `Property ${name} is violated by the initial state:`,
239
+ };
240
+
241
+ const printTraceOutput = (printer: MessagePrinter, lines: OutputLine[] | undefined) =>
242
+ lines?.forEach((line) => {
243
+ if (typeof line === "string") return console.log(line);
244
+ if (line.kind === "initial-states-progress") {
245
+ return printInitialStatesProgress(printer, line.count);
246
+ }
247
+ const headline = getInitialViolationHeadline(line.status, line.name);
248
+ printer.print(
249
+ headline.code,
250
+ MESSAGE_LEVEL.error,
251
+ `${headline.text}\n${formatState(line.state)}`,
252
+ );
253
+ });
254
+
255
+ const printTrace = (
256
+ printer: MessagePrinter,
257
+ trace: TraceStep[],
258
+ heading: { code: number; text: string } = {
259
+ code: MESSAGE_CODE.behaviorUpToThisPoint,
260
+ text: "The behavior up to this point is:",
261
+ },
262
+ isRebuiltAfterHeading = false,
263
+ ) => {
264
+ if (trace.length > 0) printer.print(heading.code, MESSAGE_LEVEL.error, heading.text);
110
265
  trace.forEach((step, index) => {
111
- console.log(`State ${index + 1}: <${step.label ?? step.action ?? "Initial predicate"}>`);
112
- printState(step.state);
266
+ if (index > 0 || isRebuiltAfterHeading) printTraceOutput(printer, step.output);
267
+ printer.print(
268
+ MESSAGE_CODE.statePrint2,
269
+ MESSAGE_LEVEL.state,
270
+ `${index + 1}: <${step.label ?? step.action ?? "Initial predicate"}>\n${formatState(step.state)}`,
271
+ );
113
272
  });
114
273
  };
115
274
 
116
- const printResult = (result: CheckResult) => {
117
- if (result.failure) {
118
- console.log(`Error: ${result.failure.message}`);
119
- if (result.failure.initialState) {
120
- console.log("While working on the initial state:");
121
- printState(result.failure.initialState);
275
+ const COUNTER_EXAMPLE = {
276
+ code: MESSAGE_CODE.counterExample,
277
+ text: "The following behavior constitutes a counter-example:\n",
278
+ };
279
+
280
+ // TLC 1.7.4 doesn't name the properties, and later versions name none when they can't tell which.
281
+ const getTemporalHeadline = (names: string[], version: TlcVersion) =>
282
+ version === "1.7.4" || names.length === 0
283
+ ? "Temporal properties were violated.\n"
284
+ : names.length === 1
285
+ ? `Temporal property ${names[0]} was violated.\n`
286
+ : `Temporal properties ${names.slice(0, -1).join(", ")}${names.length > 2 ? "," : ""} and ${names[names.length - 1]} were violated.\n`;
287
+
288
+ // TLC's FingerprintException#getTrace: the range of each source, innermost first, skipping a
289
+ // source the same as the one inside it.
290
+ const formatFingerprintTrace = (sources: Expression[]) =>
291
+ sources
292
+ .filter((source, index) => source !== sources[index - 1])
293
+ .map((source, index) => `${index}) ${describeRange(source)}\n`)
294
+ .toReversed()
295
+ .join("");
296
+
297
+ // TLC's CallStack.toString: the range of each expression, skipping an expression that it evaluates
298
+ // again right inside itself.
299
+ const formatCallStack = (expressions: Expression[]) => {
300
+ if (expressions.length === 0) return " The error call stack is empty.\n";
301
+ const lines: string[] = [];
302
+ expressions.forEach((expression, index) => {
303
+ const range = expression.location.range;
304
+ if (expression === expressions[index - 1] || !range) return;
305
+ lines.push(
306
+ `${lines.length}. Line ${range.start.line}, column ${range.start.column} to line ${range.end.line}, column ${range.end.column} in ${range.module}\n`,
307
+ );
308
+ });
309
+ return `${lines.join("")}\n`;
310
+ };
311
+
312
+ const printInitialStates = (printer: MessagePrinter, initialStates: InitialStates) => {
313
+ const generated = initialStates.generated;
314
+ const distinct = initialStates.distinct;
315
+ const date = formatTlcDate(new Date());
316
+ if (generated === distinct) {
317
+ printer.print(
318
+ MESSAGE_CODE.initGenerated1,
319
+ MESSAGE_LEVEL.none,
320
+ `Finished computing initial states: ${distinct} distinct state${distinct === 1 ? "" : "s"} generated at ${date}.`,
321
+ );
322
+ return;
323
+ }
324
+ printer.print(
325
+ MESSAGE_CODE.initGenerated2,
326
+ MESSAGE_LEVEL.none,
327
+ `Finished computing initial states: ${generated} state${generated === 1 ? "" : "s"} generated, with ${distinct} of them distinct at ${date}.`,
328
+ );
329
+ };
330
+
331
+ interface Timing {
332
+ start: number;
333
+ // Whether TLC has printed that SANY finished.
334
+ isParsed: boolean;
335
+ // When TLC started to check the temporal properties on the complete state graph.
336
+ liveness: number | undefined;
337
+ }
338
+
339
+ // TLC reports how far the search got when it prints messages for a program to read, at level 1 or
340
+ // deeper even before it finds a state. As the search goes and when it ends, it adds how many
341
+ // states it generated and found a minute.
342
+ const printProgress = (
343
+ printer: MessagePrinter,
344
+ statistics: SearchStatistics,
345
+ startTime?: number,
346
+ ) => {
347
+ const minutes = Math.max(Date.now() - (startTime ?? 0), 1) / 60_000;
348
+ const format = (count: number) => count.toLocaleString("en-US");
349
+ const getRate = (count: number, unit: string) =>
350
+ startTime === undefined ? "" : ` (${format(Math.floor(count / minutes))} ${unit}/min)`;
351
+ printer.print(
352
+ MESSAGE_CODE.progress,
353
+ MESSAGE_LEVEL.none,
354
+ `Progress(${Math.max(statistics.depth, 1)}) at ${formatTlcDate(new Date())}: ${format(statistics.generatedStates)} states generated${getRate(statistics.generatedStates, "s")}, ${format(statistics.distinctStates)} distinct states found${getRate(statistics.distinctStates, "ds")}, ${format(statistics.queuedStates)} states left on queue.`,
355
+ );
356
+ };
357
+
358
+ const getClassPath = (directory: string, module: string) => join(directory, `${module}.class`);
359
+
360
+ // The messages TLC prints as the search goes.
361
+ const printCheckProgress = (
362
+ printer: MessagePrinter,
363
+ progress: CheckProgress,
364
+ timing: Timing,
365
+ directory: string,
366
+ ) => {
367
+ const print = printer.print;
368
+ switch (progress.kind) {
369
+ case "parsed":
370
+ timing.isParsed = true;
371
+ if (printer.isTool) print(MESSAGE_CODE.sanyFinished, MESSAGE_LEVEL.none, "SANY finished.");
372
+ print(
373
+ MESSAGE_CODE.starting,
374
+ MESSAGE_LEVEL.none,
375
+ `Starting... (${formatTlcDate(new Date())})`,
376
+ );
377
+ return;
378
+ // TLC 1.7.4 warns about neither a constant-level invariant nor a state-level property.
379
+ case "constant-level-invariant":
380
+ if (printer.version === "1.7.4") return;
381
+ print(
382
+ MESSAGE_CODE.constantLevelInvariant,
383
+ MESSAGE_LEVEL.warning,
384
+ `The invariant ${progress.name} is a constant-level formula (i.e., it contains no variables, primes, or temporal operators) and evaluates to TRUE. To assert constant-level formulas in your spec, use ASSUME ConstInv. If you optionally want to give the assumption a name, write ASSUME YourAssumption == ConstInv instead. See https://explain.tlapl.us/assumptions-and-invariants for additional details.`,
385
+ );
386
+ return;
387
+ case "state-level-property":
388
+ if (printer.version === "1.7.4") return;
389
+ print(
390
+ MESSAGE_CODE.stateLevelProperty,
391
+ MESSAGE_LEVEL.warning,
392
+ `The formula ${progress.name} is a state-level formula, but it was used as a PROPERTY (or PROPERTIES), where a temporal formula is typically expected. State-level formulas used as PROPERTY or PROPERTIES are only checked in the initial state. To verify that the formula ${progress.name} holds in all states of every behavior, use INVARIANT ${progress.name} instead. Alternatively, applying the "always" temporal operator ([]) to the state-level formula ${progress.name} changes it into a temporal formula, asserting that ${progress.name} holds in all states of every behavior. See https://explain.tlapl.us/invariants-and-properties for additional details.`,
393
+ );
394
+ return;
395
+ case "liveness-initializing":
396
+ if (progress.isSymmetric) {
397
+ print(
398
+ MESSAGE_CODE.livenessSymmetry,
399
+ MESSAGE_LEVEL.warning,
400
+ "Declaring symmetry during liveness checking is dangerous. It might cause TLC to miss violations of the stated liveness properties. Please check liveness without symmetry defined.",
401
+ );
402
+ }
403
+ // Only TLC 1.7.4 warns about constraints.
404
+ if (progress.isConstrained && printer.version === "1.7.4") {
405
+ print(
406
+ MESSAGE_CODE.livenessConstraints,
407
+ MESSAGE_LEVEL.warning,
408
+ "Declaring state or action constraints during liveness checking is dangerous: Please read section 14.3.5 on page 247 of Specifying Systems (https://lamport.azurewebsites.net/tla/book.html) and optionally the discussion at https://discuss.tlapl.us/msg00994.html for more details.",
409
+ );
410
+ }
411
+ return;
412
+ case "liveness-prepared":
413
+ print(
414
+ MESSAGE_CODE.temporalBranches,
415
+ MESSAGE_LEVEL.none,
416
+ `Implied-temporal checking--satisfiability problem has ${progress.branches} branches.`,
417
+ );
418
+ return;
419
+ case "java-override": {
420
+ // Class#getResource, which names the class file TLC loads the override from.
421
+ const location = pathToFileURL(resolve(getClassPath(directory, progress.module))).href;
422
+ print(
423
+ progress.isMatched ? MESSAGE_CODE.javaOverrideLoaded : MESSAGE_CODE.javaOverrideMismatch,
424
+ progress.isMatched ? MESSAGE_LEVEL.none : MESSAGE_LEVEL.warning,
425
+ `${progress.isMatched ? "Loading" : "Failed to match"} ${progress.operator} operator override from ${location.replace("file:///", "file:/")} with signature: <Java Method: ${progress.signature}>.`,
426
+ );
427
+ return;
122
428
  }
123
- printTrace(result.failure.trace);
124
- } else if (result.violation) {
125
- const violation = result.violation;
126
- const name = violation.name;
127
- const loopStart = violation.loopStart;
128
- // TLC prints a violation by an initial state without the behavior or the statistics.
129
- const isInitial =
130
- loopStart === undefined &&
131
- violation.trace.length === 1 &&
132
- (result.status === "invariant-violation" || result.status === "liveness-violation");
133
- const headline = {
134
- success: "",
135
- error: "",
136
- "assumption-violation": violation.message
137
- ? `Error: Evaluating assumption ${name} failed.\n${violation.message}`
138
- : `Error: Assumption ${name} is false.`,
139
- deadlock: "Error: Deadlock reached.",
140
- "invariant-violation": isInitial
141
- ? `Error: Invariant ${name} is violated by the initial state:`
142
- : `Error: Invariant ${name} is violated.`,
143
- "property-violation": `Error: Property ${name} is violated.`,
144
- "liveness-violation":
145
- loopStart !== undefined
146
- ? `Error: Temporal property ${name} was violated.\n`
147
- : isInitial
148
- ? `Error: Property ${name} is violated by the initial state:`
149
- : `Error: Action property ${name} is violated.`,
150
- "postcondition-violation": `Error: ${violation.message ?? `Postcondition ${name} is false.`}`,
151
- }[result.status];
152
- if (violation.counts) console.log(violation.counts);
153
- console.log(headline);
154
- if (isInitial) printState(violation.trace[0].state);
155
- else if (loopStart === undefined) printTrace(violation.trace);
156
- else {
157
- printTrace(violation.trace, "Error: The following behavior constitutes a counter-example:\n");
158
- const isStuttering = loopStart === violation.trace.length - 1;
159
- console.log(
160
- isStuttering
161
- ? `State ${loopStart + 2}: Stuttering`
162
- : `Back to state ${loopStart + 1}${violation.loopLabel ? `: <${violation.loopLabel}>\n` : ""}`,
429
+ case "initial-states-started":
430
+ print(MESSAGE_CODE.computingInit, MESSAGE_LEVEL.none, "Computing initial states...");
431
+ return;
432
+ case "initial-states-progress":
433
+ printInitialStatesProgress(printer, progress.count);
434
+ return;
435
+ case "initial-states-computed":
436
+ printInitialStates(printer, progress.initialStates);
437
+ return;
438
+ case "progress":
439
+ printProgress(printer, progress.statistics, timing.start);
440
+ return;
441
+ case "liveness-started": {
442
+ timing.liveness = Date.now();
443
+ // TLC reports how far the search got before it checks the complete state graph.
444
+ if (progress.isComplete) printProgress(printer, progress.statistics);
445
+ const branches = progress.branches > 1 ? `${progress.branches} branches of ` : "";
446
+ // TLC counts the states of the behavior graph of each branch, without its tableau nodes.
447
+ const states = progress.branches * progress.states;
448
+ print(
449
+ MESSAGE_CODE.checkingTemporal,
450
+ MESSAGE_LEVEL.none,
451
+ `Checking ${branches}temporal properties for the ${progress.isComplete ? "complete" : "current"} state space with ${states} total distinct states at (${formatTlcDate(new Date())})`,
452
+ );
453
+ return;
454
+ }
455
+ case "liveness-finished":
456
+ printLivenessEnd(printer, timing);
457
+ return;
458
+ case "warning":
459
+ print(progress.code, MESSAGE_LEVEL.warning, progress.text);
460
+ }
461
+ };
462
+
463
+ const printLivenessEnd = (printer: MessagePrinter, timing: Timing) => {
464
+ if (timing.liveness === undefined) return;
465
+ printer.print(
466
+ MESSAGE_CODE.checkingTemporalEnd,
467
+ MESSAGE_LEVEL.none,
468
+ `Finished checking temporal properties in ${formatTlcDuration(Date.now() - timing.liveness)} at ${formatTlcDate(new Date())}`,
469
+ );
470
+ timing.liveness = undefined;
471
+ };
472
+
473
+ // Prints a violation, and returns whether TLC goes on to print the statistics of the search.
474
+ const printViolation = (status: CheckStatus, violation: Violation, printer: MessagePrinter) => {
475
+ const print = printer.print;
476
+ const name = violation.name;
477
+ const loopStart = violation.loopStart;
478
+ // TLC prints a violation by an initial state without the behavior or the statistics.
479
+ const isInitial =
480
+ loopStart === undefined &&
481
+ violation.trace.length === 1 &&
482
+ (status === "invariant-violation" || status === "liveness-violation");
483
+ const temporal = {
484
+ code: MESSAGE_CODE.temporalPropertyViolated,
485
+ text: getTemporalHeadline(violation.properties ?? [name], printer.version),
486
+ };
487
+ const headline = {
488
+ success: undefined,
489
+ error: undefined,
490
+ "assumption-violation": violation.message
491
+ ? {
492
+ code: MESSAGE_CODE.assumptionEvaluationError,
493
+ text: formatInnerMessage(
494
+ MESSAGE_CODE.assumptionEvaluationError,
495
+ `Evaluating assumption ${name} failed.\n${violation.message}`,
496
+ printer.isTool,
497
+ ),
498
+ }
499
+ : { code: MESSAGE_CODE.assumptionFalse, text: `Assumption ${name} is false.` },
500
+ deadlock: { code: MESSAGE_CODE.deadlockReached, text: "Deadlock reached." },
501
+ "invariant-violation": isInitial
502
+ ? getInitialViolationHeadline("invariant-violation", name)
503
+ : { code: MESSAGE_CODE.invariantViolatedBehavior, text: `Invariant ${name} is violated.` },
504
+ "property-violation": temporal,
505
+ "liveness-violation":
506
+ loopStart !== undefined
507
+ ? temporal
508
+ : isInitial
509
+ ? getInitialViolationHeadline("liveness-violation", name)
510
+ : {
511
+ code: MESSAGE_CODE.actionPropertyViolatedBehavior,
512
+ text: `Action property ${name} is violated.`,
513
+ },
514
+ "postcondition-violation": {
515
+ code: violation.postcondition?.code ?? MESSAGE_CODE.general,
516
+ text: violation.message ?? `Postcondition ${name} is false.`,
517
+ },
518
+ }[status];
519
+ // A safety property's counterexample ends where it breaks, and a liveness one loops back.
520
+ const isProperty = status === "property-violation";
521
+ const isLasso = loopStart !== undefined && !isProperty;
522
+ const isCounterExample = isProperty || isLasso;
523
+ // TLC rebuilds a liveness counterexample before it reports the violation, and 1.7.4's
524
+ // LiveWorker#printTrace after it prints the heading of the counterexample.
525
+ const isRebuiltFirst = isCounterExample && printer.version !== "1.7.4";
526
+ if (isRebuiltFirst) printTraceOutput(printer, violation.trace[0]?.output);
527
+ if (violation.counts) console.log(violation.counts);
528
+ if (headline) {
529
+ // TLC prints the initial state that violates a property in the same message.
530
+ const text = isInitial
531
+ ? `${headline.text}\n${formatState(violation.trace[0].state)}`
532
+ : headline.text;
533
+ print(headline.code, MESSAGE_LEVEL.error, text);
534
+ }
535
+ if (!isInitial) {
536
+ if (!isCounterExample) printTraceOutput(printer, violation.trace[0]?.output);
537
+ printTrace(
538
+ printer,
539
+ violation.trace,
540
+ isCounterExample ? COUNTER_EXAMPLE : undefined,
541
+ isCounterExample && !isRebuiltFirst,
542
+ );
543
+ printTraceOutput(printer, violation.traceOutput);
544
+ }
545
+ if (isLasso) {
546
+ const label = violation.loopLabel;
547
+ if (loopStart === violation.trace.length - 1)
548
+ print(MESSAGE_CODE.statePrint3, MESSAGE_LEVEL.state, `${loopStart + 2}: Stuttering`);
549
+ else if (printer.isTool)
550
+ print(
551
+ MESSAGE_CODE.backToState,
552
+ MESSAGE_LEVEL.state,
553
+ `${loopStart + 1}: Back to state${label ? `: <${label}>\n` : ""}`,
554
+ );
555
+ else console.log(`Back to state ${loopStart + 1}${label ? `: <${label}>\n` : ""}`);
556
+ }
557
+ // TLC 1.7.4 doesn't explain a stuttering counterexample.
558
+ if (violation.warning && printer.version !== "1.7.4")
559
+ print(violation.warning.code, MESSAGE_LEVEL.warning, violation.warning.text);
560
+ // TLC checks the postconditions after it prints a counterexample.
561
+ const postcondition =
562
+ violation.unwitnessed ??
563
+ (status === "postcondition-violation" ? undefined : violation.postcondition);
564
+ if (postcondition?.counts) console.log(postcondition.counts);
565
+ if (postcondition) print(postcondition.code, MESSAGE_LEVEL.error, postcondition.message);
566
+ // TLC checks assumptions before it starts the search, so it has no statistics to print.
567
+ return !isInitial && status !== "assumption-violation";
568
+ };
569
+
570
+ const printNestedExpressions = (printer: MessagePrinter, callStack: Expression[]) =>
571
+ printer.print(
572
+ MESSAGE_CODE.nestedExpression,
573
+ MESSAGE_LEVEL.error,
574
+ `The error occurred when TLC was evaluating the nested\nexpressions at the following positions:\n${formatCallStack(callStack)}`,
575
+ );
576
+
577
+ const printResult = (result: CheckResult, printer: MessagePrinter, timing: Timing) => {
578
+ const print = printer.print;
579
+ if (result.failure) {
580
+ const failure = result.failure;
581
+ const message = printer.isTool ? failure.toolMessage : failure.message;
582
+ const printCallStack = () => {
583
+ const fingerprint = failure.fingerprint;
584
+ if (fingerprint) {
585
+ // TLC prints the call stack when the replay has one, and otherwise the sources of the
586
+ // values it failed to fingerprint, innermost first. TLC 1.7.4 always prints the sources.
587
+ const trace =
588
+ failure.callStack?.length && printer.version !== "1.7.4"
589
+ ? formatCallStack(failure.callStack)
590
+ : formatFingerprintTrace(fingerprint.sources);
591
+ print(
592
+ MESSAGE_CODE.fingerprintFailed,
593
+ MESSAGE_LEVEL.error,
594
+ `TLC was unable to fingerprint.\n\nFingerprint Stack Trace:\n${trace}\nReason:\n${formatNestedMessage(fingerprint.reason, printer.isTool)}`,
595
+ );
596
+ return;
597
+ }
598
+ if (failure.callStack) printNestedExpressions(printer, failure.callStack);
599
+ };
600
+ if (failure.isCallStackFirst) printCallStack();
601
+ // TLC prints the state as it reports the error, so a state it can't print fails outside the
602
+ // checker, which TLC reports as an exception it did not expect.
603
+ const initialState =
604
+ failure.initialState &&
605
+ (() => {
606
+ try {
607
+ return `While working on the initial state:\n${formatState(failure.initialState)}`;
608
+ } catch (error) {
609
+ if (!(error instanceof TlaEvaluationError)) throw error;
610
+ throw setExitCode(
611
+ new TlaEvaluationError(`${UNEXPECTED_EXCEPTION}${error.message}`),
612
+ EXIT_STATUS.error,
613
+ );
614
+ }
615
+ })();
616
+ // TLC prints an error on an initial state and the state as one message.
617
+ print(
618
+ initialState ? MESSAGE_CODE.initialState : failure.code,
619
+ MESSAGE_LEVEL.error,
620
+ initialState ? `${message}\n${initialState}` : message,
621
+ );
622
+ printTraceOutput(printer, failure.trace[0]?.output);
623
+ printTrace(printer, failure.trace);
624
+ const traceFailure = failure.traceFailure;
625
+ if (traceFailure) {
626
+ print(
627
+ traceFailure.code,
628
+ MESSAGE_LEVEL.error,
629
+ printer.isTool ? traceFailure.toolMessage : traceFailure.message,
163
630
  );
164
631
  }
165
- const unwitnessed = violation.unwitnessed;
166
- if (unwitnessed?.counts) console.log(unwitnessed.counts);
167
- if (unwitnessed) console.log(`Error: ${unwitnessed.message}`);
168
- // TLC checks assumptions before it starts the search, so it has no statistics to print.
169
- if (isInitial || result.status === "assumption-violation") return;
632
+ printTraceOutput(printer, failure.traceOutput);
633
+ const postcondition = failure.postcondition;
634
+ if (postcondition?.counts) console.log(postcondition.counts);
635
+ if (postcondition) print(postcondition.code, MESSAGE_LEVEL.error, postcondition.message);
636
+ if (!failure.isCallStackFirst) printCallStack();
637
+ } else if (result.violation) {
638
+ if (!printViolation(result.status, result.violation, printer)) return;
639
+ // TLC adds a deadlocked state to the behavior graph after it reports the deadlock, which can
640
+ // violate a temporal property too.
641
+ const additional = result.additionalViolation;
642
+ if (additional) printViolation("property-violation", additional, printer);
643
+ if (result.liveCallStack) printNestedExpressions(printer, result.liveCallStack);
170
644
  } else {
645
+ printLivenessEnd(printer, timing);
171
646
  const optimistic = getOptimisticProbability(result.distinctStates, result.generatedStates);
172
- console.log("Model checking completed. No error has been found.");
173
- console.log(" Estimates of the probability that TLC did not check all reachable states");
174
- console.log(" because two distinct states had the same fingerprint:");
175
- console.log(` calculated (optimistic): val = ${formatProbability(optimistic)}`);
176
- if (result.fingerprintDistance !== undefined) {
177
- const actual = getActualProbability(result.fingerprintDistance);
178
- console.log(` based on the actual fingerprints: val = ${formatProbability(actual)}`);
179
- }
647
+ const actual =
648
+ result.fingerprintDistance === undefined
649
+ ? []
650
+ : [
651
+ ` based on the actual fingerprints: val = ${formatProbability(getActualProbability(result.fingerprintDistance))}`,
652
+ ];
653
+ print(
654
+ MESSAGE_CODE.success,
655
+ MESSAGE_LEVEL.none,
656
+ [
657
+ "Model checking completed. No error has been found.",
658
+ " Estimates of the probability that TLC did not check all reachable states",
659
+ " because two distinct states had the same fingerprint:",
660
+ ` calculated (optimistic): val = ${formatProbability(optimistic)}`,
661
+ ...actual,
662
+ ].join("\n"),
663
+ );
180
664
  }
181
- console.log(
665
+ if (result.failure?.isWithoutStatistics) return;
666
+ if (result.status !== "success") printLivenessEnd(printer, timing);
667
+ if (printer.isTool) printProgress(printer, result, timing.start);
668
+ print(
669
+ MESSAGE_CODE.stats,
670
+ MESSAGE_LEVEL.none,
182
671
  `${result.generatedStates} states generated, ${result.distinctStates} distinct states found, ${result.queuedStates} states left on queue.`,
183
672
  );
184
- console.log(`The depth of the complete state graph search is ${result.depth}.`);
185
- const outDegree = result.outDegrees && getOutDegreeSummary(result.outDegrees);
186
- if (outDegree) console.log(outDegree);
673
+ // ModelChecker#printSummary prints the depth, which TLC 1.7.4 prints only after a search it
674
+ // reports as successful, and as at least 1, and then the outdegree of a successful search.
675
+ const is174 = printer.version === "1.7.4";
676
+ const outDegrees = is174 ? (result.outDegrees ?? result.violationOutDegrees) : result.outDegrees;
677
+ if (!is174 || outDegrees) {
678
+ print(
679
+ MESSAGE_CODE.searchDepth,
680
+ MESSAGE_LEVEL.none,
681
+ `The depth of the complete state graph search is ${is174 ? Math.max(result.depth, 1) : result.depth}.`,
682
+ );
683
+ }
684
+ const outDegree = outDegrees && getOutDegreeSummary(outDegrees);
685
+ if (outDegree) print(MESSAGE_CODE.stateGraphOutdegree, MESSAGE_LEVEL.none, outDegree);
187
686
  };
188
687
 
189
- const checkSpec = async (specPath: string, args: ParsedArgs) => {
190
- if (!existsSync(specPath)) {
191
- console.error(`Cannot find the specification file ${specPath}`);
192
- return EXIT_STATUS.configParseError;
688
+ // Like TLC, tla-ts finds a module in the directory of the spec, then in each library directory.
689
+ const findModuleFile = (directories: string[], name: string) =>
690
+ directories.map((directory) => join(directory, `${name}.tla`)).find(existsSync);
691
+
692
+ const createModuleLoader = (directories: string[]) => (name: string) => {
693
+ const path = findModuleFile(directories, name);
694
+ return path === undefined ? undefined : readFileSync(path, "utf8");
695
+ };
696
+
697
+ // SimpleFilenameToStream: SANY names the file of a module it can't find, and where it looked.
698
+ const printMissingFile = (userDirectory: string, fileName: string, directories: string[]) =>
699
+ console.error(
700
+ `File does not exist: ${userDirectory}/${fileName} while looking in these directories: ${userDirectory}, ${directories.join(", ")}, classpath:/tla2sany/StandardModules, classpath:/`,
701
+ );
702
+
703
+ // The URL of the directory of SANY's standard modules in a tla2tools.jar.
704
+ const getStandardModulesUrl = (jar: string) =>
705
+ `jar:file:${pathToFileURL(resolve(jar)).pathname}!/tla2sany/StandardModules/`;
706
+
707
+ // Java's Files.createTempDirectory names a directory by a random unsigned long. tla-ts derives it
708
+ // from what the directory holds, so that each run of a spec prints the same files.
709
+ const getTemporaryName = (contents: string) =>
710
+ createHash("sha256").update(contents).digest().readBigUInt64BE().toString();
711
+
712
+ // The file TLC's SANY says it parses each module from: the real path of a module's own file, or a
713
+ // copy in a temporary directory of a module from the root module's file or from the jar on the
714
+ // class path, followed by where TLC copied it from.
715
+ const createFileDescriber = (
716
+ specPath: string,
717
+ directories: string[],
718
+ java: JavaProperties,
719
+ metadir: string | undefined,
720
+ version: TlcVersion,
721
+ ) => {
722
+ const temporary = java.temporaryDirectory ?? tmpdir();
723
+ const temporaryDirectory = existsSync(temporary) ? realpathSync(temporary) : resolve(temporary);
724
+ const libraryDirectory = join(temporaryDirectory, `tlc-${getTemporaryName(resolve(specPath))}`);
725
+ const jar = getJar(java);
726
+ return (name: string, origin: SanyModuleOrigin) => {
727
+ const fileName = `${name}.tla`;
728
+ if (origin === "file") return realpathSync(findModuleFile(directories, name) ?? specPath);
729
+ // TLC 1.7.4 copies a standard module into the temporary directory itself.
730
+ if (version === "1.7.4") return join(temporaryDirectory, fileName);
731
+ // FileUtil.createTempFile copies a module from the root module's file into the -metadir.
732
+ if (origin === "root file") {
733
+ const directory = metadir === undefined ? temporaryDirectory : resolve(metadir);
734
+ const root = realpathSync(specPath);
735
+ return `${join(directory, getTemporaryName(`${root} ${name}`), fileName)} (${root})`;
736
+ }
737
+ const copy = join(libraryDirectory, fileName);
738
+ return jar === undefined ? copy : `${copy} (${getStandardModulesUrl(jar)}${fileName})`;
739
+ };
740
+ };
741
+
742
+ const printWelcome = (printer: MessagePrinter) =>
743
+ printer.print(MESSAGE_CODE.version, MESSAGE_LEVEL.none, `TLC2 Version ${version} (rev: tla-ts)`);
744
+
745
+ // TLC.printErrorMsg: TLC says which version it is, then why it can't read its options.
746
+ const printCommandLineError = (printer: MessagePrinter, message: string) => {
747
+ printWelcome(printer);
748
+ printer.print(
749
+ MESSAGE_CODE.commandLineError,
750
+ MESSAGE_LEVEL.error,
751
+ `${message}\nUsage: java tlc2.TLC [-help] [-option] inputfile`,
752
+ );
753
+ return 1;
754
+ };
755
+
756
+ // TLC.printStartupBanner, with what runs tla-ts in place of the JVM. tla-ts keeps its fingerprints
757
+ // and its queue of states in memory.
758
+ const printStartupBanner = (printer: MessagePrinter, seed: string, workers: number) =>
759
+ printer.print(
760
+ MESSAGE_CODE.modelChecking,
761
+ MESSAGE_LEVEL.none,
762
+ `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).`,
763
+ );
764
+
765
+ // TLC loads Integers for the binary trace that its trace exploration spec records. -generateSpecTE
766
+ // turns the spec on, and -tool, -continue, -noGenerateSpecTE and -noTE turn it off, as
767
+ // -noGenerateSpecTEBin and -noTEBin turn off the binary trace. TLC 1.7.4 records no such trace.
768
+ const isTraceRecorded = (args: ParsedArgs, version: TlcVersion) => {
769
+ const flags = [...args.unknown, ...args.options.map((option) => option.name)];
770
+ const has = (name: string, alias = name) =>
771
+ flags.some((flag) => flag === name || flag.toLowerCase() === alias.toLowerCase());
772
+ const isSpecGenerated =
773
+ has("-generateSpecTE") ||
774
+ (!has("-noGenerateSpecTE", "-noTE") && !has("-tool") && !has("-continue"));
775
+ return version !== "1.7.4" && isSpecGenerated && !has("-noGenerateSpecTEBin", "-noTEBin");
776
+ };
777
+
778
+ const checkSpec = async (
779
+ specPath: string,
780
+ args: ParsedArgs,
781
+ java: JavaProperties,
782
+ printer: MessagePrinter,
783
+ ) => {
784
+ // TLC.handleParameters: TLC reads its options before it says which version it is.
785
+ const seed = args.has("-seed") ? args.get("-seed")?.[0] : "0";
786
+ if (seed === undefined) return printCommandLineError(printer, "Error: seed required.");
787
+ if (!isJavaLong(seed)) {
788
+ return printCommandLineError(
789
+ printer,
790
+ `Error: An integer for seed required. But encountered ${seed}`,
791
+ );
193
792
  }
793
+ const livenessCheck = args.has("-lncheck") ? args.get("-lncheck")?.[0]?.toLowerCase() : "default";
794
+ if (livenessCheck === undefined) {
795
+ return printCommandLineError(
796
+ printer,
797
+ "Error: expect a strategy such as final for -lncheck option.",
798
+ );
799
+ }
800
+ const dumpValues = args.get("-dump");
801
+ if (dumpValues?.length === 0) {
802
+ return printCommandLineError(printer, "Error: A file name for dumping states required.");
803
+ }
804
+ const unsupportedFormat =
805
+ dumpValues?.length === 2 &&
806
+ UNSUPPORTED_DUMP_FORMATS.find((format) => dumpValues[0].toLowerCase().includes(format));
807
+ if (unsupportedFormat) {
808
+ console.error(`Error: tla-ts does not support the -dump format ${unsupportedFormat}.`);
809
+ return 1;
810
+ }
811
+ // tla-ts fingerprints states as TLC does with -fp 0.
812
+ const fingerprint = args.get("-fp")?.[0];
813
+ if (fingerprint !== undefined && Number(fingerprint) !== 0) {
814
+ console.error(
815
+ `Error: tla-ts fingerprints states as TLC does with -fp 0, not -fp ${fingerprint}.`,
816
+ );
817
+ return 1;
818
+ }
819
+ const workers = getWorkerCount(args.get("-workers"));
820
+ const version = printer.version;
821
+ printWelcome(printer);
822
+ printStartupBanner(printer, seed, workers);
194
823
  const configPath =
195
824
  args.get("-config")?.[0] ??
196
825
  (args.has("-config") ? undefined : specPath.replace(/\.tla$/, ".cfg"));
197
826
  if (!configPath || !existsSync(configPath)) {
198
- console.error(`Cannot find the configuration file ${configPath ?? ""}`);
827
+ printer.print(
828
+ MESSAGE_CODE.configFileError,
829
+ MESSAGE_LEVEL.error,
830
+ `TLC encountered the following error when trying to read the configuration file ${configPath ?? ""}:\nFile not found.`,
831
+ );
199
832
  return EXIT_STATUS.configParseError;
200
833
  }
201
- const config = parseConfig(readFileSync(configPath, "utf8"));
202
- if (args.has("-deadlock")) config.checkDeadlock = false;
203
- const seed = args.has("-seed") ? args.get("-seed")?.[0] : "0";
204
- if (seed === undefined) {
205
- console.error("Error: seed required.");
206
- return 1;
834
+ const fileName = basename(specPath, ".tla");
835
+ const timing: Timing = { start: Date.now(), liveness: undefined, isParsed: false };
836
+ // Without -tool, TLC prints how long it ran for a person to read.
837
+ const printFinished = () => {
838
+ const runtime = Date.now() - timing.start;
839
+ printer.print(
840
+ MESSAGE_CODE.finished,
841
+ MESSAGE_LEVEL.none,
842
+ `Finished in ${printer.isTool ? `${runtime}ms` : formatTlcDuration(runtime)} at (${formatTlcDate(new Date())})`,
843
+ );
844
+ };
845
+ const printParsingFailed = () =>
846
+ printer.print(
847
+ MESSAGE_CODE.parsingFailed,
848
+ MESSAGE_LEVEL.error,
849
+ "Parsing or semantic analysis failed.",
850
+ );
851
+ // TLC prints how long it ran even when it stops at an error.
852
+ const printFailure = (error: TlaError) => {
853
+ if (error instanceof TlaSyntaxError) {
854
+ printParsingFailed();
855
+ } else {
856
+ printError(error, printer);
857
+ }
858
+ printFinished();
859
+ return getErrorExitCode(error);
860
+ };
861
+ // TLC reads the configuration file before it parses the spec, and prints how long it ran even
862
+ // when it can't read it.
863
+ const config = (() => {
864
+ try {
865
+ return parseConfig(readFileSync(configPath, "utf8"), version);
866
+ } catch (error) {
867
+ if (!(error instanceof TlaConfigError)) throw error;
868
+ return error;
869
+ }
870
+ })();
871
+ // TLC 1.7.4 reports a configuration file it can't parse as an exception it didn't expect.
872
+ if (config instanceof TlaConfigError && version === "1.7.4") {
873
+ printer.print(
874
+ MESSAGE_CODE.general,
875
+ MESSAGE_LEVEL.error,
876
+ `${getUnexpectedException("tlc2.tool.ConfigFileException")}${formatNestedMessage(config.message, printer.isTool)}`,
877
+ );
878
+ printFinished();
879
+ return EXIT_STATUS.error;
207
880
  }
208
- if (!isJavaLong(seed)) {
209
- console.error(`Error: An integer for seed required. But encountered ${seed}`);
210
- return 1;
881
+ if (config instanceof TlaConfigError) return printFailure(config);
882
+ if (args.has("-deadlock")) config.checkDeadlock = false;
883
+ const directory = dirname(specPath);
884
+ const directories = [directory, ...java.libraries];
885
+ const loadModule = createModuleLoader(directories);
886
+ const isRecorded = isTraceRecorded(args, version);
887
+ const run = async () => {
888
+ const source = readFileSync(specPath, "utf8");
889
+ const moduleName = parseModule(source).name;
890
+ if (moduleName !== fileName) {
891
+ throw new TlaSanyFatalError(
892
+ `File name '${fileName}' does not match the name '${moduleName}' of the top level module it contains.`,
893
+ undefined,
894
+ );
895
+ }
896
+ const result = await check({
897
+ workers,
898
+ livenessCheck: ["final", "seqfinal", "off"].includes(livenessCheck) ? "final" : "default",
899
+ seed: BigInt(seed),
900
+ dump: dumpValues && getDump(dumpValues),
901
+ isTool: printer.isTool,
902
+ isTraceRecorded: isRecorded,
903
+ isSanyReported: true,
904
+ isWarningEnabled: !args.has("-nowarning"),
905
+ version,
906
+ onProgress: (progress) => printCheckProgress(printer, progress, timing, directory),
907
+ source,
908
+ config,
909
+ onPause: () => readSync(0, Buffer.alloc(1)),
910
+ loadModule,
911
+ loadClass: (name) => {
912
+ const classPath = getClassPath(directory, name);
913
+ return existsSync(classPath) ? readFileSync(classPath) : undefined;
914
+ },
915
+ readFile: (path) => (existsSync(path) ? readFileSync(path, "utf8") : undefined),
916
+ writeFile: (path, content) => {
917
+ mkdirSync(dirname(resolve(path)), { recursive: true });
918
+ writeFileSync(path, content);
919
+ },
920
+ });
921
+ printResult(result, printer, timing);
922
+ printFinished();
923
+ return result.failure?.exitCode ?? EXIT_CODES[result.status];
924
+ };
925
+ if (printer.isTool) {
926
+ printer.print(MESSAGE_CODE.startingSany, MESSAGE_LEVEL.none, "Starting SANY...");
211
927
  }
212
- const livenessCheck = args.has("-lncheck") ? args.get("-lncheck")?.[0]?.toLowerCase() : "default";
213
- if (livenessCheck === undefined) {
214
- console.error("Error: expect a strategy such as final for -lncheck option.");
215
- return 1;
928
+ // TLC.handleParameters: SANY names the spec as TLC's arguments do, except that TLC runs from the
929
+ // directory of a spec given by an absolute path, and names it by its file name. SANY looks for
930
+ // the spec's modules in the spec's directory and the TLA-Library directories.
931
+ const isAbsoluteSpec = isAbsolute(specPath);
932
+ const specName = isAbsoluteSpec ? fileName : specPath.replace(/\.tla$/, "");
933
+ const jar = getJar(java);
934
+ const reportMissingFile =
935
+ version === "1.7.4" ? createMissingFilePrinter174(specPath, java, jar) : undefined;
936
+ if (reportMissingFile) {
937
+ if (!existsSync(specPath) && !SANY_174_STANDARD_MODULES.has(fileName)) {
938
+ reportMissingFile(`${fileName}.tla`);
939
+ }
940
+ } else if (!existsSync(specPath) && !SANY_STANDARD_MODULES.has(fileName)) {
941
+ printMissingFile(
942
+ isAbsoluteSpec ? directory : process.cwd(),
943
+ isAbsoluteSpec ? `${fileName}.tla` : `./${specName}.tla`,
944
+ [...(isAbsoluteSpec || directory === "." ? [] : [directory]), ...java.libraries],
945
+ );
216
946
  }
217
- const directory = dirname(specPath);
218
- console.log(`Checking ${basename(specPath)} with ${basename(configPath)}`);
219
- const result = await check({
220
- workers: getWorkerCount(args.get("-workers")),
221
- livenessCheck: ["final", "seqfinal", "off"].includes(livenessCheck) ? "final" : "default",
222
- seed: BigInt(seed),
223
- source: readFileSync(specPath, "utf8"),
224
- config,
225
- onPause: () => readSync(0, Buffer.alloc(1)),
226
- loadModule: (name) => {
227
- const modulePath = join(directory, `${name}.tla`);
228
- return existsSync(modulePath) ? readFileSync(modulePath, "utf8") : undefined;
229
- },
230
- loadClass: (name) => {
231
- const classPath = join(directory, `${name}.class`);
232
- return existsSync(classPath) ? readFileSync(classPath) : undefined;
233
- },
234
- readFile: (path) => (existsSync(path) ? readFileSync(path, "utf8") : undefined),
235
- writeFile: (path, content) => {
236
- mkdirSync(dirname(resolve(path)), { recursive: true });
237
- writeFileSync(path, content);
947
+ // TLC prints what SANY prints as it parses the spec, and the errors it rejects the spec for.
948
+ const sany = getSanyReport(
949
+ specPath,
950
+ reportMissingFile ? reportMissingModules174(loadModule, reportMissingFile) : loadModule,
951
+ {
952
+ fileName: specName,
953
+ describeFile: createFileDescriber(
954
+ specPath,
955
+ directories,
956
+ java,
957
+ args.get("-metadir")?.[0],
958
+ version,
959
+ ),
960
+ version,
961
+ // TLC's trace exploration spec records the trace with the post condition of _TLCTrace.
962
+ rootExtendees: isRecorded ? ["_TLCTrace"] : undefined,
963
+ onPrint: (text) => process.stdout.write(text),
964
+ onPrintError: (text) => process.stderr.write(text),
238
965
  },
239
- });
240
- printResult(result);
241
- return result.failure?.exitCode ?? EXIT_CODES[result.status];
966
+ );
967
+ if (sany.isFailed) {
968
+ printCheckProgress(printer, { kind: "parsed" }, timing, directory);
969
+ printParsingFailed();
970
+ printFinished();
971
+ return EXIT_STATUS.specParseError;
972
+ }
973
+ try {
974
+ return await run();
975
+ } catch (error) {
976
+ if (!(error instanceof TlaError)) throw error;
977
+ if (error instanceof TlaSyntaxError) console.log(formatSanyErrors(error, fileName));
978
+ if (!timing.isParsed) printCheckProgress(printer, { kind: "parsed" }, timing, directory);
979
+ return printFailure(error);
980
+ }
981
+ };
982
+
983
+ // What SANY prints about a spec it rejects: a module it can't find or parse is a fatal error, and
984
+ // it reports the other errors as semantic errors.
985
+ const formatSanyErrors = (error: TlaSyntaxError, specName: string) => {
986
+ const isFatal = error instanceof TlaSanyFatalError;
987
+ if (!isFatal && !error.failure)
988
+ return `Semantic errors:\n\n*** Errors: 1\n\n${error.message}\n\n`;
989
+ const report = !isFatal
990
+ ? `In module ${specName}\n\nCould not parse module ${specName} from file ${specName}.tla`
991
+ : error.location === undefined
992
+ ? `Unknown location\n\n${error.message}`
993
+ : `In module ${error.location}\n\n${error.message}`;
994
+ const parseError = error.failure ? `***Parse Error***\n${error.message}\n\n` : "";
995
+ return `${parseError}\nFatal errors while parsing TLA+ spec in file ${specName}\n\n${report}\n*** Errors: 1\n\n${report}\n\n\n`;
242
996
  };
243
997
 
244
998
  // TLC prints the errors it raises itself. tla-ts names the others, such as a module SANY rejects.
245
- const printError = (error: TlaError) => {
999
+ const printError = (error: TlaError, printer: MessagePrinter) => {
246
1000
  if (error instanceof TlaConfigError || error instanceof TlaEvaluationError) {
247
- return console.log(`Error: ${error.message}`);
1001
+ // TLC prints an error it raises with a message code, such as a configuration error, with
1002
+ // that code.
1003
+ const coded = getCodedMessage(error.message);
1004
+ const code = coded && !coded.isEvalException ? coded.code : MESSAGE_CODE.general;
1005
+ return printer.print(
1006
+ code,
1007
+ MESSAGE_LEVEL.error,
1008
+ formatInnerMessage(code, error.message, printer.isTool),
1009
+ );
248
1010
  }
249
1011
  console.error(`${error.name}: ${error.message}`);
250
1012
  };
251
1013
 
252
1014
  // Prints a TlaError and returns its exit code.
253
- const reportErrors = async (run: () => number | Promise<number>) => {
1015
+ const reportErrors = async (
1016
+ run: () => number | Promise<number>,
1017
+ printer = createMessagePrinter(false),
1018
+ ) => {
254
1019
  try {
255
1020
  return await run();
256
1021
  } catch (error) {
257
1022
  if (!(error instanceof TlaError)) throw error;
258
- printError(error);
1023
+ printError(error, printer);
259
1024
  return getErrorExitCode(error);
260
1025
  }
261
1026
  };
262
1027
 
263
- // Runs each path in turn, so an error in one leaves the others to report. The exit code is the
264
- // first that is not success.
265
- const runEach = async (paths: string[], runPath: (path: string) => number | Promise<number>) => {
1028
+ // Runs each path in turn, as TLC runs in a process of its own, so an error in one leaves the others
1029
+ // to report. The exit code is the first that is not success.
1030
+ const runEach = async (
1031
+ paths: string[],
1032
+ runPath: (path: string, printer: MessagePrinter) => number | Promise<number>,
1033
+ createPrinter: () => MessagePrinter,
1034
+ ) => {
266
1035
  const exitCodes: number[] = [];
267
1036
  for (const [index, path] of paths.entries()) {
268
1037
  if (index > 0) console.log("");
269
- exitCodes.push(await reportErrors(() => runPath(path)));
1038
+ const printer = createPrinter();
1039
+ exitCodes.push(await reportErrors(() => runPath(path, printer), printer));
270
1040
  }
271
1041
  return exitCodes.find((exitCode) => exitCode !== EXIT_STATUS.success) ?? EXIT_STATUS.success;
272
1042
  };
@@ -310,15 +1080,10 @@ const TLAPM_VERSION = "5f5037f";
310
1080
  const quoteArgument = (arg: string) =>
311
1081
  /^[+,\-./0-9:=@A-Z_a-z]+$/.test(arg) ? arg : `'${arg.replaceAll("'", "'\\''")}'`;
312
1082
 
313
- const printToolboxHeader = (args: string[]) => {
314
- const now = new Date();
315
- const pad = (value: number) => String(value).padStart(2, "0");
316
- const date = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`;
317
- const time = `${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}`;
1083
+ const printToolboxHeader = (args: string[]) =>
318
1084
  console.log(
319
- `\n\\* TLAPM version ${TLAPM_VERSION}\n\\* launched at ${date} ${time} with command line:\n\\* ${["tla-ts", "prove", ...args].map(quoteArgument).join(" ")}\n`,
1085
+ `\n\\* TLAPM version ${TLAPM_VERSION}\n\\* launched at ${formatTlcDate(new Date())} with command line:\n\\* ${["tla-ts", "prove", ...args].map(quoteArgument).join(" ")}\n`,
320
1086
  );
321
- };
322
1087
 
323
1088
  const STRICT_EXIT_STATUS = { incomplete: 11, emptyTarget: 12 };
324
1089
 
@@ -448,14 +1213,20 @@ const prove = (args: string[]) => {
448
1213
  : (failures[0] ?? EXIT_STATUS.success);
449
1214
  };
450
1215
 
451
- const run = async (args: string[]) => {
452
- if (args[0] === "prove") return reportErrors(() => prove(args.slice(1)));
1216
+ const checkSpecs = async (args: string[], java: JavaProperties) => {
453
1217
  const parsed = CHECK_COMMAND.parse(args);
454
1218
  const inputs = getInputPaths(parsed.positionals);
455
1219
  const isConfigured = parsed.has("-config");
456
- // A glob also matches modules that only other specs import, which have no configuration.
1220
+ // Like TLC, a spec named without an extension is the .tla file of that name. A glob also matches
1221
+ // modules that only other specs import, which have no configuration.
457
1222
  const specPaths = inputs
458
- .map((input) => ({ ...input, path: input.path.replace(/\.cfg$/, ".tla") }))
1223
+ .map((input) => ({
1224
+ ...input,
1225
+ path:
1226
+ input.isGlobbed || /\.(tla|cfg)$/.test(input.path)
1227
+ ? input.path.replace(/\.cfg$/, ".tla")
1228
+ : `${input.path}.tla`,
1229
+ }))
459
1230
  .filter(
460
1231
  (input) =>
461
1232
  input.path.endsWith(".tla") &&
@@ -470,7 +1241,305 @@ const run = async (args: string[]) => {
470
1241
  console.error("Error: -config applies to one specification, but several were given.");
471
1242
  return 1;
472
1243
  }
473
- return runEach([...new Set(specPaths)], (path) => checkSpec(path, parsed));
1244
+ // TLC also looks for the spec itself in the library directories.
1245
+ const findSpec = (path: string) =>
1246
+ existsSync(path) || isAbsolute(path)
1247
+ ? path
1248
+ : (java.libraries.map((directory) => join(directory, path)).find(existsSync) ?? path);
1249
+ const paths = [...new Set(specPaths.map(findSpec))];
1250
+ const tlcVersion = getJavaTlcVersion(java);
1251
+ return runEach(
1252
+ paths,
1253
+ (path, printer) => {
1254
+ // TLC checks one spec, so tla-ts names each of several it checks.
1255
+ if (paths.length > 1)
1256
+ console.log(`Checking ${basename(path)} with ${basename(path, ".tla")}.cfg`);
1257
+ return checkSpec(path, parsed, java, printer);
1258
+ },
1259
+ () => createMessagePrinter(parsed.has("-tool"), !parsed.has("-nowarning"), tlcVersion),
1260
+ );
1261
+ };
1262
+
1263
+ // XMLExporter.run prints why it cannot parse its arguments, and its usage.
1264
+ const printXmlExportUsageError = (message: string) => {
1265
+ process.stderr.write(`ERROR: ${message}\n${XML_EXPORT_USAGE}`);
1266
+ return XML_EXPORT_EXIT_CODE.argsParsingFailure;
1267
+ };
1268
+
1269
+ // XMLExporter.run writes the XML of a specification, and why it can't when it can't.
1270
+ const writeXml = (specification: SanySpecification, options: XmlExportOptions) => {
1271
+ try {
1272
+ process.stdout.write(exportSanyXml(specification, options));
1273
+ return EXIT_STATUS.success;
1274
+ } catch (error) {
1275
+ if (!(error instanceof TlaUnsupportedError)) throw error;
1276
+ const exitCode = getErrorExitCode(error);
1277
+ const unwound = error instanceof TlaJavaException ? error.unwound : "";
1278
+ console.error(
1279
+ exitCode === XML_EXPORT_EXIT_CODE.uncaughtException
1280
+ ? `${unwound}Exception in thread "main" ${error.message}`
1281
+ : `ERROR: ${error.message}`,
1282
+ );
1283
+ return exitCode;
1284
+ }
1285
+ };
1286
+
1287
+ interface XmlExportArgs {
1288
+ flags: Set<string>;
1289
+ includes: string[];
1290
+ error: "missing-include" | "several-files" | undefined;
1291
+ }
1292
+
1293
+ // XMLExporter reads the flags before the last argument, which names the module, and skips an
1294
+ // argument it does not know, which then counts as another module.
1295
+ const parseXmlExportArgs = (args: string[], flagNames: Set<string>): XmlExportArgs => {
1296
+ const parsed: XmlExportArgs = { flags: new Set(), includes: [], error: undefined };
1297
+ const last = { flag: -1 };
1298
+ for (let index = 0; index < args.length - 1; index++) {
1299
+ if (flagNames.has(args[index])) {
1300
+ parsed.flags.add(args[index]);
1301
+ last.flag = index;
1302
+ continue;
1303
+ }
1304
+ if (args[index] !== "-I") continue;
1305
+ index++;
1306
+ if (index > args.length - 2) return { ...parsed, error: "missing-include" };
1307
+ parsed.includes.push(args[index]);
1308
+ last.flag = index;
1309
+ }
1310
+ return last.flag === args.length - 2 ? parsed : { ...parsed, error: "several-files" };
1311
+ };
1312
+
1313
+ const exportXml = (args: string[]) => {
1314
+ if (args.length === 0) return printXmlExportUsageError("at least one .tla file must be given");
1315
+ const parsed = parseXmlExportArgs(args, XML_EXPORT_FLAGS);
1316
+ if (parsed.error === "missing-include") {
1317
+ return printXmlExportUsageError(
1318
+ "the -I flag must be followed by a directory and at least one .tla file",
1319
+ );
1320
+ }
1321
+ if (parsed.error === "several-files") {
1322
+ return printXmlExportUsageError("Only one TLA file to check allowed!");
1323
+ }
1324
+ const name = args[args.length - 1];
1325
+ if (name === "-help") {
1326
+ process.stdout.write(XML_EXPORT_USAGE);
1327
+ return EXIT_STATUS.success;
1328
+ }
1329
+ const fileName = name.endsWith(".tla") ? name : `${name}.tla`;
1330
+ // SANY looks for each module in the working directory, then in the -I directories, which
1331
+ // XMLExporter passes in place of TLA-Library, then among its standard modules.
1332
+ const directories = [".", ...parsed.includes];
1333
+ const path = directories.map((directory) => resolve(directory, fileName)).find(existsSync);
1334
+ if (path === undefined && !SANY_STANDARD_MODULES.has(fileName.slice(0, -".tla".length))) {
1335
+ printMissingFile(process.cwd(), `./${fileName}`, parsed.includes);
1336
+ }
1337
+ // XMLExporter.parseSpec prints SANY's errors, and XMLExporter.run why it fails.
1338
+ const sany = getSanyReport(path ?? fileName, createModuleLoader(directories), {
1339
+ fileName: name,
1340
+ isXmlExport: true,
1341
+ });
1342
+ process.stderr.write(sany.text);
1343
+ if (sany.isFailed || sany.specification === undefined) {
1344
+ console.error("ERROR: Failed to parse module.");
1345
+ return XML_EXPORT_EXIT_CODE.specParsingFailure;
1346
+ }
1347
+ return writeXml(sany.specification, {
1348
+ version: "master",
1349
+ isRestricted: parsed.flags.has("-r"),
1350
+ isUncommented: parsed.flags.has("-u"),
1351
+ isTerse: parsed.flags.has("-t"),
1352
+ });
1353
+ };
1354
+
1355
+ // TLC 1.7.4's FileUtil.createNamedInputStream names the last file that SimpleFilenameToStream
1356
+ // looked for a module in, and the directories it looks in, the standard modules in the jar last,
1357
+ // which tla-ts leaves out without a jar.
1358
+ const printMissingFile174 = (path: string, libraries: string[], jar: string | undefined) =>
1359
+ console.error(
1360
+ `File does not exist: ${isAbsolute(path) ? path : `${process.cwd()}/${path}`} while looking in these directories: ${[...libraries, ...(jar === undefined ? [] : [getStandardModulesUrl(jar)])].join(", ")}`,
1361
+ );
1362
+
1363
+ // SimpleFilenameToStream ends a library directory with a separator.
1364
+ const toLibraryPath = (directory: string) =>
1365
+ directory.endsWith("/") ? directory : `${directory}/`;
1366
+
1367
+ // TLC 1.7.4's SimpleFilenameToStream looks for a module in the directory of a spec that TLC is
1368
+ // given by an absolute path, then in the directory that a relative path names, or else in the
1369
+ // TLA-Library directories.
1370
+ const createMissingFilePrinter174 = (
1371
+ specPath: string,
1372
+ java: JavaProperties,
1373
+ jar: string | undefined,
1374
+ ) => {
1375
+ const specDirectory = specPath.slice(0, specPath.lastIndexOf("/") + 1);
1376
+ const isRelativeToDirectory = !isAbsolute(specPath) && specDirectory !== "";
1377
+ const libraries = (isRelativeToDirectory ? [specDirectory] : java.libraries).map(toLibraryPath);
1378
+ const lastDirectory =
1379
+ libraries.length > 0
1380
+ ? libraries[libraries.length - 1]
1381
+ : isAbsolute(specPath)
1382
+ ? specDirectory
1383
+ : "";
1384
+ return (fileName: string) => printMissingFile174(`${lastDirectory}${fileName}`, libraries, jar);
1385
+ };
1386
+
1387
+ // TLC 1.7.4's SANY reports each module it can't find as it looks for it.
1388
+ const reportMissingModules174 =
1389
+ (loadModule: (name: string) => string | undefined, onMissing: (fileName: string) => void) =>
1390
+ (name: string) => {
1391
+ const text = loadModule(name);
1392
+ if (text === undefined && !SANY_174_STANDARD_MODULES.has(name)) onMissing(`${name}.tla`);
1393
+ return text;
1394
+ };
1395
+
1396
+ // TLC 1.7.4's XMLExporter.main throws an exception for an argument it can't take or a
1397
+ // specification without a root module.
1398
+ const printXmlExporterException = (exception: string, line: number) => {
1399
+ console.error(
1400
+ `Exception in thread "main" ${exception}\n\tat tla2sany.xml.XMLExporter.main(XMLExporter.java:${line})`,
1401
+ );
1402
+ return XML_EXPORT_EXIT_CODE.uncaughtException;
1403
+ };
1404
+
1405
+ // TLC 1.7.4's XMLExporter.main, which takes only -o, as it can't validate the XML without
1406
+ // fetching its schema, and -I, and exports a specification that SANY finds errors in.
1407
+ const exportXml174 = (args: string[], jar: string | undefined) => {
1408
+ if (args.length === 0) {
1409
+ return printXmlExporterException(
1410
+ "java.lang.IllegalArgumentException: at least one .tla file must be given",
1411
+ 59,
1412
+ );
1413
+ }
1414
+ const parsed = parseXmlExportArgs(args, XML_EXPORT_174_FLAGS);
1415
+ if (parsed.error === "missing-include") {
1416
+ return printXmlExporterException(
1417
+ "java.lang.IllegalArgumentException: the -I flag must be followed by a directory and at least one .tla file",
1418
+ 71,
1419
+ );
1420
+ }
1421
+ if (parsed.error === "several-files") {
1422
+ return printXmlExporterException(
1423
+ "java.lang.IllegalArgumentException: Only one TLA file to check allowed!",
1424
+ 83,
1425
+ );
1426
+ }
1427
+ const name = args[args.length - 1];
1428
+ const fileName = `${name.replace(/\.tla$/i, "")}.tla`;
1429
+ // SimpleFilenameToStream looks for a module in the working directory, then in the -I
1430
+ // directories, or the root directory when there are none, then among the standard modules.
1431
+ const libraries = (parsed.includes.length === 0 ? ["/"] : parsed.includes).map(toLibraryPath);
1432
+ const directories = [".", ...libraries];
1433
+ const printMissingFile = (moduleFileName: string) =>
1434
+ printMissingFile174(`${libraries[libraries.length - 1]}${moduleFileName}`, libraries, jar);
1435
+ const path = directories.map((directory) => resolve(directory, fileName)).find(existsSync);
1436
+ if (path === undefined && !SANY_174_STANDARD_MODULES.has(basename(fileName, ".tla"))) {
1437
+ printMissingFile(fileName);
1438
+ return EXIT_STATUS.success;
1439
+ }
1440
+ const sany = getSanyReport(
1441
+ path ?? fileName,
1442
+ reportMissingModules174(createModuleLoader(directories), printMissingFile),
1443
+ {
1444
+ fileName: name,
1445
+ isXmlExport: true,
1446
+ version: "1.7.4",
1447
+ },
1448
+ );
1449
+ process.stderr.write(sany.text);
1450
+ if (sany.specification === undefined) {
1451
+ return printXmlExporterException(
1452
+ `tla2sany.xml.XMLExportingException: spec ${(path && getSanyModuleName(readFileSync(path, "utf8"), "1.7.4")) ?? "null"} is malformed - does not have a root module`,
1453
+ 110,
1454
+ );
1455
+ }
1456
+ return writeXml(sany.specification, {
1457
+ version: "1.7.4",
1458
+ isRestricted: false,
1459
+ isUncommented: false,
1460
+ isTerse: true,
1461
+ });
1462
+ };
1463
+
1464
+ // Tools that run TLC with Java, such as the statechart skill of pstack, can run tla-ts in place of
1465
+ // java, as in `tla-ts -DTLA-Library=lib -cp tla2tools.jar tlc2.TLC Spec`. tla-ts searches the
1466
+ // TLA-Library directories for modules as TLC does, though not as XMLExporter, which ignores them,
1467
+ // names the files in java.io.tmpdir and the jar on the class path that TLC would copy and read
1468
+ // modules from, and ignores the other options. It reproduces the TLC of that jar, or the one that
1469
+ // -Dtla-ts.tlc names without a jar, as in `tla-ts -Dtla-ts.tlc=1.7.4 tlc2.TLC Spec`.
1470
+ const JAVA_MAIN_CLASSES = ["tlc2.TLC", "tla2sany.xml.XMLExporter"];
1471
+
1472
+ const TLA_LIBRARY_PROPERTY = "-DTLA-Library=";
1473
+
1474
+ const TEMPORARY_DIRECTORY_PROPERTY = "-Djava.io.tmpdir=";
1475
+
1476
+ const TLC_VERSION_PROPERTY = "-Dtla-ts.tlc=";
1477
+
1478
+ // What the java command sets for TLC: the TLA-Library directories it searches for modules, the
1479
+ // class path it finds its standard modules on, and java.io.tmpdir, where it copies them.
1480
+ interface JavaProperties {
1481
+ libraries: string[];
1482
+ classPath?: string;
1483
+ temporaryDirectory?: string;
1484
+ tlcVersion?: TlcVersion;
1485
+ }
1486
+
1487
+ // The tla2tools.jar on the class path.
1488
+ const getJar = (java: JavaProperties) =>
1489
+ java.classPath?.split(delimiter).find((entry) => entry.endsWith(".jar"));
1490
+
1491
+ // The TLC that -Dtla-ts.tlc names, or else the one of the jar on the class path.
1492
+ const getJavaTlcVersion = (java: JavaProperties) => java.tlcVersion ?? getTlcVersion(getJar(java));
1493
+
1494
+ interface JavaLaunch {
1495
+ mainClass: string;
1496
+ args: string[];
1497
+ java: JavaProperties;
1498
+ }
1499
+
1500
+ const getJavaLaunch = (args: string[]): JavaLaunch | undefined => {
1501
+ const java: JavaProperties = { libraries: [] };
1502
+ for (let index = 0; index < args.length; index++) {
1503
+ const arg = args[index];
1504
+ if (arg === "-cp" || arg === "-classpath" || arg === "--class-path") {
1505
+ index++;
1506
+ java.classPath = args[index];
1507
+ } else if (arg === "-jar") {
1508
+ java.classPath = args[index + 1];
1509
+ return { mainClass: "tlc2.TLC", args: args.slice(index + 2), java };
1510
+ } else if (arg.startsWith(TLA_LIBRARY_PROPERTY)) {
1511
+ java.libraries.push(...arg.slice(TLA_LIBRARY_PROPERTY.length).split(delimiter));
1512
+ } else if (arg.startsWith(TEMPORARY_DIRECTORY_PROPERTY)) {
1513
+ java.temporaryDirectory = arg.slice(TEMPORARY_DIRECTORY_PROPERTY.length);
1514
+ } else if (arg.startsWith(TLC_VERSION_PROPERTY)) {
1515
+ java.tlcVersion = arg.slice(TLC_VERSION_PROPERTY.length) === "1.7.4" ? "1.7.4" : "master";
1516
+ } else if (!arg.startsWith("-D") && !arg.startsWith("-X")) {
1517
+ const isLaunch = index > 0 || JAVA_MAIN_CLASSES.includes(arg);
1518
+ return isLaunch ? { mainClass: arg, args: args.slice(index + 1), java } : undefined;
1519
+ }
1520
+ }
1521
+ return undefined;
1522
+ };
1523
+
1524
+ const runJavaClass = (launch: JavaLaunch) => {
1525
+ if (launch.mainClass === "tlc2.TLC") return checkSpecs(launch.args, launch.java);
1526
+ if (launch.mainClass === "tla2sany.xml.XMLExporter") {
1527
+ return reportErrors(() =>
1528
+ getJavaTlcVersion(launch.java) === "1.7.4"
1529
+ ? exportXml174(launch.args, getJar(launch.java))
1530
+ : exportXml(launch.args),
1531
+ );
1532
+ }
1533
+ console.error(
1534
+ `Error: tla-ts runs the Java classes ${JAVA_MAIN_CLASSES.join(" and ")}, not ${launch.mainClass}.`,
1535
+ );
1536
+ return 1;
1537
+ };
1538
+
1539
+ const run = async (args: string[]) => {
1540
+ if (args[0] === "prove") return reportErrors(() => prove(args.slice(1)));
1541
+ const launch = getJavaLaunch(args);
1542
+ return launch ? runJavaClass(launch) : checkSpecs(args, { libraries: [] });
474
1543
  };
475
1544
 
476
1545
  export const runCli = async () => {