tla-ts 0.0.2 → 0.0.3-dev.07eab97

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 (68) hide show
  1. package/README.md +78 -12
  2. package/dist/index.cjs +1 -1
  3. package/dist/index.d.cts +98 -15
  4. package/dist/index.d.ts +98 -15
  5. package/dist/index.js +1 -1
  6. package/dist/parallel-worker.cjs +2 -2
  7. package/dist/parallel-worker.js +2 -2
  8. package/dist/parallel.cjs +1 -1
  9. package/dist/parallel.js +2 -2
  10. package/dist/run-cli.cjs +23 -2
  11. package/dist/run-cli.js +23 -2
  12. package/dist/transfer.cjs +36 -16
  13. package/dist/transfer.js +36 -16
  14. package/package.json +3 -1
  15. package/src/ast.ts +139 -4
  16. package/src/builtins.ts +9 -3
  17. package/src/check.ts +555 -107
  18. package/src/cli-options.ts +64 -0
  19. package/src/codegen.ts +15 -22
  20. package/src/config.ts +224 -170
  21. package/src/dependencies.ts +2 -2
  22. package/src/environment.ts +156 -48
  23. package/src/errors.ts +123 -3
  24. package/src/evaluate.ts +258 -160
  25. package/src/exit-codes.ts +39 -42
  26. package/src/fingerprints.ts +48 -12
  27. package/src/instances.ts +16 -15
  28. package/src/levels.ts +181 -45
  29. package/src/lexer.ts +11 -2
  30. package/src/live-check.ts +772 -0
  31. package/src/liveness.ts +120 -543
  32. package/src/obligation-action.ts +384 -0
  33. package/src/obligation-anon.ts +575 -0
  34. package/src/obligation-deref.ts +637 -0
  35. package/src/obligation-expression.ts +1060 -0
  36. package/src/obligation-format.ts +406 -0
  37. package/src/obligation-generate.ts +1074 -0
  38. package/src/obligation-levels.ts +329 -0
  39. package/src/obligation-module.ts +1042 -0
  40. package/src/obligation-printer.ts +889 -0
  41. package/src/obligation-proof.ts +76 -0
  42. package/src/obligation-source.ts +1084 -0
  43. package/src/obligation-tuples.ts +184 -0
  44. package/src/obligations.ts +316 -0
  45. package/src/parallel-worker.ts +168 -212
  46. package/src/parallel.ts +78 -37
  47. package/src/parser.ts +350 -63
  48. package/src/resolve.ts +124 -44
  49. package/src/run-cli.ts +405 -45
  50. package/src/runtime.ts +3 -1
  51. package/src/spec-description.ts +19 -8
  52. package/src/standard-levels.ts +3 -3
  53. package/src/standard-modules.ts +54 -45
  54. package/src/state-graph.ts +157 -0
  55. package/src/subexpressions.ts +10 -10
  56. package/src/substitution-levels.ts +38 -17
  57. package/src/successors.ts +183 -39
  58. package/src/symmetry.ts +30 -8
  59. package/src/tableau.ts +51 -24
  60. package/src/tlc-ext.ts +29 -12
  61. package/src/tlc-module.ts +14 -33
  62. package/src/tlc-modules.ts +4 -0
  63. package/src/tlc-order.ts +25 -7
  64. package/src/tlc-random.ts +9 -6
  65. package/src/tlc-summary.ts +20 -5
  66. package/src/transfer.ts +22 -1
  67. package/src/value-sources.ts +29 -0
  68. package/src/values.ts +300 -83
package/src/run-cli.ts CHANGED
@@ -1,19 +1,42 @@
1
- import { existsSync, mkdirSync, readFileSync, readSync, writeFileSync } from "node:fs";
2
- import { basename, dirname, join, resolve } from "node:path";
1
+ import {
2
+ existsSync,
3
+ globSync,
4
+ mkdirSync,
5
+ readFileSync,
6
+ readSync,
7
+ realpathSync,
8
+ writeFileSync,
9
+ } from "node:fs";
10
+ import { spawnSync } from "node:child_process";
11
+ import { basename, delimiter, dirname, join, resolve } from "node:path";
3
12
  import { availableParallelism } from "node:os";
4
- import type { CheckResult, CheckStatus, TraceStep } from "./check";
13
+ import type { CheckResult, CheckStatus, Replay, TraceStep } from "./check";
14
+ import { defineCommand, type ParsedArgs } from "./cli-options";
5
15
  import { parseConfig } from "./config";
6
- import { getErrorExitCode, TlaConfigError, TlaError, TlaEvaluationError } from "./errors";
16
+ import {
17
+ createSanyError,
18
+ getErrorExitCode,
19
+ TlaConfigError,
20
+ TlaError,
21
+ TlaEvaluationError,
22
+ TlaProofError,
23
+ TlaSyntaxError,
24
+ type SanyReport,
25
+ } from "./errors";
7
26
  import { EXIT_STATUS } from "./exit-codes";
