tla-ts 0.0.3-dev.6979965 → 0.0.3-dev.6d0aeb6

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 +16 -2
  2. package/dist/index.cjs +1 -1
  3. package/dist/index.d.cts +60 -22
  4. package/dist/index.d.ts +60 -22
  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 +20 -17
  11. package/dist/run-cli.js +22 -19
  12. package/dist/transfer.cjs +45 -16
  13. package/dist/transfer.js +45 -16
  14. package/package.json +1 -1
  15. package/src/ast.ts +101 -1
  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 +158 -49
  23. package/src/errors.ts +98 -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 +181 -45
  29. package/src/lexer.ts +5 -1
  30. package/src/live-check.ts +772 -0
  31. package/src/liveness.ts +120 -543
  32. package/src/parallel-worker.ts +102 -115
  33. package/src/parallel.ts +34 -23
  34. package/src/parser.ts +83 -20
  35. package/src/resolve.ts +490 -95
  36. package/src/run-cli.ts +113 -20
  37. package/src/runtime.ts +3 -1
  38. package/src/sany-lexer.ts +615 -0
  39. package/src/sany-parse-error.ts +3143 -0
  40. package/src/spec-description.ts +19 -8
  41. package/src/standard-modules.ts +54 -45
  42. package/src/state-graph.ts +157 -0
  43. package/src/subexpressions.ts +35 -23
  44. package/src/substitution-levels.ts +38 -17
  45. package/src/successors.ts +183 -39
  46. package/src/symmetry.ts +30 -8
  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 +249 -65
package/src/run-cli.ts CHANGED
@@ -10,29 +10,33 @@ 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,
17
18
  getErrorExitCode,
18
19
  TlaConfigError,
19
20
  TlaError,
20
21
  TlaEvaluationError,
21
22
  TlaProofError,
23
+ TlaSyntaxError,
24
+ type SanyReport,
22
25
  } from "./errors";
23
26
  import { EXIT_STATUS } from "./exit-codes";
24
27
  import type { LineRange } from "./obligation-generate";
25
28
  import { getAtPrefix, getLocusText } from "./obligation-expression";
26
29
  import { formatSummary, getObligations, WHOLE_MODULE, type ModuleObligations } from "./obligations";
27
30
  import { check } from "./parallel";
28
- import { prettyPrint } from "./pretty-print";
31
+ import { parseModuleFile } from "./sany-parse-error";
32
+ import type { StateDump } from "./state-graph";
29
33
  import {
30
34
  formatProbability,
31
35
  getActualProbability,
32
36
  getOptimisticProbability,
33
37
  getOutDegreeSummary,
34
38
  } from "./tlc-summary";
35
- import { formatValue, type Value } from "./values";
39
+ import { formatState, type Value } from "./values";
36
40
 
37
41
  const EXIT_CODES: Record<CheckStatus, number> = {
38
42
  success: EXIT_STATUS.success,
@@ -48,6 +52,11 @@ const EXIT_CODES: Record<CheckStatus, number> = {
48
52
  const CHECK_COMMAND = defineCommand("tla-ts <Spec.tla|Spec.cfg|glob>... {options}", [
49
53
  { flag: "-config <Spec.cfg>" },
50
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
+ },
51
60
  { flag: "-lncheck <final|default>" },
52
61
  { flag: "-seed <num>" },
53
62
  { flag: "-workers <count|auto>" },
@@ -95,14 +104,24 @@ const getWorkerCount = (values: string[] | undefined) => {
95
104
  : Math.max(1, Number.parseInt(values[0], 10) || 1);
96
105
  };
97
106
 
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("");
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
+ };
106
125
  };
107
126
 
108
127
  const printTrace = (trace: TraceStep[], heading = "Error: The behavior up to this point is:") => {
@@ -113,14 +132,47 @@ const printTrace = (trace: TraceStep[], heading = "Error: The behavior up to thi
113
132
  });
114
133
  };
