tla-ts 0.0.7 → 0.0.8-dev.d9bffda

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/symmetry.ts CHANGED
@@ -13,41 +13,16 @@ import {
13
13
  isEnumerable,
14
14
  isFunctionValue,
15
15
  isModelValue,
16
- isSameValue,
17
16
  isSetValue,
18
17
  toFiniteFunction,
19
18
  toFiniteSet,
20
19
  type ModelValue,
21
- type ObjectValue,
22
20
  type Value,
23
21
  } from "./values";
24
22
 
23
+ // The image of each model value a permutation moves, by name.
25
24
  type Images = Map<string, ModelValue>;
26
25
 
27
- const CACHE_LIMIT = 1 << 22;
28
- const CACHED_SIZE_LIMIT = 64;
29
-
30
- interface Permutation {
31
- images: Images;
32
- cache: WeakMap<ObjectValue, Value>;
33
- cacheSize: number;
34
- cacheLimit: number;
35
- }
36
-
37
- // The images of one value under every permutation, the identity first, and how each image compares
38
- // with the image of each permutation the search has held as the smallest.
39
- interface Orbit {
40
- images: Value[];
41
- comparisons: (Int8Array | undefined)[];
42
- }
43
-
44
- interface SymmetryGroup {
45
- permutations: Permutation[];
46
- orbits: WeakMap<ObjectValue, Orbit>;
47
- orbitCount: number;
48
- orbitLimit: number;
49
- }
50
-
51
26
  const getPermutationKey = (permutation: Images) =>
52
27
  [...permutation]
53
28
  .map(([name, image]) => `${name}>${image.name}`)
@@ -104,7 +79,7 @@ export const getSymmetryGroup = (
104
79
  name: string,
105
80
  environment: Environment,
106
81
  substitutions: Substitution[],
107
- ): SymmetryGroup | undefined => {
82
+ ): Images[] | undefined => {
108
83
  const definition = environment.definitions.get(name);
109
84
  if (definition === undefined && !environment.constants.has(name)) {
110
85
  throw new TlaConfigError(
@@ -187,29 +162,18 @@ export const getSymmetryGroup = (
187
162
  }),
188
163
  );
189
164
  if (group.size === 0) return undefined;
190
- const cacheLimit = Math.max(256, Math.floor(CACHE_LIMIT / group.size));
191
- return {
192
- permutations: [...group.values()].map((images) => ({
193
- images,
194
- cache: new WeakMap<ObjectValue, Value>(),
195
- cacheSize: 0,
196
- cacheLimit,
197
- })),
198
- orbits: new WeakMap(),
199
- orbitCount: 0,
200
- orbitLimit: cacheLimit,
201
- };
165
+ return [...group.values()];
202
166
  };
203
167
 
