@sublang/spex 6.0.0 → 7.0.0-beta.2

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 (108) hide show
  1. package/README.md +419 -12
  2. package/dist/cli.js +12 -1
  3. package/dist/commands/add.d.ts +1 -1
  4. package/dist/commands/add.js +2 -2
  5. package/dist/commands/environment.d.ts +3 -3
  6. package/dist/commands/environment.js +5 -7
  7. package/dist/commands/export.js +2 -2
  8. package/dist/commands/home.d.ts +2 -2
  9. package/dist/commands/home.js +3 -3
  10. package/dist/commands/list.js +1 -1
  11. package/dist/commands/login.js +12 -7
  12. package/dist/commands/logout.js +2 -3
  13. package/dist/commands/publish.js +1 -1
  14. package/dist/commands/remove.js +1 -1
  15. package/dist/commands/run.d.ts +1 -1
  16. package/dist/commands/run.js +16 -0
  17. package/dist/commands/settle.d.ts +1 -1
  18. package/dist/commands/settle.js +1 -1
  19. package/dist/guards/approval.d.ts +56 -0
  20. package/dist/guards/approval.js +158 -0
  21. package/dist/guards/checks.d.ts +207 -0
  22. package/dist/guards/checks.js +681 -0
  23. package/dist/guards/commands.d.ts +15 -0
  24. package/dist/guards/commands.js +313 -0
  25. package/dist/guards/copy.d.ts +67 -0
  26. package/dist/guards/copy.js +306 -0
  27. package/dist/guards/declaration.d.ts +45 -0
  28. package/dist/guards/declaration.js +224 -0
  29. package/dist/guards/files.d.ts +137 -0
  30. package/dist/guards/files.js +544 -0
  31. package/dist/guards/harness.d.ts +58 -0
  32. package/dist/guards/harness.js +420 -0
  33. package/dist/guards/items.d.ts +61 -0
  34. package/dist/guards/items.js +161 -0
  35. package/dist/guards/patch.d.ts +55 -0
  36. package/dist/guards/patch.js +258 -0
  37. package/dist/guards/processes.d.ts +49 -0
  38. package/dist/guards/processes.js +233 -0
  39. package/dist/guards/proofs.d.ts +88 -0
  40. package/dist/guards/proofs.js +503 -0
  41. package/dist/guards/records.d.ts +176 -0
  42. package/dist/guards/records.js +513 -0
  43. package/dist/guards/report.d.ts +26 -0
  44. package/dist/guards/report.js +492 -0
  45. package/dist/guards/runner.d.ts +42 -0
  46. package/dist/guards/runner.js +167 -0
  47. package/dist/guards/tla.d.ts +51 -0
  48. package/dist/guards/tla.js +352 -0
  49. package/dist/guards/tlapm.d.ts +81 -0
  50. package/dist/guards/tlapm.js +172 -0
  51. package/dist/guards/tlc.d.ts +191 -0
  52. package/dist/guards/tlc.js +457 -0
  53. package/dist/guards/translation.d.ts +66 -0
  54. package/dist/guards/translation.js +202 -0
  55. package/dist/guards/types.d.ts +185 -0
  56. package/dist/guards/types.js +437 -0
  57. package/dist/guards/verify.d.ts +290 -0
  58. package/dist/guards/verify.js +1191 -0
  59. package/dist/guards/xml.d.ts +18 -0
  60. package/dist/guards/xml.js +105 -0
  61. package/dist/lib/environment/archive.d.ts +2 -2
  62. package/dist/lib/environment/archive.js +1 -1
  63. package/dist/lib/environment/builtins.d.ts +10 -12
  64. package/dist/lib/environment/builtins.js +17 -19
  65. package/dist/lib/environment/exports.d.ts +14 -13
  66. package/dist/lib/environment/exports.js +31 -16
  67. package/dist/lib/environment/format.d.ts +2 -2
  68. package/dist/lib/environment/format.js +3 -3
  69. package/dist/lib/environment/git-source.js +6 -3
  70. package/dist/lib/environment/install.d.ts +14 -16
  71. package/dist/lib/environment/install.js +66 -61
  72. package/dist/lib/environment/lock.d.ts +4 -3
  73. package/dist/lib/environment/lock.js +6 -5
  74. package/dist/lib/environment/marker.js +1 -2
  75. package/dist/lib/environment/own-paths.d.ts +7 -10
  76. package/dist/lib/environment/own-paths.js +10 -13
  77. package/dist/lib/environment/placed-record.d.ts +3 -2
  78. package/dist/lib/environment/placed-record.js +5 -4
  79. package/dist/lib/environment/registry.d.ts +1 -1
  80. package/dist/lib/environment/registry.js +1 -1
  81. package/dist/lib/environment/requests.d.ts +2 -2
  82. package/dist/lib/environment/requests.js +2 -2
  83. package/dist/lib/environment/resolve.d.ts +4 -4
  84. package/dist/lib/environment/resolve.js +3 -4
  85. package/dist/lib/environment/store.d.ts +34 -8
  86. package/dist/lib/environment/store.js +138 -43
  87. package/dist/lib/files.d.ts +72 -12
  88. package/dist/lib/files.js +200 -65
  89. package/dist/lib/git-host.d.ts +52 -258
  90. package/dist/lib/git-host.js +52 -265
  91. package/dist/lib/home-file.d.ts +13 -10
  92. package/dist/lib/home-file.js +28 -18
  93. package/dist/lib/instance.d.ts +1 -1
  94. package/dist/lib/instance.js +1 -1
  95. package/dist/lint.d.ts +22 -0
  96. package/dist/lint.js +36 -0
  97. package/dist/testing/standin-registry.js +1 -1
  98. package/package.json +7 -3
  99. package/scaffold/.file-history.json +14 -7
  100. package/scaffold/i18n/zh/source-pins.json +41 -0
  101. package/scaffold/i18n/zh/specs/decisions/000-spec-structure-format.md +0 -1
  102. package/scaffold/i18n/zh/specs/intents/000-spdx-headers.md +0 -1
  103. package/scaffold/i18n/zh/specs/map.md +0 -1
  104. package/scaffold/i18n/zh/specs/meta.md +18 -35
  105. package/scaffold/i18n/zh/specs/packages/git.md +0 -1
  106. package/scaffold/i18n/zh/specs/packages/licensing.md +0 -1
  107. package/scaffold/specs/meta.md +18 -3
  108. package/scripts/test-exit-guard.mjs +28 -0
