tla-ts 0.0.3-dev.037ac3b → 0.0.3-dev.0ad0249

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