tla-ts 0.0.3-dev.c949d82 → 0.0.3-dev.ccbff8c

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 (81) 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 +167 -36
  5. package/dist/index.d.ts +167 -36
  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 -21
  12. package/dist/run-cli.js +1351 -21
  13. package/dist/transfer.cjs +83 -34
  14. package/dist/transfer.js +83 -34
  15. package/package.json +5 -1
  16. package/src/ast.ts +55 -7
  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 +1344 -285
  22. package/src/cli.ts +8 -1
  23. package/src/codegen.ts +68 -21
  24. package/src/config.ts +225 -206
  25. package/src/environment.ts +423 -127
  26. package/src/errors.ts +168 -9
  27. package/src/evaluate.ts +722 -146
  28. package/src/exit-codes.ts +6 -24
  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 +32 -4
  34. package/src/live-check.ts +204 -148
  35. package/src/liveness.ts +190 -117
  36. package/src/obligation-expression.ts +2 -2
  37. package/src/obligation-source.ts +2 -0
  38. package/src/parallel-worker.ts +6 -1
  39. package/src/parallel.ts +57 -6
  40. package/src/parser.ts +412 -139
  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 +1405 -416
  48. package/src/run-cli.ts +1167 -174
  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 +25 -5
  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 +158 -120
  69. package/src/symmetry.ts +168 -50
  70. package/src/tableau.ts +3 -1
  71. package/src/tlc-ext.ts +13 -17
  72. package/src/tlc-messages.ts +329 -0
  73. package/src/tlc-module.ts +49 -21
  74. package/src/tlc-modules.ts +0 -4
  75. package/src/tlc-order.ts +55 -9
  76. package/src/tlc-random.ts +28 -3
  77. package/src/tlc-replay.ts +655 -0
  78. package/src/tlc-version.ts +18 -0
  79. package/src/transfer.ts +15 -3
  80. package/src/value-sources.ts +29 -0
  81. package/src/values.ts +683 -256
package/src/run-cli.ts CHANGED
@@ -8,22 +8,41 @@ 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 {
17
- createSanyError,
18
33
  getErrorExitCode,
19
34
  TlaConfigError,
20
35
  TlaError,
21
36
  TlaEvaluationError,
22
37
  TlaProofError,
23
38
  TlaSyntaxError,
24
- type SanyReport,
39
+ getUnexpectedException,
40
+ TlaJavaException,
41
+ UNEXPECTED_EXCEPTION,
42
+ TlaSanyFatalError,
43
+ TlaUnsupportedError,
25
44
  } from "./errors";
26
- import { EXIT_STATUS } from "./exit-codes";
45
+ import { EXIT_STATUS, setExitCode } from "./exit-codes";
27
46
  import type { LineRange } from "./obligation-generate";
28
47
  import { getAtPrefix, getLocusText } from "./obligation-expression";
29
48
  import { formatSummary, getObligations, WHOLE_MODULE, type ModuleObligations } from "./obligations";
@@ -36,7 +55,23 @@ import {
36
55
  getOptimisticProbability,
37
56
  getOutDegreeSummary,
38
57
  } from "./tlc-summary";
39
- 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";
40
75
 
41
76
  const EXIT_CODES: Record<CheckStatus, number> = {
42
77
  success: EXIT_STATUS.success,
@@ -57,8 +92,12 @@ const CHECK_COMMAND = defineCommand("tla-ts <Spec.tla|Spec.cfg|glob>... {options
57
92
  flag: "-dump [<format>] <file>",
58
93
  getArity: (rest) => (rest.length > 1 && rest[0].startsWith("dot") ? 2 : 1),
59
94
  },
95
+ { flag: "-fp <num>" },
60
96
  { flag: "-lncheck <final|default>" },
97
+ { flag: "-metadir <directory>" },
98
+ { flag: "-nowarning" },
61
99
  { flag: "-seed <num>" },
100
+ { flag: "-tool" },
62
101
  { flag: "-workers <count|auto>" },
63
102
  ]);
64
103
 
@@ -72,10 +111,64 @@ const PROVE_COMMAND = defineCommand("tla-ts prove {options} <Module.tla|glob>...
72
111
  { flag: "-I <directory>", isRepeatable: true },
73
112
  ]);
74
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
+
75
166
  const USAGE = [
76
167
  `Usage: ${CHECK_COMMAND.usage}`,
77
168
  ` ${PROVE_COMMAND.usage}`,
78
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>",
79
172
  ].join("\n");
80
173
 
