everystate 0.1.0 → 0.3.0

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 (51) hide show
  1. package/README.md +111 -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 +23 -24
  9. package/wasm/cli.mjs +26 -0
  10. package/wasm/everystate.d.ts +33 -0
  11. package/wasm/everystate.mjs +112 -0
  12. package/wasm/everystate.wasm +0 -0
  13. package/CONFORMANCE.md +0 -64
  14. package/dist/bundled.d.ts +0 -1
  15. package/dist/bundled.js +0 -2
  16. package/dist/cfg.d.ts +0 -24
  17. package/dist/cfg.js +0 -252
  18. package/dist/checker.d.ts +0 -96
  19. package/dist/checker.js +0 -520
  20. package/dist/cli.d.ts +0 -2
  21. package/dist/cli.js +0 -4
  22. package/dist/community.d.ts +0 -17
  23. package/dist/community.js +0 -1381
  24. package/dist/entry.d.ts +0 -2
  25. package/dist/entry.js +0 -39
  26. package/dist/eval.d.ts +0 -119
  27. package/dist/eval.js +0 -1533
  28. package/dist/index.d.ts +0 -33
  29. package/dist/index.js +0 -24
  30. package/dist/java.d.ts +0 -2
  31. package/dist/java.js +0 -6
  32. package/dist/lexer.d.ts +0 -17
  33. package/dist/lexer.js +0 -255
  34. package/dist/liveness.d.ts +0 -80
  35. package/dist/liveness.js +0 -855
  36. package/dist/main.d.ts +0 -40
  37. package/dist/main.js +0 -494
  38. package/dist/model.d.ts +0 -56
  39. package/dist/model.js +0 -582
  40. package/dist/modules.d.ts +0 -91
  41. package/dist/modules.js +0 -649
  42. package/dist/node-host.d.ts +0 -2
  43. package/dist/node-host.js +0 -25
  44. package/dist/parser.d.ts +0 -30
  45. package/dist/parser.js +0 -1114
  46. package/dist/pprint.d.ts +0 -7
  47. package/dist/pprint.js +0 -647
  48. package/dist/stdlib.d.ts +0 -14
  49. package/dist/stdlib.js +0 -588
  50. package/dist/values.d.ts +0 -150
  51. package/dist/values.js +0 -822
package/README.md CHANGED
@@ -1,125 +1,150 @@
1
1
  # everystate
2
2
 
3
- A TLA+ model checker written in pure TypeScript. No Java, no native code, no runtime dependencies.
3
+ A TLA+ model checker with no Java dependency, written in Rust. It reads ordinary `.tla` specs and
4
+ TLC `.cfg` files, checks every reachable state, and reports results in TLC's format.
4
5
 
5
- It reads ordinary TLA+ modules and TLC configuration files, explores the state space the way TLC
6
- does, and prints results in TLC's format, so tools written against TLC keep working.
6
+ - Safety and liveness checking, fairness, symmetry, `VIEW`, `ALIAS`.
7
+ - TLC-compatible text output, exit codes, `-tool` framing and `-dump`.
8
+ - The standard and community modules are built in.
9
+ - One native binary, or WebAssembly for Node, Bun and workers.
10
+
11
+ ## Install
12
+
13
+ ```sh
14
+ npm install -g everystate # prebuilt binary for Linux, macOS and Windows
15
+ cargo install everystate # or build from source
16
+ ```
17
+
18
+ ## Example
19
+
20
+ `examples/Counter.tla`:
21
+
22
+ ```tla
23
+ ---- MODULE Counter ----
24
+ EXTENDS Naturals
25
+ VARIABLE n
26
+
27
+ Init == n = 0
28
+ Next == n < 5 /\ n' = n + 1
29
+ Spec == Init /\ [][Next]_n
30
+
31
+ TypeOK == n \in 0..5
32
+ NeverFour == n /= 4
33
+ ====
34
+ ```
35
+
36
+ `examples/Counter.cfg`:
37
+
38
+ ```
39
+ SPECIFICATION Spec
40
+ INVARIANT TypeOK
41
+ INVARIANT NeverFour
42
+ CHECK_DEADLOCK FALSE
43
+ ```
7
44
 
8
45
  ```sh
9
- npx everystate Spec.tla # uses Spec.cfg next to the spec
10
- npx everystate -config MC.cfg -deadlock Spec.tla
46
+ everystate examples/Counter.tla
11
47
  ```
