tla-ts 0.0.4-dev.b254db0 → 0.0.4-dev.ca40dfe

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 (207) hide show
  1. package/README.md +31 -10
  2. package/dist/cli.cjs +1 -1
  3. package/dist/cli.js +1 -1
  4. package/dist/deciders.cjs +27 -27
  5. package/dist/deciders.js +34 -34
  6. package/dist/index.cjs +1 -1
  7. package/dist/index.d.cts +12 -14
  8. package/dist/index.d.ts +12 -14
  9. package/dist/index.js +1 -1
  10. package/dist/parallel-worker.cjs +1 -1
  11. package/dist/parallel-worker.js +1 -1
  12. package/dist/prove-worker.cjs +1 -1
  13. package/dist/prove-worker.js +1 -1
  14. package/dist/prove.cjs +37 -27
  15. package/dist/prove.js +39 -29
  16. package/dist/run.cjs +45 -0
  17. package/dist/run.js +45 -0
  18. package/dist/tlapm.cjs +2 -2
  19. package/dist/tlapm.js +2 -2
  20. package/dist/transfer.cjs +76 -86
  21. package/dist/transfer.js +73 -83
  22. package/dist/worker.cjs +6 -6
  23. package/dist/worker.js +6 -6
  24. package/package.json +1 -1
  25. package/src/ast.ts +2 -2
  26. package/src/bags.ts +22 -23
  27. package/src/builtins.ts +16 -8
  28. package/src/check.ts +131 -1154
  29. package/src/{cli-options.ts → cli/options.ts} +54 -9
  30. package/src/cli/run.ts +63 -0
  31. package/src/cli/shared.ts +106 -0
  32. package/src/cli/tlapm.ts +374 -0
  33. package/src/cli/tlc.ts +941 -0
  34. package/src/cli/xml-exporter.ts +221 -0
  35. package/src/cli.ts +1 -1
  36. package/src/codegen.ts +17 -15
  37. package/src/config.ts +5 -5
  38. package/src/dependencies.ts +4 -6
  39. package/src/environment.ts +55 -60
  40. package/src/errors.ts +12 -36
  41. package/src/evaluate.ts +81 -101
  42. package/src/exit-codes.ts +1 -1
  43. package/src/fingerprints.ts +3 -3
  44. package/src/instances.ts +56 -46
  45. package/src/java-overrides.ts +79 -41
  46. package/src/json.ts +31 -36
  47. package/src/levels.ts +10 -13
  48. package/src/{live-check.ts → liveness-checker.ts} +169 -142
  49. package/src/liveness.ts +38 -34
  50. package/src/obligations/action.ts +9 -45
  51. package/src/obligations/{anon.ts → anonymize.ts} +13 -25
  52. package/src/obligations/equality.ts +260 -0
  53. package/src/obligations/expression.ts +42 -517
  54. package/src/obligations/generate.ts +88 -778
  55. package/src/obligations/index.ts +20 -22
  56. package/src/obligations/levels.ts +36 -41
  57. package/src/obligations/module.ts +88 -708
  58. package/src/obligations/normalize.ts +554 -0
  59. package/src/obligations/operators.ts +176 -0
  60. package/src/obligations/pragma.ts +21 -15
  61. package/src/obligations/printer.ts +81 -188
  62. package/src/obligations/proof.ts +0 -1
  63. package/src/obligations/regroup.ts +100 -0
  64. package/src/obligations/simplify.ts +668 -0
  65. package/src/obligations/source.ts +25 -131
  66. package/src/obligations/{deref.ts → subexpression.ts} +48 -56
  67. package/src/obligations/substitution.ts +261 -0
  68. package/src/obligations/temporal.ts +28 -26
  69. package/src/obligations/tuples.ts +37 -53
  70. package/src/parallel-worker.ts +37 -33
  71. package/src/parallel.ts +30 -24
  72. package/src/parser.ts +67 -74
  73. package/src/{pcal-ast.ts → pcal/ast.ts} +2 -17
  74. package/src/{pcal-parse.ts → pcal/parse.ts} +28 -64
  75. package/src/{pcal-tokenize.ts → pcal/tokenize.ts} +10 -39
  76. package/src/{pcal-translate.ts → pcal/translate.ts} +30 -109
  77. package/src/{pcal-validate.ts → pcal/validate.ts} +10 -20
  78. package/src/prove/decide-pool.ts +7 -12
  79. package/src/{obligations/pickle.ts → prove/first-order.ts} +79 -2
  80. package/src/prove/isabelle/decide.ts +3 -6
  81. package/src/prove/isabelle/encode.ts +35 -93
  82. package/src/prove/isabelle/isar/inner-syntax.ts +1 -1
  83. package/src/prove/isabelle/isar/method.ts +3 -3
  84. package/src/prove/isabelle/isar/type-check.ts +1 -1
  85. package/src/prove/isabelle/provers/blast/blast.ts +1 -1
  86. package/src/prove/isabelle/provers/blast/branch.ts +1 -1
  87. package/src/prove/isabelle/provers/blast/term.ts +3 -4
  88. package/src/prove/isabelle/provers/clasimp.ts +1 -1
  89. package/src/prove/isabelle/provers/classical.ts +3 -3
  90. package/src/prove/isabelle/provers/hypsubst.ts +1 -9
  91. package/src/prove/isabelle/pure/conv.ts +1 -1
  92. package/src/prove/isabelle/pure/drule.ts +2 -2
  93. package/src/prove/isabelle/pure/envir.ts +3 -35
  94. package/src/prove/isabelle/pure/logic.ts +4 -76
  95. package/src/prove/isabelle/pure/name.ts +1 -13
  96. package/src/prove/isabelle/pure/net.ts +2 -49
  97. package/src/prove/isabelle/pure/pattern.ts +3 -22
  98. package/src/prove/isabelle/pure/raw-simplifier.ts +3 -18
  99. package/src/prove/isabelle/pure/seq.ts +0 -23
  100. package/src/prove/isabelle/pure/simplifier.ts +2 -8
  101. package/src/prove/isabelle/pure/table.ts +1 -8
  102. package/src/prove/isabelle/pure/tactic.ts +5 -113
  103. package/src/prove/isabelle/pure/tactical.ts +1 -84
  104. package/src/prove/isabelle/pure/term-ord.ts +1 -55
  105. package/src/prove/isabelle/pure/term.ts +8 -128
  106. package/src/prove/isabelle/pure/thm.ts +4 -27
  107. package/src/prove/isabelle/pure/type.ts +0 -12
  108. package/src/prove/isabelle/pure/unify.ts +1 -1
  109. package/src/prove/isabelle/tla/classical-setup.ts +1 -1
  110. package/src/prove/ocaml.ts +1 -1
  111. package/src/prove/prep/action.ts +23 -36
  112. package/src/prove/prep/enabled-axioms.ts +2 -2
  113. package/src/prove/prep/fingerprint.ts +3 -3
  114. package/src/prove/prep/level-comparison.ts +9 -37
  115. package/src/prove/prep/md5.ts +2 -9
  116. package/src/prove/prep/normalize.ts +309 -0
  117. package/src/prove/prove-worker.ts +2 -5
  118. package/src/prove/prove.ts +98 -111
  119. package/src/prove/ptl/encode.ts +19 -31
  120. package/src/prove/smt/axioms.ts +45 -58
  121. package/src/prove/smt/encode.ts +124 -15
  122. package/src/prove/smt/instances.ts +2 -3
  123. package/src/prove/smt/rewrite.ts +24 -31
  124. package/src/prove/smt/solver/ast-util.ts +0 -56
  125. package/src/prove/smt/solver/case-split-queue.ts +1 -1
  126. package/src/prove/smt/solver/enode.ts +1 -1
  127. package/src/prove/smt/solver/lp/dep-intervals.ts +0 -14
  128. package/src/prove/smt/solver/model-macro-solver.ts +1 -1
  129. package/src/prove/smt/solver/nlsat/algebraic.ts +3 -3
  130. package/src/prove/smt/solver/nlsat/atoms.ts +1 -1
  131. package/src/prove/smt/solver/nlsat/explain.ts +1 -1
  132. package/src/prove/smt/solver/nlsat/interval-set.ts +1 -1
  133. package/src/prove/smt/solver/nlsat/levelwise.ts +4 -7
  134. package/src/prove/smt/solver/nlsat/polynomial.ts +4 -4
  135. package/src/prove/smt/solver/nlsat/upolynomial.ts +2 -2
  136. package/src/prove/smt/solver/pattern-inference.ts +1 -1
  137. package/src/prove/smt/solver/relevancy.ts +2 -2
  138. package/src/prove/smt/solver/rewriter.ts +1 -1
  139. package/src/prove/smt/solver/solver.ts +2 -2
  140. package/src/{tlapm-cache.ts → prove/tlapm/cache.ts} +11 -11
  141. package/src/{ocaml-marshal.ts → prove/tlapm/ocaml-marshal.ts} +1 -1
  142. package/src/prove/verdict.ts +0 -5
  143. package/src/prove/zenon/decide.ts +5 -11
  144. package/src/prove/zenon/encode.ts +21 -80
  145. package/src/prove/zenon/eqrel.ts +1 -1
  146. package/src/prove/zenon/equality-rules.ts +1 -1
  147. package/src/prove/zenon/expr.ts +2 -2
  148. package/src/prove/zenon/index-table.ts +1 -1
  149. package/src/prove/zenon/isar.ts +1 -1
  150. package/src/prove/zenon/llproof.ts +1 -1
  151. package/src/prove/zenon/mltoll.ts +1 -1
  152. package/src/prove/zenon/node.ts +1 -1
  153. package/src/prove/zenon/search.ts +1 -1
  154. package/src/prove/zenon/tla/terms.ts +1 -20
  155. package/src/prove/zenon/tla/tla.ts +1 -1
  156. package/src/randomization.ts +19 -24
  157. package/src/resolve.ts +15 -22
  158. package/src/runtime.ts +8 -8
  159. package/src/{sany-builtins.ts → sany/builtins.ts} +1 -1
  160. package/src/{sany-generator.ts → sany/generator.ts} +38 -55
  161. package/src/{sany-levels.ts → sany/levels.ts} +45 -48
  162. package/src/{sany-lexer.ts → sany/lexer.ts} +2 -3
  163. package/src/{sany-linter.ts → sany/linter.ts} +1 -1
  164. package/src/{sany-modules.ts → sany/modules.ts} +2 -2
  165. package/src/{sany-nodes.ts → sany/nodes.ts} +2 -2
  166. package/src/{sany-parse-error.ts → sany/parse-error.ts} +2 -2
  167. package/src/{sany-report.ts → sany/report.ts} +16 -17
  168. package/src/{sany-selectors.ts → sany/selectors.ts} +3 -5
  169. package/src/{sany-source.ts → sany/source.ts} +6 -7
  170. package/src/{sany-xml.ts → sany/xml.ts} +5 -6
  171. package/src/search.ts +969 -0
  172. package/src/spec-description.ts +26 -20
  173. package/src/{standard-levels.ts → standard-definitions.ts} +118 -2
  174. package/src/standard-modules.ts +16 -20
  175. package/src/state-graph.ts +9 -8
  176. package/src/substitution-levels.ts +2 -2
  177. package/src/successors.ts +16 -19
  178. package/src/symmetry.ts +1 -1
  179. package/src/tableau.ts +6 -7
  180. package/src/tlc/fingerprint.ts +214 -0
  181. package/src/{tlc-messages.ts → tlc/messages.ts} +119 -7
  182. package/src/{tlc-order.ts → tlc/order.ts} +7 -7
  183. package/src/{tlc-random.ts → tlc/random.ts} +3 -213
  184. package/src/{tlc-replay.ts → tlc/replay.ts} +40 -36
  185. package/src/{tlc-module.ts → tlc/tlc-operators.ts} +9 -9
  186. package/src/{tlc-ext.ts → tlc/tlcext-operators.ts} +30 -25
  187. package/src/transfer.ts +32 -32
  188. package/src/values.ts +72 -67
  189. package/src/worker.ts +1 -4
  190. package/dist/run-cli.cjs +0 -45
  191. package/dist/run-cli.js +0 -45
  192. package/src/canonical.ts +0 -40
  193. package/src/obligations/ctx.ts +0 -64
  194. package/src/prove/prep/defs.ts +0 -33
  195. package/src/prove/prep/elab.ts +0 -156
  196. package/src/prove/prep/enabled.ts +0 -43
  197. package/src/prove/prep/flatten.ts +0 -70
  198. package/src/prove/prep/trivial.ts +0 -22
  199. package/src/prove/smt/axiomatize.ts +0 -69
  200. package/src/prove/smt/simplify.ts +0 -57
  201. package/src/run-cli.ts +0 -1806
  202. package/src/standard-ranges.ts +0 -116
  203. package/src/value-sources.ts +0 -29
  204. /package/src/prove/prep/{pragma.ts → methods.ts} +0 -0
  205. /package/src/{tlc-modules.ts → tlc/jar-data.ts} +0 -0
  206. /package/src/{tlc-summary.ts → tlc/summary.ts} +0 -0
  207. /package/src/{tlc-version.ts → tlc/version.ts} +0 -0
