@sublang/spex 5.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 (114) hide show
  1. package/README.md +453 -41
  2. package/dist/cli.js +12 -1
  3. package/dist/commands/add.d.ts +1 -1
  4. package/dist/commands/add.js +3 -3
  5. package/dist/commands/auth-target.d.ts +1 -0
  6. package/dist/commands/auth-target.js +4 -2
  7. package/dist/commands/environment.d.ts +15 -21
  8. package/dist/commands/environment.js +43 -57
  9. package/dist/commands/export.js +2 -2
  10. package/dist/commands/home.d.ts +2 -2
  11. package/dist/commands/home.js +3 -3
  12. package/dist/commands/list.js +1 -1
  13. package/dist/commands/login.js +12 -7
  14. package/dist/commands/logout.js +2 -3
  15. package/dist/commands/publish.js +16 -16
  16. package/dist/commands/remove.js +1 -1
  17. package/dist/commands/run.d.ts +1 -1
  18. package/dist/commands/run.js +22 -3
  19. package/dist/commands/search.js +1 -1
  20. package/dist/commands/settle.d.ts +1 -1
  21. package/dist/commands/settle.js +3 -3
  22. package/dist/commands/whoami.js +2 -6
  23. package/dist/guards/approval.d.ts +56 -0
  24. package/dist/guards/approval.js +158 -0
  25. package/dist/guards/checks.d.ts +207 -0
  26. package/dist/guards/checks.js +681 -0
  27. package/dist/guards/commands.d.ts +15 -0
  28. package/dist/guards/commands.js +313 -0
  29. package/dist/guards/copy.d.ts +67 -0
  30. package/dist/guards/copy.js +306 -0
  31. package/dist/guards/declaration.d.ts +45 -0
  32. package/dist/guards/declaration.js +224 -0
  33. package/dist/guards/files.d.ts +137 -0
  34. package/dist/guards/files.js +544 -0
  35. package/dist/guards/harness.d.ts +58 -0
  36. package/dist/guards/harness.js +420 -0
  37. package/dist/guards/items.d.ts +61 -0
  38. package/dist/guards/items.js +161 -0
  39. package/dist/guards/patch.d.ts +55 -0
  40. package/dist/guards/patch.js +258 -0
  41. package/dist/guards/processes.d.ts +49 -0
  42. package/dist/guards/processes.js +233 -0
  43. package/dist/guards/proofs.d.ts +88 -0
  44. package/dist/guards/proofs.js +503 -0
  45. package/dist/guards/records.d.ts +176 -0
  46. package/dist/guards/records.js +513 -0
  47. package/dist/guards/report.d.ts +26 -0
  48. package/dist/guards/report.js +492 -0
  49. package/dist/guards/runner.d.ts +42 -0
  50. package/dist/guards/runner.js +167 -0
  51. package/dist/guards/tla.d.ts +51 -0
  52. package/dist/guards/tla.js +352 -0
  53. package/dist/guards/tlapm.d.ts +81 -0
  54. package/dist/guards/tlapm.js +172 -0
  55. package/dist/guards/tlc.d.ts +191 -0
  56. package/dist/guards/tlc.js +457 -0
  57. package/dist/guards/translation.d.ts +66 -0
  58. package/dist/guards/translation.js +202 -0
  59. package/dist/guards/types.d.ts +185 -0
  60. package/dist/guards/types.js +437 -0
  61. package/dist/guards/verify.d.ts +290 -0
  62. package/dist/guards/verify.js +1191 -0
  63. package/dist/guards/xml.d.ts +18 -0
  64. package/dist/guards/xml.js +105 -0
  65. package/dist/lib/environment/archive.d.ts +16 -3
  66. package/dist/lib/environment/archive.js +39 -8
  67. package/dist/lib/environment/builtins.d.ts +10 -12
  68. package/dist/lib/environment/builtins.js +18 -20
  69. package/dist/lib/environment/exports.d.ts +14 -13
  70. package/dist/lib/environment/exports.js +31 -16
  71. package/dist/lib/environment/format.d.ts +2 -2
  72. package/dist/lib/environment/format.js +3 -3
  73. package/dist/lib/environment/git-source.js +6 -3
  74. package/dist/lib/environment/install.d.ts +14 -16
  75. package/dist/lib/environment/install.js +66 -61
  76. package/dist/lib/environment/lock.d.ts +4 -3
  77. package/dist/lib/environment/lock.js +6 -5
  78. package/dist/lib/environment/marker.js +1 -2
  79. package/dist/lib/environment/own-paths.d.ts +7 -10
  80. package/dist/lib/environment/own-paths.js +10 -13
  81. package/dist/lib/environment/placed-record.d.ts +3 -2
  82. package/dist/lib/environment/placed-record.js +5 -4
  83. package/dist/lib/environment/registries.d.ts +7 -9
  84. package/dist/lib/environment/registries.js +9 -36
  85. package/dist/lib/environment/registry.d.ts +6 -7
  86. package/dist/lib/environment/registry.js +12 -12
  87. package/dist/lib/environment/requests.d.ts +6 -5
  88. package/dist/lib/environment/requests.js +6 -8
  89. package/dist/lib/environment/resolve.d.ts +4 -4
  90. package/dist/lib/environment/resolve.js +3 -4
  91. package/dist/lib/environment/store.d.ts +34 -8
  92. package/dist/lib/environment/store.js +138 -43
  93. package/dist/lib/files.d.ts +72 -12
  94. package/dist/lib/files.js +200 -65
  95. package/dist/lib/git-host.d.ts +52 -258
  96. package/dist/lib/git-host.js +52 -265
  97. package/dist/lib/home-file.d.ts +13 -10
  98. package/dist/lib/home-file.js +28 -18
  99. package/dist/lib/instance.d.ts +1 -1
  100. package/dist/lib/instance.js +1 -1
  101. package/dist/lint.d.ts +22 -0
  102. package/dist/lint.js +36 -0
  103. package/dist/testing/standin-registry.js +1 -1
  104. package/package.json +7 -3
  105. package/scaffold/.file-history.json +14 -7
  106. package/scaffold/i18n/zh/source-pins.json +41 -0
  107. package/scaffold/i18n/zh/specs/decisions/000-spec-structure-format.md +0 -1
  108. package/scaffold/i18n/zh/specs/intents/000-spdx-headers.md +0 -1
  109. package/scaffold/i18n/zh/specs/map.md +0 -1
  110. package/scaffold/i18n/zh/specs/meta.md +18 -35
  111. package/scaffold/i18n/zh/specs/packages/git.md +0 -1
  112. package/scaffold/i18n/zh/specs/packages/licensing.md +0 -1
  113. package/scaffold/specs/meta.md +18 -3
  114. package/scripts/test-exit-guard.mjs +28 -0
