tla-ts 0.0.3-dev.6979965 → 0.0.3-dev.6f3cbdb

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.
@@ -21,56 +21,21 @@ import { createStateDecoder, createStateEncoder, type EncodedStates } from "./tr
21
21
  import { getRankedStringCount, setStringOrder, type Value } from "./values";
22
22
 
23
23
  const WORKER_THREADS_MODULE = "node:worker_threads";
24
-
25
- interface PeerMessage {
26
- phase: "balance";
27
- level: number;
28
- from: number;
29
- states: EncodedStates;
30
- }
24
+ const LOCKED = -1;
31
25
 
32
26
  interface Expansion {
27
+ states: Value[][];
33
28
  origin: number;
29
+ end: number;
34
30
  successors: Successor[] | undefined;
35
31
  index: number;
32
+ added: number;
36
33
  generated: number;
37
- newStates: Int32Array;
34
+ outDegrees: number[];
38
35
  next: Value[][];
39
36
  fingerprintStates: Value[][];
40
37
  }
41
38
 
42
- interface Transfer {
43
- from: number;
44
- to: number;
45
- count: number;
46
- }
47
-
48
- const getBalancePlan = (sizes: number[]) => {
49
- const total = sizes.reduce((sum, size) => sum + size, 0);
50
- const average = total / sizes.length;
51
- if (Math.max(...sizes) - Math.min(...sizes) <= Math.max(64, average / 4)) return [];
52
- const targets = sizes.map(
53
- (_, index) => Math.floor(average) + (index < total % sizes.length ? 1 : 0),
54
- );
55
- const donors = sizes.flatMap((size, index) =>
56
- size > targets[index] ? [{ index, amount: size - targets[index] }] : [],
57
- );
58
- const receivers = sizes.flatMap((size, index) =>
59
- size < targets[index] ? [{ index, amount: targets[index] - size }] : [],
60
- );
61
- const transfers: Transfer[] = [];
62
- for (const donor of donors) {
63
- for (const receiver of receivers) {
64
- const moved = Math.min(donor.amount, receiver.amount);
65
- if (moved === 0) continue;
66
- transfers.push({ from: donor.index, to: receiver.index, count: moved });
67
- donor.amount -= moved;
68
- receiver.amount -= moved;
69
- }
70
- }
71
- return transfers;
72
- };
73
-
74
39
  const getParentPort = async () => {
75
40
  if (typeof (globalThis as { postMessage?: unknown }).postMessage === "function") {
76
41
  return globalThis as unknown as Port;
@@ -81,33 +46,6 @@ const getParentPort = async () => {
81
46
  return threads.parentPort as unknown as Port;
82
47
  };
83
48
 
84
- const createInbox = () => {
85
- const messages = new Map<string, PeerMessage[]>();
86
- const waiters = new Map<string, { count: number; resolve: (messages: PeerMessage[]) => void }>();
87
- const getKey = (phase: PeerMessage["phase"], level: number) => `${phase}:${level}`;
88
- const settle = (key: string) => {
89
- const waiter = waiters.get(key);
90
- const received = messages.get(key) ?? [];
91
- if (!waiter || received.length < waiter.count) return;
92
- waiters.delete(key);
93
- messages.delete(key);
94
- waiter.resolve(received);
95
- };
96
- return {
97
- deliver: (message: PeerMessage) => {
98
- const key = getKey(message.phase, message.level);
99
- messages.set(key, [...(messages.get(key) ?? []), message]);
100
- settle(key);
101
- },
102
- receive: (phase: PeerMessage["phase"], level: number, count: number) =>
103
- new Promise<PeerMessage[]>((resolve) => {
104
- const key = getKey(phase, level);
105
- waiters.set(key, { count, resolve });
106
- settle(key);
107
- }),
108
- };
109
- };
110
-
111
49
  const run = (start: StartMessage, parent: Port) => {
112
50
  const modules = new Map(start.modules);
113
51
  const loadModule = (name: string) => modules.get(name);
@@ -132,26 +70,55 @@ const run = (start: StartMessage, parent: Port) => {
132
70
  const canonicalize = createCanonicalizer();
133
71
  const decode = createStateDecoder(environment.variables.length);
134
72
  const shared = { fingerprints: start.fingerprints };
73
+ const requests = start.requests;
74
+ const remaining = start.remaining;
135
75
  // Under symmetry, a successor the worker generated before has the representative it had then,
136
76
  // so the worker skips the search for one.
137
77
  const generatedStates = search.isSymmetric ? createFingerprintTable() : undefined;
138
78
  const fingerprint = new Int32Array(2);
139
- const inbox = createInbox();
140
- const peers = start.ports.flatMap((port, index) => (port ? [{ port, index }] : []));
141
- peers.forEach((peer) => {
142
- peer.port.addEventListener("message", (event) => inbox.deliver(event.data as PeerMessage));
143
- peer.port.start?.();
79
+ const waiters = { resume: () => {}, loot: (_states: EncodedStates) => {} };
80
+ start.ports.forEach((port) => {
81
+ port?.addEventListener("message", (event) => waiters.loot(event.data as EncodedStates));
82
+ port?.start?.();
144
83
  });
145
84
  const frontier = { states: decode(start.seed).map(canonicalize) };
146
- const send = (index: number, message: PeerMessage, transfer: unknown[]) =>
147
- start.ports[index]?.postMessage(message, transfer);
85
+
86
+ // A worker that runs out of states asks a peer for some by writing its index + 1 to the peer's
87
+ // request word. The peer sends half of the states it hasn't started, keeps expanding, and wakes
88
+ // the workers waiting to ask it next.
89
+ const answer = (expansion: Expansion, request: number) => {
90
+ const thief = Atomics.load(requests, self) - 1;
91
+ const given = Math.floor((expansion.end - expansion.origin - 1) / 2);
92
+ const encoder = createStateEncoder();
93
+ const states = expansion.states.slice(expansion.end - given, expansion.end);
94
+ const isEncoded = given > 0 && states.every(encoder.encode);
95
+ if (isEncoded) expansion.end -= given;
96
+ const loot = isEncoded ? encoder.finish() : createStateEncoder().finish();
97
+ start.ports[thief]?.postMessage(loot, [loot.words.buffer]);
98
+ Atomics.store(requests, self, request);
99
+ Atomics.notify(requests, self);
100
+ };
101
+
102
+ // A worker answers any request before it pauses or runs out of states, and takes no more until
103
+ // it resumes.
104
+ const lock = (expansion: Expansion) => {
105
+ Atomics.store(remaining, self, 0);
106
+ if (Atomics.compareExchange(requests, self, 0, LOCKED) === 0) return;
107
+ answer(expansion, LOCKED);
108
+ };
109
+
110
+ const unlock = (expansion: Expansion) => {
111
+ Atomics.store(remaining, self, expansion.end - expansion.origin);
112
+ Atomics.store(requests, self, 0);
113
+ };
148
114
 
149
115
  // The worker pauses before a successor when the shared table needs to grow, and resumes there.
150
116
  const expand = (expansion: Expansion) => {
151
- const states = frontier.states;
152
- for (; expansion.origin < states.length; expansion.origin++) {
153
- const state = states[expansion.origin];
117
+ for (; expansion.origin < expansion.end; expansion.origin++) {
118
+ const state = expansion.states[expansion.origin];
154
119
  if (!expansion.successors) {
120
+ if (Atomics.load(requests, self) > 0) answer(expansion, 0);
121
+ Atomics.store(remaining, self, expansion.end - expansion.origin - 1);
155
122
  expansion.successors = getSuccessors(nextAction, state, environment, search.spec.scope);
156
123
  expansion.generated += expansion.successors.length;
157
124
  if (expansion.successors.length === 0 && start.config.checkDeadlock) return undefined;
@@ -161,7 +128,11 @@ const run = (start: StartMessage, parent: Port) => {
161
128
  if (isSharedFingerprintsFull(shared.fingerprints)) return "paused";
162
129
  const successor = successors[expansion.index];
163
130
  if (search.findViolatedActionProperty(state, successor.state)) return undefined;
164
- if (!search.satisfiesActionConstraints(state, successor.state)) continue;
131
+ if (!search.satisfiesActionConstraints(state, successor.state)) {
132
+ // TLC checks the invariants of every successor it has not seen, even outside the model.
133
+ if (search.findViolatedInvariant(successor.state, state)) return undefined;
134
+ continue;
135
+ }
165
136
  if (generatedStates) {
166
137
  writeStateFingerprint(successor.state, fingerprint);
167
138
  if (!generatedStates.insert(fingerprint[0], fingerprint[1])) continue;
@@ -174,69 +145,85 @@ const run = (start: StartMessage, parent: Port) => {
174
145
  if (!search.satisfiesConstraints(successor.state, state)) continue;
175
146
  expansion.next.push(successor.state);
176
147
  expansion.fingerprintStates.push(fingerprintState);
177
- expansion.newStates[expansion.origin]++;
148
+ expansion.added++;
178
149
  }
150
+ expansion.outDegrees[Math.min(expansion.added, OUT_DEGREE_BUCKETS - 1)]++;
179
151
  expansion.successors = undefined;
180
152
  expansion.index = 0;
153
+ expansion.added = 0;
181
154
  }
182
155
  return "done";
183
156
  };
184
157
 
185
- const balance = async (level: number, next: Value[][], sizes: number[]) => {
186
- const transfers = getBalancePlan(sizes);
187
- if (transfers.length === 0) return true;
188
- const outgoing = new Map(peers.map((peer) => [peer.index, createStateEncoder()]));
189
- for (const transfer of transfers.filter((candidate) => candidate.from === self)) {
190
- const encoder = outgoing.get(transfer.to);
191
- const states = next.splice(next.length - transfer.count, transfer.count);
192
- if (!encoder || !states.every(encoder.encode)) return false;
158
+ // Each attempt asks the peer with the most states left. While another worker's request to that
159
+ // peer is open, the worker waits for the peer to answer it. The worker stops once no peer that
160
+ // takes requests has two states left.
161
+ const steal = async (expansion: Expansion) => {
162
+ const skipped = new Set<number>();
163
+ for (;;) {
164
+ const victim = start.ports.reduce<number | undefined>((best, port, index) => {
165
+ if (!port || skipped.has(index) || Atomics.load(remaining, index) < 2) return best;
166
+ return best === undefined || Atomics.load(remaining, index) > Atomics.load(remaining, best)
167
+ ? index
168
+ : best;
169
+ }, undefined);
170
+ if (victim === undefined) return false;
171
+ const request = Atomics.compareExchange(requests, victim, 0, self + 1);
172
+ if (request === LOCKED) skipped.add(victim);
173
+ if (request > 0) Atomics.wait(requests, victim, request);
174
+ if (request !== 0) continue;
175
+ const loot = await new Promise<EncodedStates>((resolve) => (waiters.loot = resolve));
176
+ if (loot.count === 0) {
177
+ skipped.add(victim);
178
+ continue;
179
+ }
180
+ expansion.states = decode(loot).map(canonicalize);
181
+ expansion.origin = 0;
182
+ expansion.end = expansion.states.length;
183
+ unlock(expansion);
184
+ return true;
193
185
  }
194
- outgoing.forEach((encoder, index) => {
195
- const states = encoder.finish();
196
- send(index, { phase: "balance", level, from: self, states }, [states.words.buffer]);
197
- });
198
- const incoming = await inbox.receive("balance", level, peers.length);
199
- incoming.forEach((message) => next.push(...decode(message.states).map(canonicalize)));
200
- return true;
201
186
  };
202
187
 
203
- const waiters = { resume: () => {}, balance: (_sizes: number[]) => {} };
204
188
  const report = (message: WorkerMessage) =>
205
189
  parent.postMessage(message, message.type === "level" ? [message.fingerprints.buffer] : []);
206
190
 
207
191
  const runLevel = async (level: number): Promise<LevelMessage | undefined> => {
208
192
  const expansion: Expansion = {
193
+ states: frontier.states,
209
194
  origin: 0,
195
+ end: frontier.states.length,
210
196
  successors: undefined,
211
197
  index: 0,
198
+ added: 0,
212
199
  generated: 0,
213
- newStates: new Int32Array(frontier.states.length),
200
+ outDegrees: Array.from({ length: OUT_DEGREE_BUCKETS }, () => 0),
214
201
  next: [],
215
202
  fingerprintStates: [],
216
203
  };
217
- for (let status = expand(expansion); status !== "done"; status = expand(expansion)) {
204
+ for (;;) {
205
+ const status = expand(expansion);
218
206
  if (status === undefined) return undefined;
219
- const resumed = new Promise<void>((resolve) => (waiters.resume = resolve));
220
- report({ type: "paused" });
221
- await resumed;
207
+ lock(expansion);
208
+ if (status === "paused") {
209
+ const resumed = new Promise<void>((resolve) => (waiters.resume = resolve));
210
+ report({ type: "paused" });
211
+ await resumed;
212
+ unlock(expansion);
213
+ continue;
214
+ }
215
+ if (!(await steal(expansion))) break;
222
216
  }
223
217
  if (getRankedStringCount() !== startupStrings) return undefined;
224
- const next = expansion.next;
225
- const added = next.length;
226
- const outDegrees = Array.from({ length: OUT_DEGREE_BUCKETS }, () => 0);
227
- expansion.newStates.forEach((degree) => outDegrees[Math.min(degree, OUT_DEGREE_BUCKETS - 1)]++);
228
- const fingerprints = search.getStoredFingerprints(next, expansion.fingerprintStates);
229
- const sizes = new Promise<number[]>((resolve) => (waiters.balance = resolve));
230
- report({ type: "expanded", from: self, added });
231
- if (!(await balance(level, next, await sizes))) return undefined;
232
- frontier.states = next;
218
+ frontier.states = expansion.next;
219
+ Atomics.store(remaining, self, frontier.states.length);
233
220
  return {
234
221
  type: "level",
235
222
  level,
236
223
  generated: expansion.generated,
237
- added,
238
- outDegrees,
239
- fingerprints,
224
+ added: expansion.next.length,
225
+ outDegrees: expansion.outDegrees,
226
+ fingerprints: search.getStoredFingerprints(expansion.next, expansion.fingerprintStates),
240
227
  };
241
228
  };
242
229
 
@@ -253,8 +240,8 @@ const run = (start: StartMessage, parent: Port) => {
253
240
  shared.fingerprints = message.fingerprints;
254
241
  waiters.resume();
255
242
  }
256
- if (message.type === "balance") waiters.balance(message.sizes);
257
243
  });
244
+ Atomics.store(remaining, self, frontier.states.length);
258
245
  report({ type: "ready" });
259
246
  };
260
247
 
package/src/parallel.ts CHANGED
@@ -44,6 +44,8 @@ export interface StartMessage {
44
44
  ports: (Port | undefined)[];
45
45
  seed: EncodedStates;
46
46
  fingerprints: SharedFingerprints;
47
+ requests: Int32Array;
48
+ remaining: Int32Array;
47
49
  }
48
50
 
49
51
  export interface LevelMessage {
@@ -59,13 +61,11 @@ export type WorkerMessage =
59
61
  | { type: "ready" }
60
62
  | { type: "abort" }
61
63
  | { type: "paused" }
62
- | { type: "expanded"; from: number; added: number }
63
64
  | LevelMessage;
64
65
 
65
66
  export type CoordinatorMessage =
66
67
  | { type: "level"; level: number }
67
- | { type: "resize"; fingerprints: SharedFingerprints }
68
- | { type: "balance"; sizes: number[] };
68
+ | { type: "resize"; fingerprints: SharedFingerprints };
69
69
 
70
70
  interface WorkerHandle {
71
71
  postMessage: (message: unknown, transfer?: unknown[]) => void;
@@ -102,11 +102,24 @@ const spawnWorker = async (onMessage: (message: WorkerMessage) => void): Promise
102
102
 
103
103
  export const check = async (options: CheckOptions): Promise<CheckResult> => {
104
104
  const config = typeof options.config === "string" ? parseConfig(options.config) : options.config;
105
- const fallBack = () => checkSequentially({ ...options, config });
105
+ const print = options.onPrint ?? console.log;
106
+ const printed = { count: 0 };
107
+ // The search on the calling thread prints what this one printed while it started, so it skips that.
108
+ const fallBack = () => {
109
+ const skipped = { count: printed.count };
110
+ return checkSequentially({
111
+ ...options,
112
+ config,
113
+ onPrint: (text) => (skipped.count-- > 0 ? undefined : print(text)),
114
+ });
115
+ };
106
116
  const count = options.workers ?? 1;
117
+ // TLC's workers write the -dump state graph in whichever order they find it, so one worker
118
+ // writes the graph a single TLC worker does.
107
119
  const isSequential =
108
120
  count < 2 ||
109
121
  typeof SharedArrayBuffer !== "function" ||
122
+ options.dump !== undefined ||
110
123
  config.view !== undefined ||
111
124
  config.postconditions.length > 0 ||
112
125
  config.possible.length > 0;
@@ -129,7 +142,10 @@ export const check = async (options: CheckOptions): Promise<CheckResult> => {
129
142
  source: options.source,
130
143
  loadModule,
131
144
  loadClass,
132
- print: options.onPrint ?? console.log,
145
+ print: (text) => {
146
+ printed.count++;
147
+ print(text);
148
+ },
133
149
  files: { readFile: options.readFile, writeFile: options.writeFile },
134
150
  });
135
151
  const environment = specification.environment;
@@ -225,6 +241,8 @@ export const check = async (options: CheckOptions): Promise<CheckResult> => {
225
241
  pending.resolve = resolve;
226
242
  });
227
243
  const ready = waitForReports(count);
244
+ const requests = new Int32Array(new SharedArrayBuffer(count * 4));
245
+ const remaining = new Int32Array(new SharedArrayBuffer(count * 4));
228
246
  const workers = await Promise.all(Array.from({ length: count }, () => spawnWorker(onMessage)));
229
247
  const terminate = () => workers.forEach((worker) => worker.terminate());
230
248
  const channels = new Map<string, MessageChannel>();
@@ -249,6 +267,8 @@ export const check = async (options: CheckOptions): Promise<CheckResult> => {
249
267
  ports,
250
268
  seed,
251
269
  fingerprints: shared.fingerprints,
270
+ requests,
271
+ remaining,
252
272
  };
253
273
  worker.postMessage(message, [...ports.filter((port) => port !== undefined), seed.words.buffer]);
254
274
  });
@@ -257,34 +277,25 @@ export const check = async (options: CheckOptions): Promise<CheckResult> => {
257
277
  const send = (message: CoordinatorMessage) =>
258
278
  workers.forEach((worker) => worker.postMessage(message));
259
279
  // Workers pause when the shared table needs to grow, and resume once it has.
260
- const collectExpansions = async (messages: WorkerMessage[]): Promise<WorkerMessage[]> => {
280
+ const collectLevels = async (messages: WorkerMessage[]): Promise<WorkerMessage[]> => {
261
281
  const paused = messages.filter((message) => message.type === "paused").length;
262
282
  if (paused === 0 || isAborted(messages)) return messages;
263
283
  shared.fingerprints = growSharedFingerprints(shared.fingerprints);
264
284
  const resumed = waitForReports(paused);
265
285
  send({ type: "resize", fingerprints: shared.fingerprints });
266
- const expanded = messages.filter((message) => message.type !== "paused");
267
- return [...expanded, ...(await collectExpansions(await resumed))];
286
+ const reported = messages.filter((message) => message.type !== "paused");
287
+ return [...reported, ...(await collectLevels(await resumed))];
268
288
  };
269
289
  if (isAborted(await ready)) {
270
290
  terminate();
271
291
  return fallBack();
272
292
  }
273
293
  for (let level = 1; ; level++) {
274
- const expanding = waitForReports(count);
275
- send({ type: "level", level });
276
- const expansions = await collectExpansions(await expanding);
277
- if (isAborted(expansions)) {
278
- terminate();
279
- return fallBack();
280
- }
281
- const sizes = Array.from({ length: count }, () => 0);
282
- expansions.forEach((message) => {
283
- if (message.type === "expanded") sizes[message.from] = message.added;
284
- });
285
294
  const reported = waitForReports(count);
286
- send({ type: "balance", sizes });
287
- const messages = await reported;
295
+ // Every worker is idle, so peers can ask any of them for states once the level starts.
296
+ requests.forEach((_, index) => Atomics.store(requests, index, 0));
297
+ send({ type: "level", level });
298
+ const messages = await collectLevels(await reported);
288
299
  if (isAborted(messages)) {
289
300
  terminate();
290
301
  return fallBack();
package/src/parser.ts CHANGED
@@ -135,6 +135,8 @@ const INFIX_OPERATORS = new Map<string, InfixOperator>([
135
135
  ["^^", createInfix(14, 14, false)],
136
136
  ]);
137
137
 
138
+ const NEGATION_PRECEDENCE = 12;
139
+
138
140
  const POSTFIX_OPERATORS = new Set(["^+", "^*", "^#"]);
139
141
 
140
142
  const PREFIX_OPERATOR_REFERENCES = new Set(["-", "~", "-."]);
@@ -977,7 +979,12 @@ const parse = (source: string, isTlapm: boolean): Module => {
977
979
  return { kind: "Apply", operator: "~", args: [parseExpression(5)], location };
978
980
  case "-":
979
981
  advance();
980
- return { kind: "Apply", operator: "-.", args: [parseExpression(13)], location };
982
+ return {
983
+ kind: "Apply",
984
+ operator: "-.",
985
+ args: [parseExpression(NEGATION_PRECEDENCE + 1)],
986
+ location,
987
+ };
981
988
  case "[]":
982
989
  advance();
983
990
  return { kind: "Always", expression: parseExpression(16), location };
@@ -1054,6 +1061,10 @@ const parse = (source: string, isTlapm: boolean): Module => {
1054
1061
  }
1055
1062
  }
1056
1063
  advance();
1064
+ // SANY reads - after an infix operator as prefix -, and rejects it after one that binds tighter.
1065
+ if (infix.low > NEGATION_PRECEDENCE && isAt("-")) {
1066
+ throw createError(`Precedence conflict between ${token.text} and -`, peek());
1067
+ }
1057
1068
  const right = parseExpression(infix.high + 1);
1058
1069
  const left = state.left;
1059
1070
  if (token.text === "/\\" || token.text === "\\/") {
package/src/resolve.ts CHANGED
@@ -1,20 +1,21 @@
1
- import type {
2
- AssumeProve,
3
- Bound,
4
- BoundPattern,
5
- Definition,
6
- Expression,
7
- Instance,
8
- Module,
9
- NewSymbol,
10
- OperatorParam,
11
- Proof,
12
- ProofStep,
13
- SourceLocation,
14
- Theorem,
1
+ import {
2
+ getChildren,
3
+ isLocallyResolved,
4
+ type AssumeProve,
5
+ type Bound,
6
+ type BoundPattern,
7
+ type Definition,
8
+ type Expression,
9
+ type Instance,
10
+ type Module,
11
+ type NewSymbol,
12
+ type OperatorParam,
13
+ type Proof,
14
+ type ProofStep,
15
+ type SourceLocation,
16
+ type Theorem,
15
17
  } from "./ast";
16
18
  import { TlaSyntaxError } from "./errors";
17
- import { getChildren, isLocallyResolved } from "./evaluate";
18
19
 
19
20
  export interface ModuleSymbol {
20
21
  key: string;
package/src/run-cli.ts CHANGED
@@ -19,20 +19,22 @@ import {
19
19
  TlaError,
20
20
  TlaEvaluationError,
21
21
  TlaProofError,
22
+ TlaSyntaxError,
22
23
  } from "./errors";
23
24
  import { EXIT_STATUS } from "./exit-codes";
24
25
  import type { LineRange } from "./obligation-generate";
25
26
  import { getAtPrefix, getLocusText } from "./obligation-expression";
26
27
  import { formatSummary, getObligations, WHOLE_MODULE, type ModuleObligations } from "./obligations";
27
28
  import { check } from "./parallel";
28
- import { prettyPrint } from "./pretty-print";
29
+ import { parseModule } from "./parser";
30
+ import type { StateDump } from "./state-graph";
29
31
  import {
30
32
  formatProbability,
31
33
  getActualProbability,
32
34
  getOptimisticProbability,
33
35
  getOutDegreeSummary,
34
36
  } from "./tlc-summary";
35
- import { formatValue, type Value } from "./values";
37
+ import { formatState, type Value } from "./values";
36
38
 
37
39
  const EXIT_CODES: Record<CheckStatus, number> = {
38
40
  success: EXIT_STATUS.success,
@@ -48,6 +50,11 @@ const EXIT_CODES: Record<CheckStatus, number> = {
48
50
  const CHECK_COMMAND = defineCommand("tla-ts <Spec.tla|Spec.cfg|glob>... {options}", [
49
51
  { flag: "-config <Spec.cfg>" },
50
52
  { flag: "-deadlock" },
53
+ // Like TLC, -dump takes a format only when the next argument starts with dot and a file follows.
54
+ {
55
+ flag: "-dump [<format>] <file>",
56
+ getArity: (rest) => (rest.length > 1 && rest[0].startsWith("dot") ? 2 : 1),
57
+ },
51
58
  { flag: "-lncheck <final|default>" },
52
59
  { flag: "-seed <num>" },
53
60
  { flag: "-workers <count|auto>" },
@@ -95,14 +102,24 @@ const getWorkerCount = (values: string[] | undefined) => {
95
102
  : Math.max(1, Number.parseInt(values[0], 10) || 1);
96
103
  };
97
104
 
98
- const printState = (state: Record<string, Value>) => {
99
- const entries = Object.entries(state);
100
- entries.forEach(([name, value]) =>
101
- console.log(
102
- `${entries.length === 1 ? "" : "/\\ "}${name} = ${prettyPrint(formatValue(value))}`,
103
- ),
104
- );
105
- console.log("");
105
+ const printState = (state: Record<string, Value>) => console.log(formatState(state));
106
+
107
+ const UNSUPPORTED_DUMP_FORMATS = ["constrained", "stuttering", "strict"];
108
+
109
+ // TLC names the file of a -dump by its format unless the name already ends that way.
110
+ const getDumpPath = (path: string, extension: string) =>
111
+ path.endsWith(extension) ? path : `${path}${extension}`;
112
+
113
+ const getDump = (values: string[]): StateDump => {
114
+ if (values.length === 1) return { path: getDumpPath(values[0], ".dump") };
115
+ const format = values[0].toLowerCase();
116
+ return {
117
+ path: getDumpPath(values[1], ".dot"),
118
+ dot: true,
119
+ colorize: format.includes("colorize"),
120
+ actionLabels: format.includes("actionlabels"),
121
+ snapshot: format.includes("snapshot"),
122
+ };
106
123
  };
107
124
 
108
125
  const printTrace = (trace: TraceStep[], heading = "Error: The behavior up to this point is:") => {
@@ -113,6 +130,11 @@ const printTrace = (trace: TraceStep[], heading = "Error: The behavior up to thi
113
130
  });
114
131
  };
115
132
 
133
+ const getTemporalHeadline = (names: string[]) =>
134
+ names.length === 1
135
+ ? `Error: Temporal property ${names[0]} was violated.\n`
136
+ : `Error: Temporal properties ${names.slice(0, -1).join(", ")}${names.length > 2 ? "," : ""} and ${names[names.length - 1]} were violated.\n`;
137
+
116
138
  const printResult = (result: CheckResult) => {
117
139
  if (result.failure) {
118
140
  console.log(`Error: ${result.failure.message}`);
@@ -140,10 +162,10 @@ const printResult = (result: CheckResult) => {
140
162
  "invariant-violation": isInitial
141
163
  ? `Error: Invariant ${name} is violated by the initial state:`
142
164
  : `Error: Invariant ${name} is violated.`,
143
- "property-violation": `Error: Property ${name} is violated.`,
165
+ "property-violation": getTemporalHeadline(violation.properties ?? [name]),
144
166
  "liveness-violation":
145
167
  loopStart !== undefined
146
- ? `Error: Temporal property ${name} was violated.\n`
168
+ ? getTemporalHeadline(violation.properties ?? [name])
147
169
  : isInitial
148
170
  ? `Error: Property ${name} is violated by the initial state:`
149
171
  : `Error: Action property ${name} is violated.`,
@@ -152,6 +174,8 @@ const printResult = (result: CheckResult) => {
152
174
  if (violation.counts) console.log(violation.counts);
153
175
  console.log(headline);
154
176
  if (isInitial) printState(violation.trace[0].state);
177
+ else if (result.status === "property-violation")
178
+ printTrace(violation.trace, "Error: The following behavior constitutes a counter-example:\n");
155
179
  else if (loopStart === undefined) printTrace(violation.trace);
156
180
  else {
157
181
  printTrace(violation.trace, "Error: The following behavior constitutes a counter-example:\n");
@@ -191,6 +215,14 @@ const checkSpec = async (specPath: string, args: ParsedArgs) => {
191
215
  console.error(`Cannot find the specification file ${specPath}`);
192
216
  return EXIT_STATUS.configParseError;
193
217
  }
218
+ const source = readFileSync(specPath, "utf8");
219
+ const fileName = basename(specPath, ".tla");
220
+ const moduleName = parseModule(source).name;
221
+ if (moduleName !== fileName) {
222
+ throw new TlaSyntaxError(
223
+ `File name '${fileName}' does not match the name '${moduleName}' of the top level module it contains.`,
224
+ );
225
+ }
194
226
  const configPath =
195
227
  args.get("-config")?.[0] ??
196
228
  (args.has("-config") ? undefined : specPath.replace(/\.tla$/, ".cfg"));
@@ -214,13 +246,26 @@ const checkSpec = async (specPath: string, args: ParsedArgs) => {
214
246
  console.error("Error: expect a strategy such as final for -lncheck option.");
215
247
  return 1;
216
248
  }
249
+ const dumpValues = args.get("-dump");
250
+ if (dumpValues?.length === 0) {
251
+ console.error("Error: A file name for dumping states required.");
252
+ return 1;
253
+ }
254
+ const unsupportedFormat =
255
+ dumpValues?.length === 2 &&
256
+ UNSUPPORTED_DUMP_FORMATS.find((format) => dumpValues[0].toLowerCase().includes(format));
257
+ if (unsupportedFormat) {
258
+ console.error(`Error: tla-ts does not support the -dump format ${unsupportedFormat}.`);
259
+ return 1;
260
+ }
217
261
  const directory = dirname(specPath);
218
262
  console.log(`Checking ${basename(specPath)} with ${basename(configPath)}`);
219
263
  const result = await check({
220
264
  workers: getWorkerCount(args.get("-workers")),
221
265
  livenessCheck: ["final", "seqfinal", "off"].includes(livenessCheck) ? "final" : "default",
222
266
  seed: BigInt(seed),
223
- source: readFileSync(specPath, "utf8"),
267
+ dump: dumpValues && getDump(dumpValues),
268
+ source,
224
269
  config,
225
270
  onPause: () => readSync(0, Buffer.alloc(1)),
226
271
  loadModule: (name) => {
package/src/runtime.ts CHANGED
@@ -6,7 +6,7 @@ export interface CheckerRuntime {
6
6
  getBehavior: (state: Value[]) => Value[][];
7
7
  getSpecification: () => Value;
8
8
  counterExample: Value | undefined;
9
- setLivenessSource: (index: number) => void;
9
+ setLivenessSource: (index: number | undefined) => void;
10
10
  getCurrentState: () => Value[] | undefined;
11
11
  getFingerprint: (state: Value[]) => bigint;
12
12
  getRandom: () => JavaRandom;
@@ -24,6 +24,7 @@ export interface CheckerRuntime {
24
24
  properties: Map<string, string>;
25
25
  possibleCounts: Map<string, number>;
26
26
  isStopped: boolean;
27
+ isStarted: boolean;
27
28
  checkDeadlock: boolean;
28
29
  startedAt: number;
29
30
  }
@@ -75,6 +76,7 @@ export const createRuntime = (checkDeadlock: boolean, seed = 0n): CheckerRuntime
75
76
  properties: new Map(),
76
77
  possibleCounts: new Map(),
77
78
  isStopped: false,
79
+ isStarted: false,
78
80
  checkDeadlock,
79
81
  startedAt: Date.now(),
80
82
  };