@@ -9,13 +9,15 @@ import { decide } from "./deciders";
9
9
  import { createDecidePool, type DecidePool } from "./decide-pool";
10
10
  import { encodeIsabelle, encodeIsabelleTheory } from "./isabelle/encode";
11
11
  import { processObligation } from "./prep/action";
12
- import { expandDefs } from "./prep/defs";
13
- import { normalizeSequent } from "./prep/elab";
14
- import { expandEnabledCdot } from "./prep/enabled";
15
12
  import { getFingerprint } from "./prep/fingerprint";
16
- import { flatten } from "./prep/flatten";
17
- import { findMethods, type Method } from "./prep/pragma";
18
- import { isTrivial } from "./prep/trivial";
13
+ import {
14
+ expandDefs,
15
+ flatten,
16
+ isTrivial,
17
+ normalizeExpand,
18
+ normalizeSequent,
19
+ } from "./prep/normalize";
20
+ import { findMethods, type Method } from "./prep/methods";
19
21
  import { encodePtl } from "./ptl/encode";
20
22
  import { encodeSmt } from "./smt/encode";
21
23
  import type { EncodingSession } from "./smt/rewrite";
@@ -54,17 +56,10 @@ export interface ProveResult {
54
56
  omittedProofCount: number;
55
57
  }
