tla-ts 0.0.3-dev.d34b19a → 0.0.3-dev.e5b05b9

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 (55) hide show
  1. package/README.md +5 -1
  2. package/dist/index.cjs +1 -1
  3. package/dist/index.d.cts +71 -22
  4. package/dist/index.d.ts +71 -22
  5. package/dist/index.js +1 -1
  6. package/dist/parallel-worker.cjs +1 -1
  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 +20 -17
  11. package/dist/run-cli.js +22 -19
  12. package/dist/transfer.cjs +45 -15
  13. package/dist/transfer.js +45 -15
  14. package/package.json +1 -1
  15. package/src/ast.ts +121 -4
  16. package/src/builtins.ts +9 -3
  17. package/src/check.ts +514 -99
  18. package/src/cli-options.ts +11 -5
  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 +334 -96
  23. package/src/errors.ts +109 -3
  24. package/src/evaluate.ts +255 -159
  25. package/src/exit-codes.ts +39 -42
  26. package/src/fingerprints.ts +2 -1
  27. package/src/instances.ts +16 -15
  28. package/src/levels.ts +185 -44
  29. package/src/live-check.ts +772 -0
  30. package/src/liveness.ts +120 -543
  31. package/src/parallel-worker.ts +2 -2
  32. package/src/parallel.ts +20 -4
  33. package/src/parser.ts +182 -53
  34. package/src/resolve.ts +1302 -412
  35. package/src/run-cli.ts +115 -20
  36. package/src/runtime.ts +3 -1
  37. package/src/sany-lexer.ts +615 -0
  38. package/src/sany-parse-error.ts +3143 -0
  39. package/src/spec-description.ts +19 -8
  40. package/src/standard-modules.ts +54 -45
  41. package/src/standard-ranges.ts +116 -0
  42. package/src/state-graph.ts +157 -0
  43. package/src/subexpressions.ts +124 -159
  44. package/src/substitution-levels.ts +38 -17
  45. package/src/successors.ts +183 -39
  46. package/src/symmetry.ts +16 -6
  47. package/src/tableau.ts +51 -24
  48. package/src/tlc-ext.ts +29 -12
  49. package/src/tlc-module.ts +14 -33
  50. package/src/tlc-modules.ts +4 -0
  51. package/src/tlc-order.ts +25 -7
  52. package/src/tlc-random.ts +9 -6
  53. package/src/tlc-summary.ts +20 -5
  54. package/src/value-sources.ts +29 -0
  55. package/src/values.ts +242 -61