81
174
  const GLOB_CHARACTERS = /[*?[{]/;
@@ -104,8 +197,6 @@ const getWorkerCount = (values: string[] | undefined) => {
104
197
  : Math.max(1, Number.parseInt(values[0], 10) || 1);
105
198
  };
106
199
 
107
- const printState = (state: Record<string, Value>) => console.log(formatState(state));
108
-
109
200
  const UNSUPPORTED_DUMP_FORMATS = ["constrained", "stuttering", "strict"];
110
201
 
111
202
  // TLC names the file of a -dump by its format unless the name already ends that way.
@@ -124,140 +215,590 @@ const getDump = (values: string[]): StateDump => {
124
215
  };
125
216
  };
126
217
 
127
- const printTrace = (trace: TraceStep[], heading = "Error: The behavior up to this point is:") => {
128
- 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);
129
264
  trace.forEach((step, index) => {
130
- console.log(`State ${index + 1}: <${step.label ?? step.action ?? "Initial predicate"}>`);
131
- 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
+ );
132
271
  });
133
272
  };
134
273
 
135
- const getTemporalHeadline = (names: string[]) =>
136
- names.length === 1
137
- ? `Error: Temporal property ${names[0]} was violated.\n`
138
- : `Error: Temporal properties ${names.slice(0, -1).join(", ")}${names.length > 2 ? "," : ""} and ${names[names.length - 1]} were violated.\n`;
274
+ const COUNTER_EXAMPLE = {
275
+ code: MESSAGE_CODE.counterExample,
276
+ text: "The following behavior constitutes a counter-example:\n",
277
+ };
139
278
 