56
58
 
57
- export const PROVE_BACKENDS = ["tla-ts", "tlapm"] as const;
58
-
59
- type ProveBackend = (typeof PROVE_BACKENDS)[number];
60
-
61
- export const isProveBackend = (name: string | undefined): name is ProveBackend =>
62
- PROVE_BACKENDS.some((backend) => backend === name);
63
-
64
59
  export interface ProveOptions {
65
60
  source: string;
66
61
  loadModule?: (name: string) => string | undefined;
67
- backend?: ProveBackend;
62
+ backend?: "tla-ts" | "tlapm";
68
63
  signal?: AbortSignal;
69
64
  onObligation?: (obligation: ProofObligation) => void;
70
65
  workers?: number;
@@ -85,6 +80,12 @@ interface ProofReport {
85
80
  attempts: ProofAttempt[];
86
81
  }
87
82
 
83
+ // Why a method left an obligation unproved: a prover decided so, or tla-ts couldn't try it.
84
+ interface MethodFailure {
85
+ reason: string;
86
+ isDecided: boolean;
87
+ }
88
+
88
89
  // The SMT encoder numbers the CASE errors it standardizes across the run, so an obligation it
89
90
  // encodes one in waits for every earlier obligation and starts from the count they leave.
90
91
  interface ObligationTask {
@@ -103,34 +104,28 @@ interface ProveRun {
103
104
  decide: DecidePool["decide"];
104
105
  }
105
106
 
106
- interface Backend {
107
- // The text Prep.ship sends the backend after Prep.normalize_expand. It throws a
108
- // TlaUnsupportedError for what tla-ts can't encode.
109
- encode: (id: number, sequent: Sequent, method: Method, session: EncodingSession) => string;
110
- }
107
+ // The text Prep.ship sends a backend after Prep.normalize_expand. It throws a TlaUnsupportedError
108
+ // for what tla-ts can't encode.
109
+ type Encoder = (id: number, sequent: Sequent, method: Method, session: EncodingSession) => string;
111
110
 
112
111
  // Action.process_obligation, the frontend for every backend but LS4, Isabelle included, then
113
112
  // Prep.flatten.
114
113
  const shipFirstOrder = (sequent: Sequent) => flatten(processObligation(sequent));
115
114
 
116
- const SMT: Backend = {
117
- // Prep.gen_smt_solve writes the resource budget before the encoding.
118
- encode: (_id, sequent, method, session) =>
119
- (method.rlimit === undefined ? "" : `(set-option :rlimit ${method.rlimit})\n`) +
120
- encodeSmt(shipFirstOrder(sequent), session),
121
- };
115
+ // Prep.gen_smt_solve writes the resource budget before the encoding.
116
+ const encodeSmtProblem: Encoder = (_id, sequent, method, session) =>
117
+ (method.rlimit === undefined ? "" : `(set-option :rlimit ${method.rlimit})\n`) +
118
+ encodeSmt(shipFirstOrder(sequent), session);
122
119
 
123
- const BACKENDS: Record<string, Backend> = {
124
- smt: SMT,
125
- z3: SMT,
126
- zenon: { encode: (id, sequent) => encodeZenon(id, shipFirstOrder(sequent)) },
120
+ const ENCODERS: Record<string, Encoder> = {
121
+ smt: encodeSmtProblem,
122
+ z3: encodeSmtProblem,
123
+ zenon: (id, sequent) => encodeZenon(id, shipFirstOrder(sequent)),
127
124
  // tlapm names the theory after its temporary file, and tla-ts after the obligation.
128
- isabelle: {
129
- encode: (id, sequent, method) =>
130
- encodeIsabelle(id, shipFirstOrder(sequent), method.tactic ?? "auto", `tlapm_${id}`),
131
- },
125
+ isabelle: (id, sequent, method) =>
126
+ encodeIsabelle(id, shipFirstOrder(sequent), method.tactic ?? "auto"),
132
127
  // Pltl.process_obligation is LS4's frontend.
133
- ls4: { encode: (_id, sequent) => encodePtl(sequent) },
128
+ ls4: (_id, sequent) => encodePtl(sequent),
134
129
  };
135
130
 
136
131
  // The frontends and Prep.flatten add no CASE without OTHER, so the SMT encoder standardizes one
@@ -160,21 +155,18 @@ const isIncompleteCaseHyp = (hyp: Hyp) => {
160
155
 
161
156
  const getModuleName = (source: string) => /-{4,}\s*MODULE\s+(\w+)/.exec(source)?.[1] ?? "Main";
162
157
 
163
- const getBase = (obligation: PrintedObligation): ObligationBase => ({
158
+ const getObligationBase = (obligation: PrintedObligation): ObligationBase => ({
164
159
  id: obligation.id,
165
160
  location: obligation.location,
166
161
  text: obligation.text,
167
162
  });
168
163
 
169
- const getUnproved = (
164
+ const getUnprovedReport = (
170
165
  obligation: PrintedObligation,
171
166
  status: "failed" | "unsupported",
172
167
  reason: string,
173
- ): ProofObligation => ({ ...getBase(obligation), status, reason });
174
-
175
- // Prep.normalize_expand: expand_defs, Elab.normalize, then the frontends the step cites.
176
- const normalizeExpand = (obligation: PrintedObligation, methods = findMethods(obligation)) =>
177
- expandEnabledCdot(normalizeSequent(expandDefs(obligation.sequent)), methods.frontends);
168
+ attempts: ProofAttempt[] = [],
169
+ ): ProofReport => ({ obligation: { ...getObligationBase(obligation), status, reason }, attempts });
178
170
 
179
171
  // A failed obligation as tlapm prints it: Prep.normalize_expand for a new failure, and
180
172
  // Toolbox.normalize, which keeps pragmas, for a reused one.
@@ -213,14 +205,14 @@ export const encodeForBackend = (
213
205
  prover: string,
214
206
  session: EncodingSession,
215
207
  ) => {
216
- const backend = BACKENDS[prover];
217
- if (!backend) throw new TlaUnsupportedError(`the ${prover} backend`);
208
+ const encode = ENCODERS[prover];
209
+ if (!encode) throw new TlaUnsupportedError(`the ${prover} backend`);
218
210
  const methods = findMethods(obligation);
219
211
  const method = methods.provers.find((candidate) => candidate.prover === prover) ?? {
220
212
  prover,
221
213
  timeLimitMs: Infinity,
222
214
  };
223
- return backend.encode(obligation.id, normalizeExpand(obligation, methods), method, session);
215
+ return encode(obligation.id, normalizeExpand(obligation, methods), method, session);
224
216
  };
225
217
 
226
218
  // The SMT encoder's session for an obligation, from the count of CASE errors every earlier
@@ -251,18 +243,19 @@ const proveWithBackends = async (
251
243
  signal: AbortSignal | undefined,
252
244
  ): Promise<ProofReport> => {
253
245
  if (obligation.kind.kind === "Error")
254
- return { obligation: getUnproved(obligation, "failed", obligation.kind.message), attempts: [] };
246
+ return getUnprovedReport(obligation, "failed", obligation.kind.message);
255
247
  const methods = findMethods(obligation);
256
248
  const fingerprint = getFingerprint(obligation.sequent);
257
249
  const earlier = run.lastByFingerprint.get(fingerprint);
258
250
  run.lastByFingerprint.set(fingerprint, run.tasks[index].done);
259
251
  await earlier;
260
252
  const attempts: ProofAttempt[] = [];
261
- const getProved = (prover: string): ProofReport => ({
262
- obligation: { ...getBase(obligation), status: "proved", prover },
253
+ const failures: MethodFailure[] = [];
254
+ const getProvedReport = (prover: string): ProofReport => ({
255
+ obligation: { ...getObligationBase(obligation), status: "proved", prover },
263
256
  attempts,
264
257
  });
265
- // Prep.already_processed.
258
+ // Prep.already_processed, which forgets the fingerprint's results on each call under --nofp.
266
259
  const getPrior = (method: Method) => {
267
260
  if (!run.isFingerprinted(obligation)) run.results.delete(fingerprint);
268
261
  const prior = run.results.get(fingerprint)?.get(method.prover);
@@ -272,55 +265,56 @@ const proveWithBackends = async (
272
265
  const getBudget = (method: Method) => method.rlimit ?? method.timeLimitMs / 1000;
273
266
  const reuse = (prior: ProofAttempt) =>
274
267
  attempts.push({ ...prior, isReused: true, timeUsedMs: undefined });
268
+ const record = (attempt: ProofAttempt) => {
269
+ attempts.push(attempt);
270
+ run.results.set(
271
+ fingerprint,
272
+ (run.results.get(fingerprint) ?? new Map()).set(attempt.method.prover, attempt),
273
+ );
274
+ };
275
+ const skip = (method: Method, reason: string) => {
276
+ attempts.push({ method, isProved: false, isReused: false, reason });
277
+ failures.push({ reason, isDecided: false });
278
+ };
275
279
  const firstPrior = getPrior(methods.provers[0]);
276
280
  if (firstPrior?.isProved) {
277
281
  reuse(firstPrior);
278
- return getProved(firstPrior.method.prover);
282
+ return getProvedReport(firstPrior.method.prover);
279
283
  }
280
284
  const sequent = normalizeExpand(obligation, methods);
281
285
  // Fpfile.fp_writes keeps no trivial result, but adds the fingerprint.
282
286
  if (obligation.kind.kind === "Support" && isTrivial(sequent)) {
283
287
  run.results.set(fingerprint, run.results.get(fingerprint) ?? new Map());
284
- return { obligation: { ...getBase(obligation), status: "trivial" }, attempts };
288
+ return { obligation: { ...getObligationBase(obligation), status: "trivial" }, attempts };
285
289
  }
286
- const reasons: string[] = [];
287
- const state = { isDecided: false };
288
- const decideAttempt = (attempt: ProofAttempt) => {
289
- attempts.push(attempt);
290
- run.results.set(
291
- fingerprint,
292
- (run.results.get(fingerprint) ?? new Map()).set(attempt.method.prover, attempt),
293
- );
294
- state.isDecided = true;
295
- };
296
290
  for (const method of methods.provers) {
297
291
  const prior = getPrior(method);
298
292
  if (prior?.isProved) {
299
293
  reuse(prior);
300
- return getProved(method.prover);
294
+ return getProvedReport(method.prover);
301
295
  }
302
296
  if (prior && getBudget(prior.method) >= getBudget(method)) {
303
297
  reuse(prior);
304
- state.isDecided = true;
305
- reasons.push(`${method.prover} failed on an obligation with the same fingerprint`);
298
+ failures.push({
299
+ reason: `${method.prover} failed on an obligation with the same fingerprint`,
300
+ isDecided: true,
301
+ });
306
302
  continue;
307
303
  }
308
304
  if (!run.isProving) continue;
309
305
  // Prep.prove_with: the Trivial method proves anything.
310
- if (method.prover === "trivial") return getProved(method.prover);
311
- const backend = BACKENDS[method.prover];
312
- if (!backend) {
313
- const reason = `tla-ts has no ${method.prover} backend`;
314
- attempts.push({ method, isProved: false, isReused: false, reason });
315
- reasons.push(reason);
306
+ if (method.prover === "trivial") return getProvedReport(method.prover);
307
+ const encode = ENCODERS[method.prover];
308
+ if (!encode) {
309
+ skip(method, `tla-ts has no ${method.prover} backend`);
316
310
  continue;
317
311
  }
318
312
  try {
319
313
  const isCaseNumbered =
320
- backend === SMT &&
314
+ encode === encodeSmtProblem &&
321
315
  (sequent.context.some(isIncompleteCaseHyp) || hasIncompleteCase(sequent.active));
322
316
  const session = isCaseNumbered ? await getSession(run, index) : { caseErrors: 0 };
323
- const text = backend.encode(obligation.id, sequent, method, session);
317
+ const text = encode(obligation.id, sequent, method, session);
324
318
  const decision = await run.decide(
325
319
  method.prover,
326
320
  text,
@@ -328,7 +322,7 @@ const proveWithBackends = async (
328
322
  index,
329
323
  );
330
324
  const isProved = decision.verdict === "unsat";
331
- decideAttempt({
325
+ record({
332
326
  method,
333
327
  isProved,
334
328
  isReused: false,
@@ -338,45 +332,34 @@ const proveWithBackends = async (
338
332
  verdict: decision.verdict,
339
333
  timeUsedMs: decision.timeUsedMs,
340
334
  });
341
- if (isProved) return getProved(method.prover);
342
- reasons.push(`${method.prover} answered ${decision.verdict}`);
335
+ if (isProved) return getProvedReport(method.prover);
336
+ failures.push({ reason: `${method.prover} answered ${decision.verdict}`, isDecided: true });
343
337
  } catch (error) {
344
338
  if (error instanceof TlaProverError) {
345
- decideAttempt({ method, isProved: false, isReused: false, reason: "false" });
346
- reasons.push(`${method.prover} failed: ${error.message}`);
339
+ record({ method, isProved: false, isReused: false, reason: "false" });
340
+ failures.push({ reason: `${method.prover} failed: ${error.message}`, isDecided: true });
347
341
  continue;
348
342
  }
349
343
  if (!(error instanceof TlaUnsupportedError)) throw error;
350
- const reason = `${method.prover} can't encode ${error.message}`;
351
- attempts.push({ method, isProved: false, isReused: false, reason });
352
- reasons.push(reason);
344
+ skip(method, `${method.prover} can't encode ${error.message}`);
353
345
  }
354
346
  }
355
- return {
356
- obligation: getUnproved(
357
- obligation,
358
- state.isDecided ? "failed" : "unsupported",
359
- reasons.join(", "),
360
- ),
347
+ return getUnprovedReport(
348
+ obligation,
349
+ failures.some((failure) => failure.isDecided) ? "failed" : "unsupported",
350
+ failures.map((failure) => failure.reason).join(", "),
361
351
  attempts,
362
- };
352
+ );
363
353
  };
364
354
 
365
- // The one place an error becomes a result: what tla-ts can't handle is unsupported, and what tlapm
355
+ // An error that escapes proveWithBackends: what tla-ts can't handle is unsupported, and what tlapm
366
356
  // refuses, as a frontend's soundness check, fails.
367
- const getResult = async (
368
- obligation: PrintedObligation,
369
- getReport: () => Promise<ProofReport>,
370
- ): Promise<ProofReport> => {
371
- try {
372
- return await getReport();
373
- } catch (error) {
374
- if (error instanceof TlaUnsupportedError)
375
- return { obligation: getUnproved(obligation, "unsupported", error.message), attempts: [] };
376
- if (error instanceof TlaProverError)
377
- return { obligation: getUnproved(obligation, "failed", error.message), attempts: [] };
378
- throw error;
379
- }
357
+ const getErrorReport = (obligation: PrintedObligation, error: unknown) => {
358
+ if (error instanceof TlaUnsupportedError)
359
+ return getUnprovedReport(obligation, "unsupported", error.message);
360
+ if (error instanceof TlaProverError)
361
+ return getUnprovedReport(obligation, "failed", error.message);
362
+ throw error;
380
363
  };
381
364
 
382
365
  interface ObligationsOptions {
@@ -394,8 +377,9 @@ export const proveObligations = async (
394
377
  obligations: PrintedObligation[],
395
378
  options: ObligationsOptions,
396
379
  ) => {
397
- const count = options.workers ?? 1;
398
- const pool = count > 1 && isWorkerSupported() ? await createDecidePool(count) : undefined;
380
+ const workerCount = options.workers ?? 1;
381
+ const pool =
382
+ workerCount > 1 && isWorkerSupported() ? await createDecidePool(workerCount) : undefined;
399
383
  const onAbort = () => pool?.terminate(options.signal?.reason);
400
384
  options.signal?.addEventListener("abort", onAbort);
401
385
  const run: ProveRun = {
@@ -408,7 +392,7 @@ export const proveObligations = async (
408
392
  pool?.decide ?? (async (prover, text, decideOptions) => decide(prover, text, decideOptions)),
409
393
  };
410
394
  // A few obligations per worker prove at once, and each reports once every earlier one has.
411
- const limit = pool ? count * 4 : 1;
395
+ const limit = pool ? workerCount * 4 : 1;
412
396
  const pending: Promise<ProofReport>[] = [];
413
397
  const isSettled: boolean[] = [];
414
398
  const running = new Set<Promise<void>>();
@@ -428,8 +412,8 @@ export const proveObligations = async (
428
412
  options.signal?.throwIfAborted();
429
413
  const done = Promise.withResolvers<void>();
430
414
  run.tasks.push({ done: done.promise, session: undefined });
431
- const report = getResult(obligation, () =>
432
- proveWithBackends(obligation, index, run, options.signal),
415
+ const report = proveWithBackends(obligation, index, run, options.signal).catch(
416
+ (error: unknown) => getErrorReport(obligation, error),
433
417
  );
434
418
  pending.push(report);
435
419
  running.add(done.promise);
@@ -451,10 +435,13 @@ export const proveObligations = async (
451
435
  return reports;
452
436
  };
453
437
 
454
- const getFromTlapm = (obligation: PrintedObligation, result: TlapmResult | undefined) =>
455
- result
456
- ? { ...getBase(obligation), ...result }
457
- : getUnproved(obligation, "unsupported", "tlapm reported no result");
438
+ const getTlapmObligation = (
439
+ obligation: PrintedObligation,
440
+ result: TlapmResult | undefined,
441
+ ): ProofObligation => ({
442
+ ...getObligationBase(obligation),
443
+ ...(result ?? { status: "unsupported", reason: "tlapm reported no result" }),
444
+ });
458
445
 
459
446
  export const prove = async (options: ProveOptions): Promise<ProveResult> => {
460
447
  const name = getModuleName(options.source);
@@ -485,13 +472,13 @@ export const prove = async (options: ProveOptions): Promise<ProveResult> => {
485
472
  signal: options.signal,
486
473
  onResult: (id, result) => {
487
474
  const obligation = byId.get(id);
488
- if (obligation) options.onObligation?.(getFromTlapm(obligation, result));
475
+ if (obligation) options.onObligation?.(getTlapmObligation(obligation, result));
489
476
  },
490
477
  },
491
478
  );
492
479
  return {
493
480
  obligations: obligations.map((obligation) =>
494
- getFromTlapm(obligation, reported.get(obligation.id)),
481
+ getTlapmObligation(obligation, reported.get(obligation.id)),
495
482
  ),
496
483
  ...counts,
497
484
  };
@@ -4,39 +4,28 @@
4
4
  // The text is the negated obligation.
5
5
 
6
6
  import {
7
- adjoin,
8
- applyBuiltin,
9
- at,
10
7
  bumpBy,
11
- mapAccumulate,
12
- mapScoped,
13
8
  shift,
14
9
  shiftExpr,
15
10
  substituteExpr,
16
11
  substituteHyp,
12
+ type Substitution,
13
+ } from "../../obligations/substitution";
14
+ import {
15
+ adjoin,
16
+ applyBuiltin,
17
+ at,
18
+ mapAccumulate,
19
+ mapScoped,
17
20
  type Builtin,
18
21
  type Expr,
19
22
  type Hyp,
20
- type Level,
21
23
  type Scope,
22
24
  type Sequent,
23
- type Substitution,
24
25
  } from "../../obligations/expression";
25
- import { renderDoc } from "../../obligations/format";
26
26
  import { getLevelInfo } from "../../obligations/levels";
27
- import { printExpression } from "../../obligations/printer";
28
27
  import { expandAction, expandFairness, expandLeadsto, getTime } from "../../obligations/temporal";
29
- import { getMd5 } from "../prep/md5";
30
-
31
- const KIND_NAMES: Record<Level, string> = {
32
- Constant: "CONSTANT",
33
- State: "STATE",
34
- Action: "ACTION",
35
- Temporal: "TEMPORAL",
36
- Unknown: "Unknown",
37
- };
38
-
39
- const LEVEL_NAMES = ["CONSTANT", "STATE", "ACTION", "TEMPORAL"];
28
+ import { getHashName, LEVEL_NUMBER_PREFIXES, LEVEL_PREFIXES } from "../prep/action";
40
29
 
41
30
  // Coalesce.rename_with_loc: each declared name gets its kind in front, or its level for a definition,
42
31
  // as in VARIABLE_x_ and CONSTANT_i_, so atoms print with the names tlapm hashes. A variable a
@@ -51,7 +40,7 @@ const renameSequent = (scope: Scope | undefined, sequent: Sequent): Sequent => {
51
40
  case "Fresh":
52
41
  return {
53
42
  ...hyp,
54
- name: `${KIND_NAMES[hyp.level]}_${hyp.name}_`,
43
+ name: `${LEVEL_PREFIXES[hyp.level]}_${hyp.name}_`,
55
44
  domain: hyp.domain && renameDeclarations(current, hyp.domain),
56
45
  };
57
46
  case "Flex":
@@ -60,7 +49,7 @@ const renameSequent = (scope: Scope | undefined, sequent: Sequent): Sequent => {
60
49
  const definition = hyp.definition;
61
50
  if (definition.kind !== "Operator") return hyp;
62
51
  const body = renameDeclarations(current, definition.body);
63
- const level = LEVEL_NAMES[getLevelInfo(current, body).level];
52
+ const level = LEVEL_NUMBER_PREFIXES[getLevelInfo(current, body).level];
64
53
  return {
65
54
  ...hyp,
66
55
  definition: { ...definition, name: `${level}_${definition.name}_`, body },
@@ -93,7 +82,7 @@ const renameDeclarations = (scope: Scope | undefined, expression: Expr): Expr =>
93
82
  ...mapped,
94
83
  bounds: mapped.bounds.map((bound) => ({
95
84
  ...bound,
96
- name: `${KIND_NAMES[bound.level]}_${bound.name}_`,
85
+ name: `${LEVEL_PREFIXES[bound.level]}_${bound.name}_`,
97
86
  })),
98
87
  };
99
88
  case "Choose":
@@ -126,13 +115,12 @@ const prepareHyps = (scope: Scope | undefined, expression: Expr): Expr => {
126
115
  };
127
116
  for (const original of expression.sequent.context) {
128
117
  const hyp = substituteHyp(state.substitution, original);
129
- if (hyp.kind === "Fact") {
130
- push({ ...hyp, expression: prepareHyps(state.scope, hyp.expression) });
131
- state.substitution = bumpBy(1, state.substitution);
132
- continue;
133
- }
134
118
  if (hyp.kind !== "Fresh" || !hyp.domain || original.kind !== "Fresh" || !original.domain) {
135
- push(hyp);
119
+ push(
120
+ hyp.kind === "Fact"
121
+ ? { ...hyp, expression: prepareHyps(state.scope, hyp.expression) }
122
+ : hyp,
123
+ );
136
124
  state.substitution = bumpBy(1, state.substitution);
137
125
  continue;
138
126
  }
@@ -247,8 +235,8 @@ export const encodePtl = (sequent: Sequent): string => {
247
235
  return facts.length === 0 ? goal : `(${facts.join(" & ")} -> ${goal})`;
248
236
  }
249
237
  }
250
- // Pltl.coalesce_fol: an atom is named by the first five hex digits of the MD5 of its print.
251
- return `h${getMd5(renderDoc(printExpression(hyps, expression))).slice(0, 5)}`;
238
+ // Pltl.coalesce_fol names an atom as Coalesce does.
239
+ return getHashName(hyps, expression);
252
240
  };
253
241
  const renamed = renameDeclarations(undefined, { kind: "Sequent", sequent });
254
242
  const prepared = prepareHyps(undefined, expandAction(expandLeadsto(expandFairness(renamed))));
@@ -81,7 +81,7 @@ export const getFieldKeys = (fields: string[]) => fields.map((field) => tla(`Str
81
81
 
82
82
  // TupExcept and RecExcept: updating one component of a tuple or record.
83
83
  const getComponentExcepts = (
84
- name: string,
84
+ prefix: string,
85
85
  args: AxiomArgument[],
86
86
  symbol: string,
87
87
  keys: string[],
@@ -91,7 +91,7 @@ const getComponentExcepts = (
91
91
  const updated = `(${FUN_EXCEPT} ${call(symbol, elements)} ${key} x)`;
92
92
  const replaced = elements.map((element, position) => (position === index ? "x" : element));
93
93
  return axiom(
94
- name,
94
+ `${prefix}Except`,
95
95
  [...args, index + 1],
96
96
  forall([...elements, "x"], `(= ${updated} ${call(symbol, replaced)})`, [[updated]]),
97
97
  );
@@ -99,45 +99,54 @@ const getComponentExcepts = (
99
99
  };
100
100
 
101
101
  export const getTupleExcepts = (count: number) =>
102
- getComponentExcepts("TupExcept", [count], tla(`Tuple_${count}`), getIntegers(count));
102
+ getComponentExcepts("Tup", [count], tla(`Tuple_${count}`), getIntegers(count));
103
103
 
104
104
  export const getRecordExcepts = (fields: string[]) =>
105
- getComponentExcepts(
106
- "RecExcept",
107
- [fields],
108
- tla(`Record_${fields.join("_")}`),
109
- getFieldKeys(fields),
105
+ getComponentExcepts("Rec", [fields], tla(`Record_${fields.join("_")}`), getFieldKeys(fields));
106
+
107
+ // TupIsafcn, TupDomDef and TupAppDef, or their Rec counterparts: a tuple or record is the
108
+ // function from its keys to its components. The empty tuple has no domain or components to define.
109
+ const getComponentFunction = (
110
+ prefix: string,
111
+ args: AxiomArgument[],
112
+ symbol: string,
113
+ keys: string[],
114
+ ) => {
115
+ const elements = getNames("x", keys.length);
116
+ const value = call(symbol, elements);
117
+ const isafcn = axiom(
118
+ `${prefix}Isafcn`,
119
+ args,
120
+ forall(elements, `(${FUN_ISAFCN} ${value})`, [[value]]),
110
121
  );
122
+ if (keys.length === 0) return [isafcn];
123
+ return [
124
+ isafcn,
125
+ axiom(
126
+ `${prefix}DomDef`,
127
+ args,
128
+ forall(elements, `(= (${FUN_DOM} ${value}) ${call(tla(`SetEnum_${keys.length}`), keys)})`, [
129
+ [value],
130
+ ]),
131
+ ),
132
+ axiom(
133
+ `${prefix}AppDef`,
134
+ args,
135
+ forall(
136
+ elements,
137
+ conjoin(keys.map((key, index) => `(= (${FUN_APP} ${value} ${key}) ${elements[index]})`)),
138
+ [[value]],
139
+ ),
140
+ ),
141
+ ];
142
+ };
111
143
 
112
144
  export const getTupleAxioms = (count: number, isExcept: boolean) => {
113
145
  const symbol = tla(`Tuple_${count}`);
114
146
  const elements = getNames("x", count);
115
147
  const value = call(symbol, elements);
116
- const keys = getIntegers(count);
117
148
  return [
118
- axiom("TupIsafcn", [count], forall(elements, `(${FUN_ISAFCN} ${value})`, [[value]])),
119
- ...(count === 0
120
- ? []
121
- : [
122
- axiom(
123
- "TupDomDef",
124
- [count],
125
- forall(elements, `(= (${FUN_DOM} ${value}) ${call(tla(`SetEnum_${count}`), keys)})`, [
126
- [value],
127
- ]),
128
- ),
129
- axiom(
130
- "TupAppDef",
131
- [count],
132
- forall(
133
- elements,
134
- conjoin(
135
- keys.map((key, index) => `(= (${FUN_APP} ${value} ${key}) ${elements[index]})`),
136
- ),
137
- [[value]],
138
- ),
139
- ),
140
- ]),
149
+ ...getComponentFunction("Tup", [count], symbol, getIntegers(count)),
141
150
  axiom(
142
151
  "SeqTupTyping",
143
152
  [count],
@@ -158,32 +167,10 @@ export const getTupleAxioms = (count: number, isExcept: boolean) => {
158
167
  ];
159
168
  };
160
169
 
161
- export const getRecordAxioms = (fields: string[], isExcept: boolean) => {
162
- const symbol = tla(`Record_${fields.join("_")}`);
163
- const keys = getFieldKeys(fields);
164
- const elements = getNames("x", fields.length);
165
- const value = call(symbol, elements);
166
- return [
167
- axiom("RecIsafcn", [fields], forall(elements, `(${FUN_ISAFCN} ${value})`, [[value]])),
168
- axiom(
169
- "RecDomDef",
170
- [fields],
171
- forall(elements, `(= (${FUN_DOM} ${value}) ${call(tla(`SetEnum_${fields.length}`), keys)})`, [
172
- [value],
173
- ]),
174
- ),
175
- axiom(
176
- "RecAppDef",
177
- [fields],
178
- forall(
179
- elements,
180
- conjoin(keys.map((key, index) => `(= (${FUN_APP} ${value} ${key}) ${elements[index]})`)),
181
- [[value]],
182
- ),
183
- ),
184
- ...(isExcept ? getRecordExcepts(fields) : []),
185
- ];
186
- };
170
+ export const getRecordAxioms = (fields: string[], isExcept: boolean) => [
171
+ ...getComponentFunction("Rec", [fields], tla(`Record_${fields.join("_")}`), getFieldKeys(fields)),
172
+ ...(isExcept ? getRecordExcepts(fields) : []),
173
+ ];
187
174
 
188
175
  // The set of tuples or records whose components are in the given sets.
189
176
  export const getComponentSet = (