tla-ts 0.0.2 → 0.0.3-dev.252cf06

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 (57) hide show
  1. package/README.md +73 -11
  2. package/dist/index.cjs +1 -1
  3. package/dist/index.d.cts +52 -1
  4. package/dist/index.d.ts +52 -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 +19 -15
  13. package/dist/transfer.js +19 -15
  14. package/package.json +3 -1
  15. package/src/ast.ts +134 -4
  16. package/src/check.ts +120 -40
  17. package/src/cli-options.ts +58 -0
  18. package/src/codegen.ts +1 -3
  19. package/src/dependencies.ts +2 -2
  20. package/src/environment.ts +10 -10
  21. package/src/errors.ts +42 -1
  22. package/src/evaluate.ts +57 -114
  23. package/src/exit-codes.ts +20 -30
  24. package/src/fingerprints.ts +46 -11
  25. package/src/instances.ts +12 -11
  26. package/src/levels.ts +8 -8
  27. package/src/lexer.ts +11 -2
  28. package/src/live-check.ts +710 -0
  29. package/src/liveness.ts +5 -523
  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 +73 -35
  45. package/src/parser.ts +297 -53
  46. package/src/resolve.ts +16 -15
  47. package/src/run-cli.ts +304 -29
  48. package/src/runtime.ts +1 -1
  49. package/src/spec-description.ts +7 -2
  50. package/src/standard-levels.ts +3 -3
  51. package/src/subexpressions.ts +10 -10
  52. package/src/successors.ts +17 -9
  53. package/src/symmetry.ts +14 -2
  54. package/src/tlc-ext.ts +2 -10
  55. package/src/tlc-order.ts +17 -3
  56. package/src/transfer.ts +22 -1
  57. package/src/values.ts +59 -23
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,10 +1,29 @@
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
+ } from "./errors";
7
23
  import { EXIT_STATUS } from "./exit-codes";
24
+ import type { LineRange } from "./obligation-generate";
25
+ import { getAtPrefix, getLocusText } from "./obligation-expression";
26
+ import { formatSummary, getObligations, WHOLE_MODULE, type ModuleObligations } from "./obligations";
8
27
  import { check } from "./parallel";
9
28
  import { prettyPrint } from "./pretty-print";