140
- const printResult = (result: CheckResult) => {
141
- if (result.failure) {
142
- console.log(`Error: ${result.failure.message}`);
143
- if (result.failure.initialState) {
144
- console.log("While working on the initial state:");
145
- printState(result.failure.initialState);
146
- }
147
- printTrace(result.failure.trace);
148
- } else if (result.violation) {
149
- const violation = result.violation;
150
- const name = violation.name;
151
- const loopStart = violation.loopStart;
152
- // TLC prints a violation by an initial state without the behavior or the statistics.
153
- const isInitial =
154
- loopStart === undefined &&
155
- violation.trace.length === 1 &&
156
- (result.status === "invariant-violation" || result.status === "liveness-violation");
157
- const headline = {
158
- success: "",
159
- error: "",
160
- "assumption-violation": violation.message
161
- ? `Error: Evaluating assumption ${name} failed.\n${violation.message}`
162
- : `Error: Assumption ${name} is false.`,
163
- deadlock: "Error: Deadlock reached.",
164
- "invariant-violation": isInitial
165
- ? `Error: Invariant ${name} is violated by the initial state:`
166
- : `Error: Invariant ${name} is violated.`,
167
- "property-violation": getTemporalHeadline(violation.properties ?? [name]),
168
- "liveness-violation":
169
- loopStart !== undefined
170
- ? getTemporalHeadline(violation.properties ?? [name])
171
- : isInitial
172
- ? `Error: Property ${name} is violated by the initial state:`
173
- : `Error: Action property ${name} is violated.`,
174
- "postcondition-violation": `Error: ${violation.message ?? `Postcondition ${name} is false.`}`,
175
- }[result.status];
176
- if (violation.counts) console.log(violation.counts);
177
- console.log(headline);
178
- if (isInitial) printState(violation.trace[0].state);
179
- else if (result.status === "property-violation")
180
- printTrace(violation.trace, "Error: The following behavior constitutes a counter-example:\n");
181
- else if (loopStart === undefined) printTrace(violation.trace);
182
- else {
183
- printTrace(violation.trace, "Error: The following behavior constitutes a counter-example:\n");
184
- const isStuttering = loopStart === violation.trace.length - 1;
185
- console.log(
186
- isStuttering
187
- ? `State ${loopStart + 2}: Stuttering`
188
- : `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.`,
189
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}>.`,
425
+ );
426
+ return;
190
427
  }
191
- const unwitnessed = violation.unwitnessed;
192
- if (unwitnessed?.counts) console.log(unwitnessed.counts);
193
- if (unwitnessed) console.log(`Error: ${unwitnessed.message}`);
194
- // TLC checks assumptions before it starts the search, so it has no statistics to print.
195
- if (isInitial || result.status === "assumption-violation") return;
196
- } else {
197
- const optimistic = getOptimisticProbability(result.distinctStates, result.generatedStates);
198
- console.log("Model checking completed. No error has been found.");
199
- console.log(" Estimates of the probability that TLC did not check all reachable states");
200
- console.log(" because two distinct states had the same fingerprint:");
201
- console.log(` calculated (optimistic): val = ${formatProbability(optimistic)}`);
202
- if (result.fingerprintDistance !== undefined) {
203
- const actual = getActualProbability(result.fingerprintDistance);
204
- 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;
205
453
  }
454
+ case "liveness-finished":
455
+ printLivenessEnd(printer, timing);
456
+ return;
457
+ case "warning":
458
+ print(progress.code, MESSAGE_LEVEL.warning, progress.text);
206
459
  }
207
- console.log(
208
- `${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())}`,
209
468
  );
210
- console.log(`The depth of the complete state graph search is ${result.depth}.`);
211
- const outDegree = result.outDegrees && getOutDegreeSummary(result.outDegrees);
212
- if (outDegree) console.log(outDegree);
469
+ timing.liveness = undefined;
213
470
  };
214
471
 
215
- const checkSpec = async (specPath: string, args: ParsedArgs) => {
216
- if (!existsSync(specPath)) {
217
- console.error(`Cannot find the specification file ${specPath}`);
218
- 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);
219
533
  }
220
- const source = readFileSync(specPath, "utf8");
221
- const fileName = basename(specPath, ".tla");
222
- const moduleName = parseModule(source).name;
223
- if (moduleName !== fileName) {
224
- throw createSanyError(
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,
541
+ );
542
+ printTraceOutput(printer, violation.traceOutput);
543
+ }
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` : ""}`);
555
+ }
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,
225
655
  [
226
- {
227
- location: "Unknown location",
228
- message: `File name '${fileName}' does not match the name '${moduleName}' of the top level module it contains.`,
229
- },
230
- ],
231
- true,
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"),
232
662
  );
233
663
  }
234
- const configPath =
235
- args.get("-config")?.[0] ??
236
- (args.has("-config") ? undefined : specPath.replace(/\.tla$/, ".cfg"));
237
- if (!configPath || !existsSync(configPath)) {
238
- console.error(`Cannot find the configuration file ${configPath ?? ""}`);
239
- return EXIT_STATUS.configParseError;
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
+ );
240
682
  }
241
- const config = parseConfig(readFileSync(configPath, "utf8"));
242
- if (args.has("-deadlock")) config.checkDeadlock = false;
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.
243
784
  const seed = args.has("-seed") ? args.get("-seed")?.[0] : "0";
244
- if (seed === undefined) {
245
- console.error("Error: seed required.");
246
- return 1;
247
- }
785
+ if (seed === undefined) return printCommandLineError(printer, "Error: seed required.");
248
786
  if (!isJavaLong(seed)) {
249
- console.error(`Error: An integer for seed required. But encountered ${seed}`);
250
- return 1;
787
+ return printCommandLineError(
788
+ printer,
789
+ `Error: An integer for seed required. But encountered ${seed}`,
790
+ );
251
791
  }
252
792
  const livenessCheck = args.has("-lncheck") ? args.get("-lncheck")?.[0]?.toLowerCase() : "default";
253
793
  if (livenessCheck === undefined) {
254
- console.error("Error: expect a strategy such as final for -lncheck option.");
255
- return 1;
794
+ return printCommandLineError(
795
+ printer,
796
+ "Error: expect a strategy such as final for -lncheck option.",
797
+ );
256
798
  }
257
799
  const dumpValues = args.get("-dump");
258
800
  if (dumpValues?.length === 0) {
259
- console.error("Error: A file name for dumping states required.");
260
- return 1;
801
+ return printCommandLineError(printer, "Error: A file name for dumping states required.");
261
802
  }
262
803
  const unsupportedFormat =
263
804
  dumpValues?.length === 2 &&
@@ -266,71 +807,237 @@ const checkSpec = async (specPath: string, args: ParsedArgs) => {
266
807
  console.error(`Error: tla-ts does not support the -dump format ${unsupportedFormat}.`);
267
808
  return 1;
268
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;
269
882
  const directory = dirname(specPath);
270
- console.log(`Checking ${basename(specPath)} with ${basename(configPath)}`);
271
- const result = await check({
272
- workers: getWorkerCount(args.get("-workers")),
273
- livenessCheck: ["final", "seqfinal", "off"].includes(livenessCheck) ? "final" : "default",
274
- seed: BigInt(seed),
275
- dump: dumpValues && getDump(dumpValues),
276
- source,
277
- config,
278
- onPause: () => readSync(0, Buffer.alloc(1)),
279
- loadModule: (name) => {
280
- const modulePath = join(directory, `${name}.tla`);
281
- return existsSync(modulePath) ? readFileSync(modulePath, "utf8") : undefined;
282
- },
283
- loadClass: (name) => {
284
- const classPath = join(directory, `${name}.class`);
285
- return existsSync(classPath) ? readFileSync(classPath) : undefined;
286
- },
287
- readFile: (path) => (existsSync(path) ? readFileSync(path, "utf8") : undefined),
288
- writeFile: (path, content) => {
289
- mkdirSync(dirname(resolve(path)), { recursive: true });
290
- 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),
291
966
  },
292
- });
293
- printResult(result);
294
- 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
+ }
295
982
  };
296
983
 
297
- const formatSanyErrors = (report: SanyReport) =>
298
- `*** Errors: ${report.errors.length}\n\n${report.errors.map((error) => `${error.location}\n\n${error.message}\n\n`).join("\n")}`;
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`;
997
+ };
299
998
 