12
48
 
13
49
  ```
14
- Error: Invariant NotSolved is violated.
50
+ Error: Invariant NeverFour is violated.
15
51
  Error: The behavior up to this point is:
16
52
  State 1: <Initial predicate>
17
- /\ big = 0
18
- /\ small = 0
53
+ n = 0
19
54
 
20
- State 2: <FillBig line 16, col 12 to line 16, col 37 of module DieHard>
21
- /\ big = 5
22
- /\ small = 0
55
+ State 2: <Next line 6, col 9 to line 6, col 27 of module Counter>
56
+ n = 1
23
57
  ...
24
- 73 states generated, 14 distinct states found, 1 states left on queue.
58
+ State 5: <Next line 6, col 9 to line 6, col 27 of module Counter>
59
+ n = 4
60
+
61
+ 5 states generated, 5 distinct states found, 0 states left on queue.
25
62
  ```
26
63
 
27
- Runs on Node 20+ and Bun. It uses only `node:fs`, `node:path`, `node:worker_threads` and
28
- `node:child_process` in its CLI host; the checker itself (`import { check } from 'everystate'`) needs
29
- no host APIs at all and runs anywhere JavaScript does.
30
-
31
- ## What it does
32
-
33
- - **Language**: the full TLA+ expression language as TLC supports it — modules, `EXTENDS`,
34
- `INSTANCE ... WITH` (named, parameterised, `LOCAL`, inside `LET`), recursive operators and
35
- functions, higher-order operators, `LAMBDA`, `CASE`, `CHOOSE`, `EXCEPT`, junction lists, action
36
- operators (`'`, `UNCHANGED`, `ENABLED`, `[A]_v`, `<<A>>_v`, `\cdot`), temporal operators, proofs
37
- (parsed and ignored).
38
- - **Checking**: invariants, deadlock, state and action constraints, `[][A]_v` action properties,
39
- refinement (`PROPERTY OtherSpec`), and liveness under weak and strong fairness
40
- (`[]<>`, `<>[]`, `~>`, `WF_`, `SF_`) with lasso counterexamples.
41
- - **Configuration**: `SPECIFICATION`, `INIT`/`NEXT`, `CONSTANT(S)` (values, model values, `<-`
42
- substitution), `INVARIANT(S)`, `PROPERTY/PROPERTIES`, `CONSTRAINT(S)`, `ACTION_CONSTRAINT(S)`,
43
- `SYMMETRY`, `VIEW`, `CHECK_DEADLOCK`.
44
- - **Standard modules**, implemented natively: `Naturals`, `Integers`, `Reals` (integers only),
45
- `Sequences`, `FiniteSets`, `Bags`, `TLC`, `TLCExt`, `Randomization`.
46
- - **Community modules**, bundled: `FiniteSetsExt`, `SequencesExt`, `Functions`, `Folds`, `Graphs`,
47
- `UndirectedGraphs`, `Relation`, `BagsExt`, `Bitwise`, `Combinatorics`, `Json`, `CSV`, `IOUtils`,
48
- `VectorClocks`, `DyadicRationals`, `Statistics`, and the TLAPS library modules (`TLAPS`,
49
- `FiniteSetTheorems`, `NaturalsInduction`, ...) so that specs with proofs load.
50
- - **Output**: TLC's messages, `-tool` framing, exit codes, trace format with action names and
51
- source locations, 80-column value wrapping, and `-dump dot,actionlabels`.
52
-
53
- ## Using it where a tool expects Java + TLC
54
-
55
- `everystate-java` accepts the command line of `java -cp tla2tools.jar tlc2.TLC ...` (and of
56
- `tla2sany.xml.XMLExporter`). Point a TLC-driving script at it instead of a JVM:
64
+ Exit status is 12, as with TLC.
65
+
66
+ ### For scripts and agents
57
67
 
58
68
  ```sh
59
- JAVA="$(npm root)/everystate/dist/java.js" TLA2TOOLS=unused some-tool-that-runs-tlc Spec.tla
69
+ everystate -json examples/Counter.tla
70
+ ```
71
+
72
+ ```json
73
+ {"status":"invariant","name":"NeverFour","generated":5,"distinct":5,"queue":0,"depth":5,
74
+ "trace":[{"action":null,"state":{"n":"0"}},{"action":"Next","state":{"n":"1"}}, ...]}
60
75
  ```
61
76
 
