tla-ts 0.0.2 → 0.0.3-dev.037ac3b

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 (63) hide show
  1. package/README.md +78 -12
  2. package/dist/index.cjs +1 -1
  3. package/dist/index.d.cts +60 -1
  4. package/dist/index.d.ts +60 -1
  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 +21 -2
  11. package/dist/run-cli.js +21 -2
  12. package/dist/transfer.cjs +27 -15
  13. package/dist/transfer.js +27 -15
  14. package/package.json +3 -1
  15. package/src/ast.ts +134 -4
  16. package/src/check.ts +280 -80
  17. package/src/cli-options.ts +64 -0
  18. package/src/codegen.ts +9 -19
  19. package/src/dependencies.ts +2 -2
  20. package/src/environment.ts +75 -16
  21. package/src/errors.ts +46 -3
  22. package/src/evaluate.ts +88 -143
  23. package/src/exit-codes.ts +21 -43
  24. package/src/fingerprints.ts +46 -11
  25. package/src/instances.ts +15 -14
  26. package/src/levels.ts +8 -8
  27. package/src/lexer.ts +11 -2
  28. package/src/live-check.ts +692 -0
  29. package/src/liveness.ts +54 -535
  30. package/src/obligation-action.ts +384 -0
  31. package/src/obligation-anon.ts +575 -0
  32. package/src/obligation-deref.ts +637 -0
  33. package/src/obligation-expression.ts +1060 -0
  34. package/src/obligation-format.ts +406 -0
  35. package/src/obligation-generate.ts +1074 -0
  36. package/src/obligation-levels.ts +329 -0
  37. package/src/obligation-module.ts +1042 -0
  38. package/src/obligation-printer.ts +889 -0
  39. package/src/obligation-proof.ts +76 -0
  40. package/src/obligation-source.ts +1084 -0
  41. package/src/obligation-tuples.ts +184 -0
  42. package/src/obligations.ts +316 -0
  43. package/src/parallel-worker.ts +166 -210
  44. package/src/parallel.ts +76 -35
  45. package/src/parser.ts +297 -53
  46. package/src/resolve.ts +16 -15
  47. package/src/run-cli.ts +353 -40
  48. package/src/runtime.ts +3 -1
  49. package/src/spec-description.ts +18 -6
  50. package/src/standard-levels.ts +3 -3
  51. package/src/standard-modules.ts +2 -7
  52. package/src/state-graph.ts +157 -0
  53. package/src/subexpressions.ts +10 -10
  54. package/src/successors.ts +77 -13
  55. package/src/symmetry.ts +14 -2
  56. package/src/tableau.ts +50 -23
  57. package/src/tlc-ext.ts +29 -12
  58. package/src/tlc-module.ts +9 -28
  59. package/src/tlc-order.ts +17 -3
  60. package/src/tlc-random.ts +9 -6
  61. package/src/tlc-summary.ts +20 -5
  62. package/src/transfer.ts +22 -1
  63. package/src/values.ts +118 -34
