tla-ts 0.0.10-dev.28c823e4b → 0.0.10-dev.63a6693bd

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 (172) hide show
  1. package/dist/compile.cjs +6 -6
  2. package/dist/compile.js +10 -10
  3. package/dist/deciders.cjs +29 -29
  4. package/dist/deciders.js +40 -40
  5. package/dist/index.cjs +1 -1
  6. package/dist/index.js +1 -1
  7. package/dist/parallel-worker.cjs +1 -1
  8. package/dist/parallel-worker.js +1 -1
  9. package/dist/prove-worker.cjs +1 -1
  10. package/dist/prove-worker.js +1 -1
  11. package/dist/prove.cjs +54 -54
  12. package/dist/prove.js +52 -52
  13. package/dist/run.cjs +42 -42
  14. package/dist/run.js +44 -44
  15. package/dist/tlapm.cjs +2 -2
  16. package/dist/tlapm.js +2 -2
  17. package/dist/transfer.cjs +39 -39
  18. package/dist/transfer.js +41 -41
  19. package/dist/worker.cjs +4 -4
  20. package/dist/worker.js +4 -4
  21. package/package.json +1 -1
  22. package/src/ast.ts +44 -39
  23. package/src/builtins.ts +4 -13
  24. package/src/check-failure.ts +116 -0
  25. package/src/check-trace.ts +282 -0
  26. package/src/check.ts +152 -518
  27. package/src/cli/options.ts +6 -31
  28. package/src/cli/shared.ts +1 -1
  29. package/src/cli/tlapm.ts +14 -13
  30. package/src/cli/tlc-arguments.ts +222 -210
  31. package/src/cli/tlc-output.ts +687 -0
  32. package/src/cli/tlc-usage.ts +1 -1
  33. package/src/cli/tlc.ts +34 -701
  34. package/src/cli/xml-exporter.ts +23 -33
  35. package/src/codegen.ts +5 -10
  36. package/src/coverage.ts +3 -10
  37. package/src/dependencies.ts +8 -13
  38. package/src/dfid.ts +16 -16
  39. package/src/environment-config.ts +315 -0
  40. package/src/environment.ts +45 -333
  41. package/src/errors.ts +3 -2
  42. package/src/evaluate.ts +5 -4
  43. package/src/fingerprints.ts +65 -1
  44. package/src/instances.ts +47 -10
  45. package/src/java-hash.ts +7 -0
  46. package/src/json.ts +4 -7
  47. package/src/levels.ts +39 -42
  48. package/src/liveness-checker.ts +24 -37
  49. package/src/liveness.ts +47 -54
  50. package/src/obligations/action.ts +4 -11
  51. package/src/obligations/anonymize.ts +4 -2
  52. package/src/obligations/expression.ts +18 -2
  53. package/src/obligations/generate.ts +45 -38
  54. package/src/obligations/index.ts +2 -2
  55. package/src/obligations/module.ts +27 -38
  56. package/src/obligations/normalize.ts +2 -1
  57. package/src/obligations/simplify.ts +39 -44
  58. package/src/obligations/source.ts +47 -57
  59. package/src/obligations/temporal.ts +5 -5
  60. package/src/parallel-worker.ts +10 -30
  61. package/src/parallel.ts +22 -45
  62. package/src/parser.ts +19 -34
  63. package/src/prover/decide-pool.ts +3 -3
  64. package/src/prover/deciders.ts +3 -3
  65. package/src/prover/isabelle/encode.ts +1 -1
  66. package/src/prover/isabelle/isar/inner-syntax.ts +9 -4
  67. package/src/prover/isabelle/isar/method.ts +14 -25
  68. package/src/prover/isabelle/isar/theory.ts +11 -10
  69. package/src/prover/isabelle/isar/type-check.ts +6 -6
  70. package/src/prover/isabelle/provers/blast/blast.ts +7 -63
  71. package/src/prover/isabelle/provers/hypsubst.ts +17 -26
  72. package/src/prover/isabelle/pure/bicompose.ts +9 -25
  73. package/src/prover/isabelle/pure/conv.ts +2 -8
  74. package/src/prover/isabelle/pure/drule.ts +9 -2
  75. package/src/prover/isabelle/pure/logic.ts +1 -1
  76. package/src/prover/isabelle/pure/raw-simplifier.ts +4 -13
  77. package/src/prover/isabelle/pure/rewriter.ts +5 -9
  78. package/src/prover/isabelle/pure/table.ts +2 -1
  79. package/src/prover/isabelle/pure/tactical.ts +42 -35
  80. package/src/prover/isabelle/pure/thm.ts +14 -11
  81. package/src/prover/isabelle/tla/classical-setup.ts +17 -14
  82. package/src/prover/isabelle/tla/context.ts +7 -2
  83. package/src/prover/isabelle/tla/logic.ts +10 -21
  84. package/src/prover/isabelle/tla/simpdata.ts +1 -10
  85. package/src/prover/prep/action.ts +11 -19
  86. package/src/prover/prep/fingerprint.ts +2 -5
  87. package/src/prover/prep/methods.ts +24 -3
  88. package/src/prover/prove.ts +87 -64
  89. package/src/prover/smt/context.ts +1 -2
  90. package/src/prover/smt/data.ts +418 -406
  91. package/src/prover/smt/encode.ts +30 -18
  92. package/src/prover/smt/rewrite.ts +657 -626
  93. package/src/prover/smt/solver/ast.ts +0 -22
  94. package/src/prover/smt/solver/auf-solver.ts +2 -5
  95. package/src/prover/smt/solver/context.ts +3 -3
  96. package/src/prover/smt/solver/e-matching.ts +1 -1
  97. package/src/prover/smt/solver/expr-safe-replace.ts +1 -1
  98. package/src/prover/smt/solver/internalizer.ts +1 -2
  99. package/src/prover/smt/solver/lp/dioph-eq.ts +1 -8
  100. package/src/prover/smt/solver/lp/hnf-cutter.ts +1 -1
  101. package/src/prover/smt/solver/lp/nla-core.ts +2 -6
  102. package/src/prover/smt/solver/mam-compiler.ts +4 -2
  103. package/src/prover/smt/solver/model-checker.ts +1 -1
  104. package/src/prover/smt/solver/model-finder.ts +12 -17
  105. package/src/prover/smt/solver/model-macro-solver.ts +11 -19
  106. package/src/prover/smt/solver/nlsat/algebraic.ts +9 -9
  107. package/src/prover/smt/solver/nlsat/atoms.ts +20 -4
  108. package/src/prover/smt/solver/nlsat/explain.ts +7 -22
  109. package/src/prover/smt/solver/nlsat/levelwise.ts +1 -6
  110. package/src/prover/smt/solver/nlsat/polynomial.ts +12 -3
  111. package/src/prover/smt/solver/nlsat/solver.ts +12 -24
  112. package/src/prover/smt/solver/nlsat/upolynomial-factorization.ts +1 -1
  113. package/src/prover/smt/solver/proto-model.ts +0 -4
  114. package/src/prover/smt/solver/quantifier-analyzer.ts +10 -10
  115. package/src/prover/smt/solver/quantifier-manager.ts +1 -5
  116. package/src/prover/smt/solver/smtlib-parser.ts +78 -94
  117. package/src/prover/smt/solver/theory-lra-bounds.ts +1 -2
  118. package/src/prover/smt/solver/theory-lra-internalize.ts +5 -16
  119. package/src/prover/tlapm/cache.ts +28 -18
  120. package/src/prover/tlapm/tlapm.ts +15 -9
  121. package/src/prover/verdict.ts +7 -0
  122. package/src/prover/zenon/check/check.ts +1 -2
  123. package/src/prover/zenon/check/records.ts +1 -1
  124. package/src/prover/zenon/check/relations.ts +2 -1
  125. package/src/prover/zenon/check/rewrites.ts +2 -15
  126. package/src/prover/zenon/check/sets.ts +40 -58
  127. package/src/prover/zenon/check/terms.ts +1 -2
  128. package/src/prover/zenon/eqrel.ts +2 -0
  129. package/src/prover/zenon/expr.ts +7 -0
  130. package/src/prover/zenon/index-table.ts +9 -19
  131. package/src/prover/zenon/isar.ts +35 -35
  132. package/src/prover/zenon/llproof.ts +2 -11
  133. package/src/prover/zenon/mltoll.ts +12 -28
  134. package/src/prover/zenon/parse.ts +3 -6
  135. package/src/prover/zenon/search.ts +4 -14
  136. package/src/prover/zenon/tla/functions.ts +2 -2
  137. package/src/prover/zenon/tla/llproof.ts +9 -11
  138. package/src/prover/zenon/tla/records.ts +1 -6
  139. package/src/prover/zenon/tla/sets.ts +15 -14
  140. package/src/prover/zenon/tla/tla.ts +7 -6
  141. package/src/resolve.ts +55 -72
  142. package/src/sany/generation.ts +394 -0
  143. package/src/sany/generator-def-entries.ts +210 -0
  144. package/src/sany/generator-definitions.ts +686 -0
  145. package/src/sany/generator-expressions.ts +1100 -0
  146. package/src/sany/generator-proofs.ts +662 -0
  147. package/src/sany/generator.ts +155 -2625
  148. package/src/sany/lexer.ts +17 -16
  149. package/src/sany/nodes.ts +6 -13
  150. package/src/sany/report.ts +3 -6
  151. package/src/sany/selectors.ts +35 -38
  152. package/src/sany/xml.ts +23 -55
  153. package/src/search.ts +65 -27
  154. package/src/simulate.ts +157 -133
  155. package/src/spec-description.ts +33 -48
  156. package/src/standard-modules.ts +16 -32
  157. package/src/state-graph.ts +2 -7
  158. package/src/substitution-levels.ts +5 -4
  159. package/src/successors.ts +5 -7
  160. package/src/tlc/messages.ts +20 -15
  161. package/src/tlc/order.ts +2 -9
  162. package/src/tlc/random.ts +4 -4
  163. package/src/tlc/replay.ts +8 -15
  164. package/src/tlc/tlc-operators.ts +2 -3
  165. package/src/tlc/trace-spec.ts +25 -45
  166. package/src/typescript/actions.ts +2 -4
  167. package/src/typescript/collections.ts +34 -20
  168. package/src/typescript/compile.ts +1 -3
  169. package/src/typescript/formula.ts +5 -3
  170. package/src/typescript/model.ts +4 -5
  171. package/src/typescript/steps.ts +20 -18
  172. package/src/values.ts +63 -158
