@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,457 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // SPDX-FileCopyrightText: 2026 SubLang International <https://sublang.ai>
3
+ /*
4
+ * Guards package (guards-9, guards-40), DR-244 and DR-252: TLC, the
5
+ * model checker of the TLA+ tools. This file finds Java and the
6
+ * pinned `tla2tools.jar`, with the proof system (`tlapm.ts`), runs TLC
7
+ * once in a folder of its own with fixed options, and reads
8
+ * what TLC printed: its messages, a module that does not parse, the
9
+ * values a file printed, a sequence, its counts and its state dump.
10
+ * It evaluates no TLA+ and answers none of the four questions.
11
+ */
12
+ import { spawnSync } from "node:child_process";
13
+ import { createHash } from "node:crypto";
14
+ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync } from "node:fs";
15
+ import { constants as bufferLimits } from "node:buffer";
16
+ import { basename, dirname, join, resolve } from "node:path";
17
+ import { homeDir } from "../commands/home.js";
18
+ import { lastWords, runProcess } from "./processes.js";
19
+ import { parseState, parseTlaAll } from "./tla.js";
20
+ import { findProofSystem } from "./tlapm.js";
21
+ import { GuardError } from "./types.js";
22
+ // ---------------------------------------------------------------
23
+ // Java and the jar
24
+ // ---------------------------------------------------------------
25
+ /** The one TLC that Spex pins. */
26
+ export const TLC_PIN = {
27
+ version: "2.19",
28
+ release: "v1.7.4",
29
+ url: "https://github.com/tlaplus/tlaplus/releases/download/v1.7.4/tla2tools.jar",
30
+ sha256: "936a262061c914694dfd669a543be24573c45d5aa0ff20a8b96b23d01e050e88",
31
+ };
32
+ /** The oldest Java that runs TLC. */
33
+ const JAVA_FLOOR = 11;
34
+ /** The variables through which a host adds options to every JVM. A
35
+ * run of TLC takes none of them. */
36
+ const JVM_OPTIONS = ["JAVA_TOOL_OPTIONS", "_JAVA_OPTIONS", "JDK_JAVA_OPTIONS"];
37
+ /** The environment TLC and `java -version` run in. */
38
+ export function javaEnv(env) {
39
+ const clean = { ...env };
40
+ for (const name of JVM_OPTIONS)
41
+ delete clean[name];
42
+ return clean;
43
+ }
44
+ const NEEDS_JAVA = `spex verify runs TLC, which needs Java ${JAVA_FLOOR} or later`;
45
+ /**
46
+ * Find Java: `$JAVA_HOME/bin/java` where that file is there, else
47
+ * `java` on PATH. Throws a GuardError saying what to install or set.
48
+ */
49
+ export function findJava(env = process.env) {
50
+ let java = "java";
51
+ const home = env.JAVA_HOME?.trim();
52
+ if (home) {
53
+ const named = join(home, "bin", process.platform === "win32" ? "java.exe" : "java");
54
+ if (existsSync(named))
55
+ java = named;
56
+ }
57
+ const ran = spawnSync(java, ["-XX:-UsePerfData", "-version"], { env: javaEnv(env), encoding: "utf8", timeout: 60_000, windowsHide: true });
58
+ if (ran.error !== undefined || ran.status !== 0) {
59
+ throw new GuardError(`Java was not found: ${NEEDS_JAVA} — install one, or set JAVA_HOME to one`);
60
+ }
61
+ const named = /version "([^"]+)"/.exec(`${ran.stderr}\n${ran.stdout}`);
62
+ if (named === null) {
63
+ throw new GuardError(`${java} -version names no version: ${NEEDS_JAVA} — install one, or set JAVA_HOME to one`);
64
+ }
65
+ const parts = named[1].split(/[._-]/).map(Number);
66
+ const major = parts[0] === 1 ? parts[1] : parts[0];
67
+ if (!(major >= JAVA_FLOOR)) {
68
+ throw new GuardError(`Java ${named[1]} is too old: ${NEEDS_JAVA} — install one, or set JAVA_HOME to one`);
69
+ }
70
+ return { java, javaVersion: named[1] };
71
+ }
72
+ function sha256(file) {
73
+ return createHash("sha256").update(readFileSync(file)).digest("hex");
74
+ }
75
+ function isFile(path) {
76
+ return existsSync(path) && statSync(path).isFile();
77
+ }
78
+ /** Where the home keeps its copy of the pinned jar. */
79
+ export function homeJar(env = process.env) {
80
+ return join(homeDir(env), "tools", `tla2tools-${TLC_PIN.release.slice(1)}.jar`);
81
+ }
82
+ /** The program a download runs: Node itself, so that it follows the
83
+ * host's proxy variables where this Node can. */
84
+ const DOWNLOAD = `const [, url, dest] = process.argv;
85
+ fetch(url, { redirect: "follow" })
86
+ .then(async (answer) => {
87
+ if (!answer.ok) throw new Error("the server answered " + answer.status);
88
+ require("node:fs").writeFileSync(dest, Buffer.from(await answer.arrayBuffer()));
89
+ })
90
+ .catch((error) => {
91
+ console.error((error.cause && error.cause.message) || error.message);
92
+ process.exit(1);
93
+ });`;
94
+ /**
95
+ * Download `pin.url` to `dest`, once: the bytes are kept only where
96
+ * their SHA-256 is `pin.sha256`. Throws a GuardError saying what to
97
+ * do where the download fails or gives other bytes; nothing is then
98
+ * left at `dest`.
99
+ */
100
+ export async function downloadJar(pin, dest, env = process.env) {
101
+ const yourself = `download it yourself, check that its sha256 is ${pin.sha256}, and set SPEX_TLC_JAR to the file`;
102
+ const folder = dirname(dest);
103
+ const part = `${dest}.part-${process.pid}`;
104
+ try {
105
+ mkdirSync(folder, { recursive: true });
106
+ const ran = await runProcess(process.execPath, ["-e", DOWNLOAD, pin.url, part], {
107
+ cwd: folder,
108
+ env: { ...env, NODE_USE_ENV_PROXY: "1" },
109
+ seconds: 300,
110
+ errors: `${part}.err`,
111
+ });
112
+ if (ran.failed !== null || ran.timedOut || ran.code !== 0 || !isFile(part)) {
113
+ const cause = ran.timedOut ? "not done after 300 seconds" : (ran.failed ?? lastWords(ran.errors));
114
+ throw new GuardError(`TLC ${pin.version} could not be downloaded from ${pin.url}${cause === "" ? "" : `: ${cause}`} — ${yourself}`);
115
+ }
116
+ const got = sha256(part);
117
+ if (got !== pin.sha256) {
118
+ throw new GuardError(`what ${pin.url} gave is not TLC ${pin.version}: its sha256 is ${got}; nothing was kept — ${yourself}`);
119
+ }
120
+ renameSync(part, dest);
121
+ }
122
+ catch (error) {
123
+ if (error instanceof GuardError)
124
+ throw error;
125
+ const cause = error instanceof Error ? error.message : String(error);
126
+ throw new GuardError(`TLC ${pin.version} could not be kept at ${dest}: ${cause} — ${yourself}`);
127
+ }
128
+ finally {
129
+ rmSync(part, { force: true });
130
+ rmSync(`${part}.err`, { force: true });
131
+ }
132
+ }
133
+ /**
134
+ * Find the jar: the one `SPEX_TLC_JAR` names where it is set, else
135
+ * the home's copy of the pinned release, downloaded once and checked
136
+ * where the home has none. Throws a GuardError saying what to set.
137
+ */
138
+ export async function findJar(env = process.env) {
139
+ const named = env.SPEX_TLC_JAR?.trim();
140
+ if (named) {
141
+ const jar = resolve(named);
142
+ if (!isFile(jar)) {
143
+ throw new GuardError(`SPEX_TLC_JAR names ${named}, which is no file — set it to a tla2tools.jar, or unset it for Spex to download TLC ${TLC_PIN.version}`);
144
+ }
145
+ return { jar, pinned: sha256(jar) === TLC_PIN.sha256 };
146
+ }
147
+ const jar = homeJar(env);
148
+ if (!isFile(jar) || sha256(jar) !== TLC_PIN.sha256)
149
+ await downloadJar(TLC_PIN, jar, env);
150
+ return { jar, pinned: true };
151
+ }
152
+ /** Find Java, the jar and the proof system. Throws a GuardError
153
+ * saying what to install or set where Java or the jar is not there;
154
+ * a proof system that is not there is said in `proof`. */
155
+ export async function findTools(env = process.env) {
156
+ const java = findJava(env);
157
+ return { ...java, ...(await findJar(env)), proof: findProofSystem(env) };
158
+ }
159
+ /** The words of the command line after the program, for `module` in
160
+ * the folder TLC runs in. Every path but the jar's is relative to
161
+ * that folder, so the same line runs again anywhere. */
162
+ export function tlcArgs(jar, module, dump) {
163
+ return [
164
+ "-XX:+UseParallelGC",
165
+ "-XX:-UsePerfData",
166
+ "-Djava.io.tmpdir=java-tmp",
167
+ "-cp",
168
+ jar,
169
+ "tlc2.TLC",
170
+ "-tool",
171
+ "-workers",
172
+ "1",
173
+ "-fp",
174
+ "0",
175
+ "-metadir",
176
+ "states",
177
+ "-userFile",
178
+ `${module}.user`,
179
+ ...(dump ? ["-dump", `${module}.dump`] : []),
180
+ "-config",
181
+ `${module}.cfg`,
182
+ module,
183
+ ];
184
+ }
185
+ /**
186
+ * Run TLC once on `<module>.tla` with `<module>.cfg` in `folder`,
187
+ * which holds them and every module they load and is used by no other
188
+ * run. The run is stopped at `seconds`.
189
+ */
190
+ export async function runTlc(tools, folder, module, options) {
191
+ // TLC unpacks its standard modules into the JVM's temp folder, which
192
+ // must be there and be this run's own.
193
+ mkdirSync(join(folder, "java-tmp"), { recursive: true });
194
+ const args = tlcArgs(tools.jar, module, options.dump === true);
195
+ const out = join(folder, `${module}.out`);
196
+ const ran = await runProcess(tools.java, args, {
197
+ cwd: folder,
198
+ env: javaEnv(options.env ?? process.env),
199
+ seconds: options.seconds,
200
+ errors: join(folder, `${module}.err`),
201
+ output: out,
202
+ });
203
+ const read = (file) => (isFile(file) ? readFileSync(file, "utf8") : null);
204
+ const stdout = read(out) ?? "";
205
+ // A run stopped at the time limit left its dump unfinished, and the
206
+ // dump of a model without end is larger than any text Node holds.
207
+ let dump = null;
208
+ let unread = null;
209
+ if (options.dump === true && !ran.timedOut) {
210
+ const file = join(folder, `${module}.dump`);
211
+ try {
212
+ const size = isFile(file) ? statSync(file).size : 0;
213
+ if (size > bufferLimits.MAX_STRING_LENGTH)
214
+ unread = `it is too large, ${size} bytes`;
215
+ else
216
+ dump = read(file);
217
+ }
218
+ catch (error) {
219
+ unread = error instanceof Error ? error.message : String(error);
220
+ }
221
+ }
222
+ return {
223
+ module,
224
+ status: ran.code,
225
+ timedOut: ran.timedOut,
226
+ failed: ran.failed,
227
+ errors: ran.errors,
228
+ stdout,
229
+ messages: messagesOf(stdout),
230
+ user: read(join(folder, `${module}.user`)) ?? "",
231
+ dump,
232
+ unread,
233
+ command: [tools.java, ...args],
234
+ };
235
+ }
236
+ // ---------------------------------------------------------------
237
+ // Reading what TLC printed
238
+ // ---------------------------------------------------------------
239
+ /** The messages of `-tool` output, in order. An error's text can hold
240
+ * another message, so the codes are paired. */
241
+ export function messagesOf(stdout) {
242
+ const messages = [];
243
+ const re = /@!@!@STARTMSG (\d+):(\d+) @!@!@\n([\s\S]*?)\n?@!@!@ENDMSG \1 @!@!@/g;
244
+ for (const found of stdout.replace(/\r\n/g, "\n").matchAll(re)) {
245
+ messages.push({ code: Number(found[1]), severity: Number(found[2]), text: found[3] });
246
+ }
247
+ return messages;
248
+ }
249
+ /** TLC's version, from its version line (message 2262): `2.19`. */
250
+ export function versionOf(run) {
251
+ const line = run.messages.find((message) => message.code === 2262)?.text ?? "";
252
+ return /Version (\S+)/.exec(line)?.[1] ?? null;
253
+ }
254
+ /** Whether TLC got past the model's start: it reports the initial
255
+ * states computed (message 2190). */
256
+ export function pastStart(run) {
257
+ return run.messages.some((message) => message.code === 2190);
258
+ }
259
+ /**
260
+ * What the JVM wrote on standard error, on one line: its first two
261
+ * lines that are no line of a stack. Java says why it could not run
262
+ * TLC at the top, before any stack. Empty where it wrote nothing.
263
+ */
264
+ export function javaWords(errors) {
265
+ return errors
266
+ .split("\n")
267
+ .map((line) => line.trim())
268
+ .filter((line) => line !== "" && !line.startsWith("at ") && !/^\.\.\. \d+ more$/.test(line))
269
+ .slice(0, 2)
270
+ .join(" ");
271
+ }
272
+ /** The modules TLC reports loading, by name, in its order. */
273
+ export function loadedModules(run) {
274
+ const names = [];
275
+ for (const found of run.stdout.matchAll(/^Parsing file (.*)$/gm)) {
276
+ const name = basename(found[1].trim().replace(/\\/g, "/")).replace(/\.tla$/, "");
277
+ if (!names.includes(name))
278
+ names.push(name);
279
+ }
280
+ return names;
281
+ }
282
+ function oneLine(text) {
283
+ return text.split("\n").map((line) => line.trim()).filter((line) => line !== "").join(" ");
284
+ }
285
+ /**
286
+ * What TLC's parser said where the modules did not parse (exit 150):
287
+ * each error with its module, line and column where it names them.
288
+ * Empty where it said nothing this reads.
289
+ */
290
+ export function parseFaults(run) {
291
+ const stdout = run.stdout.replace(/\r\n/g, "\n");
292
+ const from = stdout.indexOf("@!@!@ENDMSG 2220 @!@!@");
293
+ if (from < 0)
294
+ return [];
295
+ const rest = stdout.slice(from + "@!@!@ENDMSG 2220 @!@!@".length);
296
+ const to = rest.indexOf("@!@!@STARTMSG");
297
+ return parserFaults(to < 0 ? rest : rest.slice(0, to));
298
+ }
299
+ /**
300
+ * What TLC's parser said of modules that do not parse or do not
301
+ * mean anything, as it prints it, within TLC or run alone
302
+ * (`tla2sany.SANY`): each error with its module, line and column where
303
+ * it names them. Empty where it said nothing this reads.
304
+ */
305
+ export function parserFaults(printed) {
306
+ const said = printed
307
+ .replace(/\r\n/g, "\n")
308
+ .split("\n")
309
+ .filter((line) => !/^(Parsing file|Semantic processing of module) /.test(line) && !/^\*{6} SANY2 Version /.test(line))
310
+ .join("\n");
311
+ const failing = /Could not parse module (\w+) from file/.exec(said)?.[1] ?? null;
312
+ const lexical = /^Lexical error at line (\d+), column (\d+)\.\s*(.*)$/m.exec(said);
313
+ if (lexical !== null) {
314
+ return [{ module: failing, line: Number(lexical[1]), col: Number(lexical[2]), message: `Lexical error. ${lexical[3].trim()}` }];
315
+ }
316
+ const syntax = /\*\*\*Parse Error\*\*\*\n([\s\S]*?)\n[ \t]*\n(?=Residual stack trace|Fatal errors)/.exec(said);
317
+ if (syntax !== null) {
318
+ const place = /at line (\d+),\s*column (\d+)/.exec(syntax[1]) ?? /line (\d+), col (\d+) to line/.exec(syntax[1]);
319
+ return [
320
+ {
321
+ module: failing,
322
+ line: place === null ? null : Number(place[1]),
323
+ col: place === null ? null : Number(place[2]),
324
+ message: oneLine(syntax[1]),
325
+ },
326
+ ];
327
+ }
328
+ const faults = [];
329
+ const seen = new Set();
330
+ for (const block of said.split(/^Semantic errors:$/m).slice(1)) {
331
+ const errors = block.split(/^\*\*\* Warnings: \d+$/m)[0];
332
+ for (const found of errors.matchAll(/^line (\d+), col (\d+) to line \d+, col \d+ of module (\w+)\n\n([\s\S]*?)(?:\n[ \t]*\n|(?![\s\S]))/gm)) {
333
+ const fault = { module: found[3], line: Number(found[1]), col: Number(found[2]), message: oneLine(found[4]) };
334
+ const mark = JSON.stringify(fault);
335
+ if (!seen.has(mark))
336
+ faults.push(fault);
337
+ seen.add(mark);
338
+ }
339
+ }
340
+ if (faults.length > 0)
341
+ return faults;
342
+ const abort = /\*\*\* Abort messages: \d+\n\n(.*)\n\n([\s\S]*?)(?:\n[ \t]*\n|$)/.exec(said);
343
+ if (abort !== null) {
344
+ return [{ module: /^In module (\w+)/.exec(abort[1])?.[1] ?? null, line: null, col: null, message: oneLine(abort[2]) }];
345
+ }
346
+ const all = oneLine(said);
347
+ return all === "" ? [] : [{ module: null, line: null, col: null, message: all }];
348
+ }
349
+ /** What TLC itself says of a Java stack overflow where it catches
350
+ * one (its message 1005), said here too where it only names the
351
+ * exception, so that one fault reads the same in every run. */
352
+ const STACK_OVERFLOW = "This was a Java StackOverflowError. It was probably the result of an incorrect recursive function definition that caused TLC to enter an infinite loop when trying to compute the function or its application to an element in its putative domain.";
353
+ /**
354
+ * TLC's first error that is not a violated invariant: its message
355
+ * and the places it names. Null where it reported none.
356
+ */
357
+ export function evalFault(run) {
358
+ const error = run.messages.find((message) => message.severity === 1 && ![2110, 2121, 2103, 3002].includes(message.code));
359
+ if (error === undefined)
360
+ return null;
361
+ // An error raised inside an operator of a standard module comes
362
+ // as a message within the message: its marks are no words of TLC's.
363
+ let text = error.text.replace(/@!@!@STARTMSG \d+:\d+ @!@!@\n?|\n?@!@!@ENDMSG \d+ @!@!@/g, "");
364
+ // An error TLC met while evaluating comes wrapped in a notice of
365
+ // the Java exception that carried it. Where Java itself threw, the
366
+ // notice is followed by the exception and its stack: the stack is
367
+ // left to `--keep`.
368
+ const wrapped = /^TLC threw an unexpected exception\.[\s\S]*?\n: /.exec(text);
369
+ const thrown = /^TLC threw an unexpected exception\.[\s\S]*?\nThe exception was a (\S+)(?:\n([^\n]*))?/.exec(text);
370
+ if (wrapped !== null)
371
+ text = text.slice(wrapped[0].length);
372
+ else if (thrown !== null) {
373
+ const said = (thrown[2] ?? "").trim();
374
+ const own = said.startsWith(`${thrown[1]}: `) ? `: ${said.slice(thrown[1].length + 2)}` : "";
375
+ text = thrown[1] === "java.lang.StackOverflowError" ? STACK_OVERFLOW : `TLC threw a ${thrown[1]}${own}`;
376
+ }
377
+ let assume = null;
378
+ const assumption = /^Evaluating assumption line (\d+), col \d+ to line \d+, col \d+ of module \w+ failed\.\n?/.exec(text);
379
+ if (assumption !== null) {
380
+ assume = Number(assumption[1]);
381
+ text = text.slice(assumption[0].length);
382
+ }
383
+ const places = [];
384
+ const nested = run.messages.find((message) => message.code === 2103);
385
+ for (const found of (nested?.text ?? "").matchAll(/^\d+\. Line (\d+), column (\d+) to line \d+, column \d+ in (\w+)$/gm)) {
386
+ places.push({ module: found[3], line: Number(found[1]), col: Number(found[2]) });
387
+ }
388
+ const lines = text.split("\n");
389
+ const innermost = /^line (\d+), col (\d+) to line \d+, col \d+ of module (\w+)$/.exec(lines[lines.length - 1].trim());
390
+ if (innermost !== null) {
391
+ lines.pop();
392
+ const place = { module: innermost[3], line: Number(innermost[1]), col: Number(innermost[2]) };
393
+ const last = places[places.length - 1];
394
+ if (last === undefined || last.module !== place.module || last.line !== place.line || last.col !== place.col) {
395
+ places.push(place);
396
+ }
397
+ }
398
+ return { message: oneLine(lines.join("\n")), assume, places };
399
+ }
400
+ /**
401
+ * The first assumption TLC found false (message 2104), by its module
402
+ * and the line its body starts on, or null. TLC names the place of
403
+ * the body only, never the assumption's name, and stops at the first.
404
+ */
405
+ export function falseAssumption(run) {
406
+ const found = run.messages.find((message) => message.code === 2104);
407
+ const place = /^Assumption line (\d+), col \d+ to line \d+, col \d+ of module (\w+) is false\./.exec(found?.text ?? "");
408
+ return place === null ? null : { module: place[2], line: Number(place[1]) };
409
+ }
410
+ /** The violated invariant's name (message 2110), or null. */
411
+ export function violated(run) {
412
+ const found = run.messages.find((message) => message.code === 2110);
413
+ return found === undefined ? null : (/^Invariant (\S+) is violated\./.exec(found.text)?.[1] ?? null);
414
+ }
415
+ /** The states of the sequence TLC printed (messages 2217), in order,
416
+ * each with its variables. */
417
+ export function traceOf(run) {
418
+ return run.messages
419
+ .filter((message) => message.code === 2217)
420
+ .map((message) => {
421
+ const head = /^\d+: <[^>]*>\n/.exec(message.text);
422
+ return parseState(head === null ? message.text : message.text.slice(head[0].length));
423
+ });
424
+ }
425
+ export function statsOf(run) {
426
+ const counts = run.messages.find((message) => message.code === 2199);
427
+ const found = counts === undefined
428
+ ? null
429
+ : /^\d+ states generated, \d+ distinct states found, (\d+) states left on queue\./.exec(counts.text);
430
+ const done = run.messages.find((message) => message.code === 2193);
431
+ return {
432
+ left: found === null ? null : Number(found[1]),
433
+ complete: done !== undefined,
434
+ collision: /calculated \(optimistic\):\s*val = (\S+)/.exec(done?.text ?? "")?.[1] ?? null,
435
+ };
436
+ }
437
+ /** Whether a run of the model checker ended complete: by its exit
438
+ * status and its messages, with no state left. */
439
+ export function completed(run) {
440
+ const stats = statsOf(run);
441
+ return run.status === 0 && !run.timedOut && stats.complete && stats.left === 0;
442
+ }
443
+ /** What the module printed with PrintT, as values in the order
444
+ * printed. */
445
+ export function printed(run) {
446
+ return parseTlaAll(run.user);
447
+ }
448
+ /** The states of a state dump, in the order TLC found them, each
449
+ * with its variables. */
450
+ export function dumpStates(dump) {
451
+ const states = [];
452
+ const re = /^State \d+:\n([\s\S]*?)(?=^State \d+:\n|(?![\s\S]))/gm;
453
+ for (const found of dump.replace(/\r\n/g, "\n").matchAll(re))
454
+ states.push(parseState(found[1]));
455
+ return states;
456
+ }
457
+ //# sourceMappingURL=tlc.js.map
@@ -0,0 +1,66 @@
1
+ /** A translation as loaded: its text is never evaluated here. */
2
+ export type Translation = {
3
+ /** The file's name without `.tla`, which its `MODULE` line names too. */
4
+ name: string;
5
+ /** Its file, relative to the root, with `/`. */
6
+ file: string;
7
+ text: string;
8
+ };
9
+ /** One error of form; `line` and `col` count from 1 where the
10
+ * error has a place. */
11
+ export type FormFault = {
12
+ line: number | null;
13
+ col: number | null;
14
+ message: string;
15
+ };
16
+ /** What a translation's name is made of. */
17
+ export declare const TRANSLATION_NAME_RE: RegExp;
18
+ /** The TLA+ modules a translation may load: the declaration in TLA+
19
+ * and four standard modules. */
20
+ export declare const MAY_LOAD: readonly string[];
21
+ /** Why `name` cannot name a translation, or null when it can. */
22
+ export declare function translationNameFault(name: string): string | null;
23
+ /**
24
+ * TLA+ text with each comment and each string's content blanked out,
25
+ * every other character at its own place, so a word found is a word
26
+ * of the translation and its line and column are the file's.
27
+ */
28
+ export declare function bare(text: string): string;
29
+ /** The line and column, from 1, of an offset in a text. */
30
+ export declare function placeOf(text: string, offset: number): {
31
+ line: number;
32
+ col: number;
33
+ };
34
+ /** What a file both TLC and the proof system read holds only:
35
+ * TLC's parser counts a column for each character and the proof
36
+ * system's for each byte, so a character of more than one byte moves
37
+ * what follows it on its line for one of them alone, and a list of
38
+ * `/\` or `\/` set under one another is read two ways. */
39
+ export declare const ASCII_ONLY = "only printable ASCII characters and line ends, which TLC and the proof system read alike";
40
+ /** Where a text first holds a character that is no printable ASCII
41
+ * character and no line end, with the character as `U+<hex>`, or null.
42
+ * `text` has its line ends as LF. */
43
+ export declare function otherCharacter(text: string): {
44
+ line: number;
45
+ col: number;
46
+ shown: string;
47
+ } | null;
48
+ /** What a file of one module is refused for where it is not one. */
49
+ export declare function oneModuleRule(name: string): string;
50
+ /**
51
+ * Whether a text is one module of this name and holds no other. The
52
+ * tools find a module by the word, wherever it stands: before a module
53
+ * begins they read no comment, so a commented line can open one, and a
54
+ * module's name may stand on the line after the word. The text is
55
+ * therefore read as it is, comments and strings included: one MODULE
56
+ * leaves no place for a second module, and nothing before its line
57
+ * that could open a comment for Spex alone. `text` has its line ends
58
+ * as LF.
59
+ */
60
+ export declare function oneModule(text: string, name: string): boolean;
61
+ /**
62
+ * The errors of form in a translation's text, in the file's order;
63
+ * none where its form holds. A check of the text only: whether the
64
+ * file parses, and what it loads, TLC says.
65
+ */
66
+ export declare function formFaults(translation: Translation): FormFault[];