tla-ts 0.0.3-dev.3c70a97 → 0.0.3-dev.45d0f50

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/evaluate.ts CHANGED
@@ -30,23 +30,26 @@ import {
30
30
  createSortedSet,
31
31
  createWrittenRecord,
32
32
  createTuple,
33
+ describeMissingField,
33
34
  formatValue,
34
35
  getDomain,
35
36
  getFunctionDomain,
36
37
  getIntervalElements,
37
38
  getSequenceElements,
38
39
  getValueHash,
39
- isEnumerable,
40
40
  isFunctionValue,
41
41
  isOverriddenSet,
42
+ isRecordValue,
42
43
  isSameValue,
43
44
  markLambdaFunction,
45
+ isReducible,
44
46
  isSetValue,
45
47
  MAXIMUM_INTEGER,
46
48
  MINIMUM_INTEGER,
47
49
  toFiniteSet,
48
50
  updateFunction,
49
51
  valuesEqual,
52
+ type FunctionValue,
50
53
  type LazyFunctionSource,
51
54
  type LazyFunctionValue,
52
55
  type Value,
@@ -182,8 +185,17 @@ export const getConjunctError = (
182
185
  };
183
186
 
184
187
  export const getFieldError =
185
- (expression: Expression & { kind: "FieldAccess" }) => (record: Value) =>
186
- `Attempted to select nonexistent field "${expression.field}" from the record\n${formatValue(record)}\n${describeRange(expression)}`;
188
+ (expression: Expression & { kind: "FieldAccess" }) => (record: FunctionValue) =>
189
+ isRecordValue(record)
190
+ ? `Attempted to select nonexistent field "${expression.field}" from the record\n${formatValue(record)}\n${describeRange(expression)}`
191
+ : describeMissingField(record, expression.field);
192
+
193
+ export const getNonFunctionError = (expression: Expression) => (value: Value) =>
194
+ `A non-function (${getKindString(value)}) was applied as a function.\n${describeRange(expression)}`;
195
+
196
+ export const getNonRecordError =
197
+ (expression: Expression & { kind: "FieldAccess" }) => (value: Value) =>
198
+ `Attempted to select field "${expression.field}" from a non-record value ${formatValue(value)}\n${describeRange(expression)}`;
187
199
 
188
200
  export const getDomainOperator = (expression: Expression) => (value: Value) => {
189
201
  if (!isFunctionValue(value)) {
@@ -1027,7 +1039,7 @@ export const getEvaluator = (expression: Expression, environment: Environment):
1027
1039
 
1028
1040
  const entryEvaluators = new WeakMap<Expression, Evaluator>();
1029
1041
 
1030
- const getEntryEvaluator = (expression: Expression, environment: Environment) => {
1042
+ export const getEntryEvaluator = (expression: Expression, environment: Environment) => {
1031
1043
  const cached = entryEvaluators.get(expression);
1032
1044
  if (cached) return cached;
1033
1045
  const evaluator =
@@ -1325,6 +1337,11 @@ const compileApply = (
1325
1337
  if (definition?.kind === "Function") {
1326
1338
  throw new TlaEvaluationError(`${expression.operator} is a function; apply it with brackets`);
1327
1339
  }
1340
+ if (expression.operator === "\\cdot") {
1341
+ throw new TlaEvaluationError(
1342
+ "The current version of TLC does not support action composition. An incomplete implementation can be enabled via the tlc2.tool.impl.Tool.cdot=true java property.",
1343
+ );
1344
+ }
1328
1345
  throw new TlaEvaluationError(
1329
1346
  `Unknown operator ${expression.operator} at ${describeLocation(expression)}`,
1330
1347
  );
@@ -1420,7 +1437,13 @@ const compileFunctionConstruction = (
1420
1437
  const set = getEvaluator(bound.set, environment);
1421
1438
  return (context) => {
1422
1439
  const domain = isSingleName ? set(context) : getBoundsDomain(bounds, context);
1423
- if (expression.isRecursive || isKeptLazy || !isEnumerable(domain)) {
1440
+ // TLC builds the function only when it reduces every domain, and evaluates the body lazily
1441
+ // otherwise.
1442
+ const domains =
1443
+ typeof domain === "object" && domain.kind === "ProductSet" && bounds.length > 1
1444
+ ? domain.factors
1445
+ : [domain];
1446
+ if (expression.isRecursive || isKeptLazy || !domains.every(isReducible)) {
1424
1447
  const functionValue = createLazyFunction(
1425
1448
  domain,
1426
1449
  (argument) => body(withScope(context, bindArgument(bounds, context.scope, argument))),
@@ -1514,10 +1537,7 @@ const compileSetComprehension = (
1514
1537
  predicate(withScope(context, bindPattern(context.scope, pattern, element))),
1515
1538
  "a set filter predicate",
1516
1539
  );
1517
- const isReducible =
1518
- typeof base === "object" &&
1519
- (base.kind === "Set" || base.kind === "MixedSet" || base.kind === "Interval");
1520
- if (!isReducible) {
1540
+ if (!isReducible(base)) {
1521
1541
  if (isSetValue(base)) return { kind: "FilteredSet", base, test };
1522
1542
  throw new TlaEvaluationError(
1523
1543
  `TLC encountered a non-enumerable quantifier bound ${formatValue(base)} at ${describeLocation(expression.bound.set)}`,
@@ -1571,7 +1591,9 @@ export const hasDuplicateFields = (sortedFields: RecordField[]) =>
1571
1591
  sortedFields.some((field, index) => index > 0 && sortedFields[index - 1].name === field.name);
1572
1592
 
1573
1593
  export const createUnassignedError = (name: string, expression: Expression) =>
1574
- new TlaEvaluationError(`The variable ${name} is not assigned at ${describeLocation(expression)}`);
1594
+ new TlaEvaluationError(
1595
+ `In evaluation, the identifier ${name} is either undefined or not an operator.\n${describeRange(expression)}`,
1596
+ );
1575
1597
 
1576
1598
  export const createPrimeOutsideActionError = (expression: Expression) =>
1577
1599
  new TlaEvaluationError(
@@ -1759,18 +1781,31 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
1759
1781
  keepLazy(expression.function);
1760
1782
  const evaluateFunction = child(expression.function);
1761
1783
  const args = expression.args.map(child);
1784
+ const describeNonFunction = getNonFunctionError(expression);
1762
1785
  if (args.length === 1) {
1763
1786
  const argument = args[0];
1764
- return (context) => applyFunction(evaluateFunction(context), argument(context));
1787
+ return (context) =>
1788
+ applyFunction(
1789
+ evaluateFunction(context),
1790
+ argument(context),
1791
+ undefined,
1792
+ describeNonFunction,
1793
+ );
1765
1794
  }
1766
1795
  return (context) =>
1767
- applyFunction(evaluateFunction(context), createTuple(args.map((arg) => arg(context))));
1796
+ applyFunction(
1797
+ evaluateFunction(context),
1798
+ createTuple(args.map((arg) => arg(context))),
1799
+ undefined,
1800
+ describeNonFunction,
1801
+ );
1768
1802
  }
1769
1803
  case "FieldAccess": {
1770
1804
  const record = child(expression.record);
1771
1805
  const field = expression.field;
1772
1806
  const describeMissing = getFieldError(expression);
1773
- return (context) => applyFunction(record(context), field, describeMissing);
1807
+ const describeNonRecord = getNonRecordError(expression);
1808
+ return (context) => applyFunction(record(context), field, describeMissing, describeNonRecord);
1774
1809
  }
1775
1810
  case "Product": {
1776
1811
  const factors = expression.factors.map(child);
package/src/instances.ts CHANGED
@@ -219,7 +219,7 @@ interface Instantiation {
219
219
  variables: Set<string>;
220
220
  getDefinition: (key: string) => Definition | undefined;
221
221
  isParameterized: (key: string) => boolean;
222
- addDefinition: (name: string, create: (key: string) => Definition) => string;
222
+ addDefinition: (source: string, name: string, create: (key: string) => Definition) => string;
223
223
  createName: (name: string) => string;
224
224
  }
225
225
 
@@ -640,7 +640,7 @@ const copyDefinition = (rewrite: Rewrite, key: string): string => {
640
640
  const instantiation = rewrite.instantiation;
641
641
  const definition = instantiation.getDefinition(key);
642
642
  if (!definition) return key;
643
- return instantiation.addDefinition(definition.name, (copyKey) => {
643
+ return instantiation.addDefinition(key, definition.name, (copyKey) => {
644
644
  rewrite.copies.set(key, copyKey);
645
645
  const rename = createRenamer(rewrite);
646
646
  const mapped = renameParams(
@@ -679,7 +679,7 @@ export const createInstantiation = (instantiation: Instantiation) => {
679
679
  if (copy !== undefined) return copy;
680
680
  const definition = instantiation.getDefinition(key);
681
681
  if (!definition) return key;
682
- return instantiation.addDefinition(definition.name, () =>
682
+ return instantiation.addDefinition(key, definition.name, () =>
683
683
  withInstanceParams(definition, instantiation.params, definition.location),
684
684
  );
685
685
  },
package/src/live-check.ts CHANGED
@@ -1,7 +1,9 @@
1
1
  import { TlaEvaluationError } from "./errors";
2
+ import { EXIT_STATUS, setExitCode } from "./exit-codes";
2
3
  import { hasRepeatedEffects, type Environment } from "./evaluate";
3
4
  import {
4
5
  evaluateLive,
6
+ TAUTOLOGY_MESSAGE,
5
7
  evaluateOnLasso,
6
8
  toLiveExpression,
7
9
  type ScopedExpression,
@@ -11,6 +13,7 @@ import {
11
13
  createJunction,
12
14
  createUnary,
13
15
  getSolutions,
16
+ getTermKey,
14
17
  isFulfilling,
15
18
  type LiveExpression,
16
19
  type Solution,
@@ -47,37 +50,21 @@ interface Check {
47
50
  actionIds: Int32Array;
48
51
  nodeStates: number[];
49
52
  nodeTableaux: number[];
50
- successors: number[][];
51
- actions: Uint8Array[];
52
- stateResults: Uint8Array[];
53
- isWritten: boolean[];
53
+ // The successors a node gathers until it is written.
54
+ pending: (number[] | undefined)[];
55
+ // Each written node's state results, then its action results edge by edge, from the node's
56
+ // offset in one buffer, so a node costs no objects of its own. An unwritten node has offset -1.
57
+ offsets: number[];
58
+ results: { bytes: Uint8Array; length: number };
59
+ // Each written node's successor count, then its successors, from the node's edge offset.
60
+ edgeOffsets: number[];
61
+ edges: { ids: Int32Array; length: number };
54
62
  initial: number[];
55
- nodeIds: Map<number, number>;
56
- nodesByState: Map<number, number[]>;
63
+ nodeIds: NodeTable;
57
64
  isDone: boolean[];
58
65
  errorNode: number | undefined;
59
66
  }
60
67
 
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
68
  const isSameState = (left: Value[], right: Value[]) =>
82
69
  left.every((value, position) => isSameValue(value, right[position]));
83
70
 
@@ -88,13 +75,43 @@ const removeRepeats = (path: number[]) =>
88
75
  const pushNode = (check: Check, state: number, tableauNode: number) => {
89
76
  check.nodeStates.push(state);
90
77
  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);
78
+ check.pending.push(undefined);
79
+ check.offsets.push(-1);
80
+ check.edgeOffsets.push(-1);
95
81
  return check.nodeStates.length - 1;
96
82
  };
97
83
 
84
+ // A Map holds at most 2^24 entries, so each tableau node of a state finds its node in an
85
+ // open-addressing table of (state plus one, tableau node, node) triples.
86
+ interface NodeTable {
87
+ slots: Int32Array;
88
+ size: number;
89
+ shift: number;
90
+ }
91
+
92
+ const getNodeSlot = (table: NodeTable, state: number, tableauNode: number) => {
93
+ const mask = table.slots.length / 3 - 1;
94
+ const hash = Math.imul(Math.imul(state, 0x9e3779b1) ^ tableauNode, 0x85ebca6b) >>> table.shift;
95
+ for (let index = hash; ; index = (index + 1) & mask) {
96
+ const slot = index * 3;
97
+ const stored = table.slots[slot];
98
+ if (stored === 0 || (stored === state + 1 && table.slots[slot + 1] === tableauNode))
99
+ return slot;
100
+ }
101
+ };
102
+
103
+ const isWritten = (check: Check, node: number) => check.offsets[node] !== -1;
104
+
105
+ const getPending = (check: Check, node: number) => (check.pending[node] ??= []);
106
+
107
+ const getSuccessors = (check: Check, node: number) => {
108
+ const offset = check.edgeOffsets[node];
109
+ return check.edges.ids.subarray(offset + 1, offset + 1 + check.edges.ids[offset]);
110
+ };
111
+
112
+ const getStateResult = (check: Check, node: number, position: number) =>
113
+ check.results.bytes[check.offsets[node] + position] === 1;
114
+
98
115
  const SUCCESSOR_CAPACITY = 16;
99
116
 
100
117
  const SCC_MARKER = -42;
@@ -121,26 +138,29 @@ export const createLivenessChecker = (
121
138
  fairness.length === 0 ? violation : createJunction("And", [...fairness, violation]);
122
139
  const solutions = getSolutions(formula);
123
140
  if (solutions.length === 0) {
124
- throw new TlaEvaluationError("Temporal formula is a tautology (its negation is unsatisfiable)");
141
+ throw setExitCode(
142
+ new TlaEvaluationError(TAUTOLOGY_MESSAGE),
143
+ EXIT_STATUS.livenessEvaluationFailure,
144
+ );
125
145
  }
126
146
  const actionIds = new Map<string, number>();
127
147
  const checks = solutions.map((solution): Check => ({
128
148
  solution,
129
149
  actionIds: Int32Array.from(solution.actionChecks, (predicate) => {
130
- const key = getLiveKey(predicate);
150
+ const key = getTermKey(predicate);
131
151
  const id = actionIds.get(key) ?? actionIds.size;
132
152
  actionIds.set(key, id);
133
153
  return id;
134
154
  }),
135
155
  nodeStates: [],
136
156
  nodeTableaux: [],
137
- successors: [],
138
- actions: [],
139
- stateResults: [],
140
- isWritten: [],
157
+ pending: [],
158
+ offsets: [],
159
+ results: { bytes: new Uint8Array(1024), length: 0 },
160
+ edgeOffsets: [],
161
+ edges: { ids: new Int32Array(1024), length: 0 },
141
162
  initial: [],
142
- nodeIds: new Map(),
143
- nodesByState: new Map(),
163
+ nodeIds: { slots: new Int32Array(3 << 10), size: 0, shift: 22 },
144
164
  isDone: [],
145
165
  errorNode: undefined,
146
166
  }));
@@ -226,18 +246,35 @@ export const createLivenessChecker = (
226
246
  model.infinitelyOftenActions.length === 0,
227
247
  );
228
248
 
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;
249
+ const getNodeId = (check: Check, state: number, tableauNode: number) => {
250
+ if (!check.solution.tableau) return state;
251
+ const slots = check.nodeIds.slots;
252
+ const slot = getNodeSlot(check.nodeIds, state, tableauNode);
253
+ return slots[slot] === 0 ? undefined : slots[slot + 2];
254
+ };
233
255
  const recordNode = (check: Check, state: number, tableauNode: number) => {
234
256
  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]);
257
+ const table = check.nodeIds;
258
+ if (++table.size * 2 > table.slots.length / 3) {
259
+ const old = table.slots;
260
+ table.slots = new Int32Array(old.length * 2);
261
+ table.shift--;
262
+ for (let slot = 0; slot < old.length; slot += 3) {
263
+ if (old[slot] !== 0)
264
+ table.slots.set(
265
+ old.subarray(slot, slot + 3),
266
+ getNodeSlot(table, old[slot] - 1, old[slot + 1]),
267
+ );
268
+ }
269
+ }
270
+ table.slots.set([state + 1, tableauNode, node], getNodeSlot(table, state, tableauNode));
239
271
  return node;
240
272
  };
273
+ // A state's nodes in the order they were recorded, which is the order of their ids.
274
+ const getStateNodes = (check: Check, tableau: Tableau, state: number) =>
275
+ tableau.nodes
276
+ .flatMap((_, tableauNode) => getNodeId(check, state, tableauNode) ?? [])
277
+ .sort((left, right) => left - right);
241
278
  const writeNode = (
242
279
  check: Check,
243
280
  node: number,
@@ -245,11 +282,32 @@ export const createLivenessChecker = (
245
282
  stateResults: Uint8Array,
246
283
  ) => {
247
284
  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;
285
+ const results = check.results;
286
+ const offset = results.length;
287
+ results.length += stateResults.length + actions.length * actionCount;
288
+ if (results.length > results.bytes.length) {
289
+ const grown = new Uint8Array(Math.max(2 * results.bytes.length, results.length));
290
+ grown.set(results.bytes);
291
+ results.bytes = grown;
292
+ }
293
+ results.bytes.set(stateResults, offset);
294
+ actions.forEach((edge, position) =>
295
+ results.bytes.set(edge, offset + stateResults.length + position * actionCount),
296
+ );
297
+ check.offsets[node] = offset;
298
+ const successors = check.pending[node] ?? [];
299
+ const edges = check.edges;
300
+ const edgeOffset = edges.length;
301
+ edges.length += successors.length + 1;
302
+ if (edges.length > edges.ids.length) {
303
+ const grown = new Int32Array(Math.max(2 * edges.ids.length, edges.length));
304
+ grown.set(edges.ids);
305
+ edges.ids = grown;
306
+ }
307
+ edges.ids[edgeOffset] = successors.length;
308
+ edges.ids.set(successors, edgeOffset + 1);
309
+ check.edgeOffsets[node] = edgeOffset;
310
+ check.pending[node] = undefined;
253
311
  };
254
312
 
255
313
  // TLC collects a state's successors and the state itself in a SetOfStates, a hash set it
@@ -302,7 +360,7 @@ export const createLivenessChecker = (
302
360
  const stateResults = checkState(check, index, state);
303
361
  const tableauNode = tableau.nodes[check.nodeTableaux[node]];
304
362
  const actions: Uint8Array[] = [];
305
- const successors = check.successors[node];
363
+ const successors = getPending(check, node);
306
364
  const selfActions =
307
365
  tableauNode.successors.length > 0
308
366
  ? checkAction(check, index, state, state)
@@ -351,8 +409,8 @@ export const createLivenessChecker = (
351
409
  );
352
410
  check.isDone[index] = true;
353
411
  // 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];
412
+ for (const node of getStateNodes(check, tableau, index)) {
413
+ const successors = getPending(check, node);
356
414
  const actions: Uint8Array[] = [];
357
415
  set.forEach((successor, position) => {
358
416
  const isDone = check.isDone[successor.index] === true;
@@ -386,10 +444,10 @@ export const createLivenessChecker = (
386
444
  index: number,
387
445
  ) => {
388
446
  while (check.nodeStates.length <= index) pushNode(check, check.nodeStates.length, -1);
389
- const successors = check.successors[index];
447
+ const successors = getPending(check, index);
390
448
  const actions: Uint8Array[] = [];
391
449
  set.forEach((successor, position) => {
392
- if (check.isWritten[successor.index] && successors.includes(successor.index)) return;
450
+ if (isWritten(check, successor.index) && successors.includes(successor.index)) return;
393
451
  successors.push(successor.index);
394
452
  actions.push(actionResults[position]);
395
453
  });
@@ -403,20 +461,20 @@ export const createLivenessChecker = (
403
461
  const parents = new Map<number, number>();
404
462
  const queue: number[] = [];
405
463
  for (const node of check.initial) {
406
- if (!check.isWritten[node]) continue;
464
+ if (!isWritten(check, node)) continue;
407
465
  queue.push(node);
408
466
  parents.set(node, -1);
409
467
  }
410
468
  for (let position = 0; position < queue.length; position++) {
411
469
  const current = queue[position];
412
- for (const next of check.successors[current]) {
470
+ for (const next of getSuccessors(check, current)) {
413
471
  if (next === current && check.solution.tableau) continue;
414
472
  if (next === target) {
415
473
  const path = [target];
416
474
  for (let node = current; node !== -1; node = parents.get(node) ?? -1) path.push(node);
417
475
  return path;
418
476
  }
419
- if (!check.isWritten[next] || parents.has(next)) continue;
477
+ if (!isWritten(check, next) || parents.has(next)) continue;
420
478
  parents.set(next, current);
421
479
  queue.push(next);
422
480
  }
@@ -428,16 +486,17 @@ export const createLivenessChecker = (
428
486
  const findInModel = (check: Check, model: Solution["models"][number]): Lasso | undefined => {
429
487
  const solution = check.solution;
430
488
  const actionCount = solution.actionChecks.length;
489
+ const stateCount = solution.stateChecks.length;
431
490
  const getAction = (node: number, edge: number, position: number) =>
432
- check.actions[node][edge * actionCount + position] === 1;
491
+ check.results.bytes[check.offsets[node] + stateCount + edge * actionCount + position] === 1;
433
492
  const isAllowed = (node: number, edge: number) =>
434
493
  model.eventuallyAlways.every((position) => getAction(node, edge, position));
435
494
  const links = new Float64Array(check.nodeStates.length).fill(UNVISITED);
436
- const queue = check.initial.filter((node) => check.isWritten[node]);
495
+ const queue = check.initial.filter((node) => isWritten(check, node));
437
496
  const components: number[] = [];
438
497
 
439
498
  const isStuttering = (node: number) => {
440
- const edge = check.successors[node].indexOf(node);
499
+ const edge = getSuccessors(check, node).indexOf(node);
441
500
  return edge !== -1 && isAllowed(node, edge);
442
501
  };
443
502
  const isFulfilled = (node: number, promise: Solution["promises"][number]) =>
@@ -461,11 +520,11 @@ export const createLivenessChecker = (
461
520
  if (member === root) break;
462
521
  }
463
522
  const isStateSatisfied = model.infinitelyOftenStates.every((position) =>
464
- [...members].some((node) => check.stateResults[node][position] === 1),
523
+ [...members].some((node) => getStateResult(check, node, position)),
465
524
  );
466
525
  const isActionSatisfied = model.infinitelyOftenActions.every((position) =>
467
526
  [...members].some((node) =>
468
- check.successors[node].some(
527
+ getSuccessors(check, node).some(
469
528
  (next, edge) =>
470
529
  members.has(next) && isAllowed(node, edge) && getAction(node, edge, position),
471
530
  ),
@@ -506,7 +565,7 @@ export const createLivenessChecker = (
506
565
  const countAtStart = remaining.count;
507
566
  while (true) {
508
567
  model.infinitelyOftenStates.forEach((position, slot) => {
509
- if (!stateDone[slot] && check.stateResults[current.node][position] === 1) {
568
+ if (!stateDone[slot] && getStateResult(check, current.node, position)) {
510
569
  stateDone[slot] = true;
511
570
  remaining.count--;
512
571
  }
@@ -520,7 +579,7 @@ export const createLivenessChecker = (
520
579
  if (remaining.count <= 0) break;
521
580
  const step = { last: -1, unvisited: -1 };
522
581
  const countBeforeActions = remaining.count;
523
- const successors = check.successors[current.node];
582
+ const successors = getSuccessors(check, current.node);
524
583
  const taken = successors.some((next, edge) => {
525
584
  if (membersByState.has(check.nodeStates[next])) {
526
585
  if (!isMember(next) || !isAllowed(current.node, edge)) return false;
@@ -555,7 +614,8 @@ export const createLivenessChecker = (
555
614
  }
556
615
  current.node = previous;
557
616
  step.unvisited =
558
- check.successors[previous].find((next) => isMember(next) && !seen.has(next)) ?? -1;
617
+ getSuccessors(check, previous).find((next) => isMember(next) && !seen.has(next)) ??
618
+ -1;
559
619
  }
560
620
  take(step.unvisited);
561
621
  seen.add(step.unvisited);
@@ -585,7 +645,7 @@ export const createLivenessChecker = (
585
645
  const queue: [number, number][] = [];
586
646
  for (let state = start, parent = -1, position = 0; ; position++) {
587
647
  for (const node of membersByState.get(state) ?? []) {
588
- for (const [edge, next] of check.successors[node].entries()) {
648
+ for (const [edge, next] of getSuccessors(check, node).entries()) {
589
649
  if (next === node || !isAllowedEdge(node, edge)) continue;
590
650
  if (next === root) {
591
651
  const path: number[] = [];
@@ -638,8 +698,8 @@ export const createLivenessChecker = (
638
698
  stack.push(lowLink, node, SCC_MARKER);
639
699
  components.push(node);
640
700
  const nextLowLink = { value: counter.link++ };
641
- check.successors[node].forEach((next, edge) => {
642
- if (!check.isWritten[next]) return;
701
+ getSuccessors(check, node).forEach((next, edge) => {
702
+ if (!isWritten(check, next)) return;
643
703
  if (!isAllowed(node, edge)) {
644
704
  if (links[next] === UNVISITED) queue.push(next);
645
705
  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 = (