package/src/cli/tlc.ts CHANGED
@@ -11,31 +11,11 @@ import {
11
11
  writeFileSync,
12
12
  } from "node:fs";
13
13
  import { basename, dirname, isAbsolute, join, resolve } from "node:path";
14
- import { arch, availableParallelism, release, tmpdir, type } from "node:os";
15
- import { pathToFileURL } from "node:url";
16
- import { getHeapStatistics } from "node:v8";
17
- import { version } from "../../package.json";
18
- import type { Expression } from "../ast";
19
- import type { CoverageReport } from "../coverage";
20
- import { describeRange } from "../evaluate";
21
- import type {
22
- CheckOptions,
23
- CheckProgress,
24
- InitialStateViolation,
25
- ModuleOperator,
26
- OutputLine,
27
- Postcondition,
28
- CheckResult,
29
- CheckStatus,
30
- InitialStates,
31
- SearchStatistics,
32
- TraceStep,
33
- Violation,
34
- } from "../check";
14
+ import { tmpdir } from "node:os";
15
+ import type { CheckOptions, ModuleOperator, CheckStatus } from "../check";
35
16
  import { parseConfig } from "../config";
36
- import { checkDepthFirst, type DepthFirstOutput } from "../dfid";
17
+ import { checkDepthFirst } from "../dfid";
37
18
  import {
38
- TlaAliasFormatError,
39
19
  TlaConfigError,
40
20
  TlaError,
41
21
  TlaEvaluationError,
@@ -43,20 +23,13 @@ import {
43
23
  TlaMissingCheckpointError,
44
24
  TlaSyntaxError,
45
25
  getUnexpectedException,
46
- UNEXPECTED_EXCEPTION,
47
26
  TlaSanyFatalError,
48
27
  } from "../errors";
49
- import { EXIT_STATUS, setExitCode } from "../exit-codes";
28
+ import { EXIT_STATUS } from "../exit-codes";
50
29
  import { check } from "../parallel";
51
30
  import { extractModule, parseModule } from "../parser";
52
- import { simulate, type SimulationOutput, type SimulationStatistics } from "../simulate";
31
+ import { simulate } from "../simulate";
53
32
  import type { StateDump } from "../state-graph";
54
- import {
55
- formatProbability,
56
- getActualProbability,
57
- getOptimisticProbability,
58
- getOutDegreeSummary,
59
- } from "../tlc/summary";
60
33
  import {
61
34
  getSanyStandardModules,
62
35
  SANY_174_STANDARD_MODULES,
@@ -68,16 +41,26 @@ import type { TlcVersion } from "../tlc/version";
68
41
  import {
69
42
  createMessagePrinter,
70
43
  formatTlcDate,
71
- formatInnerMessage,
72
44
  formatNestedMessage,
73
45
  formatTlcDuration,
74
46
  MESSAGE_CODE,
75
47
  MESSAGE_LEVEL,
76
48
  type MessagePrinter,
49
+ zeroPad,
77
50
  } from "../tlc/messages";
78
- import { formatState } from "../values";
79
51
  import { addRuntimeInvariants } from "./runtime-invariants";
80
52
  import { parseTlcArguments, type TlcArguments } from "./tlc-arguments";
53
+ import {
54
+ getClassPath,
55
+ printCheckProgress,
56
+ printCommandLineError,
57
+ printDepthFirst,
58
+ printResult,
59
+ printSimulation,
60
+ printStartupBanner,
61
+ printWelcome,
62
+ type Timing,
63
+ } from "./tlc-output";
81
64
  import { getTlcUsage } from "./tlc-usage";
82
65
  import {
83
66
  createModuleLoader,
@@ -131,559 +114,6 @@ const getStateDump = (values: string[]): StateDump => {
131
114
  };
132
115
  };
133
116
 
134
- const printInitialStatesProgress = (printer: MessagePrinter, count: number) =>
135
- printer.print(
136
- MESSAGE_CODE.computingInitProgress,
137
- MESSAGE_LEVEL.none,
138
- `Computed ${count} initial states...`,
139
- );
140
-
141
- const getInitialViolationHeadline = (
142
- status: InitialStateViolation["status"],
143
- name: string | undefined,
144
- ) =>
145
- status === "invariant-violation"
146
- ? {
147
- code: MESSAGE_CODE.invariantViolatedInitial,
148
- text: `Invariant ${name} is violated by the initial state:`,
149
- }
150
- : {
151
- code: MESSAGE_CODE.propertyViolatedInitial,
152
- text: `Property ${name} is violated by the initial state:`,
153
- };
154
-
155
- const printTraceOutput = (printer: MessagePrinter, lines: OutputLine[] | undefined) =>
156
- lines?.forEach((line) => {
157
- if (typeof line === "string") return console.log(line);
158
- if (line.kind === "initial-states-progress") {
159
- return printInitialStatesProgress(printer, line.count);
160
- }
161
- const headline = getInitialViolationHeadline(line.status, line.name);
162
- printer.print(
163
- headline.code,
164
- MESSAGE_LEVEL.error,
165
- `${headline.text}\n${formatState(line.state)}`,
166
- );
167
- });
168
-
169
- interface TlcPrinter extends MessagePrinter {
170
- isDiffTrace: boolean;
171
- }
172
-
173
- const BEHAVIOR = {
174
- code: MESSAGE_CODE.behaviorUpToThisPoint,
175
- text: "The behavior up to this point is:",
176
- };
177
-
178
- const printTrace = (
179
- printer: TlcPrinter,
180
- trace: TraceStep[],
181
- heading: { code: number; text: string } = BEHAVIOR,
182
- isRebuiltAfterHeading = false,
183
- isLastDiffed = heading !== BEHAVIOR,
184
- ) => {
185
- if (trace.length > 0) printer.print(heading.code, MESSAGE_LEVEL.error, heading.text);
186
- try {
187
- trace.forEach((step, index) => {
188
- if (index > 0 || isRebuiltAfterHeading) printTraceOutput(printer, step.output);
189
- const isDiffed =
190
- printer.isDiffTrace && index > 0 && (isLastDiffed || index < trace.length - 1);
191
- printer.print(
192
- MESSAGE_CODE.statePrint2,
193
- MESSAGE_LEVEL.state,
194
- `${index + 1}: <${step.label ?? step.action ?? "Initial predicate"}>\n${formatState(step.state, isDiffed ? trace[index - 1].state : undefined)}`,
195
- );
196
- });
197
- } catch (error) {
198
- if (!(error instanceof TlaAliasFormatError)) throw error;
199
- printer.print(MESSAGE_CODE.general, MESSAGE_LEVEL.error, error.message);
200
- }
201
- };
202
-
203
- const COUNTER_EXAMPLE = {
204
- code: MESSAGE_CODE.counterExample,
205
- text: "The following behavior constitutes a counter-example:\n",
206
- };
207
-
208
- const getTemporalHeadline = (names: string[], version: TlcVersion) =>
209
- version === "1.7.4" || names.length === 0
210
- ? "Temporal properties were violated.\n"
211
- : names.length === 1
212
- ? `Temporal property ${names[0]} was violated.\n`
213
- : `Temporal properties ${names.slice(0, -1).join(", ")}${names.length > 2 ? "," : ""} and ${names[names.length - 1]} were violated.\n`;
214
-
215
- const formatFingerprintTrace = (sources: Expression[]) =>
216
- sources
217
- .filter((source, index) => source !== sources[index - 1])
218
- .map((source, index) => `${index}) ${describeRange(source)}\n`)
219
- .toReversed()
220
- .join("");
221
-
222
- const formatCallStack = (expressions: Expression[]) => {
223
- if (expressions.length === 0) return " The error call stack is empty.\n";
224
- const lines: string[] = [];
225
- expressions.forEach((expression, index) => {
226
- const range = expression.location.range;
227
- if (expression === expressions[index - 1] || !range) return;
228
- lines.push(
229
- `${lines.length}. Line ${range.start.line}, column ${range.start.column} to line ${range.end.line}, column ${range.end.column} in ${range.module}\n`,
230
- );
231
- });
232
- return `${lines.join("")}\n`;
233
- };
234
-
235
- const printInitialStates = (printer: MessagePrinter, initialStates: InitialStates) => {
236
- const generated = initialStates.generated;
237
- const distinct = initialStates.distinct;
238
- const date = formatTlcDate(new Date());
239
- if (generated === distinct) {
240
- printer.print(
241
- MESSAGE_CODE.initGenerated1,
242
- MESSAGE_LEVEL.none,
243
- `Finished computing initial states: ${distinct} distinct state${distinct === 1 ? "" : "s"} generated at ${date}.`,
244
- );
245
- return;
246
- }
247
- printer.print(
248
- MESSAGE_CODE.initGenerated2,
249
- MESSAGE_LEVEL.none,
250
- `Finished computing initial states: ${generated} state${generated === 1 ? "" : "s"} generated, with ${distinct} of them distinct at ${date}.`,
251
- );
252
- };
253
-
254
- interface Timing {
255
- startTime: number;
256
- isParsed: boolean;
257
- livenessStartTime: number | undefined;
258
- }
259
-
260
- const printProgress = (
261
- printer: MessagePrinter,
262
- statistics: SearchStatistics,
263
- startTime?: number,
264
- ) => {
265
- const minutes = Math.max(Date.now() - (startTime ?? 0), 1) / 60_000;
266
- const formatCount = (count: number) => count.toLocaleString("en-US");
267
- const getRate = (count: number, unit: string) =>
268
- startTime === undefined ? "" : ` (${formatCount(Math.floor(count / minutes))} ${unit}/min)`;
269
- printer.print(
270
- MESSAGE_CODE.progress,
271
- MESSAGE_LEVEL.none,
272
- `Progress(${Math.max(statistics.depth, 1)}) at ${formatTlcDate(new Date())}: ${formatCount(statistics.generatedStates)} states generated${getRate(statistics.generatedStates, "s")}, ${formatCount(statistics.distinctStates)} distinct states found${getRate(statistics.distinctStates, "ds")}, ${formatCount(statistics.queuedStates)} states left on queue.`,
273
- );
274
- };
275
-
276
- const COVERAGE_CODES = {
277
- init: MESSAGE_CODE.coverageInit,
278
- next: MESSAGE_CODE.coverageNext,
279
- invariant: MESSAGE_CODE.coverageProperty,
280
- implied: MESSAGE_CODE.coverageProperty,
281
- constraint: MESSAGE_CODE.coverageConstraint,
282
- };
283
-
284
- const COVERAGE_OVERHEAD = 5 * 60_000;
285
-
286
- const printCoverage = (printer: MessagePrinter, coverage: CoverageReport, startTime: number) => {
287
- const print = (code: number, text: string) => printer.print(code, MESSAGE_LEVEL.none, text);
288
- print(
289
- MESSAGE_CODE.coverageStart,
290
- `The coverage statistics at ${formatTlcDate(new Date())} (see https://explain.tlapl.us/module-coverage-statistics for how to interpret the following statistics).`,
291
- );
292
- coverage.variables.forEach((variable) =>
293
- print(MESSAGE_CODE.coverageVariable, `<${variable.label}>: ${variable.distinct}`),
294
- );
295
- coverage.relations.forEach((relation) => {
296
- const code = COVERAGE_CODES[relation.kind];
297
- print(
298
- code,
299
- code === MESSAGE_CODE.coverageProperty
300
- ? `<${relation.label}>`
301
- : `<${relation.label}>: ${relation.distinct}:${relation.generated}`,
302
- );
303
- relation.expressions.forEach((expression) => {
304
- const location = ` ${"|".repeat(expression.depth)}${expression.location}`;
305
- if (expression.cost > 0) {
306
- print(
307
- MESSAGE_CODE.coverageValueCost,
308
- `${location}: ${expression.count}:${expression.cost}`,
309
- );
310
- } else print(MESSAGE_CODE.coverageValue, `${location}: ${expression.count}`);
311
- });
312
- });
313
- if (Date.now() - startTime > COVERAGE_OVERHEAD) {
314
- print(
315
- MESSAGE_CODE.coverageEndOverhead,
316
- "End of statistics (please note that for performance reasons large models\nare best checked with coverage and cost statistics disabled).",
317
- );
318
- } else print(MESSAGE_CODE.coverageEnd, "End of statistics.");
319
- };
320
-
321
- const getClassPath = (directory: string, module: string) => join(directory, `${module}.class`);
322
-
323
- const printCheckProgress = (
324
- printer: TlcPrinter,
325
- progress: CheckProgress,
326
- timing: Timing,
327
- directory: string,
328
- ) => {
329
- const print = printer.print;
330
- switch (progress.kind) {
331
- case "parsed":
332
- timing.isParsed = true;
333
- if (printer.isTool) print(MESSAGE_CODE.sanyFinished, MESSAGE_LEVEL.none, "SANY finished.");
334
- print(
335
- MESSAGE_CODE.starting,
336
- MESSAGE_LEVEL.none,
337
- `Starting... (${formatTlcDate(new Date())})`,
338
- );
339
- return;
340
- case "constant-level-invariant":
341
- if (printer.version === "1.7.4") return;
342
- print(
343
- MESSAGE_CODE.constantLevelInvariant,
344
- MESSAGE_LEVEL.warning,
345
- `The invariant ${progress.name} is a constant-level formula (i.e., it contains no variables, primes, or temporal operators) and evaluates to TRUE. To assert constant-level formulas in your spec, use ASSUME ConstInv. If you optionally want to give the assumption a name, write ASSUME YourAssumption == ConstInv instead. See https://explain.tlapl.us/assumptions-and-invariants for additional details.`,
346
- );
347
- return;
348
- case "state-level-property":
349
- if (printer.version === "1.7.4") return;
350
- print(
351
- MESSAGE_CODE.stateLevelProperty,
352
- MESSAGE_LEVEL.warning,
353
- `The formula ${progress.name} is a state-level formula, but it was used as a PROPERTY (or PROPERTIES), where a temporal formula is typically expected. State-level formulas used as PROPERTY or PROPERTIES are only checked in the initial state. To verify that the formula ${progress.name} holds in all states of every behavior, use INVARIANT ${progress.name} instead. Alternatively, applying the "always" temporal operator ([]) to the state-level formula ${progress.name} changes it into a temporal formula, asserting that ${progress.name} holds in all states of every behavior. See https://explain.tlapl.us/invariants-and-properties for additional details.`,
354
- );
355
- return;
356
- case "liveness-initializing":
357
- if (progress.isSymmetric) {
358
- print(
359
- MESSAGE_CODE.livenessSymmetry,
360
- MESSAGE_LEVEL.warning,
361
- "Declaring symmetry during liveness checking is dangerous. It might cause TLC to miss violations of the stated liveness properties. Please check liveness without symmetry defined.",
362
- );
363
- }
364
- if (progress.isConstrained && printer.version === "1.7.4") {
365
- print(
366
- MESSAGE_CODE.livenessConstraints,
367
- MESSAGE_LEVEL.warning,
368
- "Declaring state or action constraints during liveness checking is dangerous: Please read section 14.3.5 on page 247 of Specifying Systems (https://lamport.azurewebsites.net/tla/book.html) and optionally the discussion at https://discuss.tlapl.us/msg00994.html for more details.",
369
- );
370
- }
371
- return;
372
- case "liveness-prepared":
373
- print(
374
- MESSAGE_CODE.temporalBranches,
375
- MESSAGE_LEVEL.none,
376
- `Implied-temporal checking--satisfiability problem has ${progress.branches} branches.`,
377
- );
378
- return;
379
- case "java-override": {
380
- const location = pathToFileURL(resolve(getClassPath(directory, progress.module))).href;
381
- print(
382
- progress.isMatched ? MESSAGE_CODE.javaOverrideLoaded : MESSAGE_CODE.javaOverrideMismatch,
383
- progress.isMatched ? MESSAGE_LEVEL.none : MESSAGE_LEVEL.warning,
384
- `${progress.isMatched ? "Loading" : "Failed to match"} ${progress.operator} operator override from ${location.replace("file:///", "file:/")} with signature: <Java Method: ${progress.signature}>.`,
385
- );
386
- return;
387
- }
388
- case "initial-states-started":
389
- print(MESSAGE_CODE.computingInit, MESSAGE_LEVEL.none, "Computing initial states...");
390
- return;
391
- case "initial-states-progress":
392
- printInitialStatesProgress(printer, progress.count);
393
- return;
394
- case "initial-states-computed":
395
- printInitialStates(printer, progress.initialStates);
396
- return;
397
- case "progress":
398
- printProgress(printer, progress.statistics, timing.startTime);
399
- if (progress.statistics.coverage) {
400
- printCoverage(printer, progress.statistics.coverage, timing.startTime);
401
- }
402
- return;
403
- case "liveness-started": {
404
- timing.livenessStartTime = Date.now();
405
- if (progress.isComplete) printProgress(printer, progress.statistics);
406
- const branches = progress.branches > 1 ? `${progress.branches} branches of ` : "";
407
- const states = progress.branches * progress.states;
408
- print(
409
- MESSAGE_CODE.checkingTemporal,
410
- MESSAGE_LEVEL.none,
411
- `Checking ${branches}temporal properties for the ${progress.isComplete ? "complete" : "current"} state space with ${states} total distinct states at (${formatTlcDate(new Date())})`,
412
- );
413
- return;
414
- }
415
- case "liveness-finished":
416
- printLivenessEnd(printer, timing);
417
- return;
418
- case "sequential-fallback":
419
- process.stderr.write(
420
- `Warning: the search ordered the string ${JSON.stringify(progress.string)} against another string it created, so tla-ts checks the model again with one worker. Workers don't agree on the order of strings the search creates.\n`,
421
- );
422
- return;
423
- case "warning":
424
- print(progress.code, MESSAGE_LEVEL.warning, progress.text);
425
- return;
426
- case "violation":
427
- printViolation(progress.status, progress.violation, printer);
428
- }
429
- };
430
-
431
- const printLivenessEnd = (printer: MessagePrinter, timing: Timing) => {
432
- if (timing.livenessStartTime === undefined) return;
433
- printer.print(
434
- MESSAGE_CODE.checkingTemporalEnd,
435
- MESSAGE_LEVEL.none,
436
- `Finished checking temporal properties in ${formatTlcDuration(Date.now() - timing.livenessStartTime)} at ${formatTlcDate(new Date())}`,
437
- );
438
- timing.livenessStartTime = undefined;
439
- };
440
-
441
- const printPostcondition = (printer: MessagePrinter, postcondition: Postcondition | undefined) => {
442
- if (!postcondition) return;
443
- if (postcondition.counts) console.log(postcondition.counts);
444
- printer.print(
445
- postcondition.code,
446
- MESSAGE_LEVEL.error,
447
- formatInnerMessage(postcondition.code, postcondition.message, printer.isTool),
448
- );
449
- };
450
-
451
- const printViolation = (status: CheckStatus, violation: Violation, printer: TlcPrinter) => {
452
- const print = printer.print;
453
- const name = violation.name;
454
- const loopStart = violation.loopStart;
455
- const isInitial =
456
- loopStart === undefined &&
457
- violation.trace.length === 1 &&
458
- (status === "invariant-violation" || status === "liveness-violation");
459
- const temporal = {
460
- code: MESSAGE_CODE.temporalPropertyViolated,
461
- text: getTemporalHeadline(violation.properties ?? [name], printer.version),
462
- };
463
- const headline = {
464
- success: undefined,
465
- error: undefined,
466
- "assumption-violation": violation.message
467
- ? {
468
- code: MESSAGE_CODE.assumptionEvaluationError,
469
- text: formatInnerMessage(
470
- MESSAGE_CODE.assumptionEvaluationError,
471
- `Evaluating assumption ${name} failed.\n${violation.message}`,
472
- printer.isTool,
473
- ),
474
- }
475
- : { code: MESSAGE_CODE.assumptionFalse, text: `Assumption ${name} is false.` },
476
- deadlock: { code: MESSAGE_CODE.deadlockReached, text: "Deadlock reached." },
477
- "invariant-violation": isInitial
478
- ? getInitialViolationHeadline("invariant-violation", name)
479
- : { code: MESSAGE_CODE.invariantViolatedBehavior, text: `Invariant ${name} is violated.` },
480
- "property-violation": temporal,
481
- "liveness-violation":
482
- loopStart !== undefined
483
- ? temporal
484
- : isInitial
485
- ? getInitialViolationHeadline("liveness-violation", name)
486
- : {
487
- code: MESSAGE_CODE.actionPropertyViolatedBehavior,
488
- text: `Action property ${name} is violated.`,
489
- },
490
- "postcondition-violation": {
491
- code: violation.postcondition?.code ?? MESSAGE_CODE.general,
492
- text: formatInnerMessage(
493
- violation.postcondition?.code ?? MESSAGE_CODE.general,
494
- violation.message ?? `Postcondition ${name} is false.`,
495
- printer.isTool,
496
- ),
497
- },
498
- }[status];
499
- const isProperty = status === "property-violation";
500
- const isLasso = loopStart !== undefined && !isProperty;
501
- const isCounterExample = isProperty || isLasso;
502
- const isRebuiltFirst = isCounterExample && printer.version !== "1.7.4";
503
- if (isRebuiltFirst) printTraceOutput(printer, violation.trace[0]?.output);
504
- if (violation.counts) console.log(violation.counts);
505
- if (headline) {
506
- const text = isInitial
507
- ? `${headline.text}\n${formatState(violation.trace[0].state)}`
508
- : headline.text;
509
- print(headline.code, MESSAGE_LEVEL.error, text);
510
- }
511
- if (!isInitial) {
512
- if (!isCounterExample) printTraceOutput(printer, violation.trace[0]?.output);
513
- printTrace(
514
- printer,
515
- violation.trace,
516
- isCounterExample ? COUNTER_EXAMPLE : undefined,
517
- isCounterExample && !isRebuiltFirst,
518
- );
519
- }
520
- printTraceOutput(printer, violation.traceOutput);
521
- if (isLasso) {
522
- const label = violation.loopLabel;
523
- if (loopStart === violation.trace.length - 1)
524
- print(MESSAGE_CODE.statePrint3, MESSAGE_LEVEL.state, `${loopStart + 2}: Stuttering`);
525
- else if (printer.isTool)
526
- print(
527
- MESSAGE_CODE.backToState,
528
- MESSAGE_LEVEL.state,
529
- `${loopStart + 1}: Back to state${label ? `: <${label}>\n` : ""}`,
530
- );
531
- else console.log(`Back to state ${loopStart + 1}${label ? `: <${label}>\n` : ""}`);
532
- }
533
- if (violation.warning && printer.version !== "1.7.4")
534
- print(violation.warning.code, MESSAGE_LEVEL.warning, violation.warning.text);
535
- const postcondition =
536
- violation.unwitnessed ??
537
- (status === "postcondition-violation" ? undefined : violation.postcondition);
538
- printTraceOutput(printer, violation.postconditionOutput);
539
- printPostcondition(printer, postcondition);
540
- return !isInitial && status !== "assumption-violation";
541
- };
542
-
543
- const printNestedExpressions = (printer: MessagePrinter, callStack: Expression[]) =>
544
- printer.print(
545
- MESSAGE_CODE.nestedExpression,
546
- MESSAGE_LEVEL.error,
547
- `The error occurred when TLC was evaluating the nested\nexpressions at the following positions:\n${formatCallStack(callStack)}`,
548
- );
549
-
550
- const printSuccess = (printer: MessagePrinter, optimistic: number, actual: number | undefined) =>
551
- printer.print(
552
- MESSAGE_CODE.success,
553
- MESSAGE_LEVEL.none,
554
- [
555
- "Model checking completed. No error has been found.",
556
- " Estimates of the probability that TLC did not check all reachable states",
557
- " because two distinct states had the same fingerprint:",
558
- ` calculated (optimistic): val = ${formatProbability(optimistic)}`,
559
- ...(actual === undefined
560
- ? []
561
- : [` based on the actual fingerprints: val = ${formatProbability(actual)}`]),
562
- ].join("\n"),
563
- );
564
-
565
- const printDepthFirst = (printer: TlcPrinter, output: DepthFirstOutput) => {
566
- switch (output.kind) {
567
- case "message":
568
- printer.print(
569
- output.code,
570
- output.isError ? MESSAGE_LEVEL.error : MESSAGE_LEVEL.none,
571
- printer.isTool ? output.toolMessage : output.message,
572
- );
573
- return;
574
- case "behavior":
575
- output.states.forEach((state, index) =>
576
- output.isInvariant
577
- ? printer.print(
578
- MESSAGE_CODE.statePrint2,
579
- MESSAGE_LEVEL.state,
580
- `${index + 1}: \n${formatState(state, printer.isDiffTrace ? output.states[index - 1] : undefined)}`,
581
- )
582
- : printer.print(
583
- MESSAGE_CODE.statePrint1,
584
- MESSAGE_LEVEL.state,
585
- `${index + 1}:\n${formatState(state)}`,
586
- ),
587
- );
588
- return;
589
- case "nested-expressions":
590
- printNestedExpressions(printer, output.callStack);
591
- return;
592
- case "success":
593
- printSuccess(printer, output.optimistic, output.actual);
594
- }
595
- };
596
-
597
- const printResult = (result: CheckResult, printer: TlcPrinter, timing: Timing) => {
598
- const print = printer.print;
599
- if (result.failure) {
600
- const failure = result.failure;
601
- const message = printer.isTool ? failure.toolMessage : failure.message;
602
- const printCallStack = () => {
603
- const fingerprint = failure.fingerprint;
604
- if (fingerprint) {
605
- const trace =
606
- failure.callStack?.length && printer.version !== "1.7.4"
607
- ? formatCallStack(failure.callStack)
608
- : formatFingerprintTrace(fingerprint.sources);
609
- print(
610
- MESSAGE_CODE.fingerprintFailed,
611
- MESSAGE_LEVEL.error,
612
- `TLC was unable to fingerprint.\n\nFingerprint Stack Trace:\n${trace}\nReason:\n${formatNestedMessage(fingerprint.reason, printer.isTool)}`,
613
- );
614
- return;
615
- }
616
- if (failure.callStack) printNestedExpressions(printer, failure.callStack);
617
- };
618
- if (failure.isCallStackFirst) printCallStack();
619
- const initialState =
620
- failure.initialState &&
621
- (() => {
622
- try {
623
- return `While working on the initial state:\n${formatState(failure.initialState)}`;
624
- } catch (error) {
625
- if (!(error instanceof TlaEvaluationError)) throw error;
626
- throw setExitCode(
627
- new TlaEvaluationError(`${UNEXPECTED_EXCEPTION}${error.message}`),
628
- EXIT_STATUS.error,
629
- );
630
- }
631
- })();
632
- print(
633
- initialState ? MESSAGE_CODE.initialState : failure.code,
634
- MESSAGE_LEVEL.error,
635
- initialState ? `${message}\n${initialState}` : message,
636
- );
637
- printTraceOutput(printer, failure.trace[0]?.output);
638
- printTrace(printer, failure.trace);
639
- const traceFailure = failure.traceFailure;
640
- if (traceFailure) {
641
- print(
642
- traceFailure.code,
643
- MESSAGE_LEVEL.error,
644
- printer.isTool ? traceFailure.toolMessage : traceFailure.message,
645
- );
646
- }
647
- printTraceOutput(printer, failure.traceOutput);
648
- printPostcondition(printer, failure.postcondition);
649
- if (!failure.isCallStackFirst) printCallStack();
650
- } else if (result.violation) {
651
- if (!printViolation(result.status, result.violation, printer)) return;
652
- const additionalViolation = result.additionalViolation;
653
- if (additionalViolation) printViolation("property-violation", additionalViolation, printer);
654
- if (result.liveCallStack) printNestedExpressions(printer, result.liveCallStack);
655
- } else if (result.status === "success") {
656
- printLivenessEnd(printer, timing);
657
- printSuccess(
658
- printer,
659
- getOptimisticProbability(result.distinctStates, result.generatedStates),
660
- result.fingerprintDistance === undefined
661
- ? undefined
662
- : getActualProbability(result.fingerprintDistance),
663
- );
664
- }
665
- if (result.failure?.isWithoutStatistics) return;
666
- if (result.status !== "success") printLivenessEnd(printer, timing);
667
- if (result.coverage) printCoverage(printer, result.coverage, timing.startTime);
668
- if (printer.isTool) printProgress(printer, result, timing.startTime);
669
- print(
670
- MESSAGE_CODE.stats,
671
- MESSAGE_LEVEL.none,
672
- `${result.generatedStates} states generated, ${result.distinctStates} distinct states found, ${result.queuedStates} states left on queue.`,
673
- );
674
- const is174 = printer.version === "1.7.4";
675
- const outDegrees = is174 ? (result.outDegrees ?? result.violationOutDegrees) : result.outDegrees;
676
- if (!is174 || outDegrees) {
677
- print(
678
- MESSAGE_CODE.searchDepth,
679
- MESSAGE_LEVEL.none,
680
- `The depth of the complete state graph search is ${is174 ? Math.max(result.depth, 1) : result.depth}.`,
681
- );
682
- }
683
- const outDegree = outDegrees && getOutDegreeSummary(outDegrees);
684
- if (outDegree) print(MESSAGE_CODE.stateGraphOutdegree, MESSAGE_LEVEL.none, outDegree);
685
- };
686
-
687
117
  // Deviation from TLC: Java names the directory by a random unsigned long, and tla-ts by what the directory holds, so that each run of a spec prints the same files.
688
118
  const getTemporaryName = (contents: string) => getTlcFingerprint([contents]).toString();
689
119
 
@@ -712,9 +142,6 @@ const createFileDescriber = (
712
142
  };
713
143
  };
714
144
 
715
- const printWelcome = (printer: MessagePrinter) =>
716
- printer.print(MESSAGE_CODE.version, MESSAGE_LEVEL.none, `TLC2 Version ${version} (rev: tla-ts)`);
717
-
718
145
  const getEmbeddedConfig = (contents: string, name: string) => {
719
146
  const lines = contents.split(/\r?\n/);
720
147
  const start = lines.findIndex(
@@ -728,94 +155,6 @@ const getEmbeddedConfig = (contents: string, name: string) => {
728
155
  .trim()}\n`;
729
156
  };
730
157
 
731
- const printCommandLineError = (isTool: boolean, version: TlcVersion, message: string) => {
732
- const printer = createMessagePrinter(isTool, true, version);
733
- printWelcome(printer);
734
- printer.print(
735
- MESSAGE_CODE.commandLineError,
736
- MESSAGE_LEVEL.error,
737
- `${message}\nUsage: java tlc2.TLC [-help] [-option] inputfile`,
738
- );
739
- return 1;
740
- };
741
-
742
- // Deviation from TLC: tla-ts keeps its fingerprints and its queue of states in memory.
743
- const printStartupBanner = (printer: MessagePrinter, args: TlcArguments) => {
744
- const workers = `${args.workers} worker${args.workers === 1 ? "" : "s"} on ${availableParallelism()} cores with ${Math.floor(getHeapStatistics().heap_size_limit / 1024 / 1024)}MB heap and 0MB offheap memory [pid: ${process.pid}] (${type()} ${release()} ${arch()}, Node.js ${process.versions.node} ${process.arch.endsWith("64") ? 64 : 32}bit`;
745
- if (args.mode === "model-check" && args.dfidDepth !== undefined) {
746
- printer.print(
747
- MESSAGE_CODE.depthFirstModelChecking,
748
- MESSAGE_LEVEL.none,
749
- `Running depth-first search Model-Checking with fp ${args.fingerprintIndex} and seed ${args.seed} with ${workers}).`,
750
- );
751
- return;
752
- }
753
- if (args.mode === "model-check") {
754
- printer.print(
755
- MESSAGE_CODE.modelChecking,
756
- MESSAGE_LEVEL.none,
757
- `Running breadth-first search Model-Checking with fp ${args.fingerprintIndex} and seed ${args.seed} with ${workers}, MemFPSet, MemStateQueue).`,
758
- );
759
- return;
760
- }
761
- printer.print(
762
- MESSAGE_CODE.simulating,
763
- MESSAGE_LEVEL.none,
764
- `Running ${args.scheduler === "rl" ? "RL" : "Random"} Simulation with seed ${args.seed} with ${workers}).`,
765
- );
766
- };
767
-
768
- const printSimulation = (printer: TlcPrinter, output: SimulationOutput) => {
769
- const print = printer.print;
770
- switch (output.kind) {
771
- case "message":
772
- print(
773
- output.code,
774
- output.isError ? MESSAGE_LEVEL.error : MESSAGE_LEVEL.none,
775
- printer.isTool ? output.toolMessage : output.message,
776
- );
777
- return;
778
- case "behavior": {
779
- const last = output.trace[output.trace.length - 1];
780
- if (!output.isLastStateOnly) {
781
- printTrace(printer, output.trace, BEHAVIOR, false, true);
782
- return;
783
- }
784
- print(MESSAGE_CODE.errorState, MESSAGE_LEVEL.none, "The error state is:\n");
785
- print(MESSAGE_CODE.statePrint1, MESSAGE_LEVEL.state, `:\n${formatState(last.state)}`);
786
- return;
787
- }
788
- case "progress": {
789
- const statistics = output.statistics;
790
- if (printer.isTool) {
791
- printSimulationProgress(printer, statistics);
792
- return;
793
- }
794
- const variance = statistics.levelM2 / (statistics.traces + 1);
795
- print(
796
- MESSAGE_CODE.simulationProgress,
797
- MESSAGE_LEVEL.none,
798
- `Progress: ${statistics.generatedStates} states checked, ${statistics.traces} traces generated (trace length: mean=${statistics.levelMean}, var(x)=${Math.round(variance)}, sd=${Math.round(Math.sqrt(variance))})`,
799
- );
800
- return;
801
- }
802
- case "summary":
803
- if (printer.isTool) printSimulationProgress(printer, output.statistics);
804
- print(
805
- MESSAGE_CODE.simulationStats,
806
- MESSAGE_LEVEL.none,
807
- `The number of states generated: ${output.statistics.generatedStates}\nSimulation using seed ${output.statistics.seed} and aril ${output.statistics.aril}`,
808
- );
809
- }
810
- };
811
-
812
- const printSimulationProgress = (printer: MessagePrinter, statistics: SimulationStatistics) =>
813
- printer.print(
814
- MESSAGE_CODE.simulationProgress,
815
- MESSAGE_LEVEL.none,
816
- `Progress(${statistics.traces}) at ${formatTlcDate(new Date())}: ${statistics.generatedStates} states generated, -1 distinct states found, -1 states left on queue.`,
817
- );
818
-
819
158
  const getJavaPath = (path: string) => path.replace(/\/+/g, "/").replace(/(.)\/$/, "$1");
820
159
 
821
160
  const getJavaParent = (path: string) => {
@@ -884,8 +223,7 @@ const makeJavaDirectory = (path: string) => {
884
223
 
885
224
  const createMetadir = (args: TlcArguments) => {
886
225
  const now = new Date();
887
- const pad = (value: number, length = 2) => String(value).padStart(length, "0");
888
- const name = `${pad(now.getFullYear() % 100)}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}-${pad(now.getHours())}-${pad(now.getMinutes())}-${pad(now.getSeconds())}.${pad(now.getMilliseconds(), 3)}`;
226
+ const name = `${zeroPad(now.getFullYear() % 100)}-${zeroPad(now.getMonth() + 1)}-${zeroPad(now.getDate())}-${zeroPad(now.getHours())}-${zeroPad(now.getMinutes())}-${zeroPad(now.getSeconds())}.${zeroPad(now.getMilliseconds(), 3)}`;
889
227
  const directory = join(args.metadir ?? "states", name);
890
228
  mkdirSync(directory, { recursive: true });
891
229
  return directory;
@@ -896,7 +234,7 @@ const checkSpec = async (
896
234
  args: TlcArguments,
897
235
  dump: StateDump | undefined,
898
236
  java: JavaProperties,
899
- printer: TlcPrinter,
237
+ printer: MessagePrinter,
900
238
  ) => {
901
239
  const livenessCheck = args.livenessCheck;
902
240
  const version = printer.version;
@@ -1156,24 +494,21 @@ const formatSanyErrors = (error: TlaSyntaxError, specName: string) => {
1156
494
  export const checkSpecs = async (args: string[], java: JavaProperties) => {
1157
495
  const version = java.tlcVersion ?? "master";
1158
496
  const parsed = parseTlcArguments(args);
497
+ if (parsed === "usage") {
498
+ console.log(getTlcUsage());
499
+ return 1;
500
+ }
1159
501
  if ("error" in parsed) {
1160
- if (parsed.isUncaught) {
502
+ if (parsed.kind === "uncaught") {
1161
503
  console.error(`Exception in thread "main" ${parsed.error}`);
1162
504
  return 1;
1163
505
  }
1164
506
  return printCommandLineError(parsed.isTool, version, parsed.error);
1165
507
  }
1166
- if (parsed.isUsage) {
1167
- console.log(getTlcUsage());
1168
- return 1;
508
+ const dump = parsed.dump && getStateDump(parsed.dump);
509
+ if (dump?.path.startsWith("${metadir}")) {
510
+ dump.path = dump.path.replaceAll("${metadir}", createMetadir(parsed));
1169
511
  }
1170
- const dump =
1171
- parsed.dump &&
1172
- getStateDump(
1173
- parsed.dump.map((value) =>
1174
- value.includes("${metadir}") ? value.replace("${metadir}", createMetadir(parsed)) : value,
1175
- ),
1176
- );
1177
512
  const dumpPath = dump?.path;
1178
513
  if (dumpPath !== undefined) {
1179
514
  try {
@@ -1226,16 +561,14 @@ export const checkSpecs = async (args: string[], java: JavaProperties) => {
1226
561
  const exitCodes: number[] = [];
1227
562
  for (const [index, path] of paths.entries()) {
1228
563
  if (index > 0) console.log("");
1229
- const printer = {
1230
- ...createMessagePrinter(
1231
- parsed.isTool,
1232
- parsed.isWarningEnabled,
1233
- version,
1234
- parsed.suppressedCodes,
1235
- parsed.errorCodes,
1236
- ),
564
+ const printer = createMessagePrinter({
565
+ isTool: parsed.isTool,
566
+ isWarningEnabled: parsed.isWarningEnabled,
1237
567
  isDiffTrace: parsed.isDiffTrace,
1238
- };
568
+ version,
569
+ suppressedCodes: parsed.suppressedCodes,
570
+ errorCodes: parsed.errorCodes,
571
+ });
1239
572
  exitCodes.push(
1240
573
  await reportErrors(async () => {
1241
574
  const specPath = path.endsWith(".ts") ? await writeTypeScriptSpec(path) : path;