package/src/run-cli.ts CHANGED
@@ -10,29 +10,34 @@ import {
10
10
  import { spawnSync } from "node:child_process";
11
11
  import { basename, delimiter, dirname, join, resolve } from "node:path";
12
12
  import { availableParallelism } from "node:os";
13
- import type { CheckResult, CheckStatus, TraceStep } from "./check";
13
+ import type { CheckResult, CheckStatus, Replay, TraceStep } from "./check";
14
14
  import { defineCommand, type ParsedArgs } from "./cli-options";
15
15
  import { parseConfig } from "./config";
16
16
  import {
17
+ createSanyError,
18
+ formatSanyWarnings,
17
19
  getErrorExitCode,
18
20
  TlaConfigError,
19
21
  TlaError,
20
22
  TlaEvaluationError,
21
23
  TlaProofError,
24
+ TlaSyntaxError,
25
+ type SanyReport,
22
26
  } from "./errors";
23
27
  import { EXIT_STATUS } from "./exit-codes";
24
28
  import type { LineRange } from "./obligation-generate";
25
29
  import { getAtPrefix, getLocusText } from "./obligation-expression";
26
30
  import { formatSummary, getObligations, WHOLE_MODULE, type ModuleObligations } from "./obligations";
27
31
  import { check } from "./parallel";
28
- import { prettyPrint } from "./pretty-print";
32
+ import { parseModuleFile } from "./sany-parse-error";
33
+ import type { StateDump } from "./state-graph";
29
34
  import {
30
35
  formatProbability,
31
36
  getActualProbability,
32
37
  getOptimisticProbability,
33
38
  getOutDegreeSummary,
34
39
  } from "./tlc-summary";
35
- import { formatValue, type Value } from "./values";
40
+ import { formatState, type Value } from "./values";
36
41
 
37
42
  const EXIT_CODES: Record<CheckStatus, number> = {
38
43
  success: EXIT_STATUS.success,
@@ -48,6 +53,11 @@ const EXIT_CODES: Record<CheckStatus, number> = {
48
53
  const CHECK_COMMAND = defineCommand("tla-ts <Spec.tla|Spec.cfg|glob>... {options}", [
49
54
  { flag: "-config <Spec.cfg>" },
50
55
  { flag: "-deadlock" },
56
+ // Like TLC, -dump takes a format only when the next argument starts with dot and a file follows.
57
+ {
58
+ flag: "-dump [<format>] <file>",
59
+ getArity: (rest) => (rest.length > 1 && rest[0].startsWith("dot") ? 2 : 1),
60
+ },
51
61
  { flag: "-lncheck <final|default>" },
52
62
  { flag: "-seed <num>" },
53
63
  { flag: "-workers <count|auto>" },
@@ -95,14 +105,24 @@ const getWorkerCount = (values: string[] | undefined) => {
95
105
  : Math.max(1, Number.parseInt(values[0], 10) || 1);
96
106
  };
97
107
 
98
- const printState = (state: Record<string, Value>) => {
99
- const entries = Object.entries(state);
100
- entries.forEach(([name, value]) =>
101
- console.log(
102
- `${entries.length === 1 ? "" : "/\\ "}${name} = ${prettyPrint(formatValue(value))}`,
103
- ),
104
- );
105
- console.log("");
108
+ const printState = (state: Record<string, Value>) => console.log(formatState(state));
109
+
110
+ const UNSUPPORTED_DUMP_FORMATS = ["constrained", "stuttering", "strict"];
111
+
112
+ // TLC names the file of a -dump by its format unless the name already ends that way.
113
+ const getDumpPath = (path: string, extension: string) =>
114
+ path.endsWith(extension) ? path : `${path}${extension}`;
115
+
116
+ const getDump = (values: string[]): StateDump => {
117
+ if (values.length === 1) return { path: getDumpPath(values[0], ".dump") };
118
+ const format = values[0].toLowerCase();
119
+ return {
120
+ path: getDumpPath(values[1], ".dot"),
121
+ dot: true,
122
+ colorize: format.includes("colorize"),
123
+ actionLabels: format.includes("actionlabels"),
124
+ snapshot: format.includes("snapshot"),
125
+ };
106
126
  };
107
127
 
108
128
  const printTrace = (trace: TraceStep[], heading = "Error: The behavior up to this point is:") => {
@@ -113,14 +133,47 @@ const printTrace = (trace: TraceStep[], heading = "Error: The behavior up to thi
113
133
  });
114
134
  };
115
135
 
136
+ const getTemporalHeadline = (names: string[]) =>
137
+ names.length === 1
138
+ ? `Error: Temporal property ${names[0]} was violated.\n`
139
+ : `Error: Temporal properties ${names.slice(0, -1).join(", ")}${names.length > 2 ? "," : ""} and ${names[names.length - 1]} were violated.\n`;
140
+
141
+ const getFrames = (callStack: string[]) =>
142
+ callStack.map((frame, index) => `${index}. ${frame}\n`).join("");
143
+
144
+ const printCallStack = (frames: string) =>
145
+ console.log(
146
+ `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"}`,
147
+ );
148
+
149
+ const printReplay = (replay: Replay) => {
150
+ replay.output.forEach((line) => console.log(line));
151
+ const frames = getFrames(replay.callStack ?? []);
152
+ const fingerprint = replay.fingerprint;
153
+ if (replay.isBeforeError) {
154
+ if (frames) printCallStack(frames);
155
+ } else if (replay.callStack && fingerprint) {
156
+ const sources = fingerprint.sources.map((source) => `${source}\n`).join("");
157
+ console.log(
158
+ `Error: TLC was unable to fingerprint.\n\nFingerprint Stack Trace:\n${frames ? `${frames}\n` : sources}\nReason:\n${fingerprint.reason}`,
159
+ );
160
+ } else if (replay.callStack) {
161
+ printCallStack(frames);
162
+ }
163
+ };
164
+
116
165
  const printResult = (result: CheckResult) => {
117
166
  if (result.failure) {
167
+ const replay = result.failure.replay;
168
+ if (replay?.isBeforeError) printReplay(replay);
118
169
  console.log(`Error: ${result.failure.message}`);
119
170
  if (result.failure.initialState) {
120
171
  console.log("While working on the initial state:");
121
172
  printState(result.failure.initialState);
122
173
  }
123
174
  printTrace(result.failure.trace);
175
+ if (replay && !replay.isBeforeError) printReplay(replay);
176
+ if (result.failure.isWithoutStatistics) return;
124
177
  } else if (result.violation) {
125
178
  const violation = result.violation;
126
179
  const name = violation.name;
@@ -140,10 +193,10 @@ const printResult = (result: CheckResult) => {
140
193
  "invariant-violation": isInitial
141
194
  ? `Error: Invariant ${name} is violated by the initial state:`
142
195
  : `Error: Invariant ${name} is violated.`,
143
- "property-violation": `Error: Property ${name} is violated.`,
196
+ "property-violation": getTemporalHeadline(violation.properties ?? [name]),
144
197
  "liveness-violation":
145
198
  loopStart !== undefined
146
- ? `Error: Temporal property ${name} was violated.\n`
199
+ ? getTemporalHeadline(violation.properties ?? [name])
147
200
  : isInitial
148
201
  ? `Error: Property ${name} is violated by the initial state:`
149
202
  : `Error: Action property ${name} is violated.`,
@@ -152,6 +205,8 @@ const printResult = (result: CheckResult) => {
152
205
  if (violation.counts) console.log(violation.counts);
153
206
  console.log(headline);
154
207
  if (isInitial) printState(violation.trace[0].state);
208
+ else if (result.status === "property-violation")
209
+ printTrace(violation.trace, "Error: The following behavior constitutes a counter-example:\n");
155
210
  else if (loopStart === undefined) printTrace(violation.trace);
156
211
  else {
157
212
  printTrace(violation.trace, "Error: The following behavior constitutes a counter-example:\n");
@@ -191,6 +246,20 @@ const checkSpec = async (specPath: string, args: ParsedArgs) => {
191
246
  console.error(`Cannot find the specification file ${specPath}`);
192
247
  return EXIT_STATUS.configParseError;
193
248
  }
249
+ const source = readFileSync(specPath, "utf8");
250
+ const fileName = basename(specPath, ".tla");
251
+ const moduleName = parseModuleFile(source, fileName).name;
252
+ if (moduleName !== fileName) {
253
+ throw createSanyError(
254
+ [
255
+ {
256
+ location: "Unknown location",
257
+ message: `File name '${fileName}' does not match the name '${moduleName}' of the top level module it contains.`,
258
+ },
259
+ ],
260
+ true,
261
+ );
262
+ }
194
263
  const configPath =
195
264
  args.get("-config")?.[0] ??
196
265
  (args.has("-config") ? undefined : specPath.replace(/\.tla$/, ".cfg"));
@@ -214,13 +283,26 @@ const checkSpec = async (specPath: string, args: ParsedArgs) => {
214
283
  console.error("Error: expect a strategy such as final for -lncheck option.");
215
284
  return 1;
216
285
  }
286
+ const dumpValues = args.get("-dump");
287
+ if (dumpValues?.length === 0) {
288
+ console.error("Error: A file name for dumping states required.");
289
+ return 1;
290
+ }
291
+ const unsupportedFormat =
292
+ dumpValues?.length === 2 &&
293
+ UNSUPPORTED_DUMP_FORMATS.find((format) => dumpValues[0].toLowerCase().includes(format));
294
+ if (unsupportedFormat) {
295
+ console.error(`Error: tla-ts does not support the -dump format ${unsupportedFormat}.`);
296
+ return 1;
297
+ }
217
298
  const directory = dirname(specPath);
218
299
  console.log(`Checking ${basename(specPath)} with ${basename(configPath)}`);
219
300
  const result = await check({
220
301
  workers: getWorkerCount(args.get("-workers")),
221
302
  livenessCheck: ["final", "seqfinal", "off"].includes(livenessCheck) ? "final" : "default",
222
303
  seed: BigInt(seed),
223
- source: readFileSync(specPath, "utf8"),
304
+ dump: dumpValues && getDump(dumpValues),
305
+ source,
224
306
  config,
225
307
  onPause: () => readSync(0, Buffer.alloc(1)),
226
308
  loadModule: (name) => {
@@ -241,21 +323,34 @@ const checkSpec = async (specPath: string, args: ParsedArgs) => {
241
323
  return result.failure?.exitCode ?? EXIT_CODES[result.status];
242
324
  };
243
325
 
244
- // TLC prints the errors it raises itself. tla-ts names the others, such as a module SANY rejects.
245
- const printError = (error: TlaError) => {
326
+ const formatSanyErrors = (report: SanyReport) =>
327
+ `*** Errors: ${report.errors.length}\n\n${report.errors.map((error) => `${error.location}\n\n${error.message}\n\n`).join("\n")}`;
328
+
329
+ // TLC prints the errors it raises itself, and SANY's report of a spec it rejects. tla-ts names the
330
+ // others, such as a module it cannot parse.
331
+ const printError = (error: TlaError, path?: string) => {
246
332
  if (error instanceof TlaConfigError || error instanceof TlaEvaluationError) {
247
333
  return console.log(`Error: ${error.message}`);
248
334
  }
249
- console.error(`${error.name}: ${error.message}`);
335
+ const report = error instanceof TlaSyntaxError ? error.sany : undefined;
336
+ if (!report || path === undefined) return console.error(`${error.name}: ${error.message}`);
337
+ if (report.parseError !== undefined) console.log(report.parseError);
338
+ if (report.warnings.length > 0) console.log(formatSanyWarnings(report.warnings));
339
+ console.log(
340
+ report.isFatal
341
+ ? `\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`
342
+ : `Semantic errors:\n\n${formatSanyErrors(report)}`,
343
+ );
344
+ console.log("Error: Parsing or semantic analysis failed.");
250
345
  };
251
346
 
252
347
  // Prints a TlaError and returns its exit code.
253
- const reportErrors = async (run: () => number | Promise<number>) => {
348
+ const reportErrors = async (run: () => number | Promise<number>, path?: string) => {
254
349
  try {
255
350
  return await run();
256
351
  } catch (error) {
257
352
  if (!(error instanceof TlaError)) throw error;
258
- printError(error);
353
+ printError(error, path);
259
354
  return getErrorExitCode(error);
260
355
  }
261
356
  };
@@ -266,7 +361,7 @@ const runEach = async (paths: string[], runPath: (path: string) => number | Prom
266
361
  const exitCodes: number[] = [];
267
362
  for (const [index, path] of paths.entries()) {
268
363
  if (index > 0) console.log("");
269
- exitCodes.push(await reportErrors(() => runPath(path)));
364
+ exitCodes.push(await reportErrors(() => runPath(path), path));
270
365
  }
271
366
  return exitCodes.find((exitCode) => exitCode !== EXIT_STATUS.success) ?? EXIT_STATUS.success;
272
367
  };
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
  };