62
- The pstack `statechart` skill script runs unmodified this way.
77
+ ### From JavaScript (WebAssembly)
63
78
 
64
- ## API
79
+ The npm package also exports the engine compiled to WebAssembly:
65
80
 
66
81
  ```ts
67
- import { check, fmt } from 'everystate';
82
+ import { check } from 'everystate';
68
83
 
69
- const { result, model } = check({
70
- root: 'Spec',
71
- modules: { Spec: tlaSource }, // plus any modules it imports that are not bundled
72
- config: 'SPECIFICATION Spec\nINVARIANT TypeOK',
84
+ const { result } = check({
85
+ root: 'Counter',
86
+ modules: { Counter: tlaSource },
87
+ config: 'SPECIFICATION Spec\nINVARIANT NeverFour\nCHECK_DEADLOCK FALSE',
73
88
  });
74
- result.status; // 'ok' | 'invariant' | 'deadlock' | 'liveness' | 'action-property' | ...
75
- result.distinct; // distinct states found
76
- result.trace; // counterexample: [{ state, action }]
89
+ result.status; // 'invariant'
90
+ result.name; // 'NeverFour'
77
91
  ```
78
92
 
79
- ## How it is verified
93
+ `checkAsync` runs the same check in a worker with a large stack, for deeply recursive specs.
94
+ The WebAssembly build is about 2x slower than native and cannot use the file-based community
95
+ operators.
80
96
 
81
- Real TLC is the specification. Three suites compare against it:
97
+ ### In place of Java TLC
82
98
 