@@ -0,0 +1,681 @@
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: the runs of TLC for one guard
5
+ * (guards-40) and what `--keep` leaves of them (guards-41). Each
6
+ * check writes one of Spex's own TLA+ files beside the declaration in
7
+ * TLA+ and the translations, runs TLC once on it and reads what TLC
8
+ * printed: a translation alone (guards-42), the cases under each
9
+ * translation (guards-20), the translations against each other
10
+ * (guards-39), the model against the rule (guards-38), and the
11
+ * records of the code, the module's and the tests' (guards-22,
12
+ * guards-54, guards-55). Spex evaluates no TLA+ here and
13
+ * answers none of the four questions: it compares printed values for
14
+ * equality and puts TLC's answers into words.
15
+ */
16
+ import { cpSync, lstatSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
17
+ import { join } from "node:path";
18
+ import { assumptionAt, declarationModule } from "./declaration.js";
19
+ import { CASES_MODULE, COMPARE_MODULE, FORM_MODULE, MODEL_MODULE, casesModule, compareCfg, compareModule, evaluateCfg, formModule, modelCfg, modelModule, RECORDS_MODULE, recordsCfg, recordsModule, } from "./harness.js";
20
+ import { MOST_DIFFERENT, MOST_RECORDS, copyValues, runsOf } from "./records.js";
21
+ import { callFromTla, canon, fieldsFromTla, key, showTla, } from "./tla.js";
22
+ import { completed, dumpStates, evalFault, falseAssumption, javaWords, loadedModules, parseFaults, pastStart, printed, runTlc, statsOf, TLC_PIN, traceOf, versionOf, violated, } from "./tlc.js";
23
+ import { MAY_LOAD, formFaults } from "./translation.js";
24
+ import { GuardError, compareFields, showFields, } from "./types.js";
25
+ /** `1 second`, `300 seconds`. */
26
+ export function seconds(count) {
27
+ return `${count} ${count === 1 ? "second" : "seconds"}`;
28
+ }
29
+ /** The first line of the file that marks a folder `--keep` wrote. */
30
+ export const KEPT_MARK = "Kept by spex verify.";
31
+ /** The name of that file in `<folder>/<guard>`. */
32
+ export const KEPT_FILE = "spex-verify.txt";
33
+ /**
34
+ * Whether `dir` is a folder `spex verify --keep` wrote for a guard, so
35
+ * that a later run may replace it: a folder, no link to one, holding
36
+ * the file that marks one, a file and no link, whose first line is
37
+ * the mark and nothing more. The mark decides this alone: no copy and
38
+ * no list of a guard's files looks for it (guards-41).
39
+ */
40
+ export function keptBySpex(dir) {
41
+ try {
42
+ if (!lstatSync(dir).isDirectory() || !lstatSync(join(dir, KEPT_FILE)).isFile())
43
+ return false;
44
+ return readFileSync(join(dir, KEPT_FILE), "utf8").split(/\r?\n/, 1)[0] === KEPT_MARK;
45
+ }
46
+ catch {
47
+ return false;
48
+ }
49
+ }
50
+ /** A word of a command line as a POSIX shell takes it. */
51
+ export function quoted(word) {
52
+ return /^[A-Za-z0-9_@%+=:,./-]+$/.test(word) ? word : `'${word.replace(/'/g, "'\\''")}'`;
53
+ }
54
+ /**
55
+ * Run TLC once for `shop.guard`: a fresh folder named `name` holding
56
+ * the declaration in TLA+, the given translations and `files`, TLC
57
+ * run on `module` there, and the folder removed. With `--keep` the
58
+ * folder's files are left under that name, with the command line.
59
+ */
60
+ async function tlc(shop, name, module, translations, files, dump = false) {
61
+ const { guard } = shop;
62
+ const folder = join(shop.home, name);
63
+ mkdirSync(folder);
64
+ try {
65
+ const declaration = declarationModule(guard.binding, guard.binding.name);
66
+ const all = { "Declaration.tla": declaration, ...files };
67
+ for (const translation of translations)
68
+ all[`${translation.name}.tla`] = translation.text;
69
+ for (const [file, text] of Object.entries(all))
70
+ writeFileSync(join(folder, file), text);
71
+ const run = await runTlc(shop.tools, folder, module, { dump, seconds: guard.limits.seconds });
72
+ shop.version.tlc ??= versionOf(run);
73
+ if (shop.keep !== null) {
74
+ const kept = join(shop.keep, name);
75
+ rmSync(join(folder, "java-tmp"), { recursive: true, force: true });
76
+ rmSync(join(folder, "states"), { recursive: true, force: true });
77
+ mkdirSync(join(folder, "java-tmp"));
78
+ writeFileSync(join(folder, "command.txt"), [
79
+ "# Run in this folder, with java-tmp empty and no states folder,",
80
+ "# and without JAVA_TOOL_OPTIONS, _JAVA_OPTIONS and JDK_JAVA_OPTIONS.",
81
+ run.command.map(quoted).join(" "),
82
+ "",
83
+ ].join("\n"));
84
+ cpSync(folder, kept, { recursive: true });
85
+ }
86
+ if (run.failed !== null)
87
+ throw new GuardError(`TLC could not start: ${run.failed}`);
88
+ // TLC's first message is its version: without it Java never ran
89
+ // TLC, and no translation is at fault.
90
+ if (!run.timedOut && versionOf(run) === null)
91
+ throw new GuardError(javaFault(shop.tools, run));
92
+ // TLC checks the declaration's assumptions at the declared values
93
+ // before anything else, and stops at the first that is false. No
94
+ // translation is at fault then, and nothing can be checked.
95
+ const assumption = run.timedOut ? null : falseAssumption(run);
96
+ if (assumption !== null && assumption.module === "Declaration") {
97
+ const named = assumptionAt(declaration, assumption.line);
98
+ throw new GuardError(`${guard.binding.folder}/binding.yaml: TLC found ${named === null ? `the assumption at line ${assumption.line}` : `the assumption ${named}`} of the declaration in TLA+ false at the declared values`);
99
+ }
100
+ return run;
101
+ }
102
+ finally {
103
+ rmSync(folder, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
104
+ }
105
+ }
106
+ /** That Java ended without running TLC: its status, its own words,
107
+ * and what to set where the jar is not the pinned one. */
108
+ function javaFault(tools, run) {
109
+ const ended = run.status === null ? "was ended" : `ended with status ${run.status}`;
110
+ const said = javaWords(run.errors);
111
+ const jar = tools.pinned
112
+ ? ""
113
+ : ` \u2014 SPEX_TLC_JAR names ${tools.jar}, which is not the pinned tla2tools.jar: set it to a tla2tools.jar, or unset it for Spex to download TLC ${TLC_PIN.version}`;
114
+ return `Java ${ended} before TLC started${said === "" ? "" : `: ${said}`}${jar}`;
115
+ }
116
+ /** Prepare `<folder>/<guard>` of `--keep`: an empty folder with its
117
+ * mark. One that stands without the mark is not Spex's to replace. */
118
+ export function prepareKeep(keep, guard) {
119
+ const folder = join(keep, guard);
120
+ // Whatever stands there, a link that leads nowhere too.
121
+ if (lstatSync(folder, { throwIfNoEntry: false }) !== undefined) {
122
+ if (!keptBySpex(folder)) {
123
+ throw new GuardError(`--keep: ${folder} was not kept by spex verify — remove it, or name another folder`);
124
+ }
125
+ rmSync(folder, { recursive: true, force: true });
126
+ }
127
+ mkdirSync(folder, { recursive: true });
128
+ writeFileSync(join(folder, KEPT_FILE), [
129
+ KEPT_MARK,
130
+ `The files spex verify generated for the guard ${guard}, one folder for each run of TLC,`,
131
+ "and for each translation's proofs one folder for TLC's parser and one for the proof system.",
132
+ "lines/ holds the files of records the tests wrote, as they wrote them, and sequences.txt",
133
+ "names each sequence with its run; lines-<fault>/ and sequences-<fault>.txt are a kept fault's.",
134
+ "Each folder's command.txt holds the command lines its tools were run with there.",
135
+ "",
136
+ ].join("\n"));
137
+ return folder;
138
+ }
139
+ /** An effect in words: its fields where it is a declared effect of
140
+ * the event, else the value as TLC gave it. */
141
+ function effectWords(declaration, event, effect) {
142
+ const fields = fieldsFromTla(declaration.events[event].effect, effect, declaration);
143
+ // TLC prints a set's members in an order of its own, not one the
144
+ // declaration gives; in a fixed form the same effect reads the same.
145
+ return fields === null ? showTla(canon(effect)) : showFields(fields);
146
+ }
147
+ /** An event TLC printed, which is always a declared one. */
148
+ function callOf(declaration, event) {
149
+ const call = callFromTla(event, declaration);
150
+ if (call === null)
151
+ throw new GuardError(`TLC printed an event the declaration does not hold: ${showTla(event)}`);
152
+ return call;
153
+ }
154
+ function fieldOf(value, name) {
155
+ return typeof value === "object" && "r" in value ? value.r[name] : undefined;
156
+ }
157
+ /** A printed step `[event |-> …, effect |-> …]` as shown. */
158
+ function shownStep(declaration, step) {
159
+ const call = callOf(declaration, fieldOf(step, "event") ?? "");
160
+ const effect = fieldOf(step, "effect");
161
+ return { call, effect: effect === undefined ? null : effectWords(declaration, call.event, effect) };
162
+ }
163
+ /** A translation's file with the place TLC names in it, where it
164
+ * names one: `<file>:<line>:<col>`. */
165
+ function placed(translation, fault) {
166
+ for (let at = fault.places.length - 1; at >= 0; at -= 1) {
167
+ const place = fault.places[at];
168
+ if (place.module === translation.name)
169
+ return `${translation.file}:${place.line}:${place.col}`;
170
+ }
171
+ return translation.file;
172
+ }
173
+ /** The translation TLC was in when it could not go on: the one its
174
+ * innermost place names, else `fallback`. */
175
+ function blamed(translations, fault, fallback) {
176
+ for (let at = fault.places.length - 1; at >= 0; at -= 1) {
177
+ const found = translations.find((translation) => translation.name === fault.places[at].module);
178
+ if (found !== undefined)
179
+ return found;
180
+ }
181
+ return fallback;
182
+ }
183
+ /** How a run ended that neither finished nor was stopped at the time
184
+ * limit: TLC's own words where it gave some, else Java's. */
185
+ function unexpected(run, doing) {
186
+ const said = evalFault(run)?.message ?? parseFaults(run)[0]?.message ?? javaWords(run.errors);
187
+ const status = run.status === null ? "was ended" : `ended with status ${run.status}`;
188
+ return new GuardError(`TLC ${status} ${doing}${said === "" ? "" : `: ${said}`}`);
189
+ }
190
+ /** How many values a run printed before it ended, or -1 where what
191
+ * it printed cannot be read. */
192
+ function printedSoFar(run) {
193
+ try {
194
+ return printed(run).length;
195
+ }
196
+ catch (error) {
197
+ if (error instanceof GuardError)
198
+ return -1;
199
+ throw error;
200
+ }
201
+ }
202
+ /** That TLC was stopped at the time limit. */
203
+ function stopped(shop) {
204
+ return `TLC was stopped after ${seconds(shop.guard.limits.seconds)}`;
205
+ }
206
+ // ---------------------------------------------------------------
207
+ // 0. Form (guards-42)
208
+ // ---------------------------------------------------------------
209
+ /**
210
+ * Check one translation alone: its form by its text, then TLC parses
211
+ * it and reports what it loads. Returns each fault as
212
+ * `<file>[:<line>:<col>]: <what>`; none where its form holds.
213
+ */
214
+ export async function checkForm(shop, translation) {
215
+ const { file, name } = translation;
216
+ const at = (line, col) => line === null ? file : `${file}:${line}:${col ?? 1}`;
217
+ const faults = formFaults(translation);
218
+ if (faults.length > 0)
219
+ return faults.map((fault) => `${at(fault.line, fault.col)}: ${fault.message}`);
220
+ const run = await tlc(shop, `form-${name}`, FORM_MODULE, [translation], {
221
+ [`${FORM_MODULE}.tla`]: formModule(name, shop.guard.binding.vocabulary),
222
+ [`${FORM_MODULE}.cfg`]: evaluateCfg(shop.guard.binding.vocabulary),
223
+ });
224
+ if (run.timedOut)
225
+ return [`${file}: ${stopped(shop)} while it read the file`];
226
+ if (run.status === 150) {
227
+ const said = parseFaults(run);
228
+ if (said.length === 0)
229
+ throw unexpected(run, `reading ${file}`);
230
+ return said.map((fault) => {
231
+ if (fault.module === name)
232
+ return `${at(fault.line, fault.col)}: ${fault.message}`;
233
+ if (fault.module === "Declaration") {
234
+ return `${shop.guard.binding.folder}/binding.yaml: the declaration in TLA+ does not parse: ${fault.message}`;
235
+ }
236
+ return `${file}: ${fault.message}`;
237
+ });
238
+ }
239
+ if (!completed(run))
240
+ throw unexpected(run, `reading ${file}`);
241
+ const allowed = new Set([FORM_MODULE, name, ...MAY_LOAD]);
242
+ const stray = loadedModules(run).filter((module) => !allowed.has(module));
243
+ return stray.map((module) => `${file}: it loads the module ${module}; a translation loads only ${MAY_LOAD.join(", ")}`);
244
+ }
245
+ /** A case's steps as shown: each with the effect fields it states. */
246
+ function caseSteps(entry, upTo = entry.steps.length) {
247
+ return entry.steps.slice(0, upTo).map((step) => ({
248
+ call: { event: step.event, params: step.params },
249
+ effect: Object.keys(step.effect).length === 0 ? null : showFields(step.effect),
250
+ }));
251
+ }
252
+ function inCase(entry) {
253
+ return `TLC met it in the ${entry.kind} case "${entry.label}"`;
254
+ }
255
+ /**
256
+ * Evaluate each case under each translation in one run of TLC. A
257
+ * translation allows a permitted case where every step is legal, its
258
+ * model gives each effect field the step states and no step is
259
+ * forbidden. It forbids a forbidden case where the steps before the
260
+ * last go so and, at the last, the rule applies and forbids every
261
+ * declared effect that is as the step states.
262
+ */
263
+ export async function checkCases(shop) {
264
+ const { guard } = shop;
265
+ const { translations, cases, binding } = guard;
266
+ const names = translations.map((translation) => translation.name);
267
+ const built = casesModule(names, cases, binding.vocabulary);
268
+ const run = await tlc(shop, "cases", CASES_MODULE, translations, {
269
+ [`${CASES_MODULE}.tla`]: built.text,
270
+ [`${CASES_MODULE}.cfg`]: evaluateCfg(binding.vocabulary),
271
+ });
272
+ if (run.timedOut)
273
+ return { kind: "stopped", cause: `${stopped(shop)} while it evaluated the cases` };
274
+ const fault = run.status === 0 ? null : evalFault(run);
275
+ if (fault !== null) {
276
+ // The line TLC could not evaluate is the one it names, else the
277
+ // one after the last whose value it printed.
278
+ const assumed = fault.assume === null ? [...built.assumes.values()][printedSoFar(run)] : built.assumes.get(fault.assume);
279
+ if (assumed === undefined)
280
+ throw unexpected(run, "evaluating the cases");
281
+ const translation = translations.find((one) => one.name === assumed.translation);
282
+ const entry = assumed.case === null ? null : cases[assumed.case - 1];
283
+ return {
284
+ kind: "cannot",
285
+ cannot: [
286
+ {
287
+ cause: `${placed(translation, fault)}: ${fault.message}`,
288
+ note: entry === null ? "TLC met it in the cases" : inCase(entry),
289
+ steps: entry === null ? [] : caseSteps(entry),
290
+ },
291
+ ],
292
+ };
293
+ }
294
+ if (run.status !== 0)
295
+ throw unexpected(run, "evaluating the cases");
296
+ const failures = [];
297
+ const cannot = [];
298
+ const answers = printed(run);
299
+ if (answers.length !== names.length * (cases.length + 1))
300
+ throw unexpected(run, "evaluating the cases");
301
+ for (const answer of answers) {
302
+ const [what, name, third, fourth] = typeof answer === "object" && "t" in answer ? answer.t : [];
303
+ const translation = translations.find((one) => one.name === name);
304
+ if (translation === undefined)
305
+ throw unexpected(run, "evaluating the cases");
306
+ if (what === "applied") {
307
+ if (third !== true) {
308
+ failures.push({
309
+ case: null,
310
+ kind: null,
311
+ translation: translation.name,
312
+ found: `translation ${translation.name}: the rule applies at no step of a permitted case`,
313
+ });
314
+ }
315
+ continue;
316
+ }
317
+ const entry = cases[third - 1];
318
+ if (what !== "case" || entry === undefined)
319
+ throw unexpected(run, "evaluating the cases");
320
+ if (fieldOf(fourth, "pass") === true)
321
+ continue;
322
+ const step = fieldOf(fourth, "step");
323
+ const why = fieldOf(fourth, "why");
324
+ const event = entry.steps[step - 1].event;
325
+ const effect = fieldOf(fourth, "effect");
326
+ const gives = effect === undefined ? "" : effectWords(binding, event, effect);
327
+ const fail = (found) => {
328
+ failures.push({ case: entry.label, kind: entry.kind, translation: translation.name, found });
329
+ };
330
+ switch (why) {
331
+ case "effect not declared":
332
+ cannot.push({
333
+ cause: `${translation.file}: the model gives ${event} an effect the declaration does not hold: ${gives}`,
334
+ note: `${inCase(entry)}, at step ${step}`,
335
+ steps: caseSteps(entry, step),
336
+ });
337
+ break;
338
+ case "not legal":
339
+ fail(`step ${step} is not legal`);
340
+ break;
341
+ case "rule does not apply":
342
+ fail(`the rule does not apply at step ${step}`);
343
+ break;
344
+ case "effect differs":
345
+ fail(`at step ${step} the model gives ${gives}`);
346
+ break;
347
+ case "forbidden":
348
+ fail(`step ${step} is forbidden: the model gives ${gives}`);
349
+ break;
350
+ case "not forbidden": {
351
+ const open = fieldOf(fourth, "allowed");
352
+ const allowed = (typeof open === "object" && "s" in open ? open.s : [])
353
+ .map((one) => fieldsFromTla(binding.events[event].effect, one, binding))
354
+ .filter((one) => one !== null)
355
+ .sort((a, b) => compareFields(binding.events[event].effect, a, b, binding.vocabulary));
356
+ const more = allowed.length > 1 ? ` and ${allowed.length - 1} more` : "";
357
+ fail(`step ${step} is not forbidden: the rule allows ${allowed.length === 0 ? "it" : showFields(allowed[0])}${more}`);
358
+ break;
359
+ }
360
+ default:
361
+ fail(`step ${step}: ${typeof why === "string" ? why : "not as marked"}`);
362
+ }
363
+ }
364
+ return cannot.length > 0 ? { kind: "cannot", cannot } : { kind: "done", failures };
365
+ }
366
+ /** The steps of a printed sequence: every state whose `step` holds
367
+ * one, in order. */
368
+ function traceSteps(declaration, run) {
369
+ return traceOf(run)
370
+ .map((state) => state.step)
371
+ .filter((step) => typeof step === "object" && "r" in step)
372
+ .map((step) => shownStep(declaration, step));
373
+ }
374
+ /** TLC could not evaluate a translation while it checked a model. */
375
+ function cannotEvaluate(shop, run, translations, fallback, where, doing) {
376
+ const fault = evalFault(run);
377
+ if (fault === null)
378
+ throw unexpected(run, doing);
379
+ const translation = blamed(translations, fault, fallback);
380
+ const steps = traceSteps(shop.guard.binding, run);
381
+ // TLC prints no sequence for some faults: it met such a one at the
382
+ // start only where it had not yet computed the model's start.
383
+ const at = steps.length > 0 ? ", after this sequence" : traceOf(run).length > 0 || !pastStart(run) ? ", at the start" : "";
384
+ return {
385
+ cause: `${translation === null ? "a translation" : placed(translation, fault)}: ${fault.message}`,
386
+ note: `TLC met it ${where}${at}`,
387
+ steps,
388
+ };
389
+ }
390
+ /**
391
+ * Model-check the translations side by side in one run of TLC: at
392
+ * every step any of them reaches they give the same answers to the
393
+ * four questions.
394
+ * TLC's shortest sequence to a difference is the distinguishing
395
+ * sequence.
396
+ */
397
+ export async function compareTranslations(shop) {
398
+ const { guard } = shop;
399
+ const { translations, binding } = guard;
400
+ const names = translations.map((translation) => translation.name);
401
+ const run = await tlc(shop, "compare", COMPARE_MODULE, translations, {
402
+ [`${COMPARE_MODULE}.tla`]: compareModule(names, binding.vocabulary),
403
+ [`${COMPARE_MODULE}.cfg`]: compareCfg(binding.vocabulary),
404
+ });
405
+ if (run.timedOut)
406
+ return { kind: "not compared", cause: stopped(shop) };
407
+ if (completed(run))
408
+ return { kind: "agreement" };
409
+ if (run.status === 12 && violated(run) === "Agree") {
410
+ const trace = traceOf(run);
411
+ const diff = trace[trace.length - 1]?.diff;
412
+ const about = fieldOf(diff, "on");
413
+ const answers = fieldOf(diff, "answers");
414
+ const last = callOf(binding, fieldOf(diff, "event") ?? "");
415
+ const steps = traceSteps(binding, run);
416
+ const yesNo = (value) => (value === true ? "yes" : "no");
417
+ const byName = (record, words) => names.map((name) => ({ translation: name, answer: words(fieldOf(record, name)) }));
418
+ const words = (value) => (value === undefined ? "" : effectWords(binding, last.event, value));
419
+ if (about === "undeclared") {
420
+ // TLC says which translations' effects the declaration does not hold.
421
+ const declared = fieldOf(diff, "declared");
422
+ const cannot = translations
423
+ .filter((translation) => fieldOf(declared, translation.name) === false)
424
+ .map((translation) => ({
425
+ cause: `${translation.file}: the model gives ${last.event} an effect the declaration does not hold: ${words(fieldOf(answers, translation.name))}`,
426
+ note: `TLC met it comparing the translations, at step ${steps.length + 1} of this sequence`,
427
+ steps: [...steps, { call: last, effect: null }],
428
+ }));
429
+ if (cannot.length === 0)
430
+ throw unexpected(run, "comparing the translations");
431
+ return { kind: "cannot", cannot };
432
+ }
433
+ if (about === "legal" || about === "applies") {
434
+ return { kind: "differ", about, steps, last, effect: null, model: null, answers: byName(answers, yesNo) };
435
+ }
436
+ if (about === "effect") {
437
+ return { kind: "differ", about, steps, last, effect: null, model: null, answers: byName(answers, words) };
438
+ }
439
+ if (about === "forbidden" && typeof answers === "object" && "f" in answers) {
440
+ // The question is about the model's effect where the translations
441
+ // differ on it, else about the first such effect in declared order.
442
+ const declared = binding.events[last.event].effect;
443
+ const model = key(fieldOf(diff, "model") ?? "");
444
+ const split = answers.f
445
+ .map(([effect, said]) => ({ effect, said, fields: fieldsFromTla(declared, effect, binding) }))
446
+ .sort((a, b) => a.fields === null || b.fields === null ? 0 : compareFields(declared, a.fields, b.fields, binding.vocabulary));
447
+ const asked = split.find((one) => key(one.effect) === model) ?? split[0];
448
+ return {
449
+ kind: "differ",
450
+ about,
451
+ steps,
452
+ last,
453
+ effect: effectWords(binding, last.event, asked.effect),
454
+ model: words(fieldOf(diff, "model")),
455
+ answers: byName(asked.said, yesNo),
456
+ };
457
+ }
458
+ throw unexpected(run, "comparing the translations");
459
+ }
460
+ if (run.status !== 0 && evalFault(run) !== null) {
461
+ return {
462
+ kind: "cannot",
463
+ cannot: [cannotEvaluate(shop, run, translations, null, "comparing the translations", "comparing the translations")],
464
+ };
465
+ }
466
+ throw unexpected(run, "comparing the translations");
467
+ }
468
+ /**
469
+ * TLC's table from its state dump: every dumped state whose `step`
470
+ * holds a step of the model is one row. The paths are found by
471
+ * walking the table breadth first from the start, ties in TLC's
472
+ * order.
473
+ */
474
+ export function tableOf(declaration, states) {
475
+ if (states.length === 0)
476
+ throw new GuardError("TLC wrote no state of the model");
477
+ const start = key(states[0].state);
478
+ const rows = [];
479
+ for (const state of states) {
480
+ const step = state.step;
481
+ if (typeof step !== "object" || !("r" in step))
482
+ continue;
483
+ const call = callOf(declaration, step.r.event);
484
+ const effect = fieldsFromTla(declaration.events[call.event].effect, step.r.effect, declaration);
485
+ if (effect === null || typeof step.r.applies !== "boolean") {
486
+ throw new GuardError("TLC wrote a step of the model that cannot be read");
487
+ }
488
+ rows.push({ from: key(step.r.from), call, effect, next: key(step.r.next), applies: step.r.applies });
489
+ }
490
+ const from = new Map();
491
+ for (const row of rows) {
492
+ const list = from.get(row.from);
493
+ if (list === undefined)
494
+ from.set(row.from, [row]);
495
+ else
496
+ list.push(row);
497
+ }
498
+ const paths = new Map([[start, []]]);
499
+ let frontier = [start];
500
+ while (frontier.length > 0) {
501
+ const next = [];
502
+ for (const state of frontier) {
503
+ for (const row of from.get(state) ?? []) {
504
+ if (paths.has(row.next))
505
+ continue;
506
+ paths.set(row.next, [...paths.get(state), row]);
507
+ next.push(row.next);
508
+ }
509
+ }
510
+ frontier = next;
511
+ }
512
+ for (const row of rows) {
513
+ if (!paths.has(row.from))
514
+ throw new GuardError("TLC wrote a step of the model from a state no step reaches");
515
+ }
516
+ return { start, rows, paths };
517
+ }
518
+ /**
519
+ * Model-check the judging translation in one run of TLC: in every
520
+ * state the model reaches, for every legal event, the model's effect
521
+ * is a declared effect and the rule does not forbid it. The same run
522
+ * writes TLC's table of the model's steps.
523
+ */
524
+ export async function checkModel(shop, translation) {
525
+ const { binding } = shop.guard;
526
+ const doing = "checking the model";
527
+ const run = await tlc(shop, "model", MODEL_MODULE, [translation], {
528
+ [`${MODEL_MODULE}.tla`]: modelModule(translation.name, binding.vocabulary),
529
+ [`${MODEL_MODULE}.cfg`]: modelCfg(binding.vocabulary),
530
+ }, true);
531
+ if (run.timedOut)
532
+ return { kind: "not checked", cause: stopped(shop) };
533
+ if (completed(run)) {
534
+ if (run.unread !== null)
535
+ throw new GuardError(`TLC's table of the model's steps cannot be read: ${run.unread}`);
536
+ if (run.dump === null)
537
+ throw unexpected(run, doing);
538
+ const table = tableOf(binding, dumpStates(run.dump));
539
+ return {
540
+ kind: "checked",
541
+ table,
542
+ applied: table.rows.filter((row) => row.applies).length,
543
+ collision: statsOf(run).collision,
544
+ };
545
+ }
546
+ const invariant = run.status === 12 ? violated(run) : null;
547
+ if (invariant === "Kept" || invariant === "Declared") {
548
+ const steps = traceOf(run)
549
+ .map((state) => state.step)
550
+ .filter((step) => typeof step === "object" && "r" in step);
551
+ const last = steps[steps.length - 1];
552
+ const shown = steps.slice(0, -1).map((step) => shownStep(binding, step));
553
+ const call = callOf(binding, fieldOf(last, "event") ?? "");
554
+ const effect = effectWords(binding, call.event, fieldOf(last, "effect") ?? "");
555
+ if (invariant === "Kept")
556
+ return { kind: "conflict", steps: shown, last: call, effect };
557
+ return {
558
+ kind: "cannot",
559
+ cannot: [
560
+ {
561
+ cause: `${translation.file}: the model gives ${call.event} an effect the declaration does not hold: ${effect}`,
562
+ note: `TLC met it on the model, at step ${steps.length} of this sequence`,
563
+ steps: [...shown, { call, effect: null }],
564
+ },
565
+ ],
566
+ };
567
+ }
568
+ if (run.status !== 0 && evalFault(run) !== null) {
569
+ return { kind: "cannot", cannot: [cannotEvaluate(shop, run, [translation], translation, "on the model", doing)] };
570
+ }
571
+ throw unexpected(run, doing);
572
+ }
573
+ /** The folder of the `k`-th run of `name`, from 1: `name`, then
574
+ * `name~2`, `name~3`. */
575
+ export function runFolder(name, k) {
576
+ return k === 1 ? name : `${name}~${k}`;
577
+ }
578
+ /** Whether TLC ran out of memory: Java's `OutOfMemoryError` in one of
579
+ * its messages or on standard error, or its message 1001. */
580
+ function outOfMemory(run) {
581
+ return (run.messages.some((message) => message.code === 1001 || message.text.includes("java.lang.OutOfMemoryError")) ||
582
+ run.errors.includes("java.lang.OutOfMemoryError"));
583
+ }
584
+ /** A sequence's handed records as shown, each with the effect the code
585
+ * gave. */
586
+ function sequenceSteps(sequence, book) {
587
+ return sequence.handed.map((record) => {
588
+ const { call, effect } = book.records[record];
589
+ return { call, effect: Object.keys(effect).length === 0 ? null : showFields(effect) };
590
+ });
591
+ }
592
+ /**
593
+ * Have TLC judge every sequence of one copy, the module's and the
594
+ * tests', one run after another in the folders `name`, `name~2`, …,
595
+ * each from its own `SpexRecords.tla` with the copy's values. TLC
596
+ * walks each sequence through `translation`'s model no further than
597
+ * its first record that is not matched, and prints what it found.
598
+ */
599
+ export async function judgeRecords(shop, name, translation, sequences, book, most = { records: MOST_RECORDS, different: MOST_DIFFERENT }) {
600
+ const { vocabulary } = shop.guard.binding;
601
+ const doing = "judging the records";
602
+ const values = copyValues(book);
603
+ const runs = runsOf(sequences, most.records, most.different);
604
+ const judged = sequences.map(() => null);
605
+ for (const [at, part] of runs.entries()) {
606
+ const run = await tlc(shop, runFolder(name, at + 1), RECORDS_MODULE, [translation], {
607
+ [`${RECORDS_MODULE}.tla`]: recordsModule(translation.name, vocabulary, sequences, part, values, runs.length, book),
608
+ [`${RECORDS_MODULE}.cfg`]: recordsCfg(),
609
+ });
610
+ if (run.timedOut) {
611
+ return { kind: "judged", judged, halted: { kind: "timeout", cause: `${stopped(shop)} while it judged the records` }, runs: at + 1 };
612
+ }
613
+ if (outOfMemory(run)) {
614
+ return { kind: "judged", judged, halted: { kind: "memory", cause: "TLC ran out of memory while it judged the records" }, runs: at + 1 };
615
+ }
616
+ if (run.status !== 0 && run.messages.some((message) => message.code === 2105)) {
617
+ // The sequence TLC could not walk is the one after the last it printed.
618
+ const fault = evalFault(run);
619
+ const so = printedSoFar(run);
620
+ const k = part.from + Math.max(so, 0);
621
+ if (so < 0 || k >= part.to)
622
+ throw unexpected(run, doing);
623
+ return {
624
+ kind: "cannot",
625
+ cannot: [
626
+ {
627
+ cause: `${placed(translation, fault)}: ${fault.message}`,
628
+ note: "TLC met it judging the records of this sequence",
629
+ steps: sequenceSteps(sequences[k], book),
630
+ },
631
+ ],
632
+ sequence: k,
633
+ };
634
+ }
635
+ if (run.status !== 0 || !statsOf(run).complete)
636
+ throw unexpected(run, doing);
637
+ const answers = printed(run);
638
+ if (answers.length !== part.to - part.from)
639
+ throw unexpected(run, doing);
640
+ for (const [k, answer] of answers.entries()) {
641
+ const [what, number, tuple] = typeof answer === "object" && "t" in answer ? answer.t : [];
642
+ const [matched, applied, said, model] = typeof tuple === "object" && "t" in tuple ? tuple.t : [];
643
+ const ok = what === "sequence" && number === k + 1 && typeof matched === "number" && typeof applied === "number" &&
644
+ typeof said === "string" && model !== undefined;
645
+ if (!ok)
646
+ throw unexpected(run, doing);
647
+ const at = part.from + k;
648
+ const sequence = sequences[at];
649
+ if (said === "not declared") {
650
+ return {
651
+ kind: "cannot",
652
+ cannot: [
653
+ {
654
+ cause: `TLC finds record ${matched + 1} of the sequence ${sequence.name} outside the declaration in TLA+, which Spex read as inside it`,
655
+ note: null,
656
+ steps: sequenceSteps(sequence, book).slice(0, matched + 1),
657
+ },
658
+ ],
659
+ sequence: at,
660
+ };
661
+ }
662
+ if (!["matched", "forbidden", "differs", "not legal"].includes(said))
663
+ throw unexpected(run, doing);
664
+ // TLC stops a walk only at a record that is not matched.
665
+ const handed = sequence.handed.length;
666
+ if (said === "matched" ? matched !== handed : matched >= handed)
667
+ throw unexpected(run, doing);
668
+ judged[at] = {
669
+ matched,
670
+ applied,
671
+ said: said,
672
+ // `Missing` stands for no effect where the record matched or the
673
+ // event is not legal; of a record that did not match it is the
674
+ // model's own effect, and is kept as that.
675
+ model: said === "forbidden" || said === "differs" ? model : null,
676
+ };
677
+ }
678
+ }
679
+ return { kind: "judged", judged, halted: null, runs: runs.length };
680
+ }
681
+ //# sourceMappingURL=checks.js.map