everystate 0.1.0 → 0.3.1

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 (55) hide show
  1. package/README.md +121 -86
  2. package/bin/everystate.mjs +35 -0
  3. package/native/darwin-arm64/everystate +0 -0
  4. package/native/darwin-x64/everystate +0 -0
  5. package/native/linux-arm64/everystate +0 -0
  6. package/native/linux-x64/everystate +0 -0
  7. package/native/win32-x64/everystate.exe +0 -0
  8. package/package.json +29 -24
  9. package/skills/formal-verification/SKILL.md +115 -0
  10. package/skills/formal-verification/example/Charge.cfg +7 -0
  11. package/skills/formal-verification/example/Charge.tla +61 -0
  12. package/skills/formal-verification/example/ChargeBroken.cfg +7 -0
  13. package/wasm/cli.mjs +26 -0
  14. package/wasm/everystate.d.ts +33 -0
  15. package/wasm/everystate.mjs +112 -0
  16. package/wasm/everystate.wasm +0 -0
  17. package/CONFORMANCE.md +0 -64
  18. package/dist/bundled.d.ts +0 -1
  19. package/dist/bundled.js +0 -2
  20. package/dist/cfg.d.ts +0 -24
  21. package/dist/cfg.js +0 -252
  22. package/dist/checker.d.ts +0 -96
  23. package/dist/checker.js +0 -520
  24. package/dist/cli.d.ts +0 -2
  25. package/dist/cli.js +0 -4
  26. package/dist/community.d.ts +0 -17
  27. package/dist/community.js +0 -1381
  28. package/dist/entry.d.ts +0 -2
  29. package/dist/entry.js +0 -39
  30. package/dist/eval.d.ts +0 -119
  31. package/dist/eval.js +0 -1533
  32. package/dist/index.d.ts +0 -33
  33. package/dist/index.js +0 -24
  34. package/dist/java.d.ts +0 -2
  35. package/dist/java.js +0 -6
  36. package/dist/lexer.d.ts +0 -17
  37. package/dist/lexer.js +0 -255
  38. package/dist/liveness.d.ts +0 -80
  39. package/dist/liveness.js +0 -855
  40. package/dist/main.d.ts +0 -40
  41. package/dist/main.js +0 -494
  42. package/dist/model.d.ts +0 -56
  43. package/dist/model.js +0 -582
  44. package/dist/modules.d.ts +0 -91
  45. package/dist/modules.js +0 -649
  46. package/dist/node-host.d.ts +0 -2
  47. package/dist/node-host.js +0 -25
  48. package/dist/parser.d.ts +0 -30
  49. package/dist/parser.js +0 -1114
  50. package/dist/pprint.d.ts +0 -7
  51. package/dist/pprint.js +0 -647
  52. package/dist/stdlib.d.ts +0 -14
  53. package/dist/stdlib.js +0 -588
  54. package/dist/values.d.ts +0 -150
  55. package/dist/values.js +0 -822
