tla-ts 0.0.3-dev.bffbba3 → 0.0.3-dev.cf3b82c

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
@@ -1,4 +1,5 @@
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,
@@ -49,13 +50,17 @@ interface Check {
49
50
  actionIds: Int32Array;
50
51
  nodeStates: number[];
51
52
  nodeTableaux: number[];
52
- successors: number[][];
53
- actions: Uint8Array[];
54
- stateResults: Uint8Array[];
55
- 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 };
56
62
  initial: number[];
57
- nodeIds: Map<number, number>;
58
- nodesByState: Map<number, number[]>;
63
+ nodeIds: NodeTable;
59
64
  isDone: boolean[];
60
65
  errorNode: number | undefined;
61
66
  }
@@ -70,13 +75,43 @@ const removeRepeats = (path: number[]) =>
70
75
  const pushNode = (check: Check, state: number, tableauNode: number) => {
71
76
  check.nodeStates.push(state);
72
77
  check.nodeTableaux.push(tableauNode);
73
- check.successors.push([]);
74
- check.actions.push(new Uint8Array(0));
75
- check.stateResults.push(new Uint8Array(0));
76
- check.isWritten.push(false);
78
+ check.pending.push(undefined);
79
+ check.offsets.push(-1);
80
+ check.edgeOffsets.push(-1);
77
81
  return check.nodeStates.length - 1;
78
82
  };
79
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
+
80
115
  const SUCCESSOR_CAPACITY = 16;
81
116
 
82
117
  const SCC_MARKER = -42;
@@ -103,7 +138,10 @@ export const createLivenessChecker = (
103
138
  fairness.length === 0 ? violation : createJunction("And", [...fairness, violation]);
104
139
  const solutions = getSolutions(formula);
105
140
  if (solutions.length === 0) {
106
- throw new TlaEvaluationError(TAUTOLOGY_MESSAGE);
141
+ throw setExitCode(
142
+ new TlaEvaluationError(TAUTOLOGY_MESSAGE),
143
+ EXIT_STATUS.livenessEvaluationFailure,
144
+ );
107
145
  }
108
146
  const actionIds = new Map<string, number>();
109
147
  const checks = solutions.map((solution): Check => ({
@@ -116,13 +154,13 @@ export const createLivenessChecker = (
116
154
  }),
117
155
  nodeStates: [],
118
156
  nodeTableaux: [],
119
- successors: [],
120
- actions: [],
121
- stateResults: [],
122
- isWritten: [],
157
+ pending: [],
158
+ offsets: [],
159
+ results: { bytes: new Uint8Array(1024), length: 0 },
160
+ edgeOffsets: [],
161
+ edges: { ids: new Int32Array(1024), length: 0 },
123
162
  initial: [],
124
- nodeIds: new Map(),
125
- nodesByState: new Map(),
163
+ nodeIds: { slots: new Int32Array(3 << 10), size: 0, shift: 22 },
126
164
  isDone: [],
127
165
  errorNode: undefined,
128
166
  }));
@@ -208,18 +246,35 @@ export const createLivenessChecker = (
208
246
  model.infinitelyOftenActions.length === 0,
209
247
  );
210
248
 
211
- const getNodeId = (check: Check, state: number, tableauNode: number) =>
212
- check.solution.tableau
213
- ? check.nodeIds.get(state * check.solution.tableau.nodes.length + tableauNode)
214
- : 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
+ };
215
255
  const recordNode = (check: Check, state: number, tableauNode: number) => {
216
256
  const node = pushNode(check, state, tableauNode);
217
- check.nodeIds.set(state * (check.solution.tableau?.nodes.length ?? 1) + tableauNode, node);
218
- const siblings = check.nodesByState.get(state);
219
- if (siblings) siblings.push(node);
220
- 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));
221
271
  return node;
222
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);
223
278
  const writeNode = (
224
279
  check: Check,
225
280
  node: number,
@@ -227,11 +282,32 @@ export const createLivenessChecker = (
227
282
  stateResults: Uint8Array,
228
283
  ) => {
229
284
  const actionCount = check.solution.actionChecks.length;
230
- const packed = new Uint8Array(actions.length * actionCount);
231
- actions.forEach((results, position) => packed.set(results, position * actionCount));
232
- check.actions[node] = packed;
233
- check.stateResults[node] = stateResults;
234
- 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;
235
311
  };
236
312
 
237
313
  // TLC collects a state's successors and the state itself in a SetOfStates, a hash set it
@@ -284,7 +360,7 @@ export const createLivenessChecker = (
284
360
  const stateResults = checkState(check, index, state);
285
361
  const tableauNode = tableau.nodes[check.nodeTableaux[node]];
286
362
  const actions: Uint8Array[] = [];
287
- const successors = check.successors[node];
363
+ const successors = getPending(check, node);
288
364
  const selfActions =
289
365
  tableauNode.successors.length > 0
290
366
  ? checkAction(check, index, state, state)
@@ -333,8 +409,8 @@ export const createLivenessChecker = (
333
409
  );
334
410
  check.isDone[index] = true;
335
411
  // TLC expands the nodes recorded before the loop, not the ones the loop records.
336
- for (const node of (check.nodesByState.get(index) ?? []).slice()) {
337
- const successors = check.successors[node];
412
+ for (const node of getStateNodes(check, tableau, index)) {
413
+ const successors = getPending(check, node);
338
414
  const actions: Uint8Array[] = [];
339
415
  set.forEach((successor, position) => {
340
416
  const isDone = check.isDone[successor.index] === true;
@@ -368,10 +444,10 @@ export const createLivenessChecker = (
368
444
  index: number,
369
445
  ) => {
370
446
  while (check.nodeStates.length <= index) pushNode(check, check.nodeStates.length, -1);
371
- const successors = check.successors[index];
447
+ const successors = getPending(check, index);
372
448
  const actions: Uint8Array[] = [];
373
449
  set.forEach((successor, position) => {
374
- if (check.isWritten[successor.index] && successors.includes(successor.index)) return;
450
+ if (isWritten(check, successor.index) && successors.includes(successor.index)) return;
375
451
  successors.push(successor.index);
376
452
  actions.push(actionResults[position]);
377
453
  });
@@ -385,20 +461,20 @@ export const createLivenessChecker = (
385
461
  const parents = new Map<number, number>();
386
462
  const queue: number[] = [];
387
463
  for (const node of check.initial) {
388
- if (!check.isWritten[node]) continue;
464
+ if (!isWritten(check, node)) continue;
389
465
  queue.push(node);
390
466
  parents.set(node, -1);
391
467
  }
392
468
  for (let position = 0; position < queue.length; position++) {
393
469
  const current = queue[position];
394
- for (const next of check.successors[current]) {
470
+ for (const next of getSuccessors(check, current)) {
395
471
  if (next === current && check.solution.tableau) continue;
396
472
  if (next === target) {
397
473
  const path = [target];
398
474
  for (let node = current; node !== -1; node = parents.get(node) ?? -1) path.push(node);
399
475
  return path;
400
476
  }
401
- if (!check.isWritten[next] || parents.has(next)) continue;
477
+ if (!isWritten(check, next) || parents.has(next)) continue;
402
478
  parents.set(next, current);
403
479
  queue.push(next);
404
480
  }
@@ -410,16 +486,17 @@ export const createLivenessChecker = (
410
486
  const findInModel = (check: Check, model: Solution["models"][number]): Lasso | undefined => {
411
487
  const solution = check.solution;
412
488
  const actionCount = solution.actionChecks.length;
489
+ const stateCount = solution.stateChecks.length;
413
490
  const getAction = (node: number, edge: number, position: number) =>
414
- check.actions[node][edge * actionCount + position] === 1;
491
+ check.results.bytes[check.offsets[node] + stateCount + edge * actionCount + position] === 1;
415
492
  const isAllowed = (node: number, edge: number) =>
416
493
  model.eventuallyAlways.every((position) => getAction(node, edge, position));
417
494
  const links = new Float64Array(check.nodeStates.length).fill(UNVISITED);
418
- const queue = check.initial.filter((node) => check.isWritten[node]);
495
+ const queue = check.initial.filter((node) => isWritten(check, node));
419
496
  const components: number[] = [];
420
497
 
421
498
  const isStuttering = (node: number) => {
422
- const edge = check.successors[node].indexOf(node);
499
+ const edge = getSuccessors(check, node).indexOf(node);
423
500
  return edge !== -1 && isAllowed(node, edge);
424
501
  };
425
502
  const isFulfilled = (node: number, promise: Solution["promises"][number]) =>
@@ -443,11 +520,11 @@ export const createLivenessChecker = (
443
520
  if (member === root) break;
444
521
  }
445
522
  const isStateSatisfied = model.infinitelyOftenStates.every((position) =>
446
- [...members].some((node) => check.stateResults[node][position] === 1),
523
+ [...members].some((node) => getStateResult(check, node, position)),
447
524
  );
448
525
  const isActionSatisfied = model.infinitelyOftenActions.every((position) =>
449
526
  [...members].some((node) =>
450
- check.successors[node].some(
527
+ getSuccessors(check, node).some(
451
528
  (next, edge) =>
452
529
  members.has(next) && isAllowed(node, edge) && getAction(node, edge, position),
453
530
  ),
@@ -488,7 +565,7 @@ export const createLivenessChecker = (
488
565
  const countAtStart = remaining.count;
489
566
  while (true) {
490
567
  model.infinitelyOftenStates.forEach((position, slot) => {
491
- if (!stateDone[slot] && check.stateResults[current.node][position] === 1) {
568
+ if (!stateDone[slot] && getStateResult(check, current.node, position)) {
492
569
  stateDone[slot] = true;
493
570
  remaining.count--;
494
571
  }
@@ -502,7 +579,7 @@ export const createLivenessChecker = (
502
579
  if (remaining.count <= 0) break;
503
580
  const step = { last: -1, unvisited: -1 };
504
581
  const countBeforeActions = remaining.count;
505
- const successors = check.successors[current.node];
582
+ const successors = getSuccessors(check, current.node);
506
583
  const taken = successors.some((next, edge) => {
507
584
  if (membersByState.has(check.nodeStates[next])) {
508
585
  if (!isMember(next) || !isAllowed(current.node, edge)) return false;
@@ -537,7 +614,8 @@ export const createLivenessChecker = (
537
614
  }
538
615
  current.node = previous;
539
616
  step.unvisited =
540
- check.successors[previous].find((next) => isMember(next) && !seen.has(next)) ?? -1;
617
+ getSuccessors(check, previous).find((next) => isMember(next) && !seen.has(next)) ??
618
+ -1;
541
619
  }
542
620
  take(step.unvisited);
543
621
  seen.add(step.unvisited);
@@ -567,7 +645,7 @@ export const createLivenessChecker = (
567
645
  const queue: [number, number][] = [];
568
646
  for (let state = start, parent = -1, position = 0; ; position++) {
569
647
  for (const node of membersByState.get(state) ?? []) {
570
- for (const [edge, next] of check.successors[node].entries()) {
648
+ for (const [edge, next] of getSuccessors(check, node).entries()) {
571
649
  if (next === node || !isAllowedEdge(node, edge)) continue;
572
650
  if (next === root) {
573
651
  const path: number[] = [];
@@ -620,8 +698,8 @@ export const createLivenessChecker = (
620
698
  stack.push(lowLink, node, SCC_MARKER);
621
699
  components.push(node);
622
700
  const nextLowLink = { value: counter.link++ };
623
- check.successors[node].forEach((next, edge) => {
624
- if (!check.isWritten[next]) return;
701
+ getSuccessors(check, node).forEach((next, edge) => {
702
+ if (!isWritten(check, next)) return;
625
703
  if (!isAllowed(node, edge)) {
626
704
  if (links[next] === UNVISITED) queue.push(next);
627
705
  return;
package/src/liveness.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { isLocallyResolved, type Definition, type Expression } from "./ast";
2
- import { TlaConfigError, TlaEvaluationError } from "./errors";
2
+ import { STACK_OVERFLOW, TlaEvaluationError } from "./errors";
3
3
  import { EXIT_STATUS, setExitCode } from "./exit-codes";
4
4
  import {
5
5
  describeLocation,
@@ -191,7 +191,7 @@ export const expandTemporal = (
191
191
  getDefinitionLevel(definition, environment) > 0
192
192
  ) {
193
193
  if (expanding.has(definition)) {
194
- throw new TlaConfigError(`The definition of ${expression.name} refers to itself`);
194
+ throw setExitCode(new TlaEvaluationError(STACK_OVERFLOW), EXIT_STATUS.error);
195
195
  }
196
196
  return expand(
197
197
  definition.body,
@@ -299,9 +299,7 @@ export const toLiveExpression = (
299
299
  scope: Scope | undefined,
300
300
  ) => {
301
301
  if (expansion.depth >= MAXIMUM_EXPANSION_DEPTH) {
302
- throw new TlaEvaluationError(
303
- `TLC overflowed the stack while expanding the temporal formula at ${describeLocation(expression)}`,
304
- );
302
+ throw setExitCode(new TlaEvaluationError(STACK_OVERFLOW), EXIT_STATUS.error);
305
303
  }
306
304
  expansion.depth++;
307
305
  const result = convert(body, bodyScope);
@@ -15,7 +15,7 @@ import type {
15
15
  WorkerMessage,
16
16
  } from "./parallel";
17
17
  import { getSuccessors, type Successor } from "./successors";
18
- import { getTlcStringOrder, getTlcVariableOrder } from "./tlc-order";
18
+ import { getTlcStringOrder, getTlcDeclarationOrder } from "./tlc-order";
19
19
  import { OUT_DEGREE_BUCKETS } from "./tlc-summary";
20
20
  import { createStateDecoder, createStateEncoder, type EncodedStates } from "./transfer";
21
21
  import { getRankedStringCount, setStringOrder, type Value } from "./values";
@@ -61,7 +61,7 @@ const run = (start: StartMessage, parent: Port) => {
61
61
  });
62
62
  const environment = specification.environment;
63
63
  const search = createSearch(start.config, environment, () =>
64
- getTlcVariableOrder(start.source, loadModule),
64
+ getTlcDeclarationOrder(start.source, loadModule, "variable"),
65
65
  );
66
66
  const nextAction = search?.spec.next;
67
67
  if (!search || nextAction === undefined)
package/src/parallel.ts CHANGED
@@ -20,7 +20,7 @@ import {
20
20
  type SharedFingerprints,
21
21
  } from "./fingerprints";
22
22
  import { getInitialStates } from "./successors";
23
- import { getTlcStringOrder, getTlcVariableOrder } from "./tlc-order";
23
+ import { getTlcStringOrder, getTlcDeclarationOrder } from "./tlc-order";
24
24
  import { getFingerprintDistance, OUT_DEGREE_BUCKETS } from "./tlc-summary";
25
25
  import { createStateEncoder, type EncodedStates } from "./transfer";
26
26
  import { getRankedStringCount, setStringOrder, type Value } from "./values";
@@ -150,7 +150,7 @@ export const check = async (options: CheckOptions): Promise<CheckResult> => {
150
150
  });
151
151
  const environment = specification.environment;
152
152
  const search = createSearch(config, environment, () =>
153
- getTlcVariableOrder(options.source, loadModule),
153
+ getTlcDeclarationOrder(options.source, loadModule, "variable"),
154
154
  );
155
155
  if (findAssumptionViolation(specification.assumptions, environment)) return fallBack();
156
156
  if (
package/src/successors.ts CHANGED
@@ -7,7 +7,7 @@ import {
7
7
  type QuantifierExpression,
8
8
  } from "./ast";
9
9
  import { getReadVariables } from "./dependencies";
10
- import { TlaEvaluationError, UNEXPECTED_EXCEPTION } from "./errors";
10
+ import { TlaEvaluationError, TlaIncompleteStateError } from "./errors";
11
11
  import { EXIT_STATUS, setExitCode } from "./exit-codes";
12
12
  import {
13
13
  describeLocation,
@@ -89,14 +89,25 @@ const assign = (partial: State, index: number, value: Value) => {
89
89
  return copy;
90
90
  };
91
91
 
92
- const holds = (expression: Expression, context: Context, value = evaluate(expression, context)) => {
92
+ // TLC's Tool.getInitStates and Tool.getNextStates report a value where they expect a formula.
93
+ const expectFormula = (expression: Expression, value: Value, isInit: boolean) => {
93
94
  if (typeof value === "boolean") return value;
94
- try {
95
- return expectBoolean(value, `the action at ${describeLocation(expression)}`);
96
- } catch (error) {
97
- // TLC fails with an unexpected exception when the next-state relation isn't a boolean.
98
- throw context.next === undefined ? error : setExitCode(error, EXIT_STATUS.error);
95
+ throw new TlaEvaluationError(
96
+ `In computing ${isInit ? "initial" : "next"} states, TLC expected a boolean expression,\nbut instead found ${formatValue(value)}.\n${describeRange(expression)}`,
97
+ );
98
+ };
99
+
100
+ const holds = (expression: Expression, context: Context, value = evaluate(expression, context)) => {
101
+ // TLC rejects a number in the next-state relation when it splits the relation into actions.
102
+ if (context.next !== undefined && expression.kind === "Number") {
103
+ throw setExitCode(
104
+ new TlaEvaluationError(
105
+ `The next state relation is not a boolean expression.\n${expression.text ?? expression.value}`,
106
+ ),
107
+ EXIT_STATUS.error,
108
+ );
99
109
  }
110
+ return expectFormula(expression, value, context.next === undefined);
100
111
  };
101
112
 
102
113
  const isAssignmentOperator = (operator: string) =>
@@ -391,10 +402,7 @@ const compileConjunction = (
391
402
  };
392
403
 
393
404
  const holdsInInit = (expression: Expression, context: Context) =>
394
- expectBoolean(
395
- evaluate(expression, context),
396
- `the initial predicate at ${describeLocation(expression)}`,
397
- );
405
+ expectFormula(expression, evaluate(expression, context), true);
398
406
 
399
407
  const compileGuard =
400
408
  (expression: Expression): Runner =>
@@ -419,7 +427,7 @@ const compileMembership = (
419
427
  expression.operator === "\\subseteq" ? { kind: "Subset", base: evaluated } : evaluated;
420
428
  if (!isEnumerable(value)) {
421
429
  throw new TlaEvaluationError(
422
- `In computing next states, the right side of \\in is not enumerable: ${formatValue(value)} at ${describeLocation(expression)}`,
430
+ `In computing ${run.isInit ? "initial" : "next"} states, the right side of \\IN is not enumerable.\n${describeRange(expression)}`,
423
431
  );
424
432
  }
425
433
  const elements = getStreamedElements(value);
@@ -866,7 +874,7 @@ const compileAction = (
866
874
  const body = arm?.body ?? other;
867
875
  if (!body)
868
876
  throw new TlaEvaluationError(
869
- `${UNEXPECTED_EXCEPTION}In computing next states, TLC encountered a CASE with no conditions true.\n${describeRange(expression)}`,
877
+ `In computing ${run.isInit ? "initial" : "next"} states, TLC encountered a CASE with no conditions true.\n${describeRange(expression)}`,
870
878
  );
871
879
  body(run, scope, partial, action, isFixed, onComplete);
872
880
  };
@@ -1057,8 +1065,10 @@ export const forEachSuccessor = (
1057
1065
  (partial, action) => {
1058
1066
  if (run.isStopped) return;
1059
1067
  if (!isComplete(partial)) {
1060
- throw new TlaEvaluationError(
1061
- `Successor state is not completely specified by action ${action ?? "Next"}. The following variables are not assigned: ${getMissingVariables(partial, environment).join(", ")}`,
1068
+ throw new TlaIncompleteStateError(
1069
+ partial,
1070
+ action,
1071
+ getMissingVariables(partial, environment).sort(),
1062
1072
  );
1063
1073
  }
1064
1074
  counter.successors++;
package/src/symmetry.ts CHANGED
@@ -1,5 +1,6 @@
1
- import { TlaConfigError } from "./errors";
1
+ import { TlaConfigError, TlaEvaluationError, UNEXPECTED_EXCEPTION } from "./errors";
2
2
  import { evaluate, type Environment } from "./evaluate";
3
+ import { EXIT_STATUS, setExitCode } from "./exit-codes";
3
4
  import {
4
5
  compareValues,
5
6
  createFunction,
@@ -47,9 +48,13 @@ const composePermutations = (first: Images, second: Images) => {
47
48
  return composed;
48
49
  };
49
50
 
50
- const toImages = (value: Value, name: string) => {
51
+ // TLC checks the symmetry set outside any phase that reports an error itself.
52
+ const createSymmetryError = (message: string) =>
53
+ setExitCode(new TlaEvaluationError(`${UNEXPECTED_EXCEPTION}${message}`), EXIT_STATUS.error);
54
+
55
+ const toImages = (value: Value) => {
51
56
  if (!isFunctionValue(value)) {
52
- throw new TlaConfigError(`The symmetry values of ${name} must be functions`);
57
+ throw createSymmetryError("The symmetry values must be function records.");
53
58
  }
54
59
  const functionValue = toFiniteFunction(value);
55
60
  const permutation: Images = new Map();
@@ -65,8 +70,13 @@ const toImages = (value: Value, name: string) => {
65
70
 
66
71
  export const getSymmetryGroup = (name: string, environment: Environment): Permutation[] => {
67
72
  const definition = environment.definitions.get(name);
73
+ if (definition === undefined && !environment.constants.has(name)) {
74
+ throw new TlaConfigError(
75
+ `The symmetry function ${name} specified in the configuration file\nis not defined in the specification.`,
76
+ );
77
+ }
68
78
  if (definition?.kind !== "Operator" || definition.params.length > 0) {
69
- throw new TlaConfigError(`The symmetry function ${name} must specify a set of permutations`);
79
+ throw createSymmetryError(`The symmetry function ${name} must specify a set of permutations.`);
70
80
  }
71
81
  const value = evaluate(definition.body, {
72
82
  environment,
@@ -75,9 +85,9 @@ export const getSymmetryGroup = (name: string, environment: Environment): Permut
75
85
  next: undefined,
76
86
  });
77
87
  if (!isSetValue(value) || !isEnumerable(value)) {
78
- throw new TlaConfigError("The symmetry operator must specify a set of functions");
88
+ throw createSymmetryError("The symmetry operator must specify a set of functions.");
79
89
  }
80
- const permutations = toFiniteSet(value).elements.map((element) => toImages(element, name));
90
+ const permutations = toFiniteSet(value).elements.map(toImages);
81
91
  const isDisabled =
82
92
  definition.body.kind === "Apply" && definition.body.args.length >= permutations.length;
83
93
  if (isDisabled) return [];
package/src/tableau.ts CHANGED
@@ -289,7 +289,7 @@ const toDisjunctiveNormalForm = (expression: LiveExpression): LiveExpression =>
289
289
  total.value *= normal.operands.length;
290
290
  if (total.value > MAXIMUM_DISJUNCTS) {
291
291
  throw new TlaEvaluationError(
292
- "TLC cannot handle the temporal formula because it exceeds the maximum supported size in disjunctive normal form",
292
+ "TLC cannot handle the temporal formula because it exceeds the maximum supported size in disjunctive normal form.",
293
293
  );
294
294
  }
295
295
  }
package/src/tlc-module.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { TlaModuleError } from "./errors";
1
+ import { TlaEvaluationError, TlaModuleError } from "./errors";
2
2
  import { EXIT_STATUS } from "./exit-codes";
3
3
  import type { Builtin } from "./evaluate";
4
4
  import { prettyPrint } from "./pretty-print";
@@ -48,7 +48,7 @@ const getRuntimeValue = (
48
48
  state: (Value | undefined)[] | undefined,
49
49
  ) => {
50
50
  if (!runtime.isStarted && CHECKER_KEYS.has(key)) {
51
- throw new TlaModuleError(`TLCGet(${key}) was undefined.`);
51
+ throw new TlaEvaluationError(`TLCGet(${key}) was undefined.`);
52
52
  }
53
53
  const duration = Math.floor((Date.now() - runtime.startedAt) / 1000);
54
54
  switch (key) {
@@ -104,11 +104,11 @@ const getRuntimeValue = (
104
104
  }
105
105
  if (key.startsWith(NAMED_REGISTER_PREFIX)) {
106
106
  const value = getNamedRegisters(runtime).get(key);
107
- if (value === undefined) throw new TlaModuleError(`TLCGet(${key}) was undefined.`);
107
+ if (value === undefined) throw new TlaEvaluationError(`TLCGet(${key}) was undefined.`);
108
108
  return value;
109
109
  }
110
110
  if (key.startsWith("-D")) return rankString(runtime.properties.get(key.slice(2)) ?? key);
111
- throw new TlaModuleError(`TLCGet(${key}) was undefined.`);
111
+ throw new TlaEvaluationError(`TLCGet(${key}) was undefined.`);
112
112
  };
113
113
 
114
114
  const getPermutations = (elements: Value[]): Value[][] =>
@@ -197,11 +197,11 @@ export const createTlcOperators = (
197
197
  const key = getValue(args, 0, "TLCGet");
198
198
  if (typeof key === "number" && key >= 0) {
199
199
  const value = runtime.registers.get(key);
200
- if (value === undefined) throw new TlaModuleError(`TLCGet(${key}) was undefined.`);
200
+ if (value === undefined) throw new TlaEvaluationError(`TLCGet(${key}) was undefined.`);
201
201
  return value;
202
202
  }
203
203
  if (typeof key !== "string") {
204
- throw new TlaModuleError(
204
+ throw new TlaEvaluationError(
205
205
  `The argument of TLCGet should be a nonnegative integer, but instead it is:\n${formatValue(key)}`,
206
206
  );
207
207
  }
@@ -1013,6 +1013,10 @@ export const TLC_JAVA_METHODS = new Map([
1013
1013
  "RandomElement",
1014
1014
  "public static tlc2.value.impl.Value tlc2.module.TLC.RandomElement(tlc2.value.impl.Value)",
1015
1015
  ],
1016
+ [
1017
+ "TLCGet",
1018
+ "public static tlc2.value.impl.Value tlc2.module.TLCGetSet.TLCGetEval(tlc2.tool.impl.Tool,tla2sany.semantic.ExprOrOpArgNode[],tlc2.util.Context,tlc2.tool.TLCState,tlc2.tool.TLCState,int,tlc2.tool.coverage.CostModel)",
1019
+ ],
1016
1020
  [
1017
1021
  "TLCEval",
1018
1022
  "public static tlc2.value.impl.Value tlc2.module.TLCEval.tlcEval(tlc2.tool.impl.Tool,tla2sany.semantic.ExprOrOpArgNode[],tlc2.util.Context,tlc2.tool.TLCState,tlc2.tool.TLCState,int,tlc2.tool.coverage.CostModel)",
package/src/tlc-order.ts CHANGED
@@ -278,9 +278,13 @@ const createModuleSet = (source: string, loadModule: ModuleLoader) => {
278
278
  (name === undefined ? undefined : nestedModules.get(name)) ?? getFile(name);
279
279
  };
280
280
 
281
- // The variables in the order TLC compares them: the reverse of the root module's context
282
- // enumeration, as ModuleNode.getVariableDecls returns them.
283
- export const getTlcVariableOrder = (source: string, loadModule: ModuleLoader): string[] => {
281
+ // The constants or variables in the order of ModuleNode.getConstantDecls or getVariableDecls: the
282
+ // reverse of the root module's context enumeration. TLC compares a state's variables in this order.
283
+ export const getTlcDeclarationOrder = (
284
+ source: string,
285
+ loadModule: ModuleLoader,
286
+ kind: "constant" | "variable",
287
+ ): string[] => {
284
288
  const getParsed = createModuleSet(source, loadModule);
285
289
  const getUnits = (unit: ParsedModule) => {
286
290
  const tokens = unit.tokens;
@@ -400,7 +404,7 @@ export const getTlcVariableOrder = (source: string, loadModule: ModuleLoader): s
400
404
  };
401
405
  return getContext(undefined)
402
406
  .enumerate()
403
- .filter((entry) => entry.kind === "variable")
407
+ .filter((entry) => entry.kind === kind)
404
408
  .map((entry) => entry.name)
405
409
  .reverse();
406
410
  };
package/src/tlc-random.ts CHANGED
@@ -181,8 +181,10 @@ const createShiftTable = (length: number) => {
181
181
 
182
182
  // Extending a fingerprint by a byte is linear over GF(2), so extending it by a value's bytes
183
183
  // XORs the value's own fingerprint from zero into the fingerprint shifted by their length.
184
- // The fingerprinter caches each distinct variable value for one pass over the stored states.
185
- export const createTlcFingerprinter = () => {
184
+ // The fingerprinter caches each distinct variable value for one pass over the stored states. It
185
+ // reads a state's variables in `order` and writes each fingerprint's low and high words into
186
+ // `words`, an Int32Array over a little-endian BigInt64Array.
187
+ export const createTlcFingerprinter = (order: number[], words: Int32Array) => {
186
188
  const shiftTables = new Map<number, Int32Array>();
187
189
  const indices = new Map<Value, number>();
188
190
  const contributions: number[] = [];
@@ -204,11 +206,11 @@ export const createTlcFingerprinter = () => {
204
206
  shiftTables.set(length, table);
205
207
  return table;
206
208
  };
207
- return (state: Value[]) => {
209
+ return (state: Value[], position: number) => {
208
210
  const outer = { high, low };
209
211
  const fingerprint = { high: INITIAL_HIGH, low: INITIAL_LOW };
210
- for (const value of state) {
211
- const contribution = getContribution(value);
212
+ for (const index of order) {
213
+ const contribution = getContribution(state[index]);
212
214
  const table = getShiftTable(contributions[contribution]);
213
215
  const extended = {
214
216
  high: contributions[contribution + 1],
@@ -225,7 +227,8 @@ export const createTlcFingerprinter = () => {
225
227
  }
226
228
  high = outer.high;
227
229
  low = outer.low;
228
- return (BigInt(fingerprint.high >>> 0) << 32n) | BigInt(fingerprint.low >>> 0);
230
+ words[2 * position] = fingerprint.low;
231
+ words[2 * position + 1] = fingerprint.high;
229
232
  };
230
233
  };
231
234