115
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
+
116
164
  const printResult = (result: CheckResult) => {
117
165
  if (result.failure) {
166
+ const replay = result.failure.replay;
167
+ if (replay?.isBeforeError) printReplay(replay);
118
168
  console.log(`Error: ${result.failure.message}`);
119
169
  if (result.failure.initialState) {
120
170
  console.log("While working on the initial state:");
121
171
  printState(result.failure.initialState);
122
172
  }
123
173
  printTrace(result.failure.trace);
174
+ if (replay && !replay.isBeforeError) printReplay(replay);
175
+ if (result.failure.isWithoutStatistics) return;
124
176
  } else if (result.violation) {
125
177
  const violation = result.violation;
126
178
  const name = violation.name;
@@ -140,10 +192,10 @@ const printResult = (result: CheckResult) => {
140
192
  "invariant-violation": isInitial
141
193
  ? `Error: Invariant ${name} is violated by the initial state:`
142
194
  : `Error: Invariant ${name} is violated.`,
143
- "property-violation": `Error: Property ${name} is violated.`,
195
+ "property-violation": getTemporalHeadline(violation.properties ?? [name]),
144
196
  "liveness-violation":
145
197
  loopStart !== undefined
146
- ? `Error: Temporal property ${name} was violated.\n`
198
+ ? getTemporalHeadline(violation.properties ?? [name])
147
199
  : isInitial
148
200
  ? `Error: Property ${name} is violated by the initial state:`
149
201
  : `Error: Action property ${name} is violated.`,
@@ -152,6 +204,8 @@ const printResult = (result: CheckResult) => {
152
204
  if (violation.counts) console.log(violation.counts);
153
205
  console.log(headline);
154
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");
155
209
  else if (loopStart === undefined) printTrace(violation.trace);
156
210
  else {
157
211
  printTrace(violation.trace, "Error: The following behavior constitutes a counter-example:\n");
@@ -191,6 +245,20 @@ const checkSpec = async (specPath: string, args: ParsedArgs) => {
191
245
  console.error(`Cannot find the specification file ${specPath}`);
192
246
  return EXIT_STATUS.configParseError;
193
247
  }
248
+ const source = readFileSync(specPath, "utf8");
249
+ const fileName = basename(specPath, ".tla");
250
+ const moduleName = parseModuleFile(source, fileName).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
+ }
194
262
  const configPath =
195
263
  args.get("-config")?.[0] ??
196
264
  (args.has("-config") ? undefined : specPath.replace(/\.tla$/, ".cfg"));
@@ -214,13 +282,26 @@ const checkSpec = async (specPath: string, args: ParsedArgs) => {
214
282
  console.error("Error: expect a strategy such as final for -lncheck option.");
215
283
  return 1;
216
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
+ }
217
297
  const directory = dirname(specPath);
218
298
  console.log(`Checking ${basename(specPath)} with ${basename(configPath)}`);
219
299
  const result = await check({
220
300
  workers: getWorkerCount(args.get("-workers")),
221
301
  livenessCheck: ["final", "seqfinal", "off"].includes(livenessCheck) ? "final" : "default",
222
302
  seed: BigInt(seed),
223
- source: readFileSync(specPath, "utf8"),
303
+ dump: dumpValues && getDump(dumpValues),
304
+ source,
224
305
  config,
225
306
  onPause: () => readSync(0, Buffer.alloc(1)),
226
307
  loadModule: (name) => {
@@ -241,21 +322,33 @@ const checkSpec = async (specPath: string, args: ParsedArgs) => {
241
322
  return result.failure?.exitCode ?? EXIT_CODES[result.status];
242
323
  };
243
324
 
244
- // TLC prints the errors it raises itself. tla-ts names the others, such as a module SANY rejects.
245
- 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) => {
246
331
  if (error instanceof TlaConfigError || error instanceof TlaEvaluationError) {
247
332
  return console.log(`Error: ${error.message}`);
248
333
  }
249
- 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
+ if (report.parseError !== undefined) console.log(report.parseError);
337
+ console.log(
338
+ report.isFatal
339
+ ? `\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`
340
+ : `Semantic errors:\n\n${formatSanyErrors(report)}`,
341
+ );
342
+ console.log("Error: Parsing or semantic analysis failed.");
250
343
  };
251
344
 
252
345
  // Prints a TlaError and returns its exit code.
253
- const reportErrors = async (run: () => number | Promise<number>) => {
346
+ const reportErrors = async (run: () => number | Promise<number>, path?: string) => {
254
347
  try {
255
348
  return await run();
256
349
  } catch (error) {
257
350
  if (!(error instanceof TlaError)) throw error;
258
- printError(error);
351
+ printError(error, path);
259
352
  return getErrorExitCode(error);
260
353
  }
261
354
  };
@@ -266,7 +359,7 @@ const runEach = async (paths: string[], runPath: (path: string) => number | Prom
266
359
  const exitCodes: number[] = [];
267
360
  for (const [index, path] of paths.entries()) {
268
361
  if (index > 0) console.log("");
269
- exitCodes.push(await reportErrors(() => runPath(path)));
362
+ exitCodes.push(await reportErrors(() => runPath(path), path));
270
363
  }
271
364
  return exitCodes.find((exitCode) => exitCode !== EXIT_STATUS.success) ?? EXIT_STATUS.success;
272
365
  };
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
  };