package/dist/main.d.ts DELETED
@@ -1,40 +0,0 @@
1
- import type { Model, Action } from './model.ts';
2
- import type { State } from './checker.ts';
3
- export declare const VERSION = "0.1.0";
4
- export interface Host {
5
- fs: {
6
- readFileSync(p: string, enc: 'utf8'): string;
7
- existsSync(p: string): boolean;
8
- writeFileSync(p: string, s: string): void;
9
- appendFileSync?(p: string, s: string): void;
10
- };
11
- path: {
12
- dirname(p: string): string;
13
- join(...p: string[]): string;
14
- basename(p: string, ext?: string): string;
15
- resolve(...p: string[]): string;
16
- };
17
- stdout: (s: string) => void;
18
- exit: (code: number) => void;
19
- env?: Record<string, string | undefined>;
20
- libraryPaths?: string[];
21
- io?: {
22
- readFile(p: string): string;
23
- writeFile(p: string, d: string): void;
24
- appendFile(p: string, d: string): void;
25
- exists(p: string): boolean;
26
- readBytes?(p: string): Uint8Array;
27
- writeBytes?(p: string, d: Uint8Array): void;
28
- exec?(command: string[], env?: Record<string, string>): {
29
- exitValue: number;
30
- stdout: string;
31
- stderr: string;
32
- };
33
- env: Record<string, string>;
34
- };
35
- }
36
- export declare function stateText(model: Model, s: State): string;
37
- export declare function actionLabel(a: Action | null): string;
38
- export declare function runCli(argv: string[], host: Host): void;
39
- export declare function runXmlExporter(argv: string[], host: Host): void;
40
- export declare function runJavaShim(argv: string[], host: Host): void;
package/dist/main.js DELETED
@@ -1,494 +0,0 @@
1
- // Command-line driver. Accepts TLC's flags and prints TLC-compatible output (including -tool mode).
2
- import { parseConfig } from "./cfg.js";
3
- import { buildModel } from "./model.js";
4
- import { Loader, defLevel } from "./modules.js";
5
- import { buildStdlib, globalDefs } from "./stdlib.js";
6
- import { modelCheck } from "./liveness.js";
7
- import { BUNDLED } from "./bundled.js";
8
- import { TlaError } from "./lexer.js";
9
- import { fmt, resetInterning } from "./values.js";
10
- import { ppr } from "./pprint.js";
11
- export const VERSION = '0.1.0';
12
- const pad = (n) => String(n).padStart(2, '0');
13
- function now() {
14
- const d = new Date();
15
- return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
16
- }
17
- const commas = (n) => String(Math.round(n)).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
18
- export function stateText(model, s) {
19
- const vars = model.vars;
20
- if (vars.length === 1)
21
- return `${vars[0].name} = ${ppr(fmt(s[0]))}\n`;
22
- let out = '';
23
- for (let i = 0; i < vars.length; i++)
24
- out += `/\\ ${vars[i].name} = ${ppr(fmt(s[i]))}\n`;
25
- return out;
26
- }
27
- export function actionLabel(a) {
28
- if (!a)
29
- return '<Initial predicate>';
30
- return `<${a.name}${a.params} line ${a.loc[0]}, col ${a.loc[1]} to line ${a.loc[2]}, col ${a.loc[3]} of module ${a.module}>`;
31
- }
32
- class Reporter {
33
- tool;
34
- out;
35
- constructor(tool, out) { this.tool = tool; this.out = out; }
36
- // cls: 0 none, 1 error, 2 bug, 3 warning, 4 state
37
- msg(code, cls, text) {
38
- if (this.tool)
39
- this.out(`@!@!@STARTMSG ${code}:${cls} @!@!@\n${text}\n@!@!@ENDMSG ${code} @!@!@\n`);
40
- else
41
- this.out((cls === 1 ? 'Error: ' : cls === 3 ? 'Warning: ' : cls === 4 ? 'State ' : '') + text + '\n');
42
- }
43
- plain(text) { this.out(text + '\n'); }
44
- }
45
- const EXIT = {
46
- ok: 0, assumption: 10, deadlock: 11, invariant: 12, 'invariant-init': 12, 'action-property': 13, 'implied-init': 13,
47
- liveness: 13, incomplete: 75, error: 255, 'init-error': 255,
48
- };
49
- const ARITY1 = new Set(['-workers', '-fp', '-lncheck', '-metadir', '-seed', '-depth', '-fpmem', '-coverage', '-checkpoint',
50
- '-maxSetSize', '-fpbits', '-userFile', '-recover', '-aril', '-dfid', '-suppressMessages', '-messagesAsErrors', '-inv',
51
- '-invlevel', '-postCondition', '-teSpecOutDir']);
52
- export function runCli(argv, host) {
53
- let spec = null, config = null, deadlock = true, tool = false, json = false;
54
- let dump = null;
55
- for (let i = 0; i < argv.length; i++) {
56
- const a = argv[i];
57
- if (a === '-config')
58
- config = argv[++i];
59
- else if (a === '-deadlock')
60
- deadlock = false;
61
- else if (a === '-tool')
62
- tool = true;
63
- else if (a === '-json')
64
- json = true;
65
- else if (a === '-dump') {
66
- const x = argv[++i];
67
- if (x === 'dot' || x.startsWith('dot,'))
68
- dump = { file: argv[++i], dot: true, opts: x.toLowerCase() };
69
- else
70
- dump = { file: x, dot: false, opts: '' };
71
- }
72
- else if (a === '-dumpTrace' || a === '-loadTrace')
73
- i += 2;
74
- else if (a === '-simulate' || a === '-generate') {
75
- host.stdout('Error: simulation mode is not supported by everystate yet.\n');
76
- host.exit(1);
77
- return;
78
- }
79
- else if (a === '-h' || a === '-help' || a === '--help') {
80
- host.stdout(USAGE);
81
- host.exit(0);
82
- return;
83
- }
84
- else if (a === '-version' || a === '--version') {
85
- host.stdout(`everystate ${VERSION}\n`);
86
- host.exit(0);
87
- return;
88
- }
89
- else if (ARITY1.has(a))
90
- i++;
91
- else if (a.startsWith('-')) { /* flag without effect here (-cleanup, -nowarning, -terse, -noTE, ...) */ }
92
- else if (spec !== null) {
93
- host.stdout(`Error: more than one input files: ${spec} and ${a}\n`);
94
- host.exit(1);
95
- return;
96
- }
97
- else
98
- spec = a;
99
- }
100
- if (!spec) {
101
- host.stdout('Error: Missing input TLA+ module.\n' + USAGE);
102
- host.exit(1);
103
- return;
104
- }
105
- const specPath = spec.endsWith('.tla') ? spec : spec + '.tla';
106
- const dir = host.path.dirname(host.path.resolve(specPath));
107
- const rootName = host.path.basename(specPath, '.tla');
108
- let cfgPath = config ?? rootName + '.cfg';
109
- if (!cfgPath.endsWith('.cfg') && !host.fs.existsSync(cfgPath) && !host.fs.existsSync(host.path.join(dir, cfgPath)))
110
- cfgPath += '.cfg';
111
- if (!host.fs.existsSync(cfgPath) || config === null) {
112
- const inDir = host.path.join(dir, cfgPath);
113
- if (host.fs.existsSync(inDir))
114
- cfgPath = inDir;
115
- }
116
- const rep = new Reporter(tool, host.stdout);
117
- const t0 = Date.now();
118
- const parsed = [];
119
- const libs = [dir, ...(host.libraryPaths ?? [])];
120
- const resolve = (name) => {
121
- for (const d of libs) {
122
- const p = host.path.join(d, name + '.tla');
123
- if (host.fs.existsSync(p)) {
124
- parsed.push(p);
125
- return host.fs.readFileSync(p, 'utf8');
126
- }
127
- }
128
- return BUNDLED[name] ?? null;
129
- };
130
- const finish = (code) => {
131
- const ms = Date.now() - t0;
132
- const s = Math.floor(ms / 1000);
133
- const dur = tool ? `${ms}ms` : s < 60 ? `${pad(s)}s` : s < 3600 ? `${pad(Math.floor(s / 60))}min ${pad(s % 60)}s` : `${pad(Math.floor(s / 3600))}h ${pad(Math.floor((s % 3600) / 60))}min`;
134
- if (!json)
135
- rep.msg(2186, 0, `Finished in ${dur} at (${now()})`);
136
- host.exit(code);
137
- };
138
- resetInterning();
139
- if (!json) {
140
- rep.msg(2262, 0, `TLC2 Version 2.19 of 08 August 2024 (everystate ${VERSION})`);
141
- rep.msg(2187, 0, `Running breadth-first search Model-Checking with fp 0 and seed 0 with 1 worker on 1 cores with 0MB heap and 0MB offheap memory (everystate ${VERSION}, pure TypeScript, HashFPSet, MemStateQueue).`);
142
- }
143
- let model;
144
- try {
145
- if (!host.fs.existsSync(cfgPath))
146
- throw new TlaError(`TLC encountered the following error reading the configuration file ${cfgPath}:\nFile not found.`, undefined, undefined, 'config');
147
- const cfg = parseConfig(host.fs.readFileSync(cfgPath, 'utf8'));
148
- if (!json && tool)
149
- rep.msg(2220, 0, 'Starting SANY...');
150
- try {
151
- model = buildModel(rootName, resolve, cfg, { print: s => host.stdout(s + '\n') });
152
- }
153
- finally {
154
- if (!json) {
155
- for (const p of parsed)
156
- rep.plain(`Parsing file ${p}`);
157
- }
158
- }
159
- if (!json) {
160
- for (const m of model.loader.loadOrder)
161
- rep.plain(`Semantic processing of module ${m}`);
162
- if (tool)
163
- rep.msg(2219, 0, 'SANY finished.');
164
- }
165
- }
166
- catch (e) {
167
- if (!(e instanceof TlaError))
168
- throw e;
169
- if (json) {
170
- host.stdout(JSON.stringify({ status: 'setup-error', kind: e.kind, message: e.message }) + '\n');
171
- host.exit(e.kind === 'config' ? 151 : 150);
172
- return;
173
- }
174
- if (e.kind === 'config') {
175
- rep.msg(1000, 1, e.message);
176
- finish(151);
177
- return;
178
- }
179
- rep.plain(e.message);
180
- rep.msg(3002, 1, 'Parsing or semantic analysis failed.');
181
- finish(150);
182
- return;
183
- }
184
- model.ev.hooks.io = host.io ?? {
185
- readFile: (p) => host.fs.readFileSync(p, 'utf8'),
186
- writeFile: (p, d) => host.fs.writeFileSync(p, d),
187
- appendFile: (p, d) => host.fs.writeFileSync(p, (host.fs.existsSync(p) ? host.fs.readFileSync(p, 'utf8') : '') + d),
188
- exists: (p) => host.fs.existsSync(p),
189
- env: host.env ?? {},
190
- };
191
- if (!json)
192
- rep.msg(2185, 0, `Starting... (${now()})`);
193
- let first = true;
194
- const { result: res, checker } = modelCheck(model, {
195
- checkDeadlock: deadlock && model.checkDeadlock,
196
- recordGraph: dump !== null,
197
- onProgress: (gen, distinct, queue) => {
198
- if (json)
199
- return;
200
- if (first) {
201
- first = false;
202
- const c = checker0();
203
- rep.msg(2189, 0, 'Computing initial states...');
204
- if (c.initGenerated === c.initDistinct)
205
- rep.msg(2190, 0, `Finished computing initial states: ${c.initDistinct} distinct state${c.initDistinct === 1 ? '' : 's'} generated at ${now()}.`);
206
- else
207
- rep.msg(2191, 0, `Finished computing initial states: ${c.initGenerated} state${c.initGenerated === 1 ? '' : 's'} generated, with ${c.initDistinct} of them distinct at ${now()}.`);
208
- return;
209
- }
210
- rep.msg(2200, 0, `Progress(${checker0().depth}) at ${now()}: ${commas(gen)} states generated, ${commas(distinct)} distinct states found, ${commas(queue)} states left on queue.`);
211
- },
212
- onChecker: (c) => { theChecker = c; },
213
- onLiveness: (phase, branches) => {
214
- if (json)
215
- return;
216
- const c = checker0();
217
- if (phase === 'branches')
218
- rep.msg(2212, 0, `Implied-temporal checking--satisfiability problem has ${branches} branches.`);
219
- else if (phase === 'start') {
220
- if (!rep.tool)
221
- rep.msg(2200, 0, `Progress(${c.depth}) at ${now()}: ${commas(c.generated)} states generated, ${commas(c.states.length)} distinct states found, 0 states left on queue.`);
222
- rep.msg(2192, 0, `Checking ${branches > 1 ? branches + ' branches of ' : ''}temporal properties for the complete state space with ${c.states.length * branches} total distinct states at (${now()})`);
223
- }
224
- else
225
- rep.msg(2267, 0, `Finished checking temporal properties in 00s at ${now()}`);
226
- },
227
- });
228
- if (dump) {
229
- try {
230
- writeDump(model, checker, dump, host);
231
- }
232
- catch (e) {
233
- rep.msg(1000, 1, `Failed to write the state dump: ${e.message}`);
234
- }
235
- }
236
- if (json) {
237
- host.stdout(JSON.stringify({
238
- status: res.status, name: res.name, message: res.message, generated: res.generated, distinct: res.distinct, queue: res.queue,
239
- depth: res.depth, loopTo: res.loopTo,
240
- trace: res.trace?.map(t => ({ action: t.action?.name ?? null, state: Object.fromEntries(model.vars.map((v, i) => [v.name, fmt(t.state[i])])) })),
241
- }) + '\n');
242
- host.exit(EXIT[res.status] ?? 255);
243
- return;
244
- }
245
- if (first)
246
- rep.msg(2189, 0, 'Computing initial states...');
247
- report(rep, model, res, t0);
248
- finish(res.callStack ? 75 : res.code === 2111 ? 76 : EXIT[res.status] ?? 255);
249
- }
250
- let theChecker = null;
251
- const checker0 = () => theChecker;
252
- function printTrace(rep, model, res) {
253
- const tr = res.trace ?? [];
254
- tr.forEach((t, i) => {
255
- rep.msg(2217, 4, `${i + 1}: ${actionLabel(i === 0 ? null : t.action)}\n${stateText(model, t.state)}`);
256
- });
257
- }
258
- function report(rep, model, res, t0) {
259
- const summary = () => {
260
- if (rep.tool) {
261
- const mins = Math.max((Date.now() - t0) / 60000, 1e-6);
262
- rep.msg(2200, 0, `Progress(${res.depth}) at ${now()}: ${commas(res.generated)} states generated (${commas(res.generated / mins)} s/min), ${commas(res.distinct)} distinct states found (${commas(res.distinct / mins)} ds/min), ${commas(res.queue)} states left on queue.`);
263
- }
264
- rep.msg(2199, 0, `${res.generated} states generated, ${res.distinct} distinct states found, ${res.queue} states left on queue.`);
265
- rep.msg(2194, 0, `The depth of the complete state graph search is ${res.depth}.`);
266
- if (res.outdegree && (res.status === 'ok' || rep.tool)) {
267
- const o = res.outdegree;
268
- rep.msg(2268, 0, `The average outdegree of the complete state graph is ${o.avg} (minimum is ${o.min}, the maximum ${o.max} and the 95th percentile is ${o.p95}).`);
269
- }
270
- };
271
- switch (res.status) {
272
- case 'ok': {
273
- const p = res.distinct * ((res.generated - res.distinct) / 18446744073709551616);
274
- const ps = p === 0 ? '0.0' : p.toExponential(1).replace('e', 'E').replace('E+', 'E');
275
- rep.msg(2193, 0, `Model checking completed. No error has been found.\n Estimates of the probability that TLC did not check all reachable states\n because two distinct states had the same fingerprint:\n calculated (optimistic): val = ${ps}`);
276
- summary();
277
- return;
278
- }
279
- case 'assumption':
280
- rep.msg(2104, 1, res.message.replace(/^Assumption /, 'Assumption ').replace(/\.$/, '.'));
281
- return;
282
- case 'invariant-init':
283
- rep.msg(2107, 1, `Invariant ${res.name} is violated by the initial state:\n${stateText(model, res.trace[0].state)}`);
284
- return;
285
- case 'implied-init':
286
- rep.msg(2108, 1, `Property ${res.name} is violated by the initial state:\n${stateText(model, res.trace[0].state)}`);
287
- return;
288
- case 'invariant':
289
- rep.msg(2110, 1, `Invariant ${res.name} is violated.`);
290
- break;
291
- case 'action-property':
292
- rep.msg(2112, 1, `Action property ${res.name} is violated.`);
293
- break;
294
- case 'deadlock':
295
- rep.msg(2114, 1, 'Deadlock reached.');
296
- break;
297
- case 'liveness': {
298
- rep.msg(2116, 1, res.name ? `Temporal properties were violated.\n` : 'Temporal properties were violated.\n');
299
- rep.msg(2264, 1, 'The following behavior constitutes a counter-example:\n');
300
- printTrace(rep, model, res);
301
- const n = res.trace.length;
302
- if (res.loopTo === undefined || res.loopTo < 0)
303
- rep.msg(2218, 4, `${n + 1}: Stuttering`);
304
- else if (rep.tool)
305
- rep.msg(2122, 4, `${res.loopTo + 1}: Back to state: ${actionLabel(res.loopAction ?? null)}\n`);
306
- else
307
- rep.out(`Back to state ${res.loopTo + 1}: ${actionLabel(res.loopAction ?? null)}\n\n`);
308
- rep.msg(2267, 0, `Finished checking temporal properties in 00s at ${now()}`);
309
- if (rep.tool) {
310
- const mins = Math.max((Date.now() - t0) / 60000, 1e-6);
311
- rep.msg(2200, 0, `Progress(${res.depth}) at ${now()}: ${commas(res.generated)} states generated (${commas(res.generated / mins)} s/min), ${commas(res.distinct)} distinct states found (${commas(res.distinct / mins)} ds/min), ${commas(res.queue)} states left on queue.`);
312
- }
313
- rep.msg(2199, 0, `${res.generated} states generated, ${res.distinct} distinct states found, ${res.queue} states left on queue.`);
314
- return;
315
- }
316
- case 'incomplete':
317
- rep.msg(2109, 1, res.message + '\n');
318
- break;
319
- default: {
320
- const m = res.message ?? 'unknown error';
321
- if (res.code) {
322
- rep.msg(res.code, 1, m);
323
- break;
324
- }
325
- if (res.trace && res.trace.length === 1 && res.trace[0].id === -1 && res.trace[0].action === null) {
326
- rep.msg(2102, 1, `${m}\nWhile working on the initial state:\n${stateText(model, res.trace[0].state)}`);
327
- if (res.printSummary)
328
- summary();
329
- return;
330
- }
331
- rep.msg(1000, 1, `TLC threw an unexpected exception.\nThis was probably caused by an error in the spec or model.\nSee the User Output or TLC Console for clues to what happened.\nThe exception was a java.lang.RuntimeException\n: ${m}`);
332
- }
333
- }
334
- if (res.trace && res.trace.length) {
335
- rep.msg(2121, 1, 'The behavior up to this point is:');
336
- printTrace(rep, model, res);
337
- }
338
- if (res.callStack)
339
- rep.msg(2103, 1, `The error occurred when TLC was evaluating the nested\nexpressions at the following positions:\n${res.callStack}`);
340
- if (res.printSummary)
341
- summary();
342
- }
343
- function fpString(checker, s) {
344
- checker.fingerprint(s);
345
- const h = checker.hasher;
346
- return BigInt.asIntN(64, (BigInt(h.h1 >>> 0) << 32n) | BigInt(h.h2 >>> 0)).toString();
347
- }
348
- function writeDump(model, checker, dump, host) {
349
- const states = checker.states;
350
- if (!dump.dot) {
351
- let out = '';
352
- states.forEach((s, i) => { out += `State ${i + 1}:\n${stateText(model, s)}\n`; });
353
- host.fs.writeFileSync(dump.file.endsWith('.dump') ? dump.file : dump.file + '.dump', out);
354
- return;
355
- }
356
- const labels = dump.opts.includes('actionlabels');
357
- const esc = (s) => s.replace(/\\/g, '\\\\').replace(/"/g, '\\"').trim().replace(/\n/g, '\\n');
358
- const ids = states.map(s => fpString(checker, s));
359
- const lines = ['strict digraph DiskGraph {', 'nodesep=0.35;', 'subgraph cluster_graph {', 'color="white";'];
360
- const ranks = new Map();
361
- const rank = (i) => { let r = ranks.get(checker.level[i]); if (!r) {
362
- r = new Set();
363
- ranks.set(checker.level[i], r);
364
- } r.add(i); };
365
- const written = new Set();
366
- for (const i of checker.inits) {
367
- lines.push(`${ids[i]} [label="${esc(stateText(model, states[i]))}",style = filled]`);
368
- written.add(i);
369
- rank(i);
370
- }
371
- for (let s = 0; s < states.length; s++) {
372
- const su = checker.succ[s] ?? [], sa = checker.succAct[s] ?? [];
373
- for (let j = 0; j < su.length; j++) {
374
- const t = su[j];
375
- const a = model.actions[sa[j]];
376
- lines.push(`${ids[s]} -> ${ids[t]} [label="${labels ? esc(a.name) : ''}",color="black",fontcolor="black"];`);
377
- rank(s);
378
- if (!written.has(t)) {
379
- written.add(t);
380
- lines.push(`${ids[t]} [label="${esc(stateText(model, states[t]))}"];`);
381
- }
382
- }
383
- }
384
- for (const [, set] of [...ranks.entries()].sort((a, b) => a[0] - b[0]))
385
- lines.push(`{rank = same; ${[...set].map(i => ids[i] + ';').join('')}}`);
386
- lines.push('}', '}');
387
- host.fs.writeFileSync(dump.file.endsWith('.dot') ? dump.file : dump.file + '.dot', lines.join('\n') + '\n');
388
- }
389
- const USAGE = `everystate ${VERSION} - a TLA+ model checker in pure TypeScript (TLC-compatible command line)
390
-
391
- Usage: verify [options] SPEC[.tla]
392
-
393
- -config FILE configuration file (default: SPEC.cfg)
394
- -deadlock do not check for deadlock
395
- -tool machine-readable output (TLC's -tool message framing)
396
- -dump [dot[,actionlabels]] FILE write the reachable state graph
397
- -json print a single JSON result object instead of TLC-style output
398
- -workers N, -fp N, -lncheck S, -metadir DIR, -seed N, ... accepted for compatibility
399
-
400
- Exit status: 0 success, 10 assumption, 11 deadlock, 12 safety, 13 liveness, 150 parse error, 151 config error.
401
- `;
402
- // Emulates `java ... tla2sany.xml.XMLExporter [-o] [-I dir] SPEC`: a minimal XML description of the
403
- // root module (variables, definitions and their levels), enough for tools that only need the symbol table.
404
- export function runXmlExporter(argv, host) {
405
- let spec = null;
406
- const libs = [];
407
- for (let i = 0; i < argv.length; i++) {
408
- if (argv[i] === '-I')
409
- libs.push(argv[++i]);
410
- else if (!argv[i].startsWith('-'))
411
- spec = argv[i];
412
- }
413
- if (!spec) {
414
- host.stdout('Usage: XMLExporter [-o] [-I dir] SPEC\n');
415
- host.exit(1);
416
- return;
417
- }
418
- const specPath = spec.endsWith('.tla') ? spec : spec + '.tla';
419
- const dir = host.path.dirname(host.path.resolve(specPath));
420
- const rootName = host.path.basename(specPath, '.tla');
421
- const dirs = [dir, ...libs, ...(host.libraryPaths ?? [])];
422
- const resolve = (name) => {
423
- for (const d of dirs) {
424
- const p = host.path.join(d, name + '.tla');
425
- if (host.fs.existsSync(p))
426
- return host.fs.readFileSync(p, 'utf8');
427
- }
428
- return BUNDLED[name] ?? null;
429
- };
430
- resetInterning();
431
- try {
432
- const loader = new Loader(resolve, buildStdlib({ print: () => { } }));
433
- loader.globals = globalDefs();
434
- const root = loader.load(rootName);
435
- const escXml = (t) => t.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
436
- let uid = 1;
437
- const entries = [];
438
- const refs = [];
439
- for (const v of root.vars) {
440
- const id = ++uid;
441
- refs.push(`<OpDeclNodeRef><UID>${id}</UID></OpDeclNodeRef>`);
442
- entries.push(`<entry><UID>${id}</UID><OpDeclNode><uniquename>${escXml(v.name)}</uniquename><level>1</level><arity>0</arity><kind>3</kind></OpDeclNode></entry>`);
443
- }
444
- for (const c of root.consts) {
445
- const id = ++uid;
446
- refs.push(`<OpDeclNodeRef><UID>${id}</UID></OpDeclNodeRef>`);
447
- entries.push(`<entry><UID>${id}</UID><OpDeclNode><uniquename>${escXml(c.name)}</uniquename><level>0</level><arity>${c.arity}</arity><kind>2</kind></OpDeclNode></entry>`);
448
- }
449
- for (const [name, sym] of root.syms) {
450
- if (sym.k !== 'def' || sym.builtin)
451
- continue;
452
- const id = ++uid;
453
- refs.push(`<UserDefinedOpKindRef><UID>${id}</UID></UserDefinedOpKindRef>`);
454
- entries.push(`<entry><UID>${id}</UID><UserDefinedOpKind><uniquename>${escXml(name)}</uniquename><level>${defLevel(sym)}</level><arity>${sym.params.length}</arity></UserDefinedOpKind></entry>`);
455
- }
456
- host.stdout(`<?xml version="1.0" encoding="UTF-8"?>\n<modules><RootModule>${escXml(rootName)}</RootModule><context>` +
457
- `<entry><UID>1</UID><ModuleNode><uniquename>${escXml(rootName)}</uniquename>${refs.join('')}</ModuleNode></entry>${entries.join('')}</context></modules>\n`);
458
- host.exit(0);
459
- }
460
- catch (e) {
461
- if (!(e instanceof TlaError))
462
- throw e;
463
- host.stdout(`${e.message}\n*** Errors: 1\n`);
464
- host.exit(1);
465
- }
466
- }
467
- // Emulates the `java` command line of the TLA+ tools, so that scripts which shell out to
468
- // `java -cp tla2tools.jar tlc2.TLC ...` can run on everystate unchanged.
469
- export function runJavaShim(argv, host) {
470
- const libs = [...(host.libraryPaths ?? [])];
471
- let i = 0;
472
- for (; i < argv.length; i++) {
473
- const a = argv[i];
474
- if (a.startsWith('-DTLA-Library='))
475
- libs.push(...a.slice('-DTLA-Library='.length).split(/[:;]/).filter(Boolean));
476
- else if (a === '-cp' || a === '-classpath' || a === '-jar')
477
- i++;
478
- else if (!a.startsWith('-'))
479
- break;
480
- }
481
- const main = argv[i];
482
- const rest = argv.slice(i + 1);
483
- const h = { ...host, libraryPaths: libs };
484
- if (main === 'tlc2.TLC')
485
- runCli(rest, h);
486
- else if (main === 'tla2sany.xml.XMLExporter')
487
- runXmlExporter(rest, h);
488
- else if (main === 'tla2sany.SANY')
489
- runXmlExporter(['-quiet', ...rest], { ...h, stdout: () => { } });
490
- else {
491
- host.stdout(`everystate java shim: unsupported main class ${main ?? '(none)'}\n`);
492
- host.exit(1);
493
- }
494
- }
package/dist/model.d.ts DELETED
@@ -1,56 +0,0 @@
1
- import type { Node } from './parser.ts';
2
- import { TlaError } from './lexer.ts';
3
- import type { Loc } from './lexer.ts';
4
- import { Loader } from './modules.ts';
5
- import type { ModuleInfo, Decl, SourceResolver } from './modules.ts';
6
- import { Evaluator, Ctx } from './eval.ts';
7
- import type { Config } from './cfg.ts';
8
- import { ModelValue } from './values.ts';
9
- export interface Pred {
10
- name: string;
11
- e: Node;
12
- ctx: Ctx | null;
13
- }
14
- export interface Action {
15
- name: string;
16
- params: string;
17
- loc: Loc;
18
- module: string;
19
- e: Node;
20
- ctx: Ctx | null;
21
- }
22
- export interface Model {
23
- rootName: string;
24
- root: ModuleInfo;
25
- loader: Loader;
26
- ev: Evaluator;
27
- vars: Decl[];
28
- inits: Pred[];
29
- actions: Action[];
30
- invariants: Pred[];
31
- impliedInits: Pred[];
32
- impliedActions: Pred[];
33
- constraints: Pred[];
34
- actionConstraints: Pred[];
35
- fairness: Pred[];
36
- liveProps: Pred[];
37
- symmetry: Map<ModelValue, ModelValue>[] | null;
38
- view: Pred | null;
39
- alias: Pred | null;
40
- postconditions: (Pred & {
41
- possible?: boolean;
42
- loc: Loc;
43
- module: string;
44
- })[];
45
- checkDeadlock: boolean;
46
- warnings: string[];
47
- }
48
- export declare class ConfigError extends TlaError {
49
- constructor(msg: string);
50
- }
51
- export declare function locStr(loc: Loc, module: string): string;
52
- export declare function buildModel(rootName: string, resolve: SourceResolver, cfg: Config, io: {
53
- print: (s: string) => void;
54
- }): Model;
55
- export declare function exprLevel(ev: Evaluator, e: Node, ctx: Ctx | null): number;
56
- export declare function tlcVariableOrder(root: ModuleInfo): Decl[];