27
+ import type { LineRange } from "./obligation-generate";
28
+ import { getAtPrefix, getLocusText } from "./obligation-expression";
29
+ import { formatSummary, getObligations, WHOLE_MODULE, type ModuleObligations } from "./obligations";
8
30
  import { check } from "./parallel";
9
- import { prettyPrint } from "./pretty-print";
31
+ import { parseModule } from "./parser";
32
+ import type { StateDump } from "./state-graph";
10
33
  import {
11
34
  formatProbability,
12
35
  getActualProbability,
13
36
  getOptimisticProbability,
14
37
  getOutDegreeSummary,
15
38
  } from "./tlc-summary";
16
- import { formatValue, type Value } from "./values";
39
+ import { formatState, type Value } from "./values";
17
40
 
18
41
  const EXIT_CODES: Record<CheckStatus, number> = {
19
42
  success: EXIT_STATUS.success,
@@ -26,27 +49,79 @@ const EXIT_CODES: Record<CheckStatus, number> = {
26
49
  error: EXIT_STATUS.error,
27
50
  };
28
51
 
29
- const USAGE =
30
- "Usage: tla-ts <Spec.tla> [-config <Spec.cfg>] [-deadlock] [-lncheck <final|default>] [-seed <num>] [-workers <count|auto>]";
52
+ const CHECK_COMMAND = defineCommand("tla-ts <Spec.tla|Spec.cfg|glob>... {options}", [
53
+ { flag: "-config <Spec.cfg>" },
54
+ { flag: "-deadlock" },
55
+ // Like TLC, -dump takes a format only when the next argument starts with dot and a file follows.
56
+ {
57
+ flag: "-dump [<format>] <file>",
58
+ getArity: (rest) => (rest.length > 1 && rest[0].startsWith("dot") ? 2 : 1),
59
+ },
60
+ { flag: "-lncheck <final|default>" },
61
+ { flag: "-seed <num>" },
62
+ { flag: "-workers <count|auto>" },
63
+ ]);
64
+
65
+ const PROVE_COMMAND = defineCommand("tla-ts prove {options} <Module.tla|glob>...", [
66
+ { flag: "-N", isRequired: true },
67
+ { flag: "--toolbox <start> <end>" },
68
+ { flag: "--line <num>" },
69
+ { flag: "--printallobs" },
70
+ { flag: "--summary" },
71
+ { flag: "--strict" },
72
+ { flag: "-I <directory>", isRepeatable: true },
73
+ ]);
74
+
75
+ const USAGE = [
76
+ `Usage: ${CHECK_COMMAND.usage}`,
77
+ ` ${PROVE_COMMAND.usage}`,
78
+ " tla-ts prove [<tlapm option>]... <Module.tla|glob>...",
79
+ ].join("\n");
80
+
81
+ const GLOB_CHARACTERS = /[*?[{]/;
82
+
83
+ interface InputPath {
84
+ path: string;
85
+ isGlobbed: boolean;
86
+ }
87
+
88
+ const getInputPaths = (paths: string[]): InputPath[] =>
89
+ paths.flatMap((arg): InputPath[] =>
90
+ GLOB_CHARACTERS.test(arg)
91
+ ? globSync(arg)
92
+ .sort()
93
+ .map((path) => ({ path, isGlobbed: true }))
94
+ : [{ path: arg, isGlobbed: false }],
95
+ );
31
96
 
32
97
  const isJavaLong = (text: string) =>
33
98
  /^[+-]?\d+$/.test(text) && BigInt.asIntN(64, BigInt(text)) === BigInt(text);
34
99
 
35
- const getWorkerCount = (args: string[]) => {
36
- const flag = args.indexOf("-workers");
37
- if (flag === -1) return 1;
38
- const value = args[flag + 1];
39
- return value === "auto" ? availableParallelism() : Math.max(1, Number.parseInt(value, 10) || 1);
100
+ const getWorkerCount = (values: string[] | undefined) => {
101
+ if (!values) return 1;
102
+ return values[0] === "auto"
103
+ ? availableParallelism()
104
+ : Math.max(1, Number.parseInt(values[0], 10) || 1);
40
105
  };
41
106
 
42
- const printState = (state: Record<string, Value>) => {
43
- const entries = Object.entries(state);
44
- entries.forEach(([name, value]) =>
45
- console.log(
46
- `${entries.length === 1 ? "" : "/\\ "}${name} = ${prettyPrint(formatValue(value))}`,
47
- ),
48
- );
49
- console.log("");
107
+ const printState = (state: Record<string, Value>) => console.log(formatState(state));
108
+
109
+ const UNSUPPORTED_DUMP_FORMATS = ["constrained", "stuttering", "strict"];
110
+
111
+ // TLC names the file of a -dump by its format unless the name already ends that way.
112
+ const getDumpPath = (path: string, extension: string) =>
113
+ path.endsWith(extension) ? path : `${path}${extension}`;
114
+
115
+ const getDump = (values: string[]): StateDump => {
116
+ if (values.length === 1) return { path: getDumpPath(values[0], ".dump") };
117
+ const format = values[0].toLowerCase();
118
+ return {
119
+ path: getDumpPath(values[1], ".dot"),
120
+ dot: true,
121
+ colorize: format.includes("colorize"),
122
+ actionLabels: format.includes("actionlabels"),
123
+ snapshot: format.includes("snapshot"),
124
+ };
50
125
  };
51
126
 
52
127
  const printTrace = (trace: TraceStep[], heading = "Error: The behavior up to this point is:") => {
@@ -57,14 +132,47 @@ const printTrace = (trace: TraceStep[], heading = "Error: The behavior up to thi
57
132
  });
58
133
  };
59
134
 
135
+ const getTemporalHeadline = (names: string[]) =>
136
+ names.length === 1
137
+ ? `Error: Temporal property ${names[0]} was violated.\n`
138
+ : `Error: Temporal properties ${names.slice(0, -1).join(", ")}${names.length > 2 ? "," : ""} and ${names[names.length - 1]} were violated.\n`;
139
+
140
+ const getFrames = (callStack: string[]) =>
141
+ callStack.map((frame, index) => `${index}. ${frame}\n`).join("");
142
+
143
+ const printCallStack = (frames: string) =>
144
+ console.log(
145
+ `Error: The error occurred when TLC was evaluating the nested\nexpressions at the following positions:\n${frames ? `${frames}\n` : " The error call stack is empty.\n"}`,
146
+ );
147
+
148
+ const printReplay = (replay: Replay) => {
149
+ replay.output.forEach((line) => console.log(line));
150
+ const frames = getFrames(replay.callStack ?? []);
151
+ const fingerprint = replay.fingerprint;
152
+ if (replay.isBeforeError) {
153
+ if (frames) printCallStack(frames);
154
+ } else if (replay.callStack && fingerprint) {
155
+ const sources = fingerprint.sources.map((source) => `${source}\n`).join("");
156
+ console.log(
157
+ `Error: TLC was unable to fingerprint.\n\nFingerprint Stack Trace:\n${frames ? `${frames}\n` : sources}\nReason:\n${fingerprint.reason}`,
158
+ );
159
+ } else if (replay.callStack) {
160
+ printCallStack(frames);
161
+ }
162
+ };
163
+
60
164
  const printResult = (result: CheckResult) => {
61
165
  if (result.failure) {
166
+ const replay = result.failure.replay;
167
+ if (replay?.isBeforeError) printReplay(replay);
62
168
  console.log(`Error: ${result.failure.message}`);
63
169
  if (result.failure.initialState) {
64
170
  console.log("While working on the initial state:");
65
171
  printState(result.failure.initialState);
66
172
  }
67
173
  printTrace(result.failure.trace);
174
+ if (replay && !replay.isBeforeError) printReplay(replay);
175
+ if (result.failure.isWithoutStatistics) return;
68
176
  } else if (result.violation) {
69
177
  const violation = result.violation;
70
178
  const name = violation.name;
@@ -84,10 +192,10 @@ const printResult = (result: CheckResult) => {
84
192
  "invariant-violation": isInitial
85
193
  ? `Error: Invariant ${name} is violated by the initial state:`
86
194
  : `Error: Invariant ${name} is violated.`,
87
- "property-violation": `Error: Property ${name} is violated.`,
195
+ "property-violation": getTemporalHeadline(violation.properties ?? [name]),
88
196
  "liveness-violation":
89
197
  loopStart !== undefined
90
- ? `Error: Temporal property ${name} was violated.\n`
198
+ ? getTemporalHeadline(violation.properties ?? [name])
91
199
  : isInitial
92
200
  ? `Error: Property ${name} is violated by the initial state:`
93
201
  : `Error: Action property ${name} is violated.`,
@@ -96,6 +204,8 @@ const printResult = (result: CheckResult) => {
96
204
  if (violation.counts) console.log(violation.counts);
97
205
  console.log(headline);
98
206
  if (isInitial) printState(violation.trace[0].state);
207
+ else if (result.status === "property-violation")
208
+ printTrace(violation.trace, "Error: The following behavior constitutes a counter-example:\n");
99
209
  else if (loopStart === undefined) printTrace(violation.trace);
100
210
  else {
101
211
  printTrace(violation.trace, "Error: The following behavior constitutes a counter-example:\n");
@@ -130,26 +240,35 @@ const printResult = (result: CheckResult) => {
130
240
  if (outDegree) console.log(outDegree);
131
241
  };
132
242
 
133
- const run = async (args: string[]) => {
134
- const specPath = args.find((arg, index) => arg.endsWith(".tla") && args[index - 1] !== "-config");
135
- if (!specPath) {
136
- console.error(USAGE);
137
- return 1;
138
- }
243
+ const checkSpec = async (specPath: string, args: ParsedArgs) => {
139
244
  if (!existsSync(specPath)) {
140
245
  console.error(`Cannot find the specification file ${specPath}`);
141
246
  return EXIT_STATUS.configParseError;
142
247
  }
143
- const configFlag = args.indexOf("-config");
144
- const configPath = configFlag === -1 ? specPath.replace(/\.tla$/, ".cfg") : args[configFlag + 1];
248
+ const source = readFileSync(specPath, "utf8");
249
+ const fileName = basename(specPath, ".tla");
250
+ const moduleName = parseModule(source).name;
251
+ if (moduleName !== fileName) {
252
+ throw createSanyError(
253
+ [
254
+ {
255
+ location: "Unknown location",
256
+ message: `File name '${fileName}' does not match the name '${moduleName}' of the top level module it contains.`,
257
+ },
258
+ ],
259
+ true,
260
+ );
261
+ }
262
+ const configPath =
263
+ args.get("-config")?.[0] ??
264
+ (args.has("-config") ? undefined : specPath.replace(/\.tla$/, ".cfg"));
145
265
  if (!configPath || !existsSync(configPath)) {
146
266
  console.error(`Cannot find the configuration file ${configPath ?? ""}`);
147
267
  return EXIT_STATUS.configParseError;
148
268
  }
149
269
  const config = parseConfig(readFileSync(configPath, "utf8"));
150
- if (args.includes("-deadlock")) config.checkDeadlock = false;
151
- const seedFlag = args.indexOf("-seed");
152
- const seed = seedFlag === -1 ? "0" : args[seedFlag + 1];
270
+ if (args.has("-deadlock")) config.checkDeadlock = false;
271
+ const seed = args.has("-seed") ? args.get("-seed")?.[0] : "0";
153
272
  if (seed === undefined) {
154
273
  console.error("Error: seed required.");
155
274
  return 1;
@@ -158,19 +277,31 @@ const run = async (args: string[]) => {
158
277
  console.error(`Error: An integer for seed required. But encountered ${seed}`);
159
278
  return 1;
160
279
  }
161
- const livenessFlag = args.indexOf("-lncheck");
162
- const livenessCheck = livenessFlag === -1 ? "default" : args[livenessFlag + 1]?.toLowerCase();
280
+ const livenessCheck = args.has("-lncheck") ? args.get("-lncheck")?.[0]?.toLowerCase() : "default";
163
281
  if (livenessCheck === undefined) {
164
282
  console.error("Error: expect a strategy such as final for -lncheck option.");
165
283
  return 1;
166
284
  }
285
+ const dumpValues = args.get("-dump");
286
+ if (dumpValues?.length === 0) {
287
+ console.error("Error: A file name for dumping states required.");
288
+ return 1;
289
+ }
290
+ const unsupportedFormat =
291
+ dumpValues?.length === 2 &&
292
+ UNSUPPORTED_DUMP_FORMATS.find((format) => dumpValues[0].toLowerCase().includes(format));
293
+ if (unsupportedFormat) {
294
+ console.error(`Error: tla-ts does not support the -dump format ${unsupportedFormat}.`);
295
+ return 1;
296
+ }
167
297
  const directory = dirname(specPath);
168
298
  console.log(`Checking ${basename(specPath)} with ${basename(configPath)}`);
169
299
  const result = await check({
170
- workers: getWorkerCount(args),
300
+ workers: getWorkerCount(args.get("-workers")),
171
301
  livenessCheck: ["final", "seqfinal", "off"].includes(livenessCheck) ? "final" : "default",
172
302
  seed: BigInt(seed),
173
- source: readFileSync(specPath, "utf8"),
303
+ dump: dumpValues && getDump(dumpValues),
304
+ source,
174
305
  config,
175
306
  onPause: () => readSync(0, Buffer.alloc(1)),
176
307
  loadModule: (name) => {
@@ -191,20 +322,249 @@ const run = async (args: string[]) => {
191
322
  return result.failure?.exitCode ?? EXIT_CODES[result.status];
192
323
  };
193
324
 
194
- // TLC prints the errors it raises itself. tla-ts names the others, such as a module SANY rejects.
195
- const printError = (error: TlaError) => {
325
+ const formatSanyErrors = (report: SanyReport) =>
326
+ `*** Errors: ${report.errors.length}\n\n${report.errors.map((error) => `${error.location}\n\n${error.message}\n\n`).join("\n")}`;
327
+
328
+ // TLC prints the errors it raises itself, and SANY's report of a spec it rejects. tla-ts names the
329
+ // others, such as a module it cannot parse.
330
+ const printError = (error: TlaError, path?: string) => {
196
331
  if (error instanceof TlaConfigError || error instanceof TlaEvaluationError) {
197
332
  return console.log(`Error: ${error.message}`);
198
333
  }
199
- console.error(`${error.name}: ${error.message}`);
334
+ const report = error instanceof TlaSyntaxError ? error.sany : undefined;
335
+ if (!report || path === undefined) return console.error(`${error.name}: ${error.message}`);
336
+ console.log(
337
+ report.isFatal
338
+ ? `\nFatal errors while parsing TLA+ spec in file ${basename(path, ".tla")}\n\n${report.errors.map((item) => `${item.location}\n\n${item.message}\n`).join("")}${formatSanyErrors(report)}\n`
339
+ : `Semantic errors:\n\n${formatSanyErrors(report)}`,
340
+ );
341
+ console.log("Error: Parsing or semantic analysis failed.");
200
342
  };
201
343
 
202
- export const runCli = async () => {
344
+ // Prints a TlaError and returns its exit code.
345
+ const reportErrors = async (run: () => number | Promise<number>, path?: string) => {
203
346
  try {
204
- process.exitCode = await run(process.argv.slice(2));
347
+ return await run();
205
348
  } catch (error) {
206
349
  if (!(error instanceof TlaError)) throw error;
207
- printError(error);
208
- process.exitCode = getErrorExitCode(error);
350
+ printError(error, path);
351
+ return getErrorExitCode(error);
209
352
  }
210
353
  };
354
+
355
+ // Runs each path in turn, so an error in one leaves the others to report. The exit code is the
356
+ // first that is not success.
357
+ const runEach = async (paths: string[], runPath: (path: string) => number | Promise<number>) => {
358
+ const exitCodes: number[] = [];
359
+ for (const [index, path] of paths.entries()) {
360
+ if (index > 0) console.log("");
361
+ exitCodes.push(await reportErrors(() => runPath(path), path));
362
+ }
363
+ return exitCodes.find((exitCode) => exitCode !== EXIT_STATUS.success) ?? EXIT_STATUS.success;
364
+ };
365
+
366
+ // tlapm installs its standard library, with modules such as TLAPS, at lib/tlapm/stdlib beside
367
+ // bin/tlapm.
368
+ const getTlapmPaths = () =>
369
+ (process.env.PATH ?? "")
370
+ .split(delimiter)
371
+ .map((directory) => join(directory, "tlapm"))
372
+ .filter((path) => existsSync(path));
373
+
374
+ const getTlapmLibrary = () =>
375
+ getTlapmPaths()
376
+ .map((path) => join(dirname(dirname(realpathSync(path))), "lib/tlapm/stdlib"))
377
+ .find((path) => existsSync(path));
378
+
379
+ const expandGlobs = (paths: string[]) =>
380
+ paths.flatMap((path) => (GLOB_CHARACTERS.test(path) ? globSync(path).sort() : [path]));
381
+
382
+ const proveWithTlapm = (args: string[]) => {
383
+ const tlapm = getTlapmPaths()[0];
384
+ if (tlapm === undefined) {
385
+ console.error(
386
+ "Error: tla-ts prove runs tlapm to prove obligations, but tlapm isn't on your PATH. Install tlapm, or pass -N to only generate the obligations.",
387
+ );
388
+ return 1;
389
+ }
390
+ return spawnSync(tlapm, expandGlobs(args), { stdio: "inherit" }).status ?? 1;
391
+ };
392
+
393
+ const readModule = (path: string) =>
394
+ existsSync(path) ? { file: path, source: readFileSync(path, "utf8") } : undefined;
395
+
396
+ // A message of tlapm's toolbox protocol, which it writes to stderr.
397
+ const printToolboxMessage = (fields: string[]) =>
398
+ console.error(`@!!BEGIN\n${fields.map((field) => `@!!${field}\n`).join("")}@!!END\n`);
399
+
400
+ const TLAPM_VERSION = "5f5037f";
401
+
402
+ const quoteArgument = (arg: string) =>
403
+ /^[+,\-./0-9:=@A-Z_a-z]+$/.test(arg) ? arg : `'${arg.replaceAll("'", "'\\''")}'`;
404
+
405
+ const printToolboxHeader = (args: string[]) => {
406
+ const now = new Date();
407
+ const pad = (value: number) => String(value).padStart(2, "0");
408
+ const date = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`;
409
+ const time = `${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}`;
410
+ console.log(
411
+ `\n\\* TLAPM version ${TLAPM_VERSION}\n\\* launched at ${date} ${time} with command line:\n\\* ${["tla-ts", "prove", ...args].map(quoteArgument).join(" ")}\n`,
412
+ );
413
+ };
414
+
415
+ const STRICT_EXIT_STATUS = { incomplete: 11, emptyTarget: 12 };
416
+
417
+ const checkStrictly = (result: ModuleObligations, isTargeted: boolean, isSummary: boolean) => {
418
+ const summary = result.summary;
419
+ if (!isSummary) {
420
+ summary.absent.forEach((locus) => console.error(`Missing proof at ${getLocusText(locus)}`));
421
+ summary.omitted.forEach((locus) => console.error(`Omitted proof at ${getLocusText(locus)}`));
422
+ }
423
+ const isIncomplete = summary.absent.length + summary.omitted.length > 0;
424
+ if (isIncomplete) {
425
+ console.error(
426
+ `${getAtPrefix(result.location)}[ERROR]: Proof incomplete in module ${JSON.stringify(result.name)}: ${summary.absent.length} missing, ${summary.omitted.length} omitted proof step(s).`,
427
+ );
428
+ }
429
+ const isEmpty = isTargeted && result.obligations.length === 0;
430
+ if (isEmpty) {
431
+ console.error(
432
+ `${getAtPrefix(result.location)}[ERROR]: No proof obligation found for the selected target.`,
433
+ );
434
+ }
435
+ return [
436
+ ...(isIncomplete ? [STRICT_EXIT_STATUS.incomplete] : []),
437
+ ...(isEmpty ? [STRICT_EXIT_STATUS.emptyTarget] : []),
438
+ ];
439
+ };
440
+
441
+ const TLAPM_FAILURE_STATUS = 3;
442
+
443
+ const generateObligations = (generate: () => ModuleObligations[]) => {
444
+ try {
445
+ return generate();
446
+ } catch (error) {
447
+ if (!(error instanceof TlaProofError)) throw error;
448
+ console.error(` tlapm ending abnormally with ${error.exception}\n`);
449
+ return undefined;
450
+ }
451
+ };
452
+
453
+ const prove = (args: string[]) => {
454
+ if (!args.includes("-N") && !args.includes("--summary")) return proveWithTlapm(args);
455
+ const parsed = PROVE_COMMAND.parse(args);
456
+ const unsupported = parsed.unknown[0];
457
+ if (unsupported !== undefined) {
458
+ console.error(`Error: tla-ts prove does not support the tlapm option ${unsupported}.`);
459
+ return 1;
460
+ }
461
+ if (parsed.incomplete) {
462
+ console.error(`Error: option '${parsed.incomplete.name}' needs an argument.`);
463
+ return 1;
464
+ }
465
+ const nonInteger = parsed.options.find(
466
+ (option) => option.name !== "-I" && option.values.some((value) => !/^-?\d+$/.test(value)),
467
+ );
468
+ if (nonInteger) {
469
+ console.error(`Error: option '${nonInteger.name}' expects an integer.`);
470
+ return 1;
471
+ }
472
+ const files = expandGlobs(parsed.positionals);
473
+ const modulePaths = files.map((path) => (path.endsWith(".tla") ? path : `${path}.tla`));
474
+ if (modulePaths.length === 0) {
475
+ console.error(USAGE);
476
+ return 1;
477
+ }
478
+ const isToolbox = parsed.has("--toolbox") || parsed.has("--line");
479
+ if (isToolbox) printToolboxHeader(args);
480
+ // Like tlapm, the last of --toolbox and --line wins, and a 0 means the whole module.
481
+ const lines = parsed.options.reduce<LineRange>((range, option) => {
482
+ const [start, end] = option.values.map(Number);
483
+ if (option.name === "--toolbox") return { start, end: end === 0 ? Infinity : end };
484
+ if (option.name === "--line") return start === 0 ? WHOLE_MODULE : { start, end: start };
485
+ return range;
486
+ }, WHOLE_MODULE);
487
+ // tlapm searches the current directory and each module's, then its library, then each -I
488
+ // directory, the last given first.
489
+ const tlapmLibrary = getTlapmLibrary();
490
+ const includes = parsed.options.flatMap((option) => (option.name === "-I" ? option.values : []));
491
+ const directories = modulePaths.reduce(
492
+ (found, path) => (found.includes(dirname(path)) ? found : [dirname(path), ...found]),
493
+ [".", ...(tlapmLibrary ? [tlapmLibrary] : []), ...includes.toReversed()],
494
+ );
495
+ // tlapm names each file it reads by joining a search directory and the name, as in ./Module.tla.
496
+ const results = generateObligations(() => {
497
+ const missingIndex = modulePaths.findIndex((path) => !existsSync(path));
498
+ if (missingIndex !== -1) {
499
+ const missing = files[missingIndex];
500
+ console.error(`File "<unknown>":\nError: File ${JSON.stringify(missing)} not found`);
501
+ throw new TlaProofError(`File ${missing} not found`, { failure: "Module.Parser.parse_file" });
502
+ }
503
+ return getObligations(
504
+ modulePaths.map((path) => ({ file: `./${path}`, source: readFileSync(path, "utf8") })),
505
+ (name) =>
506
+ directories.map((directory) => readModule(`${directory}/${name}.tla`)).find(Boolean),
507
+ {
508
+ lines,
509
+ onWarning: (warning) => {
510
+ if (warning.channel === "stdout") return console.log(warning.text);
511
+ const isToolboxMessage =
512
+ warning.channel === "toolbox" || warning.channel === "toolboxOnly";
513
+ if (isToolbox && isToolboxMessage)
514
+ return printToolboxMessage(["type:warning", `msg:${warning.text}`]);
515
+ if (warning.channel !== "toolboxOnly") console.error(warning.text);
516
+ },
517
+ },
518
+ );
519
+ });
520
+ if (!results) return TLAPM_FAILURE_STATUS;
521
+ const failures = results.flatMap((result) => {
522
+ if (parsed.has("--summary")) console.log(formatSummary(result));
523
+ if (isToolbox) {
524
+ result.obligations.forEach((obligation) =>
525
+ printToolboxMessage([
526
+ "type:obligation",
527
+ `id:${obligation.id}`,
528
+ `loc:${obligation.location}`,
529
+ "status:to be proved",
530
+ ...(parsed.has("--printallobs") ? [`obl:${obligation.text}`] : []),
531
+ ]),
532
+ );
533
+ printToolboxMessage(["type:obligationsnumber", `count:${result.obligations.length}`]);
534
+ }
535
+ if (!parsed.has("--strict")) return [];
536
+ return checkStrictly(result, lines.start > 0 || lines.end < Infinity, parsed.has("--summary"));
537
+ });
538
+ return failures.includes(STRICT_EXIT_STATUS.incomplete)
539
+ ? STRICT_EXIT_STATUS.incomplete
540
+ : (failures[0] ?? EXIT_STATUS.success);
541
+ };
542
+
543
+ const run = async (args: string[]) => {
544
+ if (args[0] === "prove") return reportErrors(() => prove(args.slice(1)));
545
+ const parsed = CHECK_COMMAND.parse(args);
546
+ const inputs = getInputPaths(parsed.positionals);
547
+ const isConfigured = parsed.has("-config");
548
+ // A glob also matches modules that only other specs import, which have no configuration.
549
+ const specPaths = inputs
550
+ .map((input) => ({ ...input, path: input.path.replace(/\.cfg$/, ".tla") }))
551
+ .filter(
552
+ (input) =>
553
+ input.path.endsWith(".tla") &&
554
+ (!input.isGlobbed || isConfigured || existsSync(input.path.replace(/\.tla$/, ".cfg"))),
555
+ )
556
+ .map((input) => input.path);
557
+ if (specPaths.length === 0) {
558
+ console.error(USAGE);
559
+ return 1;
560
+ }
561
+ if (isConfigured && specPaths.length > 1) {
562
+ console.error("Error: -config applies to one specification, but several were given.");
563
+ return 1;
564
+ }
565
+ return runEach([...new Set(specPaths)], (path) => checkSpec(path, parsed));
566
+ };
567
+
568
+ export const runCli = async () => {
569
+ process.exitCode = await run(process.argv.slice(2));
570
+ };
package/src/runtime.ts CHANGED
@@ -6,7 +6,7 @@ export interface CheckerRuntime {
6
6
  getBehavior: (state: Value[]) => Value[][];
7
7
  getSpecification: () => Value;
8
8
  counterExample: Value | undefined;
9
- setLivenessSource: (index: number) => void;
9
+ setLivenessSource: (index: number | undefined) => void;
10
10
  getCurrentState: () => Value[] | undefined;
11
11
  getFingerprint: (state: Value[]) => bigint;
12
12
  getRandom: () => JavaRandom;
@@ -24,6 +24,7 @@ export interface CheckerRuntime {
24
24
  properties: Map<string, string>;
25
25
  possibleCounts: Map<string, number>;
26
26
  isStopped: boolean;
27
+ isStarted: boolean;
27
28
  checkDeadlock: boolean;
28
29
  startedAt: number;
29
30
  }
@@ -75,6 +76,7 @@ export const createRuntime = (checkDeadlock: boolean, seed = 0n): CheckerRuntime
75
76
  properties: new Map(),
76
77
  possibleCounts: new Map(),
77
78
  isStopped: false,
79
+ isStarted: false,
78
80
  checkDeadlock,
79
81
  startedAt: Date.now(),
80
82
  };
@@ -1,16 +1,20 @@
1
- import type { Definition, Expression, SourceLocation, SourceRange } from "./ast";
1
+ import {
2
+ isLocallyResolved,
3
+ type Definition,
4
+ type Expression,
5
+ type SourceLocation,
6
+ type SourceRange,
7
+ } from "./ast";
2
8
  import type { ModelConfig } from "./config";
3
9
  import type { InstanceAction } from "./environment";
4
- import { TlaError } from "./errors";
10
+ import { formatRange, TlaError } from "./errors";
5
11
  import {
6
12
  bindDefinitions,
7
13
  bindOperatorArguments,
8
14
  evaluate,
9
15
  forEachBinding,
10
- formatRange,
11
16
  getDefinition,
12
17
  isConstantLevel,
13
- isLocallyResolved,
14
18
  lookupScope,
15
19
  resolveGlobalOperator,
16
20
  type Closure,
@@ -464,10 +468,17 @@ export const getNextActions = (
464
468
  instanceActions: Map<string, InstanceAction>,
465
469
  ) => describe(config, environment, instanceActions).actions;
466
470
 
467
- export const getActionLabel = (action: SpecAction) => {
468
- const parameters = action.parameters.map((parameter) => formatValue(parameter[1]));
469
- return `${action.name === UNNAMED_ACTION ? "Action" : action.name}${parameters.length === 0 ? "" : `(${parameters.join(",")})`} ${formatRange(action.location.range ?? BUILTIN_RANGE)}`;
470
- };
471
+ const formatParameters = (action: SpecAction) =>
472
+ action.parameters.length === 0
473
+ ? ""
474
+ : `(${action.parameters.map((parameter) => formatValue(parameter[1])).join(",")})`;
475
+
476
+ export const getActionLabel = (action: SpecAction) =>
477
+ `${action.name === UNNAMED_ACTION ? "Action" : action.name}${formatParameters(action)} ${formatRange(action.location.range ?? BUILTIN_RANGE)}`;
478
+
479
+ // TLC's Action.getInvocationSignature, which names the action and the values of its parameters.
480
+ export const getActionSignature = (action: SpecAction) =>
481
+ `${action.name}${formatParameters(action)}`;
471
482
 
472
483
  export const getSpecificationValue = (
473
484
  config: ModelConfig,
@@ -28,7 +28,7 @@ const SIGNATURES: Signature[] = [
28
28
  ["Head", 0, [0], [2], [1]],
29
29
  ["Tail", 0, [0], [2], [1]],
30
30
  ["SubSeq", 0, [0, 0, 0], [2, 2, 2], [1, 1, 1]],
31
- ["SelectSeq", 0, [0, 1], [2, 2], [1, 1], [], ["1, 0, 0"]],
31
+ ["SelectSeq", 0, [0, 1], [2, 2], [1, 1], [], ["1,0,0"]],
32
32
  ["IsFiniteSet", 0, [0], [2], [1]],
33
33
  ["Cardinality", 0, [0], [2], [1]],
34
34
  ["IsABag", 0, [0], [2], [1]],
@@ -53,7 +53,7 @@ const SIGNATURES: Signature[] = [
53
53
  [":>", 0, [0, 0], [2, 3], [1, 1]],
54
54
  ["@@", 0, [0, 0], [2, 2], [1, 1]],
55
55
  ["Permutations", 0, [0], [2], [1]],
56
- ["SortSeq", 0, [0, 2], [2, 2], [1, 1], [], ["1, 0, 0", "1, 0, 1"]],
56
+ ["SortSeq", 0, [0, 2], [2, 2], [1, 1], [], ["1,0,0", "1,0,1"]],
57
57
  ["RandomElement", 0, [0], [3], [1]],
58
58
  ["Any", 0, [], [], []],
59
59
  ["ToString", 0, [0], [2], [1]],
@@ -61,7 +61,7 @@ const SIGNATURES: Signature[] = [
61
61
  ["AssertEq", 0, [0, 0], [2, 2], [1, 1]],
62
62
  ["AssertError", 0, [0, 0], [2, 3], [1, 0]],
63
63
  ["TLCGetOrDefault", 0, [0, 0], [3, 3], [0, 0]],
64
- ["TLCGetAndSet", 0, [0, 2, 0, 0], [3, 3, 3, 3], [0, 0, 0, 0], [], ["1, 2, 1"]],
64
+ ["TLCGetAndSet", 0, [0, 2, 0, 0], [3, 3, 3, 3], [0, 0, 0, 0], [], ["1,2,1"]],
65
65
  ["Trace", 0, [], [], []],
66
66
  ["CounterExample", 0, [], [], []],
67
67
  ["ToTrace", 0, [0], [3], [0]],