@@ -0,0 +1,503 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // SPDX-FileCopyrightText: 2026 SubLang International <https://sublang.ai>
3
+ /*
4
+ * Guards package, DR-244 and DR-252: a guard's proofs. Spex writes
5
+ * the statements to prove, for any values: that each translation's
6
+ * model keeps the rule and that each translation after the first
7
+ * agrees with the first. Each translation's proofs are one file,
8
+ * `guards/<guard>/proofs/<name>_proofs.tla`, which an agent writes
9
+ * and nobody approves: every run checks them again. They are
10
+ * accepted only where, for every translation, its proof file is
11
+ * kept, is one module of printable ASCII with no instruction to a
12
+ * prover, is read by TLC's parser without error and loads nothing but
13
+ * the declaration in TLA+, the translations, its statements and the
14
+ * standard modules of the TLA+ tools, holds nothing but definitions
15
+ * of new names and theorems and lemmas over the statements Spex
16
+ * wrote, and the proof system proves everything in it and the
17
+ * statements from it. Spex proves nothing here: it writes text, runs
18
+ * the tools and reads what they print.
19
+ */
20
+ import { cpSync, existsSync, mkdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
21
+ import { basename, dirname, join, resolve, sep } from "node:path";
22
+ import { quoted, seconds } from "./checks.js";
23
+ import { AGREEMENT_PROVED, RULE_PROVED, declarationModule } from "./declaration.js";
24
+ import { runProcess } from "./processes.js";
25
+ import { javaEnv, javaWords, parserFaults } from "./tlc.js";
26
+ import { endedAs, tlapmArgs, tlapmEnv, tlapmVerdict } from "./tlapm.js";
27
+ import { ASCII_ONLY, oneModule, oneModuleRule, otherCharacter } from "./translation.js";
28
+ import { parseXml, child, textAt } from "./xml.js";
29
+ import { GuardError } from "./types.js";
30
+ // ---------------------------------------------------------------
31
+ // The statements
32
+ // ---------------------------------------------------------------
33
+ /** The module of a translation's statements, which its proof file
34
+ * extends. */
35
+ export function statementsName(translation) {
36
+ return `SpexStatements_${translation}`;
37
+ }
38
+ /** The module that proves the statements from a proof file. */
39
+ export function provedName(translation) {
40
+ return `SpexProved_${translation}`;
41
+ }
42
+ /** The module of a translation's proof file, which is its file's name
43
+ * too. */
44
+ export function proofsName(translation) {
45
+ return `${translation}_proofs`;
46
+ }
47
+ /**
48
+ * What the proofs of `translation` must prove, for any values: that
49
+ * its model keeps the rule and, unless it is `first`, that it agrees
50
+ * with `first`. The same names always give the same bytes.
51
+ */
52
+ export function statementsModule(translation, first) {
53
+ const lines = [
54
+ `---- MODULE ${statementsName(translation)} ----`,
55
+ `\\* Generated by Spex. What the proofs of translation ${translation} must prove, for any values.`,
56
+ "EXTENDS Declaration",
57
+ `T == INSTANCE ${translation}`,
58
+ "",
59
+ "\\* The model keeps the rule: in every state the model reaches, at every legal",
60
+ "\\* event at which the rule applies, the rule holds of the model's effect.",
61
+ "VARIABLE state",
62
+ "RuleInit == state = T!Start",
63
+ "RuleNext == \\E e \\in Events : T!Legal(state, e) /\\ state' = T!After(state, e)",
64
+ "RuleSpec == RuleInit /\\ [][RuleNext]_state",
65
+ "RuleAt(s) ==",
66
+ " \\A e \\in Events :",
67
+ " (T!Legal(s, e) /\\ T!When(e) /\\ T!While(s, e)) => T!Shall(s, e, T!Effect(s, e))",
68
+ "KeepsRule == RuleSpec => []RuleAt(state)",
69
+ ];
70
+ if (translation !== first) {
71
+ lines.push("", `\\* The translation agrees with the first, ${first}: at every step the two reach`, "\\* together they give the same four answers.", `F == INSTANCE ${first}`, "VARIABLES first, other", "AgreeInit == first = F!Start /\\ other = T!Start", "AgreeNext ==", " \\E e \\in Events :", " /\\ F!Legal(first, e) /\\ T!Legal(other, e)", " /\\ first' = F!After(first, e) /\\ other' = T!After(other, e)", "AgreeSpec == AgreeInit /\\ [][AgreeNext]_<<first, other>>", "AgreeAt(x, y) ==", " \\A e \\in Events :", " /\\ F!Legal(x, e) = T!Legal(y, e)", " /\\ F!Legal(x, e) =>", " /\\ (F!When(e) /\\ F!While(x, e)) = (T!When(e) /\\ T!While(y, e))", " /\\ F!Effect(x, e) = T!Effect(y, e)", " /\\ (F!When(e) /\\ F!While(x, e)) =>", " \\A f \\in Effects(e) : F!Shall(x, e, f) = T!Shall(y, e, f)", "Agrees == AgreeSpec => []AgreeAt(first, other)");
72
+ }
73
+ lines.push("====", "");
74
+ return lines.join("\n");
75
+ }
76
+ /** The module that proves `translation`'s statements from its proof
77
+ * file's theorems, so that a proof file proves them and no other
78
+ * statement of its own. */
79
+ export function provedModule(translation, first) {
80
+ const lines = [
81
+ `---- MODULE ${provedName(translation)} ----`,
82
+ `\\* Generated by Spex. The statements of translation ${translation}, from its proof file.`,
83
+ `EXTENDS ${proofsName(translation)}`,
84
+ `THEOREM SpexKeepsRule == KeepsRule BY ${RULE_PROVED}`,
85
+ ];
86
+ if (translation !== first)
87
+ lines.push(`THEOREM SpexAgrees == Agrees BY ${AGREEMENT_PROVED}`);
88
+ lines.push("====", "");
89
+ return lines.join("\n");
90
+ }
91
+ // ---------------------------------------------------------------
92
+ // What a proof file holds
93
+ // ---------------------------------------------------------------
94
+ /** What a proof file holds only: definitions of new names, and
95
+ * theorems and lemmas with their proofs. */
96
+ const HOLDS_ONLY = "a proof file holds only definitions of new names, and theorems and lemmas with their proofs";
97
+ /** Where a proof file's text holds `(*{`, which the proof system reads
98
+ * as an instruction to a prover and TLC's parser as a comment, or null. */
99
+ export function instructionAt(text) {
100
+ const at = text.indexOf("(*{");
101
+ if (at < 0)
102
+ return null;
103
+ const before = text.slice(0, at).split("\n");
104
+ return { line: before.length, col: before[before.length - 1].length + 1 };
105
+ }
106
+ /**
107
+ * Why a proof file's text is refused before any tool reads it, with
108
+ * its place where it has one, or null: a character TLC's parser and
109
+ * the proof system place differently, an instruction to a prover in a
110
+ * comment, or a module beside the one the file is named after, which
111
+ * could load or define what the checks of the file's own units do not
112
+ * see.
113
+ */
114
+ export function proofTextFault(text, module) {
115
+ const plain = text.replace(/\r\n?/g, "\n");
116
+ const other = otherCharacter(plain);
117
+ if (other !== null) {
118
+ return { line: other.line, col: other.col, why: `it holds the character ${other.shown}: a proof file holds ${ASCII_ONLY}` };
119
+ }
120
+ const instruction = instructionAt(plain);
121
+ if (instruction !== null) {
122
+ return {
123
+ ...instruction,
124
+ why: `a comment opened by (*{ is an instruction to a prover, which TLC's parser does not read; ${HOLDS_ONLY}`,
125
+ };
126
+ }
127
+ if (!oneModule(plain, module))
128
+ return { line: null, col: null, why: oneModuleRule(module) };
129
+ return null;
130
+ }
131
+ /** Why a unit is not one a proof file holds, or null. */
132
+ function refusedUnit(node) {
133
+ switch (node.tag) {
134
+ case "UserDefinedOpKind":
135
+ case "TheoremNode":
136
+ return null;
137
+ case "OpDeclNode": {
138
+ const kind = textAt(node, "kind");
139
+ if (kind === "2")
140
+ return "it declares a constant";
141
+ if (kind === "3")
142
+ return "it declares a variable";
143
+ return "it declares a name it does not define";
144
+ }
145
+ case "AssumeNode":
146
+ return "it states an assumption or an axiom";
147
+ case "InstanceNode":
148
+ return "it instantiates a module";
149
+ case "UseOrHideNode":
150
+ return "it holds a USE or a HIDE";
151
+ default:
152
+ return `it holds a unit TLC's parser calls ${node.tag}`;
153
+ }
154
+ }
155
+ /**
156
+ * Read what the XML TLC's parser wrote of the module `module` holds.
157
+ * Its own units are those whose place names the module itself; the
158
+ * units it extends are listed under it too. Throws a GuardError where
159
+ * the XML is not of the shape TLC's parser writes.
160
+ */
161
+ export function proofHolds(xml, module) {
162
+ const root = parseXml(xml);
163
+ const context = child(root, "context");
164
+ if (root.tag !== "modules" || context === undefined || textAt(root, "RootModule") !== module) {
165
+ throw new GuardError("it is not TLC's parser's XML of the module");
166
+ }
167
+ const byId = new Map();
168
+ for (const entry of context.children) {
169
+ const id = textAt(entry, "UID");
170
+ const node = entry.children.find((one) => one.tag !== "UID");
171
+ if (id === undefined || node === undefined)
172
+ throw new GuardError("an entry of its context has no node");
173
+ byId.set(id, node);
174
+ }
175
+ const nodes = [...byId.values()];
176
+ const own = nodes.find((node) => node.tag === "ModuleNode" && textAt(node, "uniquename") === module);
177
+ if (own === undefined)
178
+ throw new GuardError(`it holds no module ${module}`);
179
+ const resolved = (ref) => {
180
+ if (!ref.tag.endsWith("Ref"))
181
+ return ref;
182
+ const id = textAt(ref, "UID");
183
+ const node = id === undefined ? undefined : byId.get(id);
184
+ if (node === undefined)
185
+ throw new GuardError(`it refers to a node it does not hold: ${ref.tag}`);
186
+ return node;
187
+ };
188
+ const units = [];
189
+ const defined = {};
190
+ for (const part of own.children) {
191
+ if (part.tag === "uniquename" || part.tag === "location" || part.tag === "level")
192
+ continue;
193
+ const node = resolved(part);
194
+ const file = textAt(node, "location", "filename");
195
+ const name = textAt(node, "uniquename");
196
+ if (node.tag === "UserDefinedOpKind" && name !== undefined && file !== undefined)
197
+ defined[name] = file;
198
+ if (file !== module)
199
+ continue;
200
+ const line = Number(textAt(node, "location", "line", "begin"));
201
+ const col = Number(textAt(node, "location", "column", "begin"));
202
+ units.push({ node, line: Number.isInteger(line) && line > 0 ? line : null, col: Number.isInteger(col) && col > 0 ? col : null });
203
+ }
204
+ units.sort((a, b) => (a.line ?? 0) - (b.line ?? 0) || (a.col ?? 0) - (b.col ?? 0));
205
+ let refused = null;
206
+ const theorems = [];
207
+ for (const unit of units) {
208
+ const why = refusedUnit(unit.node);
209
+ if (why !== null) {
210
+ refused ??= { line: unit.line, col: unit.col, why };
211
+ continue;
212
+ }
213
+ if (unit.node.tag !== "TheoremNode")
214
+ continue;
215
+ const definition = child(unit.node, "definition");
216
+ const ref = definition?.children[0];
217
+ if (ref === undefined)
218
+ continue;
219
+ const name = textAt(resolved(ref), "uniquename");
220
+ if (name !== undefined)
221
+ theorems.push(name);
222
+ }
223
+ return { refused, defined, theorems };
224
+ }
225
+ /** The words of the command line after `java` that run TLC's parser
226
+ * alone on `<module>.tla`, with the proof system's standard modules
227
+ * on its library path. */
228
+ export function sanyArgs(jar, stdlib, module) {
229
+ return ["-XX:+UseParallelGC", "-XX:-UsePerfData", "-Djava.io.tmpdir=java-tmp", `-DTLA-Library=${stdlib}`, "-cp", jar, "tla2sany.SANY", `${module}.tla`];
230
+ }
231
+ /** The words of the command line after `java` that write the XML of
232
+ * `<module>.tla`, written to standard output. */
233
+ export function xmlArgs(jar, stdlib, module) {
234
+ return ["-XX:+UseParallelGC", "-XX:-UsePerfData", "-Djava.io.tmpdir=java-tmp", "-cp", jar, "tla2sany.xml.XMLExporter", "-o", "-I", stdlib, `${module}.tla`];
235
+ }
236
+ /** The most of a tool's output this reads: more than any proof file's
237
+ * XML, and less than any text Node holds. */
238
+ const MOST_OUTPUT = 64 * 1024 * 1024;
239
+ function readAll(file) {
240
+ if (!existsSync(file))
241
+ return "";
242
+ const bytes = readFileSync(file);
243
+ return bytes.subarray(0, MOST_OUTPUT).toString("utf8");
244
+ }
245
+ /** A path as it stands, every link followed where it exists. */
246
+ function real(path) {
247
+ try {
248
+ return realpathSync(path);
249
+ }
250
+ catch {
251
+ return resolve(path);
252
+ }
253
+ }
254
+ /** Whether `path` is `folder` or under it. */
255
+ function within(path, folder) {
256
+ return path === folder || path.startsWith(folder.endsWith(sep) ? folder : `${folder}${sep}`);
257
+ }
258
+ /** Write `files` into a fresh folder. */
259
+ function freshFolder(folder, files, empty) {
260
+ rmSync(folder, { recursive: true, force: true });
261
+ mkdirSync(folder, { recursive: true });
262
+ for (const [file, text] of Object.entries(files))
263
+ writeFileSync(join(folder, file), text);
264
+ for (const one of empty)
265
+ mkdirSync(join(folder, one));
266
+ }
267
+ /** Leave a run's folder under `--keep`, its empty folders emptied,
268
+ * with the lines that run it again there. */
269
+ function keepFolder(shop, folder, kept, empty, commands) {
270
+ if (shop.keep === null)
271
+ return;
272
+ for (const one of empty) {
273
+ rmSync(join(folder, one), { recursive: true, force: true });
274
+ mkdirSync(join(folder, one));
275
+ }
276
+ writeFileSync(join(folder, "command.txt"), [...commands, ""].join("\n"));
277
+ mkdirSync(dirname(join(shop.keep, kept)), { recursive: true });
278
+ cpSync(folder, join(shop.keep, kept), { recursive: true });
279
+ }
280
+ /** A run of a tool in `folder`, stopped at the guard's time limit,
281
+ * both its outputs kept in files there. */
282
+ async function runIn(shop, folder, program, args, env, output, errors) {
283
+ const ran = await runProcess(program, args, {
284
+ cwd: folder,
285
+ env,
286
+ seconds: shop.guard.limits.seconds,
287
+ errors: join(folder, errors),
288
+ output: join(folder, output),
289
+ });
290
+ return { ...ran, output: readAll(join(folder, output)), said: readAll(join(folder, errors)) };
291
+ }
292
+ /** The files every run on one translation's proofs is given: the
293
+ * declaration in TLA+, every translation, its statements and its
294
+ * proof file. */
295
+ function givenFiles(shop, translation, proof, first) {
296
+ const { guard } = shop;
297
+ const files = { "Declaration.tla": declarationModule(guard.binding, guard.binding.name) };
298
+ for (const one of guard.translations)
299
+ files[`${one.name}.tla`] = one.text;
300
+ files[`${statementsName(translation.name)}.tla`] = statementsModule(translation.name, first);
301
+ files[`${proofsName(translation.name)}.tla`] = proof.text;
302
+ return files;
303
+ }
304
+ /** The parser's own words of a fault, placed in the proof file where
305
+ * they name a place in it. */
306
+ function parserReason(file, module, said) {
307
+ if (said.module === module && said.line !== null)
308
+ return `${file}:${said.line}:${said.col ?? 1}: ${said.message}`;
309
+ if (said.module === null || said.module === module)
310
+ return `${file}: ${said.message}`;
311
+ return `${file}: in the module ${said.module}: ${said.message}`;
312
+ }
313
+ /**
314
+ * Conditions 3 and 4: TLC's parser reads the proof file without
315
+ * error, loading nothing but the files given and the proof system's
316
+ * standard modules, and its XML shows the file holds nothing but
317
+ * definitions and theorems, extends its statements and holds the
318
+ * theorems that prove them. Null where they hold, else why not.
319
+ */
320
+ async function parseProof(shop, system, translation, proof, first) {
321
+ const { tools } = shop;
322
+ const module = proofsName(translation.name);
323
+ const kept = `proofs-${translation.name}/parse`;
324
+ const folder = join(shop.home, kept);
325
+ const files = givenFiles(shop, translation, proof, first);
326
+ freshFolder(folder, files, ["java-tmp"]);
327
+ const env = javaEnv(process.env);
328
+ const sany = sanyArgs(tools.jar, system.stdlib, module);
329
+ const xml = xmlArgs(tools.jar, system.stdlib, module);
330
+ const commands = [
331
+ "# Run in this folder, with java-tmp empty,",
332
+ "# and without JAVA_TOOL_OPTIONS, _JAVA_OPTIONS and JDK_JAVA_OPTIONS.",
333
+ [tools.java, ...sany].map(quoted).join(" "),
334
+ `${[tools.java, ...xml].map(quoted).join(" ")} > ${module}.xml`,
335
+ ];
336
+ const stopped = `${proof.file}: TLC's parser was stopped after ${seconds(shop.guard.limits.seconds)} while it read the file`;
337
+ try {
338
+ const parsed = await runIn(shop, folder, tools.java, sany, env, `${module}.sany`, `${module}.sany.err`);
339
+ if (parsed.failed !== null)
340
+ throw new GuardError(`TLC's parser could not start: ${parsed.failed}`);
341
+ if (parsed.timedOut)
342
+ return stopped;
343
+ if (!/^\*{6} SANY2 Version /m.test(parsed.output)) {
344
+ const said = javaWords(parsed.said);
345
+ throw new GuardError(`Java ended before TLC's parser started${said === "" ? "" : `: ${said}`}`);
346
+ }
347
+ // The parser exits 0 where a module means nothing, as where it
348
+ // defines a name twice: its words say so.
349
+ const faults = parserFaults(parsed.output);
350
+ if (parsed.code !== 0 || faults.length > 0 || /^(Semantic errors:|\*\*\* Errors:)/m.test(parsed.output)) {
351
+ if (faults.length > 0)
352
+ return parserReason(proof.file, module, faults[0]);
353
+ const said = javaWords(parsed.said);
354
+ return `${proof.file}: TLC's parser ${endedAs(parsed.code)}${said === "" ? "" : `: ${said}`}`;
355
+ }
356
+ const home = real(folder);
357
+ const library = real(system.stdlib);
358
+ for (const found of parsed.output.matchAll(/^Parsing file (.*)$/gm)) {
359
+ const path = found[1].trim();
360
+ const at = real(path);
361
+ const given = dirname(at) === home && Object.hasOwn(files, basename(at));
362
+ // What the parser unpacks from its own jar it unpacks into the
363
+ // run's temp folder, which was empty.
364
+ const own = dirname(at) === join(home, "java-tmp");
365
+ const standard = within(at, library) || within(resolve(path), resolve(system.stdlib));
366
+ if (!given && !own && !standard) {
367
+ return `${proof.file}: it loads ${path}; a proof file loads only the declaration in TLA+, the translations, its statements and the standard modules of the TLA+ tools`;
368
+ }
369
+ }
370
+ const written = await runIn(shop, folder, tools.java, xml, env, `${module}.xml`, `${module}.xml.err`);
371
+ if (written.failed !== null)
372
+ throw new GuardError(`TLC's parser could not start: ${written.failed}`);
373
+ if (written.timedOut)
374
+ return stopped;
375
+ if (written.code !== 0) {
376
+ const said = javaWords(written.said);
377
+ return `${proof.file}: TLC's parser ${endedAs(written.code)} while it wrote what the file holds${said === "" ? "" : `: ${said}`}`;
378
+ }
379
+ let holds;
380
+ try {
381
+ holds = proofHolds(written.output, module);
382
+ }
383
+ catch (error) {
384
+ if (!(error instanceof GuardError))
385
+ throw error;
386
+ return `${proof.file}: what TLC's parser wrote of it cannot be read: ${error.message}`;
387
+ }
388
+ if (holds.refused !== null) {
389
+ const { line, col, why } = holds.refused;
390
+ return `${proof.file}${line === null ? "" : `:${line}:${col ?? 1}`}: ${why}; ${HOLDS_ONLY}`;
391
+ }
392
+ // The statements a proof file's theorems speak of are the ones
393
+ // Spex wrote: the names the module that proves them will read at
394
+ // this file's own level are defined by the statements' file and by
395
+ // no other, so no module loaded another way stands in for it.
396
+ const statements = statementsName(translation.name);
397
+ const stated = translation.name === first ? ["KeepsRule"] : ["KeepsRule", "Agrees"];
398
+ if (stated.some((name) => holds.defined[name] !== statements)) {
399
+ return `${proof.file}: it does not extend ${statements}, the statements it proves`;
400
+ }
401
+ if (!holds.theorems.includes(RULE_PROVED))
402
+ return `${proof.file}: it holds no theorem ${RULE_PROVED}, which proves KeepsRule`;
403
+ if (translation.name !== first && !holds.theorems.includes(AGREEMENT_PROVED)) {
404
+ return `${proof.file}: it holds no theorem ${AGREEMENT_PROVED}, which proves Agrees`;
405
+ }
406
+ return null;
407
+ }
408
+ finally {
409
+ keepFolder(shop, folder, kept, ["java-tmp"], commands);
410
+ rmSync(folder, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
411
+ }
412
+ }
413
+ /**
414
+ * Condition 5: the proof system, with fixed options, a cache of its
415
+ * own that starts empty and nothing taken from the environment,
416
+ * proves every obligation of the proof file and the statements from
417
+ * it, with no proof omitted or missing. Null where it does, else why
418
+ * not.
419
+ */
420
+ async function prove(shop, system, translation, proof, first) {
421
+ const module = proofsName(translation.name);
422
+ const proved = provedName(translation.name);
423
+ const kept = `proofs-${translation.name}/prove`;
424
+ const folder = join(shop.home, kept);
425
+ freshFolder(folder, { ...givenFiles(shop, translation, proof, first), [`${proved}.tla`]: provedModule(translation.name, first) }, ["cache", "tmp"]);
426
+ const args = tlapmArgs(module, proved);
427
+ const scratch = join(folder, "tmp");
428
+ // The solvers it starts write their files under the run's own temp
429
+ // folder, which goes with the run.
430
+ const env = { ...tlapmEnv(process.env), TMPDIR: scratch, TMP: scratch, TEMP: scratch };
431
+ const commands = [
432
+ "# Run in this folder, with cache and tmp empty, TMPDIR set to tmp,",
433
+ "# and no variable whose name starts with TLAPM.",
434
+ [system.program, ...args].map(quoted).join(" "),
435
+ ];
436
+ try {
437
+ const ran = await runIn(shop, folder, system.program, args, env, `${module}.tlapm`, `${module}.tlapm`);
438
+ if (ran.failed !== null)
439
+ return `the proof system could not start: ${ran.failed}`;
440
+ if (ran.timedOut)
441
+ return `${proof.file}: the proof system was stopped after ${seconds(shop.guard.limits.seconds)}`;
442
+ const verdict = tlapmVerdict(ran.output, ran.code, [module, proved]);
443
+ if (verdict.kind === "proved")
444
+ return null;
445
+ const { place } = verdict;
446
+ const at = place !== null && place.module === module ? `${proof.file}:${place.line}:${place.col}` : proof.file;
447
+ switch (verdict.what) {
448
+ case "failed":
449
+ if (place === null || place.module === module)
450
+ return `${at}: the proof system could not prove this step`;
451
+ if (place.module === proved) {
452
+ const theorems = translation.name === first ? RULE_PROVED : `${RULE_PROVED} and ${AGREEMENT_PROVED}`;
453
+ return `${at}: the proof system could not prove the statements from its ${translation.name === first ? "theorem" : "theorems"} ${theorems}`;
454
+ }
455
+ return `${at}: the proof system could not prove a step of ${place.module}.tla at ${place.line}:${place.col}`;
456
+ case "omitted":
457
+ return `${at}: a proof is omitted`;
458
+ case "missing":
459
+ return `${at}: a step has no proof`;
460
+ default:
461
+ return `${at}: the proof system did not accept it: ${verdict.words}`;
462
+ }
463
+ }
464
+ finally {
465
+ keepFolder(shop, folder, kept, ["cache", "tmp"], commands);
466
+ rmSync(folder, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
467
+ }
468
+ }
469
+ /**
470
+ * Check a guard's proofs, translation by translation in name order,
471
+ * each by the five conditions in order, and stop at the first that
472
+ * does not hold. Throws a GuardError only where Java could not run
473
+ * TLC's parser: no proof is at fault then.
474
+ */
475
+ export async function checkProofs(shop) {
476
+ const { guard, tools } = shop;
477
+ const system = tools.proof;
478
+ if (system.kind === "none")
479
+ return { kind: "not accepted", reason: system.cause };
480
+ const first = guard.translations[0].name;
481
+ for (const translation of guard.translations) {
482
+ const proof = guard.proofs.find((one) => one.name === translation.name);
483
+ if (proof === undefined) {
484
+ return {
485
+ kind: "not accepted",
486
+ reason: `${guard.folder}/proofs/${proofsName(translation.name)}.tla: not found — every translation needs its proofs`,
487
+ };
488
+ }
489
+ const fault = proofTextFault(proof.text, proofsName(translation.name));
490
+ if (fault !== null) {
491
+ const at = fault.line === null ? "" : `:${fault.line}:${fault.col ?? 1}`;
492
+ return { kind: "not accepted", reason: `${proof.file}${at}: ${fault.why}` };
493
+ }
494
+ const parsed = await parseProof(shop, system, translation, proof, first);
495
+ if (parsed !== null)
496
+ return { kind: "not accepted", reason: parsed };
497
+ const proved = await prove(shop, system, translation, proof, first);
498
+ if (proved !== null)
499
+ return { kind: "not accepted", reason: proved };
500
+ }
501
+ return { kind: "accepted", translations: guard.translations.map((one) => one.name) };
502
+ }
503
+ //# sourceMappingURL=proofs.js.map
@@ -0,0 +1,176 @@
1
+ import type { Row, Table } from "./checks.js";
2
+ import { type Tla } from "./tla.js";
3
+ import { type Call, type Declaration, type Fields, type Step, type Value } from "./types.js";
4
+ /** The most records handed to TLC one run is given, unless one
5
+ * sequence holds more. */
6
+ export declare const MOST_RECORDS = 100000;
7
+ /** The most different records one run is given, unless one sequence
8
+ * holds more. */
9
+ export declare const MOST_DIFFERENT = 20000;
10
+ /** One different record: its event with its params, the effect the
11
+ * code gave, and the two as one TLA+ value. Sets hold their members
12
+ * in the order of their TLA+ text. */
13
+ export type Recorded = {
14
+ call: Call;
15
+ effect: Fields;
16
+ text: string;
17
+ };
18
+ /**
19
+ * What one copy's records share: each different record once, by the
20
+ * number it is met in, and the set each value outside the declared
21
+ * ones was first recorded under.
22
+ */
23
+ export type Book = {
24
+ declaration: Declaration;
25
+ records: Recorded[];
26
+ /** A record's TLA+ text to its place in `records`. */
27
+ index: Map<string, number>;
28
+ /** A value outside the declared ones to its set. */
29
+ homes: Map<string, string>;
30
+ };
31
+ /** An empty book for one copy of the code. */
32
+ export declare function newBook(declaration: Declaration): Book;
33
+ /** A value as TLA+ text: a set's members in the order of their text,
34
+ * the missing value as `Missing`. */
35
+ export declare function valueTla(value: Value): string;
36
+ /** Put a record in the book, once: its number there. */
37
+ export declare function addRecord(book: Book, call: Call, effect: Fields): number;
38
+ /** A sequence of records, the module's or the tests'. */
39
+ export type Sequence = {
40
+ /** How a report names it (`sequenceName`). */
41
+ name: string;
42
+ source: "module" | "tests";
43
+ /** The tests' sequence's file and `seq`; null for the module's. */
44
+ file: string | null;
45
+ seq: string | null;
46
+ /** The test its start names, or null. */
47
+ test: string | null;
48
+ /** Why it is not whole, or null where it is. */
49
+ why: string | null;
50
+ /** Its record lines, a refused one among them. */
51
+ records: number;
52
+ /** The records handed to TLC, in order, each by its number in the
53
+ * book. */
54
+ handed: number[];
55
+ };
56
+ /** How a report names a sequence of the tests: `"<test>" (<file>, seq
57
+ * "<seq>")`, without the test where its start names none. */
58
+ export declare function sequenceName(test: string | null, file: string, seq: string): string;
59
+ /** The name of the module's sequence for a permitted case. */
60
+ export declare function moduleCaseName(label: string): string;
61
+ /** The name of the module's sequence for the `k`-th step of the model,
62
+ * from 1. */
63
+ export declare function moduleStepName(k: number): string;
64
+ /** A sequence the module caused to its end: its events with their
65
+ * params and the effects the copy's process observed, whole. */
66
+ export declare function moduleSequence(book: Book, name: string, calls: readonly Call[], effects: readonly Fields[]): Sequence;
67
+ /** A line that cannot be read, by its file and line from 1. */
68
+ export type RefusedLine = {
69
+ file: string;
70
+ line: number;
71
+ cause: string;
72
+ };
73
+ /** What a folder of records holds. */
74
+ export type RecordsRead = {
75
+ /** The tests' sequences: files in name order, in a file by the line
76
+ * of each sequence's first line. */
77
+ sequences: Sequence[];
78
+ /** Each line with no place, and each refused line, in the order of
79
+ * files and lines. */
80
+ refused: RefusedLine[];
81
+ /** The entries of the folder that are no file of records, in name
82
+ * order. */
83
+ strays: string[];
84
+ };
85
+ /**
86
+ * Read every entry of a folder of records in name order (guards-51,
87
+ * guards-52). An entry that is no file named `<name>.jsonl` is told
88
+ * and not read. Each line is read by the binding's declared types into
89
+ * `book`; the lines of one file that share a `seq` are one sequence.
90
+ */
91
+ export declare function readRecords(folder: string, book: Book): Promise<RecordsRead>;
92
+ /** One set's values for TLC: its declared values and every other value
93
+ * the copy's records hold, in the order the set has. */
94
+ export type SetValues = {
95
+ values: string[];
96
+ others: number;
97
+ };
98
+ /**
99
+ * Each set, in the order of `values`: its declared values and every
100
+ * other value of it the book holds, sorted by the declared order where
101
+ * the set has one, else the declared values as declared and then the
102
+ * others in name order.
103
+ */
104
+ export declare function copyValues(book: Book): Record<string, SetValues>;
105
+ /** One run of TLC: the sequences `from` to `to` (not included) of a
106
+ * copy, the records handed in them, and each different record's place
107
+ * in the run's `SpexRecord`, from 1, by its number in the book. */
108
+ export type Run = {
109
+ from: number;
110
+ to: number;
111
+ records: number;
112
+ index: Map<number, number>;
113
+ };
114
+ /**
115
+ * Cut a copy's sequences into runs, in order: a run is closed before
116
+ * the sequence that would bring it past `mostRecords` handed records
117
+ * or past `mostDifferent` different records. A sequence with more is
118
+ * a run alone. No sequence, no run.
119
+ */
120
+ export declare function runsOf(sequences: readonly Sequence[], mostRecords?: number, mostDifferent?: number): Run[];
121
+ /** What TLC printed for one sequence: how many of its handed records
122
+ * were matched, at how many the rule applied, what the model says of
123
+ * the first not matched (`matched` where every one was), and the
124
+ * model's effect there, or null. */
125
+ export type Judged = {
126
+ matched: number;
127
+ applied: number;
128
+ said: "matched" | "forbidden" | "differs" | "not legal";
129
+ model: Tla | null;
130
+ };
131
+ /** One text for an event with its params. */
132
+ export declare function callKey(call: Call): string;
133
+ /** A field a step states whose recorded value is another. */
134
+ export type StatedDifference = {
135
+ field: string;
136
+ stated: Value;
137
+ observed: Value;
138
+ };
139
+ /**
140
+ * The first step of `steps` whose record, of `handed` in order, differs
141
+ * in a field the step states, with each such field, the values
142
+ * compared as values of their types; null where every step's record is
143
+ * as it states.
144
+ */
145
+ export declare function stepFailure(steps: readonly Step[], handed: readonly number[], book: Book): {
146
+ step: number;
147
+ differences: StatedDifference[];
148
+ } | null;
149
+ /** A sequence of the tests that opens with a permitted case, and the
150
+ * first step there that is not as the case states. */
151
+ export type Opening = {
152
+ sequence: number;
153
+ failed: {
154
+ step: number;
155
+ differences: StatedDifference[];
156
+ } | null;
157
+ };
158
+ /**
159
+ * Every sequence of the tests that opens with the case's steps: its
160
+ * first handed records, as many as the case has steps, hold the case's
161
+ * events with the case's params. By the sequence's place in
162
+ * `sequences`, in order.
163
+ */
164
+ export declare function caseOpenings(steps: readonly Step[], sequences: readonly Sequence[], book: Book): Opening[];
165
+ /**
166
+ * Follow TLC's table of the model's steps with the matched records of
167
+ * each sequence judged: from the table's start, each record's row by
168
+ * the state and its event with its params, reached where the row's
169
+ * effect is the record's; where there is none, the sequence's other
170
+ * matched records are beyond the declared values. It looks up and
171
+ * evaluates nothing.
172
+ */
173
+ export declare function reach(table: Table, sequences: readonly Sequence[], judged: readonly (Judged | null)[], book: Book): {
174
+ reached: Set<Row>;
175
+ beyond: number;
176
+ };