package/src/resolve.ts CHANGED
@@ -1,20 +1,21 @@
1
- import type {
2
- AssumeProve,
3
- Bound,
4
- BoundPattern,
5
- Definition,
6
- Expression,
7
- Instance,
8
- Module,
9
- NewSymbol,
10
- OperatorParam,
11
- Proof,
12
- ProofStep,
13
- SourceLocation,
14
- Theorem,
1
+ import {
2
+ getChildren,
3
+ isLocallyResolved,
4
+ type AssumeProve,
5
+ type Bound,
6
+ type BoundPattern,
7
+ type Definition,
8
+ type Expression,
9
+ type Instance,
10
+ type Module,
11
+ type NewSymbol,
12
+ type OperatorParam,
13
+ type Proof,
14
+ type ProofStep,
15
+ type SourceLocation,
16
+ type Theorem,
15
17
  } from "./ast";
16
18
  import { TlaSyntaxError } from "./errors";
17
- import { getChildren, isLocallyResolved } from "./evaluate";
18
19
 
19
20
  export interface ModuleSymbol {
20
21
  key: string;
package/src/run-cli.ts CHANGED
@@ -1,19 +1,40 @@
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
13
  import type { CheckResult, CheckStatus, 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
+ getErrorExitCode,
18
+ TlaConfigError,
19
+ TlaError,
20
+ TlaEvaluationError,
21
+ TlaProofError,
22
+ TlaSyntaxError,
23
+ } from "./errors";
7
24
  import { EXIT_STATUS } from "./exit-codes";
25
+ import type { LineRange } from "./obligation-generate";
26
+ import { getAtPrefix, getLocusText } from "./obligation-expression";
27
+ import { formatSummary, getObligations, WHOLE_MODULE, type ModuleObligations } from "./obligations";
8
28
  import { check } from "./parallel";
9
- import { prettyPrint } from "./pretty-print";
29
+ import { parseModule } from "./parser";
30
+ import type { StateDump } from "./state-graph";
10
31
  import {
11
32
  formatProbability,
12
33
  getActualProbability,
13
34
  getOptimisticProbability,
14
35
  getOutDegreeSummary,
15
36
  } from "./tlc-summary";
16
- import { formatValue, type Value } from "./values";
37
+ import { formatState, type Value } from "./values";
17
38
 
18
39
  const EXIT_CODES: Record<CheckStatus, number> = {
19
40
  success: EXIT_STATUS.success,
@@ -26,27 +47,79 @@ const EXIT_CODES: Record<CheckStatus, number> = {
26
47
  error: EXIT_STATUS.error,
27
48
  };
28
49
 
29
- const USAGE =
30
- "Usage: tla-ts <Spec.tla> [-config <Spec.cfg>] [-deadlock] [-lncheck <final|default>] [-seed <num>] [-workers <count|auto>]";
50
+ const CHECK_COMMAND = defineCommand("tla-ts <Spec.tla|Spec.cfg|glob>... {options}", [
51
+ { flag: "-config <Spec.cfg>" },
52
+ { flag: "-deadlock" },
53
+ // Like TLC, -dump takes a format only when the next argument starts with dot and a file follows.
54
+ {
55
+ flag: "-dump [<format>] <file>",
56
+ getArity: (rest) => (rest.length > 1 && rest[0].startsWith("dot") ? 2 : 1),
57
+ },
58
+ { flag: "-lncheck <final|default>" },
59
+ { flag: "-seed <num>" },
60
+ { flag: "-workers <count|auto>" },
61
+ ]);
62
+
63
+ const PROVE_COMMAND = defineCommand("tla-ts prove {options} <Module.tla|glob>...", [
64
+ { flag: "-N", isRequired: true },
65
+ { flag: "--toolbox <start> <end>" },
66
+ { flag: "--line <num>" },
67
+ { flag: "--printallobs" },
68
+ { flag: "--summary" },
69
+ { flag: "--strict" },
70
+ { flag: "-I <directory>", isRepeatable: true },
71
+ ]);
72
+
73
+ const USAGE = [
74
+ `Usage: ${CHECK_COMMAND.usage}`,
75
+ ` ${PROVE_COMMAND.usage}`,
76
+ " tla-ts prove [<tlapm option>]... <Module.tla|glob>...",
77
+ ].join("\n");
78
+
79
+ const GLOB_CHARACTERS = /[*?[{]/;
80
+
81
+ interface InputPath {
82
+ path: string;
83
+ isGlobbed: boolean;
84
+ }
85
+
86
+ const getInputPaths = (paths: string[]): InputPath[] =>
87
+ paths.flatMap((arg): InputPath[] =>
88
+ GLOB_CHARACTERS.test(arg)
89
+ ? globSync(arg)
90
+ .sort()
91
+ .map((path) => ({ path, isGlobbed: true }))
92
+ : [{ path: arg, isGlobbed: false }],
93
+ );
31
94
 
32
95
  const isJavaLong = (text: string) =>
33
96
  /^[+-]?\d+$/.test(text) && BigInt.asIntN(64, BigInt(text)) === BigInt(text);
34
97
 
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);
98
+ const getWorkerCount = (values: string[] | undefined) => {
99
+ if (!values) return 1;
100
+ return values[0] === "auto"
101
+ ? availableParallelism()
102
+ : Math.max(1, Number.parseInt(values[0], 10) || 1);
40
103
  };
41
104
 
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("");
105
+ const printState = (state: Record<string, Value>) => console.log(formatState(state));
106
+
107
+ const UNSUPPORTED_DUMP_FORMATS = ["constrained", "stuttering", "strict"];
108
+
109
+ // TLC names the file of a -dump by its format unless the name already ends that way.
110
+ const getDumpPath = (path: string, extension: string) =>
111
+ path.endsWith(extension) ? path : `${path}${extension}`;
112
+
113
+ const getDump = (values: string[]): StateDump => {
114
+ if (values.length === 1) return { path: getDumpPath(values[0], ".dump") };
115
+ const format = values[0].toLowerCase();
116
+ return {
117
+ path: getDumpPath(values[1], ".dot"),
118
+ dot: true,
119
+ colorize: format.includes("colorize"),
120
+ actionLabels: format.includes("actionlabels"),
121
+ snapshot: format.includes("snapshot"),
122
+ };
50
123
  };
51
124
 
52
125
  const printTrace = (trace: TraceStep[], heading = "Error: The behavior up to this point is:") => {
@@ -57,6 +130,11 @@ const printTrace = (trace: TraceStep[], heading = "Error: The behavior up to thi
57
130
  });
58
131
  };
59
132
 
133
+ const getTemporalHeadline = (names: string[]) =>
134
+ names.length === 1
135
+ ? `Error: Temporal property ${names[0]} was violated.\n`
136
+ : `Error: Temporal properties ${names.slice(0, -1).join(", ")}${names.length > 2 ? "," : ""} and ${names[names.length - 1]} were violated.\n`;
137
+
60
138
  const printResult = (result: CheckResult) => {
61
139
  if (result.failure) {
62
140
  console.log(`Error: ${result.failure.message}`);
@@ -84,10 +162,10 @@ const printResult = (result: CheckResult) => {
84
162
  "invariant-violation": isInitial
85
163
  ? `Error: Invariant ${name} is violated by the initial state:`
86
164
  : `Error: Invariant ${name} is violated.`,
87
- "property-violation": `Error: Property ${name} is violated.`,
165
+ "property-violation": getTemporalHeadline(violation.properties ?? [name]),
88
166
  "liveness-violation":
89
167
  loopStart !== undefined
90
- ? `Error: Temporal property ${name} was violated.\n`
168
+ ? getTemporalHeadline(violation.properties ?? [name])
91
169
  : isInitial
92
170
  ? `Error: Property ${name} is violated by the initial state:`
93
171
  : `Error: Action property ${name} is violated.`,
@@ -96,6 +174,8 @@ const printResult = (result: CheckResult) => {
96
174
  if (violation.counts) console.log(violation.counts);
97
175
  console.log(headline);
98
176
  if (isInitial) printState(violation.trace[0].state);
177
+ else if (result.status === "property-violation")
178
+ printTrace(violation.trace, "Error: The following behavior constitutes a counter-example:\n");
99
179
  else if (loopStart === undefined) printTrace(violation.trace);
100
180
  else {
101
181
  printTrace(violation.trace, "Error: The following behavior constitutes a counter-example:\n");
@@ -130,26 +210,29 @@ const printResult = (result: CheckResult) => {
130
210
  if (outDegree) console.log(outDegree);
131
211
  };
132
212
 
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
- }
213
+ const checkSpec = async (specPath: string, args: ParsedArgs) => {
139
214
  if (!existsSync(specPath)) {
140
215
  console.error(`Cannot find the specification file ${specPath}`);
141
216
  return EXIT_STATUS.configParseError;
142
217
  }
143
- const configFlag = args.indexOf("-config");
144
- const configPath = configFlag === -1 ? specPath.replace(/\.tla$/, ".cfg") : args[configFlag + 1];
218
+ const source = readFileSync(specPath, "utf8");
219
+ const fileName = basename(specPath, ".tla");
220
+ const moduleName = parseModule(source).name;
221
+ if (moduleName !== fileName) {
222
+ throw new TlaSyntaxError(
223
+ `File name '${fileName}' does not match the name '${moduleName}' of the top level module it contains.`,
224
+ );
225
+ }
226
+ const configPath =
227
+ args.get("-config")?.[0] ??
228
+ (args.has("-config") ? undefined : specPath.replace(/\.tla$/, ".cfg"));
145
229
  if (!configPath || !existsSync(configPath)) {
146
230
  console.error(`Cannot find the configuration file ${configPath ?? ""}`);
147
231
  return EXIT_STATUS.configParseError;
148
232
  }
149
233
  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];
234
+ if (args.has("-deadlock")) config.checkDeadlock = false;
235
+ const seed = args.has("-seed") ? args.get("-seed")?.[0] : "0";
153
236
  if (seed === undefined) {
154
237
  console.error("Error: seed required.");
155
238
  return 1;
@@ -158,19 +241,31 @@ const run = async (args: string[]) => {
158
241
  console.error(`Error: An integer for seed required. But encountered ${seed}`);
159
242
  return 1;
160
243
  }
161
- const livenessFlag = args.indexOf("-lncheck");
162
- const livenessCheck = livenessFlag === -1 ? "default" : args[livenessFlag + 1]?.toLowerCase();
244
+ const livenessCheck = args.has("-lncheck") ? args.get("-lncheck")?.[0]?.toLowerCase() : "default";
163
245
  if (livenessCheck === undefined) {
164
246
  console.error("Error: expect a strategy such as final for -lncheck option.");
165
247
  return 1;
166
248
  }
249
+ const dumpValues = args.get("-dump");
250
+ if (dumpValues?.length === 0) {
251
+ console.error("Error: A file name for dumping states required.");
252
+ return 1;
253
+ }
254
+ const unsupportedFormat =
255
+ dumpValues?.length === 2 &&
256
+ UNSUPPORTED_DUMP_FORMATS.find((format) => dumpValues[0].toLowerCase().includes(format));
257
+ if (unsupportedFormat) {
258
+ console.error(`Error: tla-ts does not support the -dump format ${unsupportedFormat}.`);
259
+ return 1;
260
+ }
167
261
  const directory = dirname(specPath);
168
262
  console.log(`Checking ${basename(specPath)} with ${basename(configPath)}`);
169
263
  const result = await check({
170
- workers: getWorkerCount(args),
264
+ workers: getWorkerCount(args.get("-workers")),
171
265
  livenessCheck: ["final", "seqfinal", "off"].includes(livenessCheck) ? "final" : "default",
172
266
  seed: BigInt(seed),
173
- source: readFileSync(specPath, "utf8"),
267
+ dump: dumpValues && getDump(dumpValues),
268
+ source,
174
269
  config,
175
270
  onPause: () => readSync(0, Buffer.alloc(1)),
176
271
  loadModule: (name) => {
@@ -199,12 +294,230 @@ const printError = (error: TlaError) => {
199
294
  console.error(`${error.name}: ${error.message}`);
200
295
  };
201
296
 
202
- export const runCli = async () => {
297
+ // Prints a TlaError and returns its exit code.
298
+ const reportErrors = async (run: () => number | Promise<number>) => {
203
299
  try {
204
- process.exitCode = await run(process.argv.slice(2));
300
+ return await run();
205
301
  } catch (error) {
206
302
  if (!(error instanceof TlaError)) throw error;
207
303
  printError(error);
208
- process.exitCode = getErrorExitCode(error);
304
+ return getErrorExitCode(error);
305
+ }
306
+ };
307
+
308
+ // Runs each path in turn, so an error in one leaves the others to report. The exit code is the
309
+ // first that is not success.
310
+ const runEach = async (paths: string[], runPath: (path: string) => number | Promise<number>) => {
311
+ const exitCodes: number[] = [];
312
+ for (const [index, path] of paths.entries()) {
313
+ if (index > 0) console.log("");
314
+ exitCodes.push(await reportErrors(() => runPath(path)));
209
315
  }
316
+ return exitCodes.find((exitCode) => exitCode !== EXIT_STATUS.success) ?? EXIT_STATUS.success;
317
+ };
318
+
319
+ // tlapm installs its standard library, with modules such as TLAPS, at lib/tlapm/stdlib beside
320
+ // bin/tlapm.
321
+ const getTlapmPaths = () =>
322
+ (process.env.PATH ?? "")
323
+ .split(delimiter)
324
+ .map((directory) => join(directory, "tlapm"))
325
+ .filter((path) => existsSync(path));
326
+
327
+ const getTlapmLibrary = () =>
328
+ getTlapmPaths()
329
+ .map((path) => join(dirname(dirname(realpathSync(path))), "lib/tlapm/stdlib"))
330
+ .find((path) => existsSync(path));
331
+
332
+ const expandGlobs = (paths: string[]) =>
333
+ paths.flatMap((path) => (GLOB_CHARACTERS.test(path) ? globSync(path).sort() : [path]));
334
+
335
+ const proveWithTlapm = (args: string[]) => {
336
+ const tlapm = getTlapmPaths()[0];
337
+ if (tlapm === undefined) {
338
+ console.error(
339
+ "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.",
340
+ );
341
+ return 1;
342
+ }
343
+ return spawnSync(tlapm, expandGlobs(args), { stdio: "inherit" }).status ?? 1;
344
+ };
345
+
346
+ const readModule = (path: string) =>
347
+ existsSync(path) ? { file: path, source: readFileSync(path, "utf8") } : undefined;
348
+
349
+ // A message of tlapm's toolbox protocol, which it writes to stderr.
350
+ const printToolboxMessage = (fields: string[]) =>
351
+ console.error(`@!!BEGIN\n${fields.map((field) => `@!!${field}\n`).join("")}@!!END\n`);
352
+
353
+ const TLAPM_VERSION = "5f5037f";
354
+
355
+ const quoteArgument = (arg: string) =>
356
+ /^[+,\-./0-9:=@A-Z_a-z]+$/.test(arg) ? arg : `'${arg.replaceAll("'", "'\\''")}'`;
357
+
358
+ const printToolboxHeader = (args: string[]) => {
359
+ const now = new Date();
360
+ const pad = (value: number) => String(value).padStart(2, "0");
361
+ const date = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`;
362
+ const time = `${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}`;
363
+ console.log(
364
+ `\n\\* TLAPM version ${TLAPM_VERSION}\n\\* launched at ${date} ${time} with command line:\n\\* ${["tla-ts", "prove", ...args].map(quoteArgument).join(" ")}\n`,
365
+ );
366
+ };
367
+
368
+ const STRICT_EXIT_STATUS = { incomplete: 11, emptyTarget: 12 };
369
+
370
+ const checkStrictly = (result: ModuleObligations, isTargeted: boolean, isSummary: boolean) => {
371
+ const summary = result.summary;
372
+ if (!isSummary) {
373
+ summary.absent.forEach((locus) => console.error(`Missing proof at ${getLocusText(locus)}`));
374
+ summary.omitted.forEach((locus) => console.error(`Omitted proof at ${getLocusText(locus)}`));
375
+ }
376
+ const isIncomplete = summary.absent.length + summary.omitted.length > 0;
377
+ if (isIncomplete) {
378
+ console.error(
379
+ `${getAtPrefix(result.location)}[ERROR]: Proof incomplete in module ${JSON.stringify(result.name)}: ${summary.absent.length} missing, ${summary.omitted.length} omitted proof step(s).`,
380
+ );
381
+ }
382
+ const isEmpty = isTargeted && result.obligations.length === 0;
383
+ if (isEmpty) {
384
+ console.error(
385
+ `${getAtPrefix(result.location)}[ERROR]: No proof obligation found for the selected target.`,
386
+ );
387
+ }
388
+ return [
389
+ ...(isIncomplete ? [STRICT_EXIT_STATUS.incomplete] : []),
390
+ ...(isEmpty ? [STRICT_EXIT_STATUS.emptyTarget] : []),
391
+ ];
392
+ };
393
+
394
+ const TLAPM_FAILURE_STATUS = 3;
395
+
396
+ const generateObligations = (generate: () => ModuleObligations[]) => {
397
+ try {
398
+ return generate();
399
+ } catch (error) {
400
+ if (!(error instanceof TlaProofError)) throw error;
401
+ console.error(` tlapm ending abnormally with ${error.exception}\n`);
402
+ return undefined;
403
+ }
404
+ };
405
+
406
+ const prove = (args: string[]) => {
407
+ if (!args.includes("-N") && !args.includes("--summary")) return proveWithTlapm(args);
408
+ const parsed = PROVE_COMMAND.parse(args);
409
+ const unsupported = parsed.unknown[0];
410
+ if (unsupported !== undefined) {
411
+ console.error(`Error: tla-ts prove does not support the tlapm option ${unsupported}.`);
412
+ return 1;
413
+ }
414
+ if (parsed.incomplete) {
415
+ console.error(`Error: option '${parsed.incomplete.name}' needs an argument.`);
416
+ return 1;
417
+ }
418
+ const nonInteger = parsed.options.find(
419
+ (option) => option.name !== "-I" && option.values.some((value) => !/^-?\d+$/.test(value)),
420
+ );
421
+ if (nonInteger) {
422
+ console.error(`Error: option '${nonInteger.name}' expects an integer.`);
423
+ return 1;
424
+ }
425
+ const files = expandGlobs(parsed.positionals);
426
+ const modulePaths = files.map((path) => (path.endsWith(".tla") ? path : `${path}.tla`));
427
+ if (modulePaths.length === 0) {
428
+ console.error(USAGE);
429
+ return 1;
430
+ }
431
+ const isToolbox = parsed.has("--toolbox") || parsed.has("--line");
432
+ if (isToolbox) printToolboxHeader(args);
433
+ // Like tlapm, the last of --toolbox and --line wins, and a 0 means the whole module.
434
+ const lines = parsed.options.reduce<LineRange>((range, option) => {
435
+ const [start, end] = option.values.map(Number);
436
+ if (option.name === "--toolbox") return { start, end: end === 0 ? Infinity : end };
437
+ if (option.name === "--line") return start === 0 ? WHOLE_MODULE : { start, end: start };
438
+ return range;
439
+ }, WHOLE_MODULE);
440
+ // tlapm searches the current directory and each module's, then its library, then each -I
441
+ // directory, the last given first.
442
+ const tlapmLibrary = getTlapmLibrary();
443
+ const includes = parsed.options.flatMap((option) => (option.name === "-I" ? option.values : []));
444
+ const directories = modulePaths.reduce(
445
+ (found, path) => (found.includes(dirname(path)) ? found : [dirname(path), ...found]),
446
+ [".", ...(tlapmLibrary ? [tlapmLibrary] : []), ...includes.toReversed()],
447
+ );
448
+ // tlapm names each file it reads by joining a search directory and the name, as in ./Module.tla.
449
+ const results = generateObligations(() => {
450
+ const missingIndex = modulePaths.findIndex((path) => !existsSync(path));
451
+ if (missingIndex !== -1) {
452
+ const missing = files[missingIndex];
453
+ console.error(`File "<unknown>":\nError: File ${JSON.stringify(missing)} not found`);
454
+ throw new TlaProofError(`File ${missing} not found`, { failure: "Module.Parser.parse_file" });
455
+ }
456
+ return getObligations(
457
+ modulePaths.map((path) => ({ file: `./${path}`, source: readFileSync(path, "utf8") })),
458
+ (name) =>
459
+ directories.map((directory) => readModule(`${directory}/${name}.tla`)).find(Boolean),
460
+ {
461
+ lines,
462
+ onWarning: (warning) => {
463
+ if (warning.channel === "stdout") return console.log(warning.text);
464
+ const isToolboxMessage =
465
+ warning.channel === "toolbox" || warning.channel === "toolboxOnly";
466
+ if (isToolbox && isToolboxMessage)
467
+ return printToolboxMessage(["type:warning", `msg:${warning.text}`]);
468
+ if (warning.channel !== "toolboxOnly") console.error(warning.text);
469
+ },
470
+ },
471
+ );
472
+ });
473
+ if (!results) return TLAPM_FAILURE_STATUS;
474
+ const failures = results.flatMap((result) => {
475
+ if (parsed.has("--summary")) console.log(formatSummary(result));
476
+ if (isToolbox) {
477
+ result.obligations.forEach((obligation) =>
478
+ printToolboxMessage([
479
+ "type:obligation",
480
+ `id:${obligation.id}`,
481
+ `loc:${obligation.location}`,
482
+ "status:to be proved",
483
+ ...(parsed.has("--printallobs") ? [`obl:${obligation.text}`] : []),
484
+ ]),
485
+ );
486
+ printToolboxMessage(["type:obligationsnumber", `count:${result.obligations.length}`]);
487
+ }
488
+ if (!parsed.has("--strict")) return [];
489
+ return checkStrictly(result, lines.start > 0 || lines.end < Infinity, parsed.has("--summary"));
490
+ });
491
+ return failures.includes(STRICT_EXIT_STATUS.incomplete)
492
+ ? STRICT_EXIT_STATUS.incomplete
493
+ : (failures[0] ?? EXIT_STATUS.success);
494
+ };
495
+
496
+ const run = async (args: string[]) => {
497
+ if (args[0] === "prove") return reportErrors(() => prove(args.slice(1)));
498
+ const parsed = CHECK_COMMAND.parse(args);
499
+ const inputs = getInputPaths(parsed.positionals);
500
+ const isConfigured = parsed.has("-config");
501
+ // A glob also matches modules that only other specs import, which have no configuration.
502
+ const specPaths = inputs
503
+ .map((input) => ({ ...input, path: input.path.replace(/\.cfg$/, ".tla") }))
504
+ .filter(
505
+ (input) =>
506
+ input.path.endsWith(".tla") &&
507
+ (!input.isGlobbed || isConfigured || existsSync(input.path.replace(/\.tla$/, ".cfg"))),
508
+ )
509
+ .map((input) => input.path);
510
+ if (specPaths.length === 0) {
511
+ console.error(USAGE);
512
+ return 1;
513
+ }
514
+ if (isConfigured && specPaths.length > 1) {
515
+ console.error("Error: -config applies to one specification, but several were given.");
516
+ return 1;
517
+ }
518
+ return runEach([...new Set(specPaths)], (path) => checkSpec(path, parsed));
519
+ };
520
+
521
+ export const runCli = async () => {
522
+ process.exitCode = await run(process.argv.slice(2));
210
523
  };
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,4 +1,10 @@
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
10
  import { TlaError } from "./errors";
@@ -10,7 +16,6 @@ import {
10
16
  formatRange,
11
17
  getDefinition,
12
18
  isConstantLevel,
13
- isLocallyResolved,
14
19
  lookupScope,
15
20
  resolveGlobalOperator,
16
21
  type Closure,
@@ -464,10 +469,17 @@ export const getNextActions = (
464
469
  instanceActions: Map<string, InstanceAction>,
465
470
  ) => describe(config, environment, instanceActions).actions;
466
471
 
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
- };
472
+ const formatParameters = (action: SpecAction) =>
473
+ action.parameters.length === 0
474
+ ? ""
475
+ : `(${action.parameters.map((parameter) => formatValue(parameter[1])).join(",")})`;
476
+
477
+ export const getActionLabel = (action: SpecAction) =>
478
+ `${action.name === UNNAMED_ACTION ? "Action" : action.name}${formatParameters(action)} ${formatRange(action.location.range ?? BUILTIN_RANGE)}`;
479
+
480
+ // TLC's Action.getInvocationSignature, which names the action and the values of its parameters.
481
+ export const getActionSignature = (action: SpecAction) =>
482
+ `${action.name}${formatParameters(action)}`;
471
483
 
472
484
  export const getSpecificationValue = (
473
485
  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]],
@@ -40,6 +40,7 @@ import {
40
40
  isEnumerable,
41
41
  isFiniteSet,
42
42
  isFunctionValue,
43
+ isReducible,
43
44
  isSetValue,
44
45
  toFiniteSet,
45
46
  unionSorted,
@@ -47,7 +48,7 @@ import {
47
48
  createEnumeratedSet,
48
49
  EMPTY_SET,
49
50
  isEnumeratedSet,
50
- type IntervalValue,
51
+ type ReducibleSet,
51
52
  type MixedSetValue,
52
53
  type SetOperationValue,
53
54
  type SetValue,
@@ -75,12 +76,6 @@ const unionInTree = (sets: SetValue[], start: number, end: number): SetValue =>
75
76
 
76
77
  const SET_OPERATORS: SetOperationValue["operator"][] = ["\\cup", "\\cap", "\\"];
77
78
 
78
- type ReducibleSet = SetValue | MixedSetValue | IntervalValue;
79
-
80
- const isReducible = (value: Value): value is ReducibleSet =>
81
- typeof value === "object" &&
82
- (value.kind === "Set" || value.kind === "MixedSet" || value.kind === "Interval");
83
-
84
79
  const isMixedSet = (value: Value) => typeof value === "object" && value.kind === "MixedSet";
85
80
 
86
81
  const getReducibleElements = (set: ReducibleSet) =>