83
- | Suite | What is compared | Command |
84
- |---|---|---|
85
- | [tlaplus/Examples](https://github.com/tlaplus/Examples) manifest | result kind and exact generated / distinct state counts recorded upstream | `npm run conformance:examples -- /path/to/Examples` |
86
- | TLC's own `test-model` directory | outcome, state counts and trace length against a live run of `tla2tools.jar` | `npm run conformance:tlc -- /path/to/test-model` |
87
- | pstack `statechart` corpus | byte-identical charts and reports produced by the real script with everystate standing in for Java | `npm run conformance:statechart -- /path/to/statechart/scripts` |
99
+ `everystate java ...` (or `everystate-java ...` from npm) accepts the `java -cp tla2tools.jar tlc2.TLC ...` command line, so tools that
100
+ shell out to TLC can point at it instead of a JVM. The pstack `statechart` script runs unmodified
101
+ this way.
88
102
 
89
- `npm test` runs the self-contained tests (no Java needed): the checker API, the value
90
- pretty-printer against 337 outputs recorded from the Java implementation, and the community-module
91
- operators against fixtures validated with real TLC.
103
+ ## Options
92
104
 
93
- Current results are in [CONFORMANCE.md](CONFORMANCE.md).
105
+ ```
106
+ everystate [options] SPEC[.tla]
107
+ -config FILE configuration file (default: SPEC.cfg)
108
+ -deadlock do not check for deadlock
109
+ -json one JSON result object
110
+ -tool TLC's machine-readable message framing
111
+ -dump dot,actionlabels FILE write the state graph
112
+ ```
94
113
 
95
- ## Not supported (yet)
114
+ Exit status: 0 success, 10 assumption, 11 deadlock, 12 safety, 13 liveness, 150 parse error,
115
+ 151 config error.
96
116
 
97
- - Simulation / generation mode (`-simulate`, `-generate`), depth-first iterative deepening.
98
- - Multiple workers, disk-backed state queues and fingerprint sets, checkpointing: everything is in
99
- memory, so the practical limit is a few million distinct states.
100
- - The PlusCal translator (specs that already contain their translation work).
101
- - Trace-explorer spec generation, the debugger, coverage statistics, Java module overrides.
102
- - TLAPS proofs are parsed and skipped, not checked.
117
+ ## How it is checked
103
118
 
104
- ## Rust port
119
+ Real TLC is the reference (details in [CONFORMANCE.md](CONFORMANCE.md)):
105
120
 
106
- `rust/` holds `verify-rs`, a Rust port of the safety checker (no liveness, `-tool` or `-dump`),
107
- built to compare speed. It is about 2x faster than this TypeScript engine on Node and roughly level
108
- with single-worker Java TLC; see `rust/BENCHMARK.md`. The TypeScript engine is the complete one.
121
+ - [tlaplus/Examples](https://github.com/tlaplus/Examples), models up to 5 s: 122 of 122 match on
122
+ result and exact state counts.
123
+ - TLC's own `test-model` suite, run side by side with `tla2tools.jar`: 384 of 414 match.
124
+ - pstack `statechart` corpus: 33 of 33 outputs byte-identical.
109
125
 
110
- ## Layout
126
+ Faster than single-worker Java TLC on all 12 benchmark models (1.1x to 4.6x, thin on three of
127
+ them), with near-instant start-up: [BENCHMARK.md](BENCHMARK.md).
111
128
 
129
+ ## Not supported
130
+
131
+ Simulation mode, multiple workers, disk-backed state storage (everything is in memory, so a few
132
+ million distinct states is the practical limit), the PlusCal translator (already-translated specs
133
+ work), Java module overrides, labels and subexpression selectors, and TLAPS proof checking (proofs
134
+ are parsed and skipped).
135
+
136
+ ## Development
137
+
138
+ ```sh
139
+ npm run build # native binary and wasm/everystate.wasm
140
+ npm test # WASM API, pretty-printer and community-module tests
112
141
  ```
113
- src/lexer.ts, parser.ts TLA+ front end
114
- src/modules.ts module loading, name resolution, expression levels
115
- src/values.ts values and TLC's ordering
116
- src/eval.ts evaluator and next-state enumeration
117
- src/stdlib.ts, community.ts native standard and community module operators
118
- src/model.ts, cfg.ts configuration -> checkable model
119
- src/checker.ts, liveness.ts breadth-first search, liveness (tableau + SCC)
120
- src/main.ts CLI, TLC-compatible output, java shim
121
- ```
142
+
143
+ Releases: bump the version in `package.json` and `Cargo.toml` and push to `main`;
144
+ `.github/workflows/release.yml` builds the binaries and publishes to npm (trusted publishing, no token).
145
+
146
+ An earlier pure-TypeScript engine is in the git history at commit `e8c67ce` (npm `everystate@0.1.0`).
122
147
 
123
148
  ## License
124
149
 
125
- MIT. Bundled TLA+ library modules keep their own (MIT / BSD) licenses.
150
+ MIT
@@ -0,0 +1,35 @@
1
+ #!/usr/bin/env node
2
+ // Launcher: runs the prebuilt native binary for this platform (shipped in ../native/<platform>-<arch>/),
3
+ // or falls back to the WebAssembly build, which only prints a JSON result.
4
+ import { spawnSync } from 'node:child_process';
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+
8
+ const exe = process.platform === 'win32' ? 'everystate.exe' : 'everystate';
9
+
10
+ function nativeBinary() {
11
+ if (process.env.EVERYSTATE_BINARY) return process.env.EVERYSTATE_BINARY;
12
+ const file = path.join(import.meta.dirname, '..', 'native', `${process.platform}-${process.arch}`, exe);
13
+ if (!fs.existsSync(file)) return null;
14
+ try { fs.accessSync(file, fs.constants.X_OK); } catch { try { fs.chmodSync(file, 0o755); } catch {} }
15
+ return file;
16
+ }
17
+
18
+ // `everystate-java ...` is `everystate java ...`: the stand-in for `java -cp tla2tools.jar tlc2.TLC`.
19
+ const asJava = path.basename(process.argv[1] ?? '').startsWith('everystate-java');
20
+ const args = asJava ? ['java', ...process.argv.slice(2)] : process.argv.slice(2);
21
+
22
+ const bin = nativeBinary();
23
+ if (bin) {
24
+ const r = spawnSync(bin, args, { stdio: 'inherit' });
25
+ if (r.error) { console.error(`everystate: cannot run ${bin}: ${r.error.message}`); process.exit(1); }
26
+ if (r.signal) process.kill(process.pid, r.signal);
27
+ process.exit(r.status ?? 1);
28
+ } else if (asJava) {
29
+ console.error(`everystate: no prebuilt binary for ${process.platform}-${process.arch}; the Java stand-in needs one (cargo install everystate).`);
30
+ process.exit(1);
31
+ } else {
32
+ console.error(`everystate: no prebuilt binary for ${process.platform}-${process.arch}; using the WebAssembly build (JSON output only).`);
33
+ process.argv = [process.argv[0], process.argv[1], ...args];
34
+ await import('../wasm/cli.mjs');
35
+ }
Binary file
Binary file
Binary file
Binary file
Binary file
package/package.json CHANGED
@@ -1,50 +1,49 @@
1
1
  {
2
2
  "name": "everystate",
3
- "version": "0.1.0",
4
- "description": "A TLA+ model checker (TLC-compatible) written in pure TypeScript. No Java.",
3
+ "version": "0.3.0",
4
+ "description": "A TLA+ model checker with no Java dependency (TLC-compatible). Prebuilt native binaries, with a WebAssembly build for use from JavaScript.",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
- "bin": {
8
- "everystate": "dist/cli.js",
9
- "everystate-java": "dist/java.js"
10
- },
11
- "main": "dist/index.js",
12
- "types": "dist/index.d.ts",
7
+ "main": "wasm/everystate.mjs",
8
+ "types": "wasm/everystate.d.ts",
13
9
  "exports": {
14
10
  ".": {
15
- "types": "./dist/index.d.ts",
16
- "default": "./dist/index.js"
11
+ "types": "./wasm/everystate.d.ts",
12
+ "default": "./wasm/everystate.mjs"
17
13
  }
18
14
  },
15
+ "bin": {
16
+ "everystate": "bin/everystate.mjs",
17
+ "everystate-java": "bin/everystate.mjs"
18
+ },
19
19
  "files": [
20
- "dist",
20
+ "bin/everystate.mjs",
21
+ "native",
22
+ "wasm/everystate.mjs",
23
+ "wasm/everystate.d.ts",
24
+ "wasm/everystate.wasm",
25
+ "wasm/cli.mjs",
21
26
  "README.md",
22
- "CONFORMANCE.md",
23
27
  "LICENSE"
24
28
  ],
25
- "engines": {
26
- "node": ">=20"
27
- },
28
29
  "scripts": {
29
- "build": "tsc -p .",
30
- "bundle": "node scripts/bundle.mjs",
31
- "test": "node --experimental-strip-types --no-warnings --test test/*.test.ts",
30
+ "build": "cargo build --release && sh wasm/build.sh",
31
+ "test": "node --experimental-strip-types --no-warnings --test test/*.test.ts && node test/community.mjs",
32
32
  "conformance:examples": "node scripts/conformance.mjs",
33
33
  "conformance:tlc": "node scripts/diff-tlc.mjs",
34
34
  "conformance:statechart": "node scripts/statechart-corpus.mjs",
35
- "prepublishOnly": "npm run build"
35
+ "bench": "node scripts/bench.mjs"
36
36
  },
37
- "devDependencies": {
38
- "typescript": "^5.8.0",
39
- "@types/node": "^22.0.0"
37
+ "engines": {
38
+ "node": ">=20"
40
39
  },
41
40
  "keywords": [
42
- "tla+",
41
+ "tla",
43
42
  "tlaplus",
44
43
  "tlc",
45
44
  "model-checker",
46
45
  "formal-verification",
47
- "formal-methods"
46
+ "wasm"
48
47
  ],
49
48
  "repository": {
50
49
  "type": "git",
package/wasm/cli.mjs ADDED
@@ -0,0 +1,26 @@
1
+ #!/usr/bin/env node
2
+ // Minimal command line for the WebAssembly build (used by bench.mjs): reads the spec, the modules next
3
+ // to it and the config from disk, runs check() and prints one JSON line like `everystate -json`.
4
+ // usage: node wasm/cli.mjs [-config FILE] [-deadlock] SPEC.tla
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import { check } from './everystate.mjs';
8
+ const argv = process.argv.slice(2);
9
+ let config = null, deadlock = true, spec = null;
10
+ for (let i = 0; i < argv.length; i++) {
11
+ if (argv[i] === '-config') config = argv[++i];
12
+ else if (argv[i] === '-deadlock') deadlock = false;
13
+ else if (!argv[i].startsWith('-')) spec = argv[i];
14
+ }
15
+ if (!spec) { console.error('usage: node wasm/cli.mjs [-config FILE] [-deadlock] SPEC.tla'); process.exit(1); }
16
+ const dir = path.dirname(path.resolve(spec)), root = path.basename(spec, '.tla');
17
+ const modules = {};
18
+ for (const f of fs.readdirSync(dir)) if (f.endsWith('.tla')) modules[f.slice(0, -4)] = fs.readFileSync(path.join(dir, f), 'utf8');
19
+ const cfg = fs.readFileSync(config ?? path.join(dir, root + '.cfg'), 'utf8');
20
+ try {
21
+ const { result } = check({ root, modules, config: cfg, deadlock, print: l => console.log(l) });
22
+ console.log(JSON.stringify({ status: result.status, name: result.name, message: result.message, generated: result.generated, distinct: result.distinct, queue: result.queue, depth: result.depth }));
23
+ } catch (e) {
24
+ console.log(JSON.stringify({ status: 'setup-error', message: e.message }));
25
+ process.exit(150);
26
+ }
@@ -0,0 +1,33 @@
1
+ export interface CheckInput {
2
+ /** Name of the root module. */
3
+ root: string;
4
+ /** Module sources by module name (the root and any modules it EXTENDS/INSTANCEs that are not bundled). */
5
+ modules: Record<string, string>;
6
+ /** Contents of the TLC configuration (.cfg) file. */
7
+ config: string;
8
+ /** Check for deadlock (default: true unless the config says CHECK_DEADLOCK FALSE). */
9
+ deadlock?: boolean;
10
+ /** Receives output of Print/PrintT. */
11
+ print?: (line: string) => void;
12
+ }
13
+ export interface TraceStep { action: { name: string } | null; state: string[] }
14
+ export interface CheckResult {
15
+ status: 'ok' | 'invariant' | 'invariant-init' | 'deadlock' | 'action-property' | 'implied-init' | 'liveness' | 'error' | 'assumption' | 'incomplete' | 'init-error';
16
+ name?: string;
17
+ message?: string;
18
+ code?: number;
19
+ generated: number;
20
+ distinct: number;
21
+ queue: number;
22
+ depth: number;
23
+ /** liveness: index (0-based) of the state the lasso returns to; -1 = stuttering */
24
+ loopTo?: number;
25
+ loopAction?: { name: string } | null;
26
+ trace?: TraceStep[];
27
+ }
28
+ export class TlaError extends Error { kind: string }
29
+ export function init(source?: WebAssembly.Module | BufferSource | Response | Promise<Response>): Promise<WebAssembly.Module>;
30
+ export function check(input: CheckInput): { result: CheckResult; model: { vars: { name: string }[] } };
31
+ export function fmt(value: unknown): string;
32
+ /** Under Node: runs `check` in a worker thread with a `stackSizeMb` call stack (default 256). */
33
+ export function checkAsync(input: CheckInput, options?: { stackSizeMb?: number }): Promise<{ result: CheckResult; model: { vars: { name: string }[] } }>;
@@ -0,0 +1,112 @@
1
+ // everystate as WebAssembly: the same `check({ root, modules, config, deadlock?, print? })` API as the
2
+ // TypeScript package's index.ts, backed by the Rust engine. Works in Node and Bun out of the box (the
3
+ // .wasm file next to this module is read synchronously); in a browser or worker call `init()` first
4
+ // with the compiled module, its bytes, or a fetch() Response.
5
+ //
6
+ // Differences from the TypeScript API: a trace state is an array of already formatted values (one
7
+ // string per variable, in `model.vars` order), so `fmt` is the identity on them; `model` only carries
8
+ // `vars`. Every call runs in a fresh WebAssembly instance (string ordering starts from scratch, as
9
+ // `resetInterning()` does in TypeScript) and its memory is released afterwards.
10
+
11
+ let compiled = null;
12
+
13
+ /** Optional: provide the compiled module (WebAssembly.Module, bytes, or a Response / Promise of one). */
14
+ export async function init(source) {
15
+ source = await source;
16
+ if (source instanceof WebAssembly.Module) compiled = source;
17
+ else if (typeof Response !== 'undefined' && source instanceof Response) compiled = await WebAssembly.compile(await source.arrayBuffer());
18
+ else if (source) compiled = await WebAssembly.compile(source);
19
+ else compiled = load();
20
+ return compiled;
21
+ }
22
+
23
+ function load() {
24
+ if (compiled) return compiled;
25
+ const url = new URL('./everystate.wasm', import.meta.url);
26
+ let bytes;
27
+ if (typeof process !== 'undefined' && process.getBuiltinModule) bytes = process.getBuiltinModule('node:fs').readFileSync(url);
28
+ else if (typeof Bun !== 'undefined' || typeof process !== 'undefined') bytes = globalThis.require?.('node:fs').readFileSync(url);
29
+ if (!bytes) throw new Error('everystate: call `await init(wasmModuleOrBytes)` before check() in this environment.');
30
+ compiled = new WebAssembly.Module(bytes);
31
+ return compiled;
32
+ }
33
+
34
+ const enc = new TextEncoder(), dec = new TextDecoder();
35
+
36
+ export class TlaError extends Error {
37
+ constructor(message, kind) { super(message); this.kind = kind; }
38
+ }
39
+
40
+ /** Formats a value of a trace state (they are already strings in TLC syntax). */
41
+ export const fmt = v => String(v);
42
+
43
+ /**
44
+ * Model-check a specification held in memory.
45
+ * @param {{root: string, modules: Record<string,string>, config: string, deadlock?: boolean, print?: (line: string) => void}} input
46
+ */
47
+ export function check(input) {
48
+ const module = load();
49
+ let memory;
50
+ const print = input.print ?? (() => {});
51
+ const instance = new WebAssembly.Instance(module, {
52
+ env: {
53
+ es_print: (ptr, len) => print(dec.decode(new Uint8Array(memory.buffer, ptr, len))),
54
+ es_now: () => Date.now(),
55
+ },
56
+ });
57
+ const ex = instance.exports;
58
+ memory = ex.memory;
59
+ const put = s => {
60
+ const b = enc.encode(s);
61
+ const p = ex.es_alloc(b.length);
62
+ new Uint8Array(memory.buffer, p, b.length).set(b);
63
+ return [p, b.length];
64
+ };
65
+ for (const [name, src] of Object.entries(input.modules)) ex.es_add_module(...put(name), ...put(src));
66
+ let json;
67
+ try {
68
+ const p = ex.es_check(...put(input.root), ...put(input.config), (input.deadlock ?? true) ? 1 : 0);
69
+ json = JSON.parse(dec.decode(new Uint8Array(memory.buffer, p, ex.es_result_len())));
70
+ } catch (e) {
71
+ // The engine's call stack (RangeError) or the 64 MiB linear-memory stack (RuntimeError) ran out.
72
+ if (e instanceof RangeError || (typeof WebAssembly !== 'undefined' && e instanceof WebAssembly.RuntimeError)) {
73
+ return {
74
+ result: { status: 'error', message: 'Stack overflow while evaluating the specification (recursion too deep). Re-run with a larger stack.', generated: 0, distinct: 0, queue: 0, depth: 0 },
75
+ model: { vars: [] },
76
+ };
77
+ }
78
+ throw e;
79
+ }
80
+ if (json.status === 'setup-error') throw new TlaError(json.message, json.kind);
81
+ const vars = json.vars ?? [];
82
+ const act = name => (name === null || name === undefined ? null : { name });
83
+ const result = {
84
+ status: json.status, name: json.name, message: json.message, code: json.code,
85
+ generated: json.generated, distinct: json.distinct, queue: json.queue, depth: json.depth,
86
+ loopTo: json.loopTo, loopAction: json.status === 'liveness' ? act(json.loopAction) : undefined,
87
+ trace: json.trace?.map(t => ({ action: act(t.action), state: vars.map(v => t.state[v]) })),
88
+ };
89
+ return { result, model: { vars: vars.map(name => ({ name })) } };
90
+ }
91
+
92
+ /**
93
+ * Like `check`, but (under Node) runs in a worker thread with a large call stack, because WebAssembly
94
+ * recursion uses the JavaScript engine's stack: the default ~1 MB allows roughly 500-1000 nested TLA+
95
+ * operator applications, 256 MB allows the evaluator's own limit of 6000. Elsewhere it falls back to `check`.
96
+ */
97
+ export async function checkAsync(input, { stackSizeMb = 256 } = {}) {
98
+ const isNode = typeof process !== 'undefined' && process.versions?.node && !process.versions.bun && typeof Deno === 'undefined';
99
+ if (!isNode) return check(input);
100
+ const { Worker } = await import('node:worker_threads');
101
+ const { print, ...plain } = input;
102
+ const code = `
103
+ import { parentPort, workerData } from 'node:worker_threads';
104
+ const { check } = await import(workerData.url);
105
+ const out = check({ ...workerData.input, print: line => parentPort.postMessage({ line }) });
106
+ parentPort.postMessage({ out });`;
107
+ return new Promise((resolve, reject) => {
108
+ const w = new Worker(code, { eval: true, type: 'module', workerData: { url: import.meta.url, input: plain }, resourceLimits: { stackSizeMb } });
109
+ w.on('message', m => { if (m.line !== undefined) print?.(m.line); else resolve(m.out); });
110
+ w.on('error', reject);
111
+ });
112
+ }
Binary file
package/CONFORMANCE.md DELETED
@@ -1,64 +0,0 @@
1
- # Conformance
2
-
3
- Real TLC is the specification. Numbers below are from 2026-11-13, commit `3c73470`, against
4
- `tla2tools.jar` 1.8.0 (and TLC 2.19 output for the statechart corpus).
5
-
6
- ## tlaplus/Examples manifest
7
-
8
- `npm run conformance:examples -- /path/to/Examples --max-runtime 5`
9
-
10
- Models whose upstream runtime is 5 seconds or less, exhaustive mode: **121 of 122** match on result
11
- kind and on exact generated and distinct state counts.
12
-
13
- - The one failure, `ewd998/EWD998ChanTrace.cfg`, reads a data file by a path relative to the
14
- Examples checkout; it passes when the script is run from that directory.
15
- - State depth is not compared: the upstream numbers were recorded with several workers, which makes
16
- depth nondeterministic. Single-worker TLC agrees with everystate on the cases checked by hand.
17
- - The manifest labels action-property violations "liveness failure" (TLC exit code 13); the script
18
- maps them the same way.
19
-
20
- Larger models (upstream runtime up to 120 seconds, 15-minute timeout each): **161 of 164** match;
21
- the other three (`MCCheckpointCoordination`, `DijkstraMutex` Safety-4-processors, `MCInnerSerial`)
22
- hit the timeout rather than disagreeing. Run before the lazy-set description fix below, which only
23
- made things faster.
24
-
25
- ## TLC's own `test-model` directory
26
-
27
- `npm run conformance:tlc -- /path/to/tlaplus/tlatools/org.lamport.tlatools/test-model`
28
-
29
- Every `X.tla` with an `X.cfg` is run through real TLC and through everystate; outcome class, violated
30
- invariant name, generated/distinct counts and trace length are compared.
31
-
32
- **377 of 414 match.** 8 are skipped because TLC itself does not finish in the time limit.
33
- The 29 mismatches:
34
-
35
- | Reason | Count | Specs |
36
- |---|---|---|
37
- | Result depends on a random seed | 4 | `RandomElement`, `RandomSubsetNext`, `SpanTreeRandom`, `RandomElementXandY` |
38
- | Out of scope: fingerprint-collision tests, Java module override | 4 | `Unicode*Fingerprint` (3), `UserModuleOverride` |
39
- | Deliberate: TLC rejects `\cdot` unless a flag is set, everystate implements it | 3 | `cdot/*` |
40
- | Labels and the full subexpression-selector syntax | 4 | `suite/test206`, `test209`, `test219`, `test219a` |
41
- | Errors only SANY reports (non-Leibniz substitution, level errors, `HIDE`) | 4 | `suite/test212`–`214`, `test217` |
42
- | Suites of hundreds of assumptions on exact TLC internals and message text | 4 | `EmptySetEqAssume`, `ValueSemanticsAssume`, `NormalizationAssume`, `KSubsetAssume` |
43
- | TLC keeps mixed-type sets unsorted until needed | 2 | `NormalizationLiveness`, `NormalizationTLCSet` |
44
- | TLC checks some temporal properties during the search, everystate only at the end | 3 | `InitialLivenessEvaluationError`, `Github710b`, `Github710d` |
45
- | `ALIAS` trace formatting | 1 | `PrintTraceException` |
46
-
47
- ## pstack `statechart` corpus
48
-
49
- `npm run conformance:statechart -- /path/to/pstack/skills/statechart/scripts`
50
-
51
- The unmodified script, with `everystate-java` in place of Java and no `tla2tools.jar`:
52
- **33 of 33** cases produce a byte-identical `chart.mmd` and `report.md`.
53
-
54
- ## Self-contained tests
55
-
56
- `npm test` — 34 pass, 0 fail, 4 todo. No Java needed.
57
-
58
- ## Known behavioural differences from TLC
59
-
60
- - Liveness is checked once, after the state space is complete (TLC's `-lncheck final`).
61
- - Fingerprints are 64-bit but not TLC's, so node ids in `-dump dot` output differ.
62
- - Sets are kept sorted from construction; TLC sorts lazily. A set mixing incomparable values fails
63
- earlier than in TLC.
64
- - `\cdot` (action composition) works without a flag.
package/dist/bundled.d.ts DELETED
@@ -1 +0,0 @@
1
- export declare const BUNDLED: Record<string, string>;