10
29
  import {
@@ -26,17 +45,54 @@ const EXIT_CODES: Record<CheckStatus, number> = {
26
45
  error: EXIT_STATUS.error,
27
46
  };
28
47
 
29
- const USAGE =
30
- "Usage: tla-ts <Spec.tla> [-config <Spec.cfg>] [-deadlock] [-lncheck <final|default>] [-seed <num>] [-workers <count|auto>]";
48
+ const CHECK_COMMAND = defineCommand("tla-ts <Spec.tla|Spec.cfg|glob>... {options}", [
49
+ { flag: "-config <Spec.cfg>" },
50
+ { flag: "-deadlock" },
51
+ { flag: "-lncheck <final|default>" },
52
+ { flag: "-seed <num>" },
53
+ { flag: "-workers <count|auto>" },
54
+ ]);
55
+
56
+ const PROVE_COMMAND = defineCommand("tla-ts prove {options} <Module.tla|glob>...", [
57
+ { flag: "-N", isRequired: true },
58
+ { flag: "--toolbox <start> <end>" },
59
+ { flag: "--line <num>" },
60
+ { flag: "--printallobs" },
61
+ { flag: "--summary" },
62
+ { flag: "--strict" },
63
+ { flag: "-I <directory>", isRepeatable: true },
64
+ ]);
65
+
66
+ const USAGE = [
67
+ `Usage: ${CHECK_COMMAND.usage}`,
68
+ ` ${PROVE_COMMAND.usage}`,
69
+ " tla-ts prove [<tlapm option>]... <Module.tla|glob>...",
70
+ ].join("\n");
71
+
72
+ const GLOB_CHARACTERS = /[*?[{]/;
73
+
74
+ interface InputPath {
75
+ path: string;
76
+ isGlobbed: boolean;
77
+ }
78
+
79
+ const getInputPaths = (paths: string[]): InputPath[] =>
80
+ paths.flatMap((arg): InputPath[] =>
81
+ GLOB_CHARACTERS.test(arg)
82
+ ? globSync(arg)
83
+ .sort()
84
+ .map((path) => ({ path, isGlobbed: true }))
85
+ : [{ path: arg, isGlobbed: false }],
86
+ );
31
87
 
32
88
  const isJavaLong = (text: string) =>
33
89
  /^[+-]?\d+$/.test(text) && BigInt.asIntN(64, BigInt(text)) === BigInt(text);
34
90
 
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);
91
+ const getWorkerCount = (values: string[] | undefined) => {
92
+ if (!values) return 1;
93
+ return values[0] === "auto"
94
+ ? availableParallelism()
95
+ : Math.max(1, Number.parseInt(values[0], 10) || 1);
40
96
  };
41
97
 
42
98
  const printState = (state: Record<string, Value>) => {
@@ -57,6 +113,11 @@ const printTrace = (trace: TraceStep[], heading = "Error: The behavior up to thi
57
113
  });
58
114
  };
59
115
 
116
+ const getTemporalHeadline = (names: string[]) =>
117
+ names.length === 1
118
+ ? `Error: Temporal property ${names[0]} was violated.\n`
119
+ : `Error: Temporal properties ${names.slice(0, -1).join(", ")}${names.length > 2 ? "," : ""} and ${names[names.length - 1]} were violated.\n`;
120
+
60
121
  const printResult = (result: CheckResult) => {
61
122
  if (result.failure) {
62
123
  console.log(`Error: ${result.failure.message}`);
@@ -84,10 +145,10 @@ const printResult = (result: CheckResult) => {
84
145
  "invariant-violation": isInitial
85
146
  ? `Error: Invariant ${name} is violated by the initial state:`
86
147
  : `Error: Invariant ${name} is violated.`,
87
- "property-violation": `Error: Property ${name} is violated.`,
148
+ "property-violation": getTemporalHeadline(violation.properties ?? [name]),
88
149
  "liveness-violation":
89
150
  loopStart !== undefined
90
- ? `Error: Temporal property ${name} was violated.\n`
151
+ ? getTemporalHeadline(violation.properties ?? [name])
91
152
  : isInitial
92
153
  ? `Error: Property ${name} is violated by the initial state:`
93
154
  : `Error: Action property ${name} is violated.`,
@@ -96,6 +157,8 @@ const printResult = (result: CheckResult) => {
96
157
  if (violation.counts) console.log(violation.counts);
97
158
  console.log(headline);
98
159
  if (isInitial) printState(violation.trace[0].state);
160
+ else if (result.status === "property-violation")
161
+ printTrace(violation.trace, "Error: The following behavior constitutes a counter-example:\n");
99
162
  else if (loopStart === undefined) printTrace(violation.trace);
100
163
  else {
101
164
  printTrace(violation.trace, "Error: The following behavior constitutes a counter-example:\n");
@@ -130,26 +193,21 @@ const printResult = (result: CheckResult) => {
130
193
  if (outDegree) console.log(outDegree);
131
194
  };
132
195
 
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
- }
196
+ const checkSpec = async (specPath: string, args: ParsedArgs) => {
139
197
  if (!existsSync(specPath)) {
140
198
  console.error(`Cannot find the specification file ${specPath}`);
141
199
  return EXIT_STATUS.configParseError;
142
200
  }
143
- const configFlag = args.indexOf("-config");
144
- const configPath = configFlag === -1 ? specPath.replace(/\.tla$/, ".cfg") : args[configFlag + 1];
201
+ const configPath =
202
+ args.get("-config")?.[0] ??
203
+ (args.has("-config") ? undefined : specPath.replace(/\.tla$/, ".cfg"));
145
204
  if (!configPath || !existsSync(configPath)) {
146
205
  console.error(`Cannot find the configuration file ${configPath ?? ""}`);
147
206
  return EXIT_STATUS.configParseError;
148
207
  }
149
208
  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];
209
+ if (args.has("-deadlock")) config.checkDeadlock = false;
210
+ const seed = args.has("-seed") ? args.get("-seed")?.[0] : "0";
153
211
  if (seed === undefined) {
154
212
  console.error("Error: seed required.");
155
213
  return 1;
@@ -158,8 +216,7 @@ const run = async (args: string[]) => {
158
216
  console.error(`Error: An integer for seed required. But encountered ${seed}`);
159
217
  return 1;
160
218
  }
161
- const livenessFlag = args.indexOf("-lncheck");
162
- const livenessCheck = livenessFlag === -1 ? "default" : args[livenessFlag + 1]?.toLowerCase();
219
+ const livenessCheck = args.has("-lncheck") ? args.get("-lncheck")?.[0]?.toLowerCase() : "default";
163
220
  if (livenessCheck === undefined) {
164
221
  console.error("Error: expect a strategy such as final for -lncheck option.");
165
222
  return 1;
@@ -167,7 +224,7 @@ const run = async (args: string[]) => {
167
224
  const directory = dirname(specPath);
168
225
  console.log(`Checking ${basename(specPath)} with ${basename(configPath)}`);
169
226
  const result = await check({
170
- workers: getWorkerCount(args),
227
+ workers: getWorkerCount(args.get("-workers")),
171
228
  livenessCheck: ["final", "seqfinal", "off"].includes(livenessCheck) ? "final" : "default",
172
229
  seed: BigInt(seed),
173
230
  source: readFileSync(specPath, "utf8"),
@@ -199,12 +256,230 @@ const printError = (error: TlaError) => {
199
256
  console.error(`${error.name}: ${error.message}`);
200
257
  };
201
258
 
202
- export const runCli = async () => {
259
+ // Prints a TlaError and returns its exit code.
260
+ const reportErrors = async (run: () => number | Promise<number>) => {
203
261
  try {
204
- process.exitCode = await run(process.argv.slice(2));
262
+ return await run();
205
263
  } catch (error) {
206
264
  if (!(error instanceof TlaError)) throw error;
207
265
  printError(error);
208
- process.exitCode = getErrorExitCode(error);
266
+ return getErrorExitCode(error);
267
+ }
268
+ };
269
+
270
+ // Runs each path in turn, so an error in one leaves the others to report. The exit code is the
271
+ // first that is not success.
272
+ const runEach = async (paths: string[], runPath: (path: string) => number | Promise<number>) => {
273
+ const exitCodes: number[] = [];
274
+ for (const [index, path] of paths.entries()) {
275
+ if (index > 0) console.log("");
276
+ exitCodes.push(await reportErrors(() => runPath(path)));
277
+ }
278
+ return exitCodes.find((exitCode) => exitCode !== EXIT_STATUS.success) ?? EXIT_STATUS.success;
279
+ };
280
+
281
+ // tlapm installs its standard library, with modules such as TLAPS, at lib/tlapm/stdlib beside
282
+ // bin/tlapm.
283
+ const getTlapmPaths = () =>
284
+ (process.env.PATH ?? "")
285
+ .split(delimiter)
286
+ .map((directory) => join(directory, "tlapm"))
287
+ .filter((path) => existsSync(path));
288
+
289
+ const getTlapmLibrary = () =>
290
+ getTlapmPaths()
291
+ .map((path) => join(dirname(dirname(realpathSync(path))), "lib/tlapm/stdlib"))
292
+ .find((path) => existsSync(path));
293
+
294
+ const expandGlobs = (paths: string[]) =>
295
+ paths.flatMap((path) => (GLOB_CHARACTERS.test(path) ? globSync(path).sort() : [path]));
296
+
297
+ const proveWithTlapm = (args: string[]) => {
298
+ const tlapm = getTlapmPaths()[0];
299
+ if (tlapm === undefined) {
300
+ console.error(
301
+ "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.",
302
+ );
303
+ return 1;
304
+ }
305
+ return spawnSync(tlapm, expandGlobs(args), { stdio: "inherit" }).status ?? 1;
306
+ };
307
+
308
+ const readModule = (path: string) =>
309
+ existsSync(path) ? { file: path, source: readFileSync(path, "utf8") } : undefined;
310
+
311
+ // A message of tlapm's toolbox protocol, which it writes to stderr.
312
+ const printToolboxMessage = (fields: string[]) =>
313
+ console.error(`@!!BEGIN\n${fields.map((field) => `@!!${field}\n`).join("")}@!!END\n`);
314
+
315
+ const TLAPM_VERSION = "5f5037f";
316
+
317
+ const quoteArgument = (arg: string) =>
318
+ /^[+,\-./0-9:=@A-Z_a-z]+$/.test(arg) ? arg : `'${arg.replaceAll("'", "'\\''")}'`;
319
+
320
+ const printToolboxHeader = (args: string[]) => {
321
+ const now = new Date();
322
+ const pad = (value: number) => String(value).padStart(2, "0");
323
+ const date = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`;
324
+ const time = `${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}`;
325
+ console.log(
326
+ `\n\\* TLAPM version ${TLAPM_VERSION}\n\\* launched at ${date} ${time} with command line:\n\\* ${["tla-ts", "prove", ...args].map(quoteArgument).join(" ")}\n`,
327
+ );
328
+ };
329
+
330
+ const STRICT_EXIT_STATUS = { incomplete: 11, emptyTarget: 12 };
331
+
332
+ const checkStrictly = (result: ModuleObligations, isTargeted: boolean, isSummary: boolean) => {
333
+ const summary = result.summary;
334
+ if (!isSummary) {
335
+ summary.absent.forEach((locus) => console.error(`Missing proof at ${getLocusText(locus)}`));
336
+ summary.omitted.forEach((locus) => console.error(`Omitted proof at ${getLocusText(locus)}`));
209
337
  }
338
+ const isIncomplete = summary.absent.length + summary.omitted.length > 0;
339
+ if (isIncomplete) {
340
+ console.error(
341
+ `${getAtPrefix(result.location)}[ERROR]: Proof incomplete in module ${JSON.stringify(result.name)}: ${summary.absent.length} missing, ${summary.omitted.length} omitted proof step(s).`,
342
+ );
343
+ }
344
+ const isEmpty = isTargeted && result.obligations.length === 0;
345
+ if (isEmpty) {
346
+ console.error(
347
+ `${getAtPrefix(result.location)}[ERROR]: No proof obligation found for the selected target.`,
348
+ );
349
+ }
350
+ return [
351
+ ...(isIncomplete ? [STRICT_EXIT_STATUS.incomplete] : []),
352
+ ...(isEmpty ? [STRICT_EXIT_STATUS.emptyTarget] : []),
353
+ ];
354
+ };
355
+
356
+ const TLAPM_FAILURE_STATUS = 3;
357
+
358
+ const generateObligations = (generate: () => ModuleObligations[]) => {
359
+ try {
360
+ return generate();
361
+ } catch (error) {
362
+ if (!(error instanceof TlaProofError)) throw error;
363
+ console.error(` tlapm ending abnormally with ${error.exception}\n`);
364
+ return undefined;
365
+ }
366
+ };
367
+
368
+ const prove = (args: string[]) => {
369
+ if (!args.includes("-N") && !args.includes("--summary")) return proveWithTlapm(args);
370
+ const parsed = PROVE_COMMAND.parse(args);
371
+ const unsupported = parsed.unknown[0];
372
+ if (unsupported !== undefined) {
373
+ console.error(`Error: tla-ts prove does not support the tlapm option ${unsupported}.`);
374
+ return 1;
375
+ }
376
+ if (parsed.incomplete) {
377
+ console.error(`Error: option '${parsed.incomplete.name}' needs an argument.`);
378
+ return 1;
379
+ }
380
+ const nonInteger = parsed.options.find(
381
+ (option) => option.name !== "-I" && option.values.some((value) => !/^-?\d+$/.test(value)),
382
+ );
383
+ if (nonInteger) {
384
+ console.error(`Error: option '${nonInteger.name}' expects an integer.`);
385
+ return 1;
386
+ }
387
+ const files = expandGlobs(parsed.positionals);
388
+ const modulePaths = files.map((path) => (path.endsWith(".tla") ? path : `${path}.tla`));
389
+ if (modulePaths.length === 0) {
390
+ console.error(USAGE);
391
+ return 1;
392
+ }
393
+ const isToolbox = parsed.has("--toolbox") || parsed.has("--line");
394
+ if (isToolbox) printToolboxHeader(args);
395
+ // Like tlapm, the last of --toolbox and --line wins, and a 0 means the whole module.
396
+ const lines = parsed.options.reduce<LineRange>((range, option) => {
397
+ const [start, end] = option.values.map(Number);
398
+ if (option.name === "--toolbox") return { start, end: end === 0 ? Infinity : end };
399
+ if (option.name === "--line") return start === 0 ? WHOLE_MODULE : { start, end: start };
400
+ return range;
401
+ }, WHOLE_MODULE);
402
+ // tlapm searches the current directory and each module's, then its library, then each -I
403
+ // directory, the last given first.
404
+ const tlapmLibrary = getTlapmLibrary();
405
+ const includes = parsed.options.flatMap((option) => (option.name === "-I" ? option.values : []));
406
+ const directories = modulePaths.reduce(
407
+ (found, path) => (found.includes(dirname(path)) ? found : [dirname(path), ...found]),
408
+ [".", ...(tlapmLibrary ? [tlapmLibrary] : []), ...includes.toReversed()],
409
+ );
410
+ // tlapm names each file it reads by joining a search directory and the name, as in ./Module.tla.
411
+ const results = generateObligations(() => {
412
+ const missingIndex = modulePaths.findIndex((path) => !existsSync(path));
413
+ if (missingIndex !== -1) {
414
+ const missing = files[missingIndex];
415
+ console.error(`File "<unknown>":\nError: File ${JSON.stringify(missing)} not found`);
416
+ throw new TlaProofError(`File ${missing} not found`, { failure: "Module.Parser.parse_file" });
417
+ }
418
+ return getObligations(
419
+ modulePaths.map((path) => ({ file: `./${path}`, source: readFileSync(path, "utf8") })),
420
+ (name) =>
421
+ directories.map((directory) => readModule(`${directory}/${name}.tla`)).find(Boolean),
422
+ {
423
+ lines,
424
+ onWarning: (warning) => {
425
+ if (warning.channel === "stdout") return console.log(warning.text);
426
+ const isToolboxMessage =
427
+ warning.channel === "toolbox" || warning.channel === "toolboxOnly";
428
+ if (isToolbox && isToolboxMessage)
429
+ return printToolboxMessage(["type:warning", `msg:${warning.text}`]);
430
+ if (warning.channel !== "toolboxOnly") console.error(warning.text);
431
+ },
432
+ },
433
+ );
434
+ });
435
+ if (!results) return TLAPM_FAILURE_STATUS;
436
+ const failures = results.flatMap((result) => {
437
+ if (parsed.has("--summary")) console.log(formatSummary(result));
438
+ if (isToolbox) {
439
+ result.obligations.forEach((obligation) =>
440
+ printToolboxMessage([
441
+ "type:obligation",
442
+ `id:${obligation.id}`,
443
+ `loc:${obligation.location}`,
444
+ "status:to be proved",
445
+ ...(parsed.has("--printallobs") ? [`obl:${obligation.text}`] : []),
446
+ ]),
447
+ );
448
+ printToolboxMessage(["type:obligationsnumber", `count:${result.obligations.length}`]);
449
+ }
450
+ if (!parsed.has("--strict")) return [];
451
+ return checkStrictly(result, lines.start > 0 || lines.end < Infinity, parsed.has("--summary"));
452
+ });
453
+ return failures.includes(STRICT_EXIT_STATUS.incomplete)
454
+ ? STRICT_EXIT_STATUS.incomplete
455
+ : (failures[0] ?? EXIT_STATUS.success);
456
+ };
457
+
458
+ const run = async (args: string[]) => {
459
+ if (args[0] === "prove") return reportErrors(() => prove(args.slice(1)));
460
+ const parsed = CHECK_COMMAND.parse(args);
461
+ const inputs = getInputPaths(parsed.positionals);
462
+ const isConfigured = parsed.has("-config");
463
+ // A glob also matches modules that only other specs import, which have no configuration.
464
+ const specPaths = inputs
465
+ .map((input) => ({ ...input, path: input.path.replace(/\.cfg$/, ".tla") }))
466
+ .filter(
467
+ (input) =>
468
+ input.path.endsWith(".tla") &&
469
+ (!input.isGlobbed || isConfigured || existsSync(input.path.replace(/\.tla$/, ".cfg"))),
470
+ )
471
+ .map((input) => input.path);
472
+ if (specPaths.length === 0) {
473
+ console.error(USAGE);
474
+ return 1;
475
+ }
476
+ if (isConfigured && specPaths.length > 1) {
477
+ console.error("Error: -config applies to one specification, but several were given.");
478
+ return 1;
479
+ }
480
+ return runEach([...new Set(specPaths)], (path) => checkSpec(path, parsed));
481
+ };
482
+
483
+ export const runCli = async () => {
484
+ process.exitCode = await run(process.argv.slice(2));
210
485
  };
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;
@@ -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,
@@ -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]],
@@ -1,15 +1,15 @@
1
- import type {
2
- Bound,
3
- Definition,
4
- Expression,
5
- Instance,
6
- Module,
7
- OperatorParam,
8
- Selector,
9
- SourceLocation,
1
+ import {
2
+ getChildren,
3
+ type Bound,
4
+ type Definition,
5
+ type Expression,
6
+ type Instance,
7
+ type Module,
8
+ type OperatorParam,
9
+ type Selector,
10
+ type SourceLocation,
10
11
  } from "./ast";
11
12
  import { TlaSyntaxError } from "./errors";
12
- import { getChildren } from "./evaluate";
13
13
  import { getSourceName, mapChildren, mapDefinition } from "./instances";
14
14
  import { getArity, getBoundNames, getPatternNames, LOCAL_RESOLUTION } from "./resolve";
15
15
 
package/src/successors.ts CHANGED
@@ -1,9 +1,16 @@
1
- import type { Bound, Definition, Expression } from "./ast";
1
+ import {
2
+ getChildren,
3
+ isLocallyResolved,
4
+ type Bound,
5
+ type Definition,
6
+ type Expression,
7
+ } from "./ast";
2
8
  import { getReadVariables } from "./dependencies";
3
- import { TlaEvaluationError } from "./errors";
9
+ import { TlaEvaluationError, UNEXPECTED_EXCEPTION } from "./errors";
4
10
  import { EXIT_STATUS, setExitCode } from "./exit-codes";
5
11
  import {
6
12
  describeLocation,
13
+ describeRange,
7
14
  bindArgument,
8
15
  bindDefinitions,
9
16
  bindOperatorArguments,
@@ -13,14 +20,12 @@ import {
13
20
  expectBoolean,
14
21
  forEachBinding,
15
22
  getBoundsDomain,
16
- getChildren,
17
23
  getDefinition,
18
24
  getEnumeratedElements,
19
25
  getReevaluatedDefinitions,
20
26
  lookupScope,
21
27
  resolveApplyOperator,
22
28
  resolveGlobalOperator,
23
- isLocallyResolved,
24
29
  type Context,
25
30
  type Environment,
26
31
  type Scope,
@@ -804,7 +809,9 @@ const compileAction = (
804
809
  );
805
810
  const body = arm?.body ?? other;
806
811
  if (!body)
807
- throw new TlaEvaluationError(`No CASE guard is true at ${describeLocation(expression)}`);
812
+ throw new TlaEvaluationError(
813
+ `${UNEXPECTED_EXCEPTION}In computing next states, TLC encountered a CASE with no conditions true.\n${describeRange(expression)}`,
814
+ );
808
815
  body(run, scope, partial, action, isFixed, onComplete);
809
816
  };
810
817
  }
@@ -913,18 +920,19 @@ export const isEnabled = (expression: Expression, context: Context): boolean =>
913
920
  );
914
921
  }
915
922
  const environment = context.environment;
916
- const found = { value: false };
923
+ const run: Run = { environment, isInit: false, current: state, isStopped: false };
924
+ // TLC stops computing ENABLED at the first successor, so it skips the rest of the action.
917
925
  getRunner(expression, environment, false)(
918
- { environment, isInit: false, current: state, isStopped: false },
926
+ run,
919
927
  context.scope,
920
928
  getEmptyState(environment),
921
929
  undefined,
922
930
  false,
923
931
  () => {
924
- found.value = true;
932
+ run.isStopped = true;
925
933
  },
926
934
  );
927
- return found.value;
935
+ return run.isStopped;
928
936
  };
929
937
 
930
938
  export const forEachInitialState = (
package/src/symmetry.ts CHANGED
@@ -9,6 +9,7 @@ import {
9
9
  isEnumerable,
10
10
  isFunctionValue,
11
11
  isModelValue,
12
+ isSameValue,
12
13
  isSetValue,
13
14
  toFiniteFunction,
14
15
  toFiniteSet,
@@ -163,7 +164,10 @@ const permuteValue = (value: Value, permutation: Permutation): Value => {
163
164
  if (size === 0 || size > CACHED_SIZE_LIMIT) return computePermutedValue(value, permutation);
164
165
  const cached = permutation.cache.get(value);
165
166
  if (cached !== undefined) return cached;
166
- const permuted = computePermutedValue(value, permutation);
167
+ const computed = computePermutedValue(value, permutation);
168
+ // A permutation often maps a value to an equal one. Keeping the original lets the comparison
169
+ // with the smallest state so far stop at identity.
170
+ const permuted = computed !== value && isSameValue(computed, value) ? value : computed;
167
171
  if (permutation.cacheSize >= permutation.cacheLimit) {
168
172
  permutation.cache = new WeakMap();
169
173
  permutation.cacheSize = 0;
@@ -184,7 +188,15 @@ const computePermutedValue = (value: ObjectValue, permutation: Permutation) => {
184
188
  const domain = permuteElements(functionValue.domain, permutation);
185
189
  const range = permuteElements(functionValue.range, permutation) ?? functionValue.range;
186
190
  if (domain) {
187
- return createFunction(domain.map((key, index): [Value, Value] => [key, range[index]]));
191
+ const permuted = createFunction(
192
+ domain.map((key, index): [Value, Value] => [key, range[index]]),
193
+ );
194
+ // A permutation often maps the domain to itself, such as a function over the symmetric set.
195
+ // Sharing the original domain array lets comparisons with other images skip the domain.
196
+ const isSameDomain = permuted.domain.every(
197
+ (key, index) => key === functionValue.domain[index],
198
+ );
199
+ return isSameDomain ? createSortedFunction(functionValue.domain, permuted.range) : permuted;
188
200
  }
189
201
  return range === functionValue.range
190
202
  ? functionValue
package/src/tlc-ext.ts CHANGED
@@ -10,16 +10,8 @@ import {
10
10
  } from "./builtins";
11
11
  import { TlaEvaluationError, TlaModuleError, TlaUnsupportedError } from "./errors";
12
12
  import { getTlcFingerprint } from "./tlc-random";
13
- import {
14
- evaluate,
15
- expectBoolean,
16
- getChildren,
17
- getDefinition,
18
- isLocallyResolved,
19
- type Builtin,
20
- type Environment,
21
- } from "./evaluate";
22
- import type { Definition, Expression } from "./ast";
13
+ import { evaluate, expectBoolean, getDefinition, type Builtin, type Environment } from "./evaluate";
14
+ import { getChildren, isLocallyResolved, type Definition, type Expression } from "./ast";
23
15
  import type { TraceStep } from "./check";
24
16
  import {
25
17
  getNamedRegisters,