300
- // TLC prints the errors it raises itself, and SANY's report of a spec it rejects. tla-ts names the
301
- // others, such as a module it cannot parse.
302
- const printError = (error: TlaError, path?: string) => {
999
+ // TLC prints the errors it raises itself. tla-ts names the others, such as a module SANY rejects.
1000
+ const printError = (error: TlaError, printer: MessagePrinter) => {
303
1001
  if (error instanceof TlaConfigError || error instanceof TlaEvaluationError) {
304
- 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
+ );
305
1011
  }
306
- const report = error instanceof TlaSyntaxError ? error.sany : undefined;
307
- if (!report || path === undefined) return console.error(`${error.name}: ${error.message}`);
308
- console.log(
309
- report.isFatal
310
- ? `\nFatal errors while parsing TLA+ spec in file ${basename(path, ".tla")}\n\n${report.errors.map((item) => `${item.location}\n\n${item.message}\n`).join("")}${formatSanyErrors(report)}\n`
311
- : `Semantic errors:\n\n${formatSanyErrors(report)}`,
312
- );
313
- console.log("Error: Parsing or semantic analysis failed.");
1012
+ console.error(`${error.name}: ${error.message}`);
314
1013
  };
315
1014
 
316
1015
  // Prints a TlaError and returns its exit code.
317
- const reportErrors = async (run: () => number | Promise<number>, path?: string) => {
1016
+ const reportErrors = async (
1017
+ run: () => number | Promise<number>,
1018
+ printer = createMessagePrinter(false),
1019
+ ) => {
318
1020
  try {
319
1021
  return await run();
320
1022
  } catch (error) {
321
1023
  if (!(error instanceof TlaError)) throw error;
322
- printError(error, path);
1024
+ printError(error, printer);
323
1025
  return getErrorExitCode(error);
324
1026
  }
325
1027
  };
326
1028
 
327
- // Runs each path in turn, so an error in one leaves the others to report. The exit code is the
328
- // first that is not success.
329
- 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
+ ) => {
330
1036
  const exitCodes: number[] = [];
331
1037
  for (const [index, path] of paths.entries()) {
332
1038
  if (index > 0) console.log("");
333
- exitCodes.push(await reportErrors(() => runPath(path), path));
1039
+ const printer = createPrinter();
1040
+ exitCodes.push(await reportErrors(() => runPath(path, printer), printer));
334
1041
  }
335
1042
  return exitCodes.find((exitCode) => exitCode !== EXIT_STATUS.success) ?? EXIT_STATUS.success;
336
1043
  };
@@ -374,15 +1081,10 @@ const TLAPM_VERSION = "5f5037f";
374
1081
  const quoteArgument = (arg: string) =>
375
1082
  /^[+,\-./0-9:=@A-Z_a-z]+$/.test(arg) ? arg : `'${arg.replaceAll("'", "'\\''")}'`;
376
1083
 
377
- const printToolboxHeader = (args: string[]) => {
378
- const now = new Date();
379
- const pad = (value: number) => String(value).padStart(2, "0");
380
- const date = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`;
381
- const time = `${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}`;
1084
+ const printToolboxHeader = (args: string[]) =>
382
1085
  console.log(
383
- `\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`,
384
1087
  );
385
- };
386
1088
 
387
1089
  const STRICT_EXIT_STATUS = { incomplete: 11, emptyTarget: 12 };
388
1090
 
@@ -512,14 +1214,20 @@ const prove = (args: string[]) => {
512
1214
  : (failures[0] ?? EXIT_STATUS.success);
513
1215
  };
514
1216
 
515
- const run = async (args: string[]) => {
516
- if (args[0] === "prove") return reportErrors(() => prove(args.slice(1)));
1217
+ const checkSpecs = async (args: string[], java: JavaProperties) => {
517
1218
  const parsed = CHECK_COMMAND.parse(args);
518
1219
  const inputs = getInputPaths(parsed.positionals);
519
1220
  const isConfigured = parsed.has("-config");
520
- // 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.
521
1223
  const specPaths = inputs
522
- .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
+ }))
523
1231
  .filter(
524
1232
  (input) =>
525
1233
  input.path.endsWith(".tla") &&
@@ -534,7 +1242,292 @@ const run = async (args: string[]) => {
534
1242
  console.error("Error: -config applies to one specification, but several were given.");
535
1243
  return 1;
536
1244
  }
537
- 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: [] });
538
1531
  };
539
1532
 
540
1533
  export const runCli = async () => {