tla-ts 0.0.3-dev.91b9cf4 → 0.0.3-dev.949cce6

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tla-ts",
3
- "version": "0.0.3-dev.91b9cf4",
3
+ "version": "0.0.3-dev.949cce6",
4
4
  "description": "A TLA+ interpreter and model checker in TypeScript, 2× faster than TLC",
5
5
  "keywords": [
6
6
  "formal verification",
package/src/check.ts CHANGED
@@ -446,12 +446,12 @@ const getProperties = (config: ModelConfig, environment: Environment): Propertie
446
446
  config.properties.forEach((name) => {
447
447
  const definition = getConfigPredicate("property", name, environment);
448
448
  if (!definition) return;
449
- expandTemporal(definition.body, undefined, environment, true).forEach((item) => {
449
+ expandTemporal(definition.body, undefined, environment, true, name).forEach((item) => {
450
450
  const conjunct = item.expression;
451
451
  if (isConstantTrue(item, environment, "property")) return;
452
452
  if (conjunct.kind === "Always" && conjunct.expression.kind === "BoxAction") {
453
453
  properties.actionProperties.push({
454
- name,
454
+ name: item.name,
455
455
  box: conjunct.expression,
456
456
  action: conjunct.expression.action,
457
457
  subscript: conjunct.expression.subscript,
@@ -463,12 +463,22 @@ const getProperties = (config: ModelConfig, environment: Environment): Propertie
463
463
  conjunct.kind === "Always" &&
464
464
  getLevel(conjunct.expression, item.scope, environment) <= 1
465
465
  ) {
466
- properties.invariants.push({ name, expression: conjunct.expression, scope: item.scope });
466
+ // TLC names the invariant []P after P when P is an operator name.
467
+ const expression = conjunct.expression;
468
+ properties.invariants.push({
469
+ name: expression.kind === "Identifier" ? expression.name : item.name,
470
+ expression,
471
+ scope: item.scope,
472
+ });
467
473
  return;
468
474
  }
469
475
  const level = getLevel(conjunct, item.scope, environment);
470
476
  if (level < ACTION_LEVEL) {
471
- properties.initialPredicates.push({ name, expression: conjunct, scope: item.scope });
477
+ properties.initialPredicates.push({
478
+ name: item.name,
479
+ expression: conjunct,
480
+ scope: item.scope,
481
+ });
472
482
  return;
473
483
  }
474
484
  if (level === ACTION_LEVEL) {
@@ -777,11 +787,13 @@ export const createSearch = (
777
787
  if (view !== undefined || isFingerprintedLikeTlc) {
778
788
  return BigInt64Array.from(states, getTlcStateFingerprint);
779
789
  }
780
- const indices = getTlcOrder();
781
- const getFingerprint = createTlcFingerprinter();
782
- return BigInt64Array.from(fingerprintStates, (state) =>
783
- getFingerprint(indices.map((index) => state[index])),
790
+ const fingerprints = new BigInt64Array(fingerprintStates.length);
791
+ const fingerprint = createTlcFingerprinter(
792
+ getTlcOrder(),
793
+ new Int32Array(fingerprints.buffer),
784
794
  );
795
+ fingerprintStates.forEach(fingerprint);
796
+ return fingerprints;
785
797
  },
786
798
  getFingerprintState: (state) => {
787
799
  if (isFingerprintedLikeTlc) return [String(getTlcStateFingerprint(state))];
@@ -1037,7 +1049,9 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1037
1049
  const parents: number[] = [];
1038
1050
  const actions: (string | undefined)[] = [];
1039
1051
  const depths: number[] = [];
1040
- const buckets = new Map<number, number | number[]>();
1052
+ // A Map holds at most 2^24 entries, so an open-addressing table keeps each seen state's hash
1053
+ // and its index plus one side by side, probed by the hash.
1054
+ const seen = { slots: new Int32Array(1 << 17), size: 0, shift: 16 };
1041
1055
  const canonicalizeState = createCanonicalizer();
1042
1056
 
1043
1057
  const toRecord = (state: Value[]): Record<string, Value> =>
@@ -1197,19 +1211,35 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1197
1211
  }
1198
1212
  return true;
1199
1213
  };
1214
+ const getSlot = (hash: number) => (Math.imul(hash, 0x9e3779b1) >>> seen.shift) << 1;
1200
1215
  const findStateIndex = (hash: number, state: Value[]) => {
1201
- const bucket = buckets.get(hash);
1202
- if (bucket === undefined) return -1;
1203
- if (typeof bucket === "number") {
1204
- return isSameState(fingerprintStates[bucket], state) ? bucket : -1;
1216
+ const mask = seen.slots.length - 1;
1217
+ for (let slot = getSlot(hash); ; slot = (slot + 2) & mask) {
1218
+ const entry = seen.slots[slot + 1];
1219
+ if (entry === 0) return -1;
1220
+ if (seen.slots[slot] === hash && isSameState(fingerprintStates[entry - 1], state)) {
1221
+ return entry - 1;
1222
+ }
1205
1223
  }
1206
- return bucket.find((index) => isSameState(fingerprintStates[index], state)) ?? -1;
1224
+ };
1225
+ const insertSeen = (hash: number, entry: number) => {
1226
+ const mask = seen.slots.length - 1;
1227
+ let slot = getSlot(hash);
1228
+ while (seen.slots[slot + 1] !== 0) slot = (slot + 2) & mask;
1229
+ seen.slots[slot] = hash;
1230
+ seen.slots[slot + 1] = entry;
1207
1231
  };
1208
1232
  const markSeen = (hash: number, index: number) => {
1209
- const bucket = buckets.get(hash);
1210
- if (bucket === undefined) buckets.set(hash, index);
1211
- else if (typeof bucket === "number") buckets.set(hash, [bucket, index]);
1212
- else bucket.push(index);
1233
+ seen.size++;
1234
+ if (seen.size * 4 > seen.slots.length) {
1235
+ const slots = seen.slots;
1236
+ seen.slots = new Int32Array(slots.length * 2);
1237
+ seen.shift--;
1238
+ for (let slot = 0; slot < slots.length; slot += 2) {
1239
+ if (slots[slot + 1] !== 0) insertSeen(slots[slot], slots[slot + 1]);
1240
+ }
1241
+ }
1242
+ insertSeen(hash, index + 1);
1213
1243
  };
1214
1244
  const countDistinctState = (depth: number) => {
1215
1245
  runtime.distinctStates = states.length + 1;
package/src/evaluate.ts CHANGED
@@ -1027,7 +1027,7 @@ export const getEvaluator = (expression: Expression, environment: Environment):
1027
1027
 
1028
1028
  const entryEvaluators = new WeakMap<Expression, Evaluator>();
1029
1029
 
1030
- const getEntryEvaluator = (expression: Expression, environment: Environment) => {
1030
+ export const getEntryEvaluator = (expression: Expression, environment: Environment) => {
1031
1031
  const cached = entryEvaluators.get(expression);
1032
1032
  if (cached) return cached;
1033
1033
  const evaluator =
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,
@@ -48,9 +50,10 @@ interface Check {
48
50
  nodeStates: number[];
49
51
  nodeTableaux: number[];
50
52
  successors: number[][];
51
- actions: Uint8Array[];
52
- stateResults: Uint8Array[];
53
- isWritten: boolean[];
53
+ // Each written node's state results, then its action results edge by edge, from the node's
54
+ // offset in one buffer, so a node costs no objects of its own. An unwritten node has offset -1.
55
+ offsets: number[];
56
+ results: { bytes: Uint8Array; length: number };
54
57
  initial: number[];
55
58
  nodeIds: Map<number, number>;
56
59
  nodesByState: Map<number, number[]>;
@@ -58,26 +61,6 @@ interface Check {
58
61
  errorNode: number | undefined;
59
62
  }
60
63
 
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
64
  const isSameState = (left: Value[], right: Value[]) =>
82
65
  left.every((value, position) => isSameValue(value, right[position]));
83
66
 
@@ -89,12 +72,15 @@ const pushNode = (check: Check, state: number, tableauNode: number) => {
89
72
  check.nodeStates.push(state);
90
73
  check.nodeTableaux.push(tableauNode);
91
74
  check.successors.push([]);
92
- check.actions.push(new Uint8Array(0));
93
- check.stateResults.push(new Uint8Array(0));
94
- check.isWritten.push(false);
75
+ check.offsets.push(-1);
95
76
  return check.nodeStates.length - 1;
96
77
  };
97
78
 
79
+ const isWritten = (check: Check, node: number) => check.offsets[node] !== -1;
80
+
81
+ const getStateResult = (check: Check, node: number, position: number) =>
82
+ check.results.bytes[check.offsets[node] + position] === 1;
83
+
98
84
  const SUCCESSOR_CAPACITY = 16;
99
85
 
100
86
  const SCC_MARKER = -42;
@@ -121,13 +107,13 @@ export const createLivenessChecker = (
121
107
  fairness.length === 0 ? violation : createJunction("And", [...fairness, violation]);
122
108
  const solutions = getSolutions(formula);
123
109
  if (solutions.length === 0) {
124
- throw new TlaEvaluationError("Temporal formula is a tautology (its negation is unsatisfiable)");
110
+ throw new TlaEvaluationError(TAUTOLOGY_MESSAGE);
125
111
  }
126
112
  const actionIds = new Map<string, number>();
127
113
  const checks = solutions.map((solution): Check => ({
128
114
  solution,
129
115
  actionIds: Int32Array.from(solution.actionChecks, (predicate) => {
130
- const key = getLiveKey(predicate);
116
+ const key = getTermKey(predicate);
131
117
  const id = actionIds.get(key) ?? actionIds.size;
132
118
  actionIds.set(key, id);
133
119
  return id;
@@ -135,9 +121,8 @@ export const createLivenessChecker = (
135
121
  nodeStates: [],
136
122
  nodeTableaux: [],
137
123
  successors: [],
138
- actions: [],
139
- stateResults: [],
140
- isWritten: [],
124
+ offsets: [],
125
+ results: { bytes: new Uint8Array(1024), length: 0 },
141
126
  initial: [],
142
127
  nodeIds: new Map(),
143
128
  nodesByState: new Map(),
@@ -245,11 +230,21 @@ export const createLivenessChecker = (
245
230
  stateResults: Uint8Array,
246
231
  ) => {
247
232
  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;
233
+ const results = check.results;
234
+ const offset = results.length;
235
+ results.length += stateResults.length + actions.length * actionCount;
236
+ if (results.length > results.bytes.length) {
237
+ const grown = new Uint8Array(Math.max(2 * results.bytes.length, results.length));
238
+ grown.set(results.bytes);
239
+ results.bytes = grown;
240
+ }
241
+ results.bytes.set(stateResults, offset);
242
+ actions.forEach((edge, position) =>
243
+ results.bytes.set(edge, offset + stateResults.length + position * actionCount),
244
+ );
245
+ check.offsets[node] = offset;
246
+ // A node gets no successors once written, so it keeps them without spare capacity.
247
+ check.successors[node] = check.successors[node].slice();
253
248
  };
254
249
 
255
250
  // TLC collects a state's successors and the state itself in a SetOfStates, a hash set it
@@ -389,7 +384,7 @@ export const createLivenessChecker = (
389
384
  const successors = check.successors[index];
390
385
  const actions: Uint8Array[] = [];
391
386
  set.forEach((successor, position) => {
392
- if (check.isWritten[successor.index] && successors.includes(successor.index)) return;
387
+ if (isWritten(check, successor.index) && successors.includes(successor.index)) return;
393
388
  successors.push(successor.index);
394
389
  actions.push(actionResults[position]);
395
390
  });
@@ -403,7 +398,7 @@ export const createLivenessChecker = (
403
398
  const parents = new Map<number, number>();
404
399
  const queue: number[] = [];
405
400
  for (const node of check.initial) {
406
- if (!check.isWritten[node]) continue;
401
+ if (!isWritten(check, node)) continue;
407
402
  queue.push(node);
408
403
  parents.set(node, -1);
409
404
  }
@@ -416,7 +411,7 @@ export const createLivenessChecker = (
416
411
  for (let node = current; node !== -1; node = parents.get(node) ?? -1) path.push(node);
417
412
  return path;
418
413
  }
419
- if (!check.isWritten[next] || parents.has(next)) continue;
414
+ if (!isWritten(check, next) || parents.has(next)) continue;
420
415
  parents.set(next, current);
421
416
  queue.push(next);
422
417
  }
@@ -428,12 +423,13 @@ export const createLivenessChecker = (
428
423
  const findInModel = (check: Check, model: Solution["models"][number]): Lasso | undefined => {
429
424
  const solution = check.solution;
430
425
  const actionCount = solution.actionChecks.length;
426
+ const stateCount = solution.stateChecks.length;
431
427
  const getAction = (node: number, edge: number, position: number) =>
432
- check.actions[node][edge * actionCount + position] === 1;
428
+ check.results.bytes[check.offsets[node] + stateCount + edge * actionCount + position] === 1;
433
429
  const isAllowed = (node: number, edge: number) =>
434
430
  model.eventuallyAlways.every((position) => getAction(node, edge, position));
435
431
  const links = new Float64Array(check.nodeStates.length).fill(UNVISITED);
436
- const queue = check.initial.filter((node) => check.isWritten[node]);
432
+ const queue = check.initial.filter((node) => isWritten(check, node));
437
433
  const components: number[] = [];
438
434
 
439
435
  const isStuttering = (node: number) => {
@@ -461,7 +457,7 @@ export const createLivenessChecker = (
461
457
  if (member === root) break;
462
458
  }
463
459
  const isStateSatisfied = model.infinitelyOftenStates.every((position) =>
464
- [...members].some((node) => check.stateResults[node][position] === 1),
460
+ [...members].some((node) => getStateResult(check, node, position)),
465
461
  );
466
462
  const isActionSatisfied = model.infinitelyOftenActions.every((position) =>
467
463
  [...members].some((node) =>
@@ -506,7 +502,7 @@ export const createLivenessChecker = (
506
502
  const countAtStart = remaining.count;
507
503
  while (true) {
508
504
  model.infinitelyOftenStates.forEach((position, slot) => {
509
- if (!stateDone[slot] && check.stateResults[current.node][position] === 1) {
505
+ if (!stateDone[slot] && getStateResult(check, current.node, position)) {
510
506
  stateDone[slot] = true;
511
507
  remaining.count--;
512
508
  }
@@ -639,7 +635,7 @@ export const createLivenessChecker = (
639
635
  components.push(node);
640
636
  const nextLowLink = { value: counter.link++ };
641
637
  check.successors[node].forEach((next, edge) => {
642
- if (!check.isWritten[next]) return;
638
+ if (!isWritten(check, next)) return;
643
639
  if (!isAllowed(node, edge)) {
644
640
  if (links[next] === UNVISITED) queue.push(next);
645
641
  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/successors.ts CHANGED
@@ -18,6 +18,7 @@ import {
18
18
  bindValue,
19
19
  compileArgumentScope,
20
20
  evaluate,
21
+ getEntryEvaluator,
21
22
  expectBoolean,
22
23
  forEachBinding,
23
24
  getBoundsDomain,
@@ -29,6 +30,7 @@ import {
29
30
  resolveGlobalOperator,
30
31
  type Context,
31
32
  type Environment,
33
+ type Evaluator,
32
34
  type Scope,
33
35
  type State,
34
36
  } from "./evaluate";
@@ -87,8 +89,7 @@ const assign = (partial: State, index: number, value: Value) => {
87
89
  return copy;
88
90
  };
89
91
 
90
- const holds = (expression: Expression, context: Context) => {
91
- const value = evaluate(expression, context);
92
+ const holds = (expression: Expression, context: Context, value = evaluate(expression, context)) => {
92
93
  if (typeof value === "boolean") return value;
93
94
  try {
94
95
  return expectBoolean(value, `the action at ${describeLocation(expression)}`);
@@ -320,6 +321,7 @@ const compileConjunction = (
320
321
  isInit: boolean,
321
322
  ): Runner => {
322
323
  const conjuncts = operands.map((operand) => toConjunct(operand, environment, isInit));
324
+ const evaluators: (Evaluator | undefined)[] = conjuncts.map(() => undefined);
323
325
  const runFrom = (
324
326
  start: number,
325
327
  run: Run,
@@ -342,12 +344,17 @@ const compileConjunction = (
342
344
  const conjunct = conjuncts[index];
343
345
  if (conjunct.kind === "Guard") {
344
346
  context ??= getContext(run, scope, current);
345
- if (!holds(conjunct.expression, context)) return;
347
+ const evaluator = (evaluators[index] ??= getEntryEvaluator(
348
+ conjunct.expression,
349
+ environment,
350
+ ));
351
+ if (!holds(conjunct.expression, context, evaluator(context))) return;
346
352
  continue;
347
353
  }
348
354
  if (conjunct.kind === "Assign") {
349
355
  context ??= getContext(run, scope, current);
350
- const value = evaluate(conjunct.value, context);
356
+ const evaluator = (evaluators[index] ??= getEntryEvaluator(conjunct.value, environment));
357
+ const value = evaluator(context);
351
358
  const assigned = current[conjunct.index];
352
359
  if (assigned === undefined) {
353
360
  current = assign(current, conjunct.index, value);
package/src/tableau.ts CHANGED
@@ -162,22 +162,39 @@ const containsAction = (expression: LiveExpression): boolean => {
162
162
  }
163
163
  };
164
164
 
165
- const isEqual = (left: LiveExpression, right: LiveExpression): boolean => {
166
- if (left.kind !== right.kind) return false;
167
- if (left.kind === "Boolean" && right.kind === "Boolean") return left.value === right.value;
168
- if (isAtom(left)) return left === right;
169
- if ("body" in left && "body" in right) return isEqual(left.body, right.body);
170
- if ("operands" in left && "operands" in right) {
171
- return (
172
- left.operands.length === right.operands.length &&
173
- left.operands.every((operand, index) => isEqual(operand, right.operands[index]))
174
- );
175
- }
176
- return false;
165
+ const termKeys = new WeakMap<LiveExpression, string>();
166
+ const atoms = { count: 0 };
167
+
168
+ // A term's structure as a string in which each atom stands for itself, so equal terms share a key.
169
+ export const getTermKey = (expression: LiveExpression): string => {
170
+ const cached = termKeys.get(expression);
171
+ if (cached !== undefined) return cached;
172
+ const key = (() => {
173
+ switch (expression.kind) {
174
+ case "Boolean":
175
+ return String(expression.value);
176
+ case "State":
177
+ case "Enabled":
178
+ case "Action":
179
+ return `#${atoms.count++}`;
180
+ case "And":
181
+ case "Or":
182
+ return `${expression.kind}(${expression.operands.map(getTermKey).join(",")})`;
183
+ default:
184
+ return `${expression.kind}(${getTermKey(expression.body)})`;
185
+ }
186
+ })();
187
+ termKeys.set(expression, key);
188
+ return key;
177
189
  };
178
190
 
179
- const isMember = (items: LiveExpression[], expression: LiveExpression) =>
180
- items.some((item) => isEqual(item, expression));
191
+ const isEqual = (left: LiveExpression, right: LiveExpression) =>
192
+ left === right || getTermKey(left) === getTermKey(right);
193
+
194
+ const isMember = (items: LiveExpression[], expression: LiveExpression) => {
195
+ const key = getTermKey(expression);
196
+ return items.some((item) => item === expression || getTermKey(item) === key);
197
+ };
181
198
 
182
199
  const getDual = (kind: LiveJunction["kind"]) => (kind === "And" ? "Or" : "And");
183
200
 
@@ -446,13 +463,14 @@ const getTriples = (
446
463
  return parts ? [{ whole: term, first: parts.first, second: parts.second }] : [];
447
464
  });
448
465
 
449
- const isSameParticle = (left: LiveExpression[], right: LiveExpression[]) =>
450
- left.every((term) => isMember(right, term)) && right.every((term) => isMember(left, term));
466
+ // A particle is a set of terms, so its key ignores order and repeats.
467
+ const getParticleKey = (particle: LiveExpression[]) =>
468
+ [...new Set(particle.map(getTermKey))].sort().join("|");
451
469
 
452
- const unionParticles = (left: LiveExpression[][], right: LiveExpression[][]) => [
453
- ...left.filter((particle) => !right.some((other) => isSameParticle(particle, other))),
454
- ...right,
455
- ];
470
+ const unionParticles = (left: LiveExpression[][], right: LiveExpression[][]) => {
471
+ const rightKeys = new Set(right.map(getParticleKey));
472
+ return [...left.filter((particle) => !rightKeys.has(getParticleKey(particle))), ...right];
473
+ };
456
474
 
457
475
  const getParticleClosure = (terms: LiveExpression[]) => {
458
476
  const closure = getPositiveClosure(terms);
@@ -516,14 +534,23 @@ const createTableauNode = (particle: LiveExpression[]): TableauNode => ({
516
534
  const createTableau = (formula: LiveExpression) => {
517
535
  const nodes = getParticleClosure([formula]).map(createTableauNode);
518
536
  const initialCount = nodes.length;
537
+ const indices = new Map<string, number>();
538
+ nodes.forEach((node, index) => {
539
+ const key = getParticleKey(node.particle);
540
+ if (!indices.has(key)) indices.set(key, index);
541
+ });
519
542
  for (let index = 0; index < nodes.length; index++) {
520
543
  const implied = nodes[index].particle.flatMap((term) =>
521
544
  term.kind === "Next" ? [term.body] : [],
522
545
  );
523
546
  for (const particle of getParticleClosure(implied)) {
524
- const existing = nodes.findIndex((node) => isSameParticle(node.particle, particle));
525
- if (existing === -1) nodes.push(createTableauNode(particle));
526
- nodes[index].successors.push(existing === -1 ? nodes.length - 1 : existing);
547
+ const key = getParticleKey(particle);
548
+ const existing = indices.get(key);
549
+ if (existing === undefined) {
550
+ indices.set(key, nodes.length);
551
+ nodes.push(createTableauNode(particle));
552
+ }
553
+ nodes[index].successors.push(existing ?? nodes.length - 1);
527
554
  }
528
555
  }
529
556
  return { nodes, initialCount };
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