tla-ts 0.0.3-dev.3c70a97 → 0.0.3-dev.4b28a29

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.
package/src/live-check.ts CHANGED
@@ -2,6 +2,7 @@ import { TlaEvaluationError } from "./errors";
2
2
  import { hasRepeatedEffects, type Environment } from "./evaluate";
3
3
  import {
4
4
  evaluateLive,
5
+ TAUTOLOGY_MESSAGE,
5
6
  evaluateOnLasso,
6
7
  toLiveExpression,
7
8
  type ScopedExpression,
@@ -11,6 +12,7 @@ import {
11
12
  createJunction,
12
13
  createUnary,
13
14
  getSolutions,
15
+ getTermKey,
14
16
  isFulfilling,
15
17
  type LiveExpression,
16
18
  type Solution,
@@ -47,37 +49,21 @@ interface Check {
47
49
  actionIds: Int32Array;
48
50
  nodeStates: number[];
49
51
  nodeTableaux: number[];
50
- successors: number[][];
51
- actions: Uint8Array[];
52
- stateResults: Uint8Array[];
53
- isWritten: boolean[];
52
+ // The successors a node gathers until it is written.
53
+ pending: (number[] | undefined)[];
54
+ // Each written node's state results, then its action results edge by edge, from the node's
55
+ // offset in one buffer, so a node costs no objects of its own. An unwritten node has offset -1.
56
+ offsets: number[];
57
+ results: { bytes: Uint8Array; length: number };
58
+ // Each written node's successor count, then its successors, from the node's edge offset.
59
+ edgeOffsets: number[];
60
+ edges: { ids: Int32Array; length: number };
54
61
  initial: number[];
55
- nodeIds: Map<number, number>;
56
- nodesByState: Map<number, number[]>;
62
+ nodeIds: NodeTable;
57
63
  isDone: boolean[];
58
64
  errorNode: number | undefined;
59
65
  }
60
66
 
61
- const liveKeys = new WeakMap<LiveExpression, string>();
62
-
63
- const atomCount = { value: 0 };
64
-
65
- // Each solution builds its own junctions over shared atoms, so equal checks get equal keys.
66
- const getLiveKey = (expression: LiveExpression): string => {
67
- const cached = liveKeys.get(expression);
68
- if (cached !== undefined) return cached;
69
- const key =
70
- expression.kind === "Boolean"
71
- ? String(expression.value)
72
- : "body" in expression
73
- ? `${expression.kind}(${getLiveKey(expression.body)})`
74
- : "operands" in expression
75
- ? `${expression.kind}(${expression.operands.map(getLiveKey).join(",")})`
76
- : `${expression.kind}#${atomCount.value++}`;
77
- liveKeys.set(expression, key);
78
- return key;
79
- };
80
-
81
67
  const isSameState = (left: Value[], right: Value[]) =>
82
68
  left.every((value, position) => isSameValue(value, right[position]));
83
69
 
@@ -88,13 +74,43 @@ const removeRepeats = (path: number[]) =>
88
74
  const pushNode = (check: Check, state: number, tableauNode: number) => {
89
75
  check.nodeStates.push(state);
90
76
  check.nodeTableaux.push(tableauNode);
91
- check.successors.push([]);
92
- check.actions.push(new Uint8Array(0));
93
- check.stateResults.push(new Uint8Array(0));
94
- check.isWritten.push(false);
77
+ check.pending.push(undefined);
78
+ check.offsets.push(-1);
79
+ check.edgeOffsets.push(-1);
95
80
  return check.nodeStates.length - 1;
96
81
  };
97
82
 
83
+ // A Map holds at most 2^24 entries, so each tableau node of a state finds its node in an
84
+ // open-addressing table of (state plus one, tableau node, node) triples.
85
+ interface NodeTable {
86
+ slots: Int32Array;
87
+ size: number;
88
+ shift: number;
89
+ }
90
+
91
+ const getNodeSlot = (table: NodeTable, state: number, tableauNode: number) => {
92
+ const mask = table.slots.length / 3 - 1;
93
+ const hash = Math.imul(Math.imul(state, 0x9e3779b1) ^ tableauNode, 0x85ebca6b) >>> table.shift;
94
+ for (let index = hash; ; index = (index + 1) & mask) {
95
+ const slot = index * 3;
96
+ const stored = table.slots[slot];
97
+ if (stored === 0 || (stored === state + 1 && table.slots[slot + 1] === tableauNode))
98
+ return slot;
99
+ }
100
+ };
101
+
102
+ const isWritten = (check: Check, node: number) => check.offsets[node] !== -1;
103
+
104
+ const getPending = (check: Check, node: number) => (check.pending[node] ??= []);
105
+
106
+ const getSuccessors = (check: Check, node: number) => {
107
+ const offset = check.edgeOffsets[node];
108
+ return check.edges.ids.subarray(offset + 1, offset + 1 + check.edges.ids[offset]);
109
+ };
110
+
111
+ const getStateResult = (check: Check, node: number, position: number) =>
112
+ check.results.bytes[check.offsets[node] + position] === 1;
113
+
98
114
  const SUCCESSOR_CAPACITY = 16;
99
115
 
100
116
  const SCC_MARKER = -42;
@@ -121,26 +137,26 @@ export const createLivenessChecker = (
121
137
  fairness.length === 0 ? violation : createJunction("And", [...fairness, violation]);
122
138
  const solutions = getSolutions(formula);
123
139
  if (solutions.length === 0) {
124
- throw new TlaEvaluationError("Temporal formula is a tautology (its negation is unsatisfiable)");
140
+ throw new TlaEvaluationError(TAUTOLOGY_MESSAGE);
125
141
  }
126
142
  const actionIds = new Map<string, number>();
127
143
  const checks = solutions.map((solution): Check => ({
128
144
  solution,
129
145
  actionIds: Int32Array.from(solution.actionChecks, (predicate) => {
130
- const key = getLiveKey(predicate);
146
+ const key = getTermKey(predicate);
131
147
  const id = actionIds.get(key) ?? actionIds.size;
132
148
  actionIds.set(key, id);
133
149
  return id;
134
150
  }),
135
151
  nodeStates: [],
136
152
  nodeTableaux: [],
137
- successors: [],
138
- actions: [],
139
- stateResults: [],
140
- isWritten: [],
153
+ pending: [],
154
+ offsets: [],
155
+ results: { bytes: new Uint8Array(1024), length: 0 },
156
+ edgeOffsets: [],
157
+ edges: { ids: new Int32Array(1024), length: 0 },
141
158
  initial: [],
142
- nodeIds: new Map(),
143
- nodesByState: new Map(),
159
+ nodeIds: { slots: new Int32Array(3 << 10), size: 0, shift: 22 },
144
160
  isDone: [],
145
161
  errorNode: undefined,
146
162
  }));
@@ -226,18 +242,35 @@ export const createLivenessChecker = (
226
242
  model.infinitelyOftenActions.length === 0,
227
243
  );
228
244
 
229
- const getNodeId = (check: Check, state: number, tableauNode: number) =>
230
- check.solution.tableau
231
- ? check.nodeIds.get(state * check.solution.tableau.nodes.length + tableauNode)
232
- : state;
245
+ const getNodeId = (check: Check, state: number, tableauNode: number) => {
246
+ if (!check.solution.tableau) return state;
247
+ const slots = check.nodeIds.slots;
248
+ const slot = getNodeSlot(check.nodeIds, state, tableauNode);
249
+ return slots[slot] === 0 ? undefined : slots[slot + 2];
250
+ };
233
251
  const recordNode = (check: Check, state: number, tableauNode: number) => {
234
252
  const node = pushNode(check, state, tableauNode);
235
- check.nodeIds.set(state * (check.solution.tableau?.nodes.length ?? 1) + tableauNode, node);
236
- const siblings = check.nodesByState.get(state);
237
- if (siblings) siblings.push(node);
238
- else check.nodesByState.set(state, [node]);
253
+ const table = check.nodeIds;
254
+ if (++table.size * 2 > table.slots.length / 3) {
255
+ const old = table.slots;
256
+ table.slots = new Int32Array(old.length * 2);
257
+ table.shift--;
258
+ for (let slot = 0; slot < old.length; slot += 3) {
259
+ if (old[slot] !== 0)
260
+ table.slots.set(
261
+ old.subarray(slot, slot + 3),
262
+ getNodeSlot(table, old[slot] - 1, old[slot + 1]),
263
+ );
264
+ }
265
+ }
266
+ table.slots.set([state + 1, tableauNode, node], getNodeSlot(table, state, tableauNode));
239
267
  return node;
240
268
  };
269
+ // A state's nodes in the order they were recorded, which is the order of their ids.
270
+ const getStateNodes = (check: Check, tableau: Tableau, state: number) =>
271
+ tableau.nodes
272
+ .flatMap((_, tableauNode) => getNodeId(check, state, tableauNode) ?? [])
273
+ .sort((left, right) => left - right);
241
274
  const writeNode = (
242
275
  check: Check,
243
276
  node: number,
@@ -245,11 +278,32 @@ export const createLivenessChecker = (
245
278
  stateResults: Uint8Array,
246
279
  ) => {
247
280
  const actionCount = check.solution.actionChecks.length;
248
- const packed = new Uint8Array(actions.length * actionCount);
249
- actions.forEach((results, position) => packed.set(results, position * actionCount));
250
- check.actions[node] = packed;
251
- check.stateResults[node] = stateResults;
252
- check.isWritten[node] = true;
281
+ const results = check.results;
282
+ const offset = results.length;
283
+ results.length += stateResults.length + actions.length * actionCount;
284
+ if (results.length > results.bytes.length) {
285
+ const grown = new Uint8Array(Math.max(2 * results.bytes.length, results.length));
286
+ grown.set(results.bytes);
287
+ results.bytes = grown;
288
+ }
289
+ results.bytes.set(stateResults, offset);
290
+ actions.forEach((edge, position) =>
291
+ results.bytes.set(edge, offset + stateResults.length + position * actionCount),
292
+ );
293
+ check.offsets[node] = offset;
294
+ const successors = check.pending[node] ?? [];
295
+ const edges = check.edges;
296
+ const edgeOffset = edges.length;
297
+ edges.length += successors.length + 1;
298
+ if (edges.length > edges.ids.length) {
299
+ const grown = new Int32Array(Math.max(2 * edges.ids.length, edges.length));
300
+ grown.set(edges.ids);
301
+ edges.ids = grown;
302
+ }
303
+ edges.ids[edgeOffset] = successors.length;
304
+ edges.ids.set(successors, edgeOffset + 1);
305
+ check.edgeOffsets[node] = edgeOffset;
306
+ check.pending[node] = undefined;
253
307
  };
254
308
 
255
309
  // TLC collects a state's successors and the state itself in a SetOfStates, a hash set it
@@ -302,7 +356,7 @@ export const createLivenessChecker = (
302
356
  const stateResults = checkState(check, index, state);
303
357
  const tableauNode = tableau.nodes[check.nodeTableaux[node]];
304
358
  const actions: Uint8Array[] = [];
305
- const successors = check.successors[node];
359
+ const successors = getPending(check, node);
306
360
  const selfActions =
307
361
  tableauNode.successors.length > 0
308
362
  ? checkAction(check, index, state, state)
@@ -351,8 +405,8 @@ export const createLivenessChecker = (
351
405
  );
352
406
  check.isDone[index] = true;
353
407
  // TLC expands the nodes recorded before the loop, not the ones the loop records.
354
- for (const node of (check.nodesByState.get(index) ?? []).slice()) {
355
- const successors = check.successors[node];
408
+ for (const node of getStateNodes(check, tableau, index)) {
409
+ const successors = getPending(check, node);
356
410
  const actions: Uint8Array[] = [];
357
411
  set.forEach((successor, position) => {
358
412
  const isDone = check.isDone[successor.index] === true;
@@ -386,10 +440,10 @@ export const createLivenessChecker = (
386
440
  index: number,
387
441
  ) => {
388
442
  while (check.nodeStates.length <= index) pushNode(check, check.nodeStates.length, -1);
389
- const successors = check.successors[index];
443
+ const successors = getPending(check, index);
390
444
  const actions: Uint8Array[] = [];
391
445
  set.forEach((successor, position) => {
392
- if (check.isWritten[successor.index] && successors.includes(successor.index)) return;
446
+ if (isWritten(check, successor.index) && successors.includes(successor.index)) return;
393
447
  successors.push(successor.index);
394
448
  actions.push(actionResults[position]);
395
449
  });
@@ -403,20 +457,20 @@ export const createLivenessChecker = (
403
457
  const parents = new Map<number, number>();
404
458
  const queue: number[] = [];
405
459
  for (const node of check.initial) {
406
- if (!check.isWritten[node]) continue;
460
+ if (!isWritten(check, node)) continue;
407
461
  queue.push(node);
408
462
  parents.set(node, -1);
409
463
  }
410
464
  for (let position = 0; position < queue.length; position++) {
411
465
  const current = queue[position];
412
- for (const next of check.successors[current]) {
466
+ for (const next of getSuccessors(check, current)) {
413
467
  if (next === current && check.solution.tableau) continue;
414
468
  if (next === target) {
415
469
  const path = [target];
416
470
  for (let node = current; node !== -1; node = parents.get(node) ?? -1) path.push(node);
417
471
  return path;
418
472
  }
419
- if (!check.isWritten[next] || parents.has(next)) continue;
473
+ if (!isWritten(check, next) || parents.has(next)) continue;
420
474
  parents.set(next, current);
421
475
  queue.push(next);
422
476
  }
@@ -428,16 +482,17 @@ export const createLivenessChecker = (
428
482
  const findInModel = (check: Check, model: Solution["models"][number]): Lasso | undefined => {
429
483
  const solution = check.solution;
430
484
  const actionCount = solution.actionChecks.length;
485
+ const stateCount = solution.stateChecks.length;
431
486
  const getAction = (node: number, edge: number, position: number) =>
432
- check.actions[node][edge * actionCount + position] === 1;
487
+ check.results.bytes[check.offsets[node] + stateCount + edge * actionCount + position] === 1;
433
488
  const isAllowed = (node: number, edge: number) =>
434
489
  model.eventuallyAlways.every((position) => getAction(node, edge, position));
435
490
  const links = new Float64Array(check.nodeStates.length).fill(UNVISITED);
436
- const queue = check.initial.filter((node) => check.isWritten[node]);
491
+ const queue = check.initial.filter((node) => isWritten(check, node));
437
492
  const components: number[] = [];
438
493
 
439
494
  const isStuttering = (node: number) => {
440
- const edge = check.successors[node].indexOf(node);
495
+ const edge = getSuccessors(check, node).indexOf(node);
441
496
  return edge !== -1 && isAllowed(node, edge);
442
497
  };
443
498
  const isFulfilled = (node: number, promise: Solution["promises"][number]) =>
@@ -461,11 +516,11 @@ export const createLivenessChecker = (
461
516
  if (member === root) break;
462
517
  }
463
518
  const isStateSatisfied = model.infinitelyOftenStates.every((position) =>
464
- [...members].some((node) => check.stateResults[node][position] === 1),
519
+ [...members].some((node) => getStateResult(check, node, position)),
465
520
  );
466
521
  const isActionSatisfied = model.infinitelyOftenActions.every((position) =>
467
522
  [...members].some((node) =>
468
- check.successors[node].some(
523
+ getSuccessors(check, node).some(
469
524
  (next, edge) =>
470
525
  members.has(next) && isAllowed(node, edge) && getAction(node, edge, position),
471
526
  ),
@@ -506,7 +561,7 @@ export const createLivenessChecker = (
506
561
  const countAtStart = remaining.count;
507
562
  while (true) {
508
563
  model.infinitelyOftenStates.forEach((position, slot) => {
509
- if (!stateDone[slot] && check.stateResults[current.node][position] === 1) {
564
+ if (!stateDone[slot] && getStateResult(check, current.node, position)) {
510
565
  stateDone[slot] = true;
511
566
  remaining.count--;
512
567
  }
@@ -520,7 +575,7 @@ export const createLivenessChecker = (
520
575
  if (remaining.count <= 0) break;
521
576
  const step = { last: -1, unvisited: -1 };
522
577
  const countBeforeActions = remaining.count;
523
- const successors = check.successors[current.node];
578
+ const successors = getSuccessors(check, current.node);
524
579
  const taken = successors.some((next, edge) => {
525
580
  if (membersByState.has(check.nodeStates[next])) {
526
581
  if (!isMember(next) || !isAllowed(current.node, edge)) return false;
@@ -555,7 +610,8 @@ export const createLivenessChecker = (
555
610
  }
556
611
  current.node = previous;
557
612
  step.unvisited =
558
- check.successors[previous].find((next) => isMember(next) && !seen.has(next)) ?? -1;
613
+ getSuccessors(check, previous).find((next) => isMember(next) && !seen.has(next)) ??
614
+ -1;
559
615
  }
560
616
  take(step.unvisited);
561
617
  seen.add(step.unvisited);
@@ -585,7 +641,7 @@ export const createLivenessChecker = (
585
641
  const queue: [number, number][] = [];
586
642
  for (let state = start, parent = -1, position = 0; ; position++) {
587
643
  for (const node of membersByState.get(state) ?? []) {
588
- for (const [edge, next] of check.successors[node].entries()) {
644
+ for (const [edge, next] of getSuccessors(check, node).entries()) {
589
645
  if (next === node || !isAllowedEdge(node, edge)) continue;
590
646
  if (next === root) {
591
647
  const path: number[] = [];
@@ -638,8 +694,8 @@ export const createLivenessChecker = (
638
694
  stack.push(lowLink, node, SCC_MARKER);
639
695
  components.push(node);
640
696
  const nextLowLink = { value: counter.link++ };
641
- check.successors[node].forEach((next, edge) => {
642
- if (!check.isWritten[next]) return;
697
+ getSuccessors(check, node).forEach((next, edge) => {
698
+ if (!isWritten(check, next)) return;
643
699
  if (!isAllowed(node, edge)) {
644
700
  if (links[next] === UNVISITED) queue.push(next);
645
701
  return;
package/src/liveness.ts CHANGED
@@ -1,7 +1,9 @@
1
1
  import { isLocallyResolved, type Definition, type Expression } from "./ast";
2
2
  import { TlaConfigError, TlaEvaluationError } from "./errors";
3
+ import { EXIT_STATUS, setExitCode } from "./exit-codes";
3
4
  import {
4
5
  describeLocation,
6
+ describeRange,
5
7
  bindDefinitions,
6
8
  bindOperatorArguments,
7
9
  evaluate,
@@ -36,6 +38,10 @@ export interface ScopedExpression {
36
38
  scope: Scope | undefined;
37
39
  }
38
40
 
41
+ export interface NamedExpression extends ScopedExpression {
42
+ name: string;
43
+ }
44
+
39
45
  export interface TemporalProperty extends ScopedExpression {
40
46
  name: string;
41
47
  }
@@ -144,21 +150,27 @@ const getDefinitionLevel = (definition: Definition, environment: Environment) =>
144
150
  return level;
145
151
  };
146
152
 
153
+ export const TAUTOLOGY_MESSAGE = "Temporal formula is a tautology (its negation is unsatisfiable).";
154
+
155
+ // TLC names each part of a property after the operator it expands, or after the location of the
156
+ // conjunct or quantifier body it splits off.
147
157
  export const expandTemporal = (
148
158
  expression: Expression,
149
159
  scope: Scope | undefined,
150
160
  environment: Environment,
151
- isUnrollingForall: boolean,
161
+ isProperty: boolean,
162
+ name = "",
152
163
  expanding = new Set<Definition>(),
153
- ): ScopedExpression[] => {
164
+ ): NamedExpression[] => {
154
165
  const expand = (
155
166
  child: Expression,
156
167
  childScope: Scope | undefined,
168
+ childName = name,
157
169
  childExpanding = expanding,
158
- ): ScopedExpression[] =>
159
- expandTemporal(child, childScope, environment, isUnrollingForall, childExpanding);
170
+ ): NamedExpression[] =>
171
+ expandTemporal(child, childScope, environment, isProperty, childName, childExpanding);
160
172
  if (expression.kind === "And") {
161
- return expression.operands.flatMap((operand) => expand(operand, scope));
173
+ return expression.operands.flatMap((operand) => expand(operand, scope, describeRange(operand)));
162
174
  }
163
175
  if (expression.kind === "Label") return expand(expression.body, scope);
164
176
  if (expression.kind === "Let") {
@@ -181,33 +193,58 @@ export const expandTemporal = (
181
193
  if (expanding.has(definition)) {
182
194
  throw new TlaConfigError(`The definition of ${expression.name} refers to itself`);
183
195
  }
184
- return expand(definition.body, undefined, new Set([...expanding, definition]));
196
+ return expand(
197
+ definition.body,
198
+ undefined,
199
+ expression.name,
200
+ new Set([...expanding, definition]),
201
+ );
185
202
  }
186
203
  }
187
204
  const context = getConstantContext(environment, scope);
188
- if (expression.kind === "Apply" && getLevel(expression, scope, environment) === TEMPORAL_LEVEL) {
205
+ // A property expands every operator it applies and unrolls every \A over constant sets, but a
206
+ // specification only expands the temporal ones.
207
+ const isExpanded = (child: Expression) =>
208
+ isProperty || getLevel(child, scope, environment) === TEMPORAL_LEVEL;
209
+ if (expression.kind === "Apply" && isExpanded(expression)) {
189
210
  const operator = resolveApplyOperator(expression, context);
190
211
  const definition = isLocallyResolved(expression)
191
212
  ? undefined
192
213
  : getDefinition(expression.operator, environment);
193
- if (operator?.kind === "Closure" && !definition?.isRecursive) {
194
- return expand(operator.body, bindOperatorArguments(operator, expression.args, context));
214
+ const isExpandable =
215
+ operator?.kind === "Closure" &&
216
+ operator.params.length === expression.args.length &&
217
+ !definition?.isRecursive;
218
+ if (isExpandable) {
219
+ return expand(
220
+ operator.body,
221
+ bindOperatorArguments(operator, expression.args, context),
222
+ expression.operator,
223
+ );
195
224
  }
196
225
  }
197
226
  const isUnrolled =
198
- isUnrollingForall &&
227
+ isProperty &&
199
228
  expression.kind === "Forall" &&
200
- getLevel(expression.body, scope, environment) === TEMPORAL_LEVEL &&
201
229
  expression.bounds.every((bound) => getLevel(bound.set, scope, environment) === 0);
202
230
  if (isUnrolled) {
203
- const expanded: ScopedExpression[] = [];
231
+ const expanded: NamedExpression[] = [];
232
+ const bindings = { count: 0 };
204
233
  forEachBinding(expression.bounds, context, (boundScope) => {
205
- expanded.push(...expand(expression.body, boundScope));
234
+ bindings.count++;
235
+ expanded.push(...expand(expression.body, boundScope, describeRange(expression.body)));
206
236
  return false;
207
237
  });
238
+ // TLC rejects a property that quantifies over no elements before it checks anything.
239
+ if (bindings.count === 0) {
240
+ throw setExitCode(
241
+ new TlaEvaluationError(TAUTOLOGY_MESSAGE),
242
+ EXIT_STATUS.livenessEvaluationFailure,
243
+ );
244
+ }
208
245
  return expanded;
209
246
  }
210
- return [{ expression, scope }];
247
+ return [{ expression, scope, name }];
211
248
  };
212
249
 
213
250
  const bindLetDefinitions = (
package/src/parallel.ts CHANGED
@@ -114,9 +114,12 @@ export const check = async (options: CheckOptions): Promise<CheckResult> => {
114
114
  });
115
115
  };
116
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.
117
119
  const isSequential =
118
120
  count < 2 ||
119
121
  typeof SharedArrayBuffer !== "function" ||
122
+ options.dump !== undefined ||
120
123
  config.view !== undefined ||
121
124
  config.postconditions.length > 0 ||
122
125
  config.possible.length > 0;
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:") => {
@@ -198,6 +215,14 @@ const checkSpec = async (specPath: string, args: ParsedArgs) => {
198
215
  console.error(`Cannot find the specification file ${specPath}`);
199
216
  return EXIT_STATUS.configParseError;
200
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
+ }
201
226
  const configPath =
202
227
  args.get("-config")?.[0] ??
203
228
  (args.has("-config") ? undefined : specPath.replace(/\.tla$/, ".cfg"));
@@ -221,13 +246,26 @@ const checkSpec = async (specPath: string, args: ParsedArgs) => {
221
246
  console.error("Error: expect a strategy such as final for -lncheck option.");
222
247
  return 1;
223
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
+ }
224
261
  const directory = dirname(specPath);
225
262
  console.log(`Checking ${basename(specPath)} with ${basename(configPath)}`);
226
263
  const result = await check({
227
264
  workers: getWorkerCount(args.get("-workers")),
228
265
  livenessCheck: ["final", "seqfinal", "off"].includes(livenessCheck) ? "final" : "default",
229
266
  seed: BigInt(seed),
230
- source: readFileSync(specPath, "utf8"),
267
+ dump: dumpValues && getDump(dumpValues),
268
+ source,
231
269
  config,
232
270
  onPause: () => readSync(0, Buffer.alloc(1)),
233
271
  loadModule: (name) => {
package/src/runtime.ts CHANGED
@@ -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
  };
@@ -469,10 +469,17 @@ export const getNextActions = (
469
469
  instanceActions: Map<string, InstanceAction>,
470
470
  ) => describe(config, environment, instanceActions).actions;
471
471
 
472
- export const getActionLabel = (action: SpecAction) => {
473
- const parameters = action.parameters.map((parameter) => formatValue(parameter[1]));
474
- return `${action.name === UNNAMED_ACTION ? "Action" : action.name}${parameters.length === 0 ? "" : `(${parameters.join(",")})`} ${formatRange(action.location.range ?? BUILTIN_RANGE)}`;
475
- };
472
+ const formatParameters = (action: SpecAction) =>
473
+ action.parameters.length === 0
474
+ ? ""
475
+ : `(${action.parameters.map((parameter) => formatValue(parameter[1])).join(",")})`;
476
+
477
+ export const getActionLabel = (action: SpecAction) =>
478
+ `${action.name === UNNAMED_ACTION ? "Action" : action.name}${formatParameters(action)} ${formatRange(action.location.range ?? BUILTIN_RANGE)}`;
479
+
480
+ // TLC's Action.getInvocationSignature, which names the action and the values of its parameters.
481
+ export const getActionSignature = (action: SpecAction) =>
482
+ `${action.name}${formatParameters(action)}`;
476
483
 
477
484
  export const getSpecificationValue = (
478
485
  config: ModelConfig,