204
- const permuteElements = (elements: Value[], permutation: Permutation) => {
168
+ const permuteElements = (elements: Value[], images: Images) => {
205
169
  for (let index = 0; index < elements.length; index++) {
206
170
  const element = elements[index];
207
- const permuted = permuteValue(element, permutation);
171
+ const permuted = permuteValue(element, images);
208
172
  if (permuted === element) continue;
209
173
  const result = elements.slice(0, index);
210
174
  result.push(permuted);
211
175
  for (let rest = index + 1; rest < elements.length; rest++) {
212
- result.push(permuteValue(elements[rest], permutation));
176
+ result.push(permuteValue(elements[rest], images));
213
177
  }
214
178
  return result;
215
179
  }
@@ -218,11 +182,11 @@ const permuteElements = (elements: Value[], permutation: Permutation) => {
218
182
 
219
183
  // A permutation maps distinct elements to distinct elements and keeps the elements it doesn't move
220
184
  // in order, so it sorts only the moved ones and merges them back.
221
- const permuteSortedElements = (elements: Value[], permutation: Permutation) => {
185
+ const permuteSortedElements = (elements: Value[], images: Images) => {
222
186
  const kept: Value[] = [];
223
187
  const moved: Value[] = [];
224
188
  for (const element of elements) {
225
- const permuted = permuteValue(element, permutation);
189
+ const permuted = permuteValue(element, images);
226
190
  if (permuted === element) kept.push(element);
227
191
  else moved.push(permuted);
228
192
  }
@@ -243,43 +207,20 @@ const permuteSortedElements = (elements: Value[], permutation: Permutation) => {
243
207
  return merged;
244
208
  };
245
209
 
246
- const getSize = (value: ObjectValue) =>
247
- value.kind === "Set"
248
- ? value.elements.length
249
- : value.kind === "Function"
250
- ? value.domain.length
251
- : 0;
252
-
253
- const permuteValue = (value: Value, permutation: Permutation): Value => {
210
+ // Value#permute: the value with each model value replaced by its image. A value the permutation
211
+ // doesn't move is returned itself, so that comparing it with itself stops at identity.
212
+ const permuteValue = (value: Value, images: Images): Value => {
254
213
  if (typeof value !== "object") return value;
255
- if (value.kind === "ModelValue") return permutation.images.get(value.name) ?? value;
256
- const size = getSize(value);
257
- if (size === 0 || size > CACHED_SIZE_LIMIT) return computePermutedValue(value, permutation);
258
- const cached = permutation.cache.get(value);
259
- if (cached !== undefined) return cached;
260
- const computed = computePermutedValue(value, permutation);
261
- // A permutation often maps a value to an equal one. Keeping the original lets the comparison
262
- // with the smallest state so far stop at identity.
263
- const permuted = computed !== value && isSameValue(computed, value) ? value : computed;
264
- if (permutation.cacheSize >= permutation.cacheLimit) {
265
- permutation.cache = new WeakMap();
266
- permutation.cacheSize = 0;
267
- }
268
- permutation.cache.set(value, permuted);
269
- permutation.cacheSize++;
270
- return permuted;
271
- };
272
-
273
- const computePermutedValue = (value: ObjectValue, permutation: Permutation) => {
274
214
  const kind = value.kind;
215
+ if (kind === "ModelValue") return images.get(value.name) ?? value;
275
216
  if (kind === "Set") {
276
- const elements = permuteSortedElements(value.elements, permutation);
217
+ const elements = permuteSortedElements(value.elements, images);
277
218
  return elements ? createSortedSet(elements) : value;
278
219
  }
279
220
  if (kind === "Function" || (kind === "LazyFunction" && isEnumerable(value.domain))) {
280
221
  const functionValue = toFiniteFunction(value);
281
- const domain = permuteElements(functionValue.domain, permutation);
282
- const range = permuteElements(functionValue.range, permutation) ?? functionValue.range;
222
+ const domain = permuteElements(functionValue.domain, images);
223
+ const range = permuteElements(functionValue.range, images) ?? functionValue.range;
283
224
  if (domain) {
284
225
  const permuted = createFunction(
285
226
  domain.map((key, index): [Value, Value] => [key, range[index]]),
@@ -297,80 +238,28 @@ const computePermutedValue = (value: ObjectValue, permutation: Permutation) => {
297
238
  }
298
239
  if (kind === "Interval" || !isSetValue(value) || !isEnumerable(value)) return value;
299
240
  const set = toFiniteSet(value);
300
- const elements = permuteElements(set.elements, permutation);
241
+ const elements = permuteElements(set.elements, images);
301
242
  return elements ? createSet(elements) : set;
302
243
  };
303
244
 
304
- const getOrbit = (value: ObjectValue, group: SymmetryGroup) => {
305
- const cached = group.orbits.get(value);
306
- if (cached !== undefined) return cached;
307
- if (group.orbitCount >= group.orbitLimit) {
308
- group.orbits = new WeakMap();
309
- group.orbitCount = 0;
310
- }
311
- const orbit: Orbit = { images: [value], comparisons: [] };
312
- group.orbits.set(value, orbit);
313
- group.orbitCount++;
314
- return orbit;
315
- };
316
-
317
- const getImage = (orbit: Orbit, permutation: number, group: SymmetryGroup) =>
318
- (orbit.images[permutation] ??= permuteValue(
319
- orbit.images[0],
320
- group.permutations[permutation - 1],
321
- ));
322
-
323
- // Two images of a value compare the same way every time, and comparing them again changes nothing,
324
- // so an orbit compares each pair once.
325
- const compareImages = (
326
- value: ObjectValue,
327
- permutation: number,
328
- minimum: number,
329
- group: SymmetryGroup,
330
- ) => {
331
- const orbit = getOrbit(value, group);
332
- const comparisons = (orbit.comparisons[minimum] ??= new Int8Array(group.permutations.length + 1));
333
- if (comparisons[permutation] === 0) {
334
- const comparison = compareValues(
335
- getImage(orbit, permutation, group),
336
- getImage(orbit, minimum, group),
337
- );
338
- comparisons[permutation] = Math.sign(comparison) + 2;
339
- }
340
- return comparisons[permutation] - 2;
341
- };
342
-
343
- const isSmallerImage = (
344
- state: Value[],
345
- permutation: number,
346
- minimum: number,
347
- group: SymmetryGroup,
348
- order: number[],
349
- ) => {
350
- for (const index of order) {
351
- const value = state[index];
352
- const comparison =
353
- typeof value === "object" ? compareImages(value, permutation, minimum, group) : 0;
354
- if (comparison !== 0) return comparison < 0;
355
- }
356
- return false;
357
- };
358
-
359
- // TLC keeps the smallest image of the state in its variable order, replacing it only with a
360
- // strictly smaller one.
245
+ // TLCStateMut#fingerPrint: the smallest image of the state under the group in TLC's variable
246
+ // order. TLC permutes the state under each permutation, variable by variable, and moves on to the
247
+ // next permutation as soon as a variable's image is larger than the smallest state's.
361
248
  export const getRepresentative = (
362
249
  state: Value[],
363
- group: SymmetryGroup,
250
+ permutations: Images[],
364
251
  order: number[],
365
252
  ): Value[] => {
366
- const minimum = group.permutations.reduce(
367
- (smallest, _, index) =>
368
- isSmallerImage(state, index + 1, smallest, group, order) ? index + 1 : smallest,
369
- 0,
370
- );
371
- return minimum === 0
372
- ? state
373
- : state.map((value) =>
374
- typeof value === "object" ? getImage(getOrbit(value, group), minimum, group) : value,
375
- );
253
+ let smallest = state;
254
+ for (const images of permutations) {
255
+ const permuted = state.slice();
256
+ let comparison = 0;
257
+ for (const index of order) {
258
+ permuted[index] = permuteValue(state[index], images);
259
+ if (comparison === 0) comparison = compareValues(permuted[index], smallest[index]);
260
+ if (comparison > 0) break;
261
+ }
262
+ if (comparison < 0) smallest = permuted;
263
+ }
264
+ return smallest;
376
265
  };
@@ -43,8 +43,48 @@ const extendByte = (byte: number) => {
43
43
  high = (high >>> 8) ^ BYTE_MOD_HIGH[index];
44
44
  };
45
45
 
46
- const extendInt = (value: number) => {
47
- for (let shift = 0; shift < 32; shift += 8) extendByte(value >>> shift);
46
+ // Extending is linear over GF(2), so extending by four bytes at once shifts the fingerprint by a
47
+ // word and adds, for each of the four, the fingerprint from zero of that byte followed by the zero
48
+ // bytes that come after it: SLICE_HIGH[k] and SLICE_LOW[k] hold them for k zero bytes after.
49
+ const createSliceTables = () => {
50
+ const highs = [BYTE_MOD_HIGH];
51
+ const lows = [BYTE_MOD_LOW];
52
+ for (let zeros = 1; zeros < 4; zeros++) {
53
+ const previousHigh = highs[zeros - 1];
54
+ const previousLow = lows[zeros - 1];
55
+ const sliceHigh = new Int32Array(256);
56
+ const sliceLow = new Int32Array(256);
57
+ for (let byte = 0; byte < 256; byte++) {
58
+ const index = previousLow[byte] & 0xff;
59
+ sliceLow[byte] =
60
+ ((previousLow[byte] >>> 8) | (previousHigh[byte] << 24)) ^ BYTE_MOD_LOW[index];
61
+ sliceHigh[byte] = (previousHigh[byte] >>> 8) ^ BYTE_MOD_HIGH[index];
62
+ }
63
+ highs.push(sliceHigh);
64
+ lows.push(sliceLow);
65
+ }
66
+ return { highs, lows };
67
+ };
68
+
69
+ const SLICES = createSliceTables();
70
+ const SLICE_HIGH_0 = SLICES.highs[0];
71
+ const SLICE_HIGH_1 = SLICES.highs[1];
72
+ const SLICE_HIGH_2 = SLICES.highs[2];
73
+ const SLICE_HIGH_3 = SLICES.highs[3];
74
+ const SLICE_LOW_0 = SLICES.lows[0];
75
+ const SLICE_LOW_1 = SLICES.lows[1];
76
+ const SLICE_LOW_2 = SLICES.lows[2];
77
+ const SLICE_LOW_3 = SLICES.lows[3];
78
+
79
+ // Extends the fingerprint by the four bytes of a word, lowest first.
80
+ const extendInt = (word: number) => {
81
+ const mixed = low ^ word;
82
+ const first = mixed & 0xff;
83
+ const second = (mixed >>> 8) & 0xff;
84
+ const third = (mixed >>> 16) & 0xff;
85
+ const fourth = mixed >>> 24;
86
+ low = high ^ SLICE_LOW_3[first] ^ SLICE_LOW_2[second] ^ SLICE_LOW_1[third] ^ SLICE_LOW_0[fourth];
87
+ high = SLICE_HIGH_3[first] ^ SLICE_HIGH_2[second] ^ SLICE_HIGH_1[third] ^ SLICE_HIGH_0[fourth];
48
88
  };
49
89
 
50
90
  const BOOL_VALUE = 0;
@@ -71,9 +111,16 @@ const extendScalar = (value: boolean | number | string | ModelValue) => {
71
111
  if (typeof value === "string") {
72
112
  extendByte(STRING_VALUE);
73
113
  extendInt(value.length);
74
- for (let index = 0; index < value.length; index++) {
75
- extendByte(value.charCodeAt(index));
114
+ const whole = value.length & ~3;
115
+ for (let index = 0; index < whole; index += 4) {
116
+ extendInt(
117
+ (value.charCodeAt(index) & 0xff) |
118
+ ((value.charCodeAt(index + 1) & 0xff) << 8) |
119
+ ((value.charCodeAt(index + 2) & 0xff) << 16) |
120
+ ((value.charCodeAt(index + 3) & 0xff) << 24),
121
+ );
76
122
  }
123
+ for (let index = whole; index < value.length; index++) extendByte(value.charCodeAt(index));
77
124
  return 5 + value.length;
78
125
  }
79
126
  extendByte(MODEL_VALUE);
@@ -114,116 +161,22 @@ export const getTlcFingerprint = (state: Value[]) => {
114
161
  return fingerprint;
115
162
  };
116
163
 
117
- // The fingerprint after `length` zero bytes, as one table per byte of the fingerprint it shifts.
118
- const createShiftTable = (length: number) => {
119
- const table = new Int32Array(8 * 256 * 2);
120
- for (let bit = 0; bit < 64; bit++) {
121
- high = bit < 32 ? 0 : 1 << (bit - 32);
122
- low = bit < 32 ? 1 << bit : 0;
123
- for (let step = 0; step < length; step++) extendByte(0);
124
- const position = bit >> 3;
125
- const mask = 1 << (bit & 7);
126
- for (let byte = mask; byte < 2 * mask; byte++) {
127
- const entry = (position * 256 + byte) * 2;
128
- const rest = (position * 256 + byte - mask) * 2;
129
- table[entry] = table[rest] ^ high;
130
- table[entry + 1] = table[rest + 1] ^ low;
131
- }
132
- }
133
- return table;
134
- };
135
-
136
- // The functions and sets a fingerprinter caches before it starts over, which bounds the values it
137
- // keeps alive.
138
- const CACHED_VALUE_LIMIT = 1 << 22;
139
-
140
- // Extending a fingerprint by a byte is linear over GF(2), so extending it by a value's bytes
141
- // XORs the value's own fingerprint from zero into the fingerprint shifted by their length.
142
- // The fingerprinter caches each distinct function or set it meets, nested ones included, across
143
- // every batch of states it fingerprints, as states share most of their values, even states of
144
- // different levels. It reads a state's variables in `order`.
145
- export const createTlcFingerprinter = (order: number[], limit = CACHED_VALUE_LIMIT) => {
146
- const shiftTables = new Map<number, Int32Array>();
147
- const ids = new Map<Value, number>();
148
- // The byte count and fingerprint from zero of each cached value, three numbers per id, and the
149
- // shift table for its byte count.
150
- const contributions: number[] = [];
151
- const contributionShiftTables: Int32Array[] = [];
152
- const getShiftTable = (length: number) => {
153
- const cached = shiftTables.get(length);
154
- if (cached) return cached;
155
- const table = createShiftTable(length);
156
- shiftTables.set(length, table);
157
- return table;
158
- };
159
- // Extends the fingerprint by a value's bytes and returns how many there are.
160
- const extendElement = (value: Value): number => {
161
- if (typeof value !== "object" || isModelValue(value)) return extendScalar(value);
162
- const id = getId(value);
163
- const table = contributionShiftTables[id];
164
- const shiftedHigh = high;
165
- const shiftedLow = low;
166
- high = contributions[3 * id + 1];
167
- low = contributions[3 * id + 2];
168
- for (let position = 0; position < 8; position++) {
169
- const word = position < 4 ? shiftedLow : shiftedHigh;
170
- const entry = (position * 256 + ((word >>> ((position & 3) * 8)) & 0xff)) * 2;
171
- high ^= table[entry];
172
- low ^= table[entry + 1];
173
- }
174
- return contributions[3 * id];
175
- };
176
- const getId = (value: Value) => {
177
- const cached = ids.get(value);
178
- if (cached !== undefined) return cached;
179
- const outerHigh = high;
180
- const outerLow = low;
181
- high = 0;
182
- low = 0;
183
- const length = { value: 5 };
184
- if (isFunctionValue(value)) {
185
- const functionValue = toFiniteFunction(value);
186
- extendByte(FCN_RCD_VALUE);
187
- extendInt(functionValue.domain.length);
188
- for (let index = 0; index < functionValue.domain.length; index++) {
189
- length.value += extendElement(functionValue.domain[index]);
190
- length.value += extendElement(functionValue.range[index]);
191
- }
192
- } else {
193
- const elements = toFiniteSet(value).elements;
194
- extendByte(SET_ENUM_VALUE);
195
- extendInt(elements.length);
196
- for (const element of elements) length.value += extendElement(element);
197
- }
198
- const id = contributionShiftTables.length;
199
- ids.set(value, id);
200
- contributions.push(length.value, high, low);
201
- contributionShiftTables.push(getShiftTable(length.value));
202
- high = outerHigh;
203
- low = outerLow;
204
- return id;
205
- };
206
- return (states: Value[][]) => {
207
- const fingerprints = new BigInt64Array(states.length);
208
- // Each fingerprint's low and high words, as a BigInt64Array is little-endian.
209
- const words = new Int32Array(fingerprints.buffer);
210
- const outerHigh = high;
211
- const outerLow = low;
212
- states.forEach((state, position) => {
213
- if (ids.size >= limit) {
214
- shiftTables.clear();
215
- ids.clear();
216
- contributions.length = 0;
217
- contributionShiftTables.length = 0;
218
- }
219
- high = INITIAL_HIGH;
220
- low = INITIAL_LOW;
221
- for (const index of order) extendElement(state[index]);
222
- words[2 * position] = low;
223
- words[2 * position + 1] = high;
224
- });
225
- high = outerHigh;
226
- low = outerLow;
227
- return fingerprints;
228
- };
164
+ // TLCStateMut#fingerPrint of each state's variables in TLC's variable order, as the fingerprint
165
+ // store reads them.
166
+ export const getTlcFingerprints = (states: Value[][], order: number[]) => {
167
+ const fingerprints = new BigInt64Array(states.length);
168
+ // Each fingerprint's low and high words, as a BigInt64Array is little-endian.
169
+ const words = new Int32Array(fingerprints.buffer);
170
+ const outerHigh = high;
171
+ const outerLow = low;
172
+ states.forEach((state, position) => {
173
+ high = INITIAL_HIGH;
174
+ low = INITIAL_LOW;
175
+ for (const index of order) extendValue(state[index]);
176
+ words[2 * position] = low;
177
+ words[2 * position + 1] = high;
178
+ });
179
+ high = outerHigh;
180
+ low = outerLow;
181
+ return fingerprints;
229
182
  };