tla-ts 0.0.7 → 0.0.8-dev.4114a01

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.
@@ -74,13 +74,14 @@ const getFieldName = (pair: OpApplNode) => {
74
74
  return name?.kind === "String" ? name : undefined;
75
75
  };
76
76
 
77
- // Records.sameDomain.
78
- const isSameDomain = (record: OpApplNode, other: OpApplNode) => {
79
- if (record === other) return true;
80
- if (record.operands.length !== other.operands.length) return false;
81
- const names = new Set(getFieldPairs(other).map((pair) => getFieldName(pair)?.value));
82
- return getFieldPairs(record).every((pair) => names.has(getFieldName(pair)?.value));
83
- };
77
+ // Records.sameDomain, given that SANY rejects a record with two fields of the same name.
78
+ const getDomain = (record: OpApplNode) =>
79
+ JSON.stringify([
80
+ record.operands.length,
81
+ ...getFieldPairs(record)
82
+ .map((pair) => getFieldName(pair)?.value)
83
+ .sort(),
84
+ ]);
84
85
 
85
86
  // ModuleNode.getExtendedModuleSet(true).
86
87
  const getExtendedModules = (module: ModuleNode, found = new Set<ModuleNode>()) => {
@@ -94,19 +95,9 @@ const getExtendedModules = (module: ModuleNode, found = new Set<ModuleNode>()) =
94
95
 
95
96
  // Linter.lintRecords: the warnings for the records of a module.
96
97
  export const lintSanyModule = (module: ModuleNode): SanyMessage[] => {
97
- const allRecords = [
98
- ...[...getExtendedModules(module)].flatMap((extended) => extended.records),
99
- ...module.records,
100
- ];
101
- return module.records.flatMap((record) => {
102
- // Linter checks the field's value, the record's fields and the fields of every record with the
103
- // same domain, which includes the record itself.
104
- const isExempt = allRecords
105
- .filter((other) => isSameDomain(other, record))
106
- .flatMap(getFieldPairs)
107
- .some(isBuiltFromDeclarations);
108
- if (isExempt) return [];
109
- return getFieldPairs(record).flatMap((pair) => {
98
+ const linted = module.records.map((record) => ({
99
+ domain: getDomain(record),
100
+ warnings: getFieldPairs(record).flatMap((pair): SanyMessage[] => {
110
101
  const name = getFieldName(pair);
111
102
  const symbol = name && getContextSymbol(module.context, name.value);
112
103
  if (name === undefined || symbol === undefined) return [];
@@ -117,6 +108,24 @@ export const lintSanyModule = (module: ModuleNode): SanyMessage[] => {
117
108
  isWarning: true,
118
109
  },
119
110
  ];
120
- });
111
+ }),
112
+ }));
113
+ const warnedDomains = new Set(
114
+ linted.flatMap((item) => (item.warnings.length > 0 ? [item.domain] : [])),
115
+ );
116
+ const exemptDomains = new Set<string>();
117
+ [
118
+ ...[...getExtendedModules(module)].flatMap((extended) => extended.records),
119
+ ...module.records,
120
+ ].forEach((record) => {
121
+ const domain = getDomain(record);
122
+ if (
123
+ warnedDomains.has(domain) &&
124
+ !exemptDomains.has(domain) &&
125
+ getFieldPairs(record).some(isBuiltFromDeclarations)
126
+ ) {
127
+ exemptDomains.add(domain);
128
+ }
121
129
  });
130
+ return linted.flatMap((item) => (exemptDomains.has(item.domain) ? [] : item.warnings));
122
131
  };
package/src/search.ts CHANGED
@@ -14,7 +14,7 @@ import type {
14
14
  Violation,
15
15
  } from "./check";
16
16
  import type { ConfigValue, ModelConfig } from "./config";
17
- import { getReadVariables } from "./dependencies";
17
+ import { getReadVariables, isConstantLevel } from "./dependencies";
18
18
  import {
19
19
  isStackOverflow,
20
20
  TlaConfigError,
@@ -27,10 +27,10 @@ import {
27
27
  describeRange,
28
28
  evaluate,
29
29
  evaluateStartupDefinitions,
30
+ getStartupValue,
30
31
  expectBoolean,
31
32
  formatRange,
32
33
  getDefinition,
33
- isConstantLevel,
34
34
  type Context,
35
35
  type Environment,
36
36
  type Scope,
@@ -49,7 +49,7 @@ import { prettyPrint } from "./pretty-print";
49
49
  import { getPossibleCounts, type CheckerRuntime } from "./runtime";
50
50
  import { getRepresentative, getSymmetryGroup } from "./symmetry";
51
51
  import { MESSAGE_CODE, MISSING_INIT_174, withHeadline } from "./tlc/messages";
52
- import { createTlcFingerprinter, getTlcFingerprint } from "./tlc/fingerprint";
52
+ import { getTlcFingerprint, getTlcFingerprints } from "./tlc/fingerprint";
53
53
  import { formatValue, isUpdatedElementOf, type Value } from "./values";
54
54
 
55
55
  interface NamedExpression {
@@ -563,6 +563,8 @@ interface Search {
563
563
  // TLC drops a constraint that is a true constant formula.
564
564
  isConstrained: boolean;
565
565
  findViolatedInvariant: (state: Value[], parent?: Value[]) => StateCheck | undefined;
566
+ // Every invariant an initial state violates, which TLC reports with -continue.
567
+ getViolatedInvariants: (state: Value[]) => StateCheck[];
566
568
  // The checks of a state that TLC evaluates when it replays the computation of the initial states
567
569
  // or of the successors of a state, with an environment that records the call stack. The first
568
570
  // returns the check that stops the replay, and the second false where TLC stops it.
@@ -760,9 +762,33 @@ export const createSearch = (
760
762
  : [getViewValue(view.expression, representative)],
761
763
  );
762
764
  };
765
+ // With -continue, TLC goes on to the successors of a state that violates an invariant.
766
+ const violatingStates = new WeakSet<Value[]>();
767
+ const isViolated = (invariant: StateCheck, state: Value[], parent: Value[] | undefined) => {
768
+ // A parent that satisfies every invariant leaves only what the step changed to fail.
769
+ const checkedParent = parent && !violatingStates.has(parent) ? parent : undefined;
770
+ if (isUnchangedFor(invariant, state, checkedParent)) return false;
771
+ try {
772
+ const context = getContext(environment, state, undefined, invariant.scope);
773
+ const membership = invariant.membership;
774
+ return checkedParent && membership
775
+ ? !isUpdatedElementOf(
776
+ state[membership.variable],
777
+ checkedParent[membership.variable],
778
+ evaluate(membership.set, context),
779
+ )
780
+ : !holdsAsConjunct(invariant, context);
781
+ } catch (error) {
782
+ // TLC reports a failure only on a state after the initial states as an invariant failure.
783
+ if (!parent) throw error;
784
+ throw withHeadline(
785
+ setExitCode(error, EXIT_STATUS.safetyEvaluationFailure),
786
+ MESSAGE_CODE.invariantEvaluationFailed,
787
+ `Evaluating invariant ${invariant.name} failed.`,
788
+ );
789
+ }
790
+ };
763
791
  const isFingerprintedLikeTlc = hasWideString(config, environment);
764
- // One fingerprinter for every level keeps the values it cached for the states of earlier levels.
765
- let storedFingerprinter: ReturnType<typeof createTlcFingerprinter> | undefined;
766
792
  runtime.getFingerprint = getTlcStateFingerprint;
767
793
  const findUnwitnessedPossible = () => {
768
794
  const unwitnessed = possible.find((item) => !runtime.possibleCounts.get(item.name));
@@ -786,8 +812,7 @@ export const createSearch = (
786
812
  if (view !== undefined || isFingerprintedLikeTlc) {
787
813
  return BigInt64Array.from(states, getTlcStateFingerprint);
788
814
  }
789
- storedFingerprinter ??= createTlcFingerprinter(getTlcOrder());
790
- return storedFingerprinter(fingerprintStates);
815
+ return getTlcFingerprints(fingerprintStates, getTlcOrder());
791
816
  },
792
817
  getFingerprintState: (state) => {
793
818
  if (isFingerprintedLikeTlc) return [String(getTlcStateFingerprint(state))];
@@ -798,30 +823,21 @@ export const createSearch = (
798
823
  : getRepresentative(state, symmetryGroup, getTlcOrder());
799
824
  return view === undefined ? representative : [getViewValue(view.expression, representative)];
800
825
  },
801
- findViolatedInvariant: (state, parent) =>
802
- invariants.find((invariant) => {
803
- if (isUnchangedFor(invariant, state, parent)) return false;
804
- try {
805
- const context = getContext(environment, state, undefined, invariant.scope);
806
- const membership = invariant.membership;
807
- // The parent satisfies every invariant, so only the entries the step changed can fail.
808
- return parent && membership
809
- ? !isUpdatedElementOf(
810
- state[membership.variable],
811
- parent[membership.variable],
812
- evaluate(membership.set, context),
813
- )
814
- : !holdsAsConjunct(invariant, context);
815
- } catch (error) {
816
- // TLC reports a failure only on a state after the initial states as an invariant failure.
817
- if (!parent) throw error;
818
- throw withHeadline(
819
- setExitCode(error, EXIT_STATUS.safetyEvaluationFailure),
820
- MESSAGE_CODE.invariantEvaluationFailed,
821
- `Evaluating invariant ${invariant.name} failed.`,
822
- );
823
- }
824
- }),
826
+ findViolatedInvariant: (state, parent) => {
827
+ const violated = invariants.find((invariant) => isViolated(invariant, state, parent));
828
+ if (violated) violatingStates.add(state);
829
+ return violated;
830
+ },
831
+ getViolatedInvariants: (state) => {
832
+ const violated = invariantPredicates.filter((predicate) =>
833
+ invariants.some(
834
+ (invariant) =>
835
+ invariant.predicate === predicate.predicate && isViolated(invariant, state, undefined),
836
+ ),
837
+ );
838
+ if (violated.length > 0) violatingStates.add(state);
839
+ return violated;
840
+ },
825
841
  checkReplayedInitialState: (state, tracing, addFingerprint) => {
826
842
  const holdsIn = (expression: Expression, scope: Scope | undefined) =>
827
843
  holdsLikeTlc(expression, getContext(tracing, state, undefined, scope));
@@ -925,7 +941,7 @@ export const createSearch = (
925
941
  // a postcondition before it checks any of them.
926
942
  const constant = config.postconditions.find((name) => {
927
943
  const definition = getDefinition(name, environment);
928
- return definition !== undefined && environment.definitionValues.has(definition);
944
+ return definition !== undefined && getStartupValue(definition, environment) !== undefined;
929
945
  });
930
946
  if (constant !== undefined) {
931
947
  if (isAfterViolation) return undefined;
@@ -1,3 +1,4 @@
1
+ import { isConstantLevel } from "./dependencies";
1
2
  import {
2
3
  isLocallyResolved,
3
4
  type Definition,
@@ -14,7 +15,6 @@ import {
14
15
  evaluate,
15
16
  forEachBinding,
16
17
  getDefinition,
17
- isConstantLevel,
18
18
  lookupScope,
19
19
  resolveGlobalOperator,
20
20
  type Closure,
package/src/successors.ts CHANGED
@@ -1056,15 +1056,9 @@ const compileAction = (
1056
1056
  }
1057
1057
  };
1058
1058
 
1059
- const emptyStates = new WeakMap<Environment, State>();
1060
-
1061
- const getEmptyState = (environment: Environment) => {
1062
- const cached = emptyStates.get(environment);
1063
- if (cached) return cached;
1064
- const state = environment.variables.map((): Value | undefined => undefined);
1065
- emptyStates.set(environment, state);
1066
- return state;
1067
- };
1059
+ // A partial state that assigns no variable, which a run fills in as it assigns them.
1060
+ const getEmptyState = (environment: Environment): State =>
1061
+ environment.variables.map((): Value | undefined => undefined);
1068
1062
 
1069
1063
  const isComplete = (partial: State): partial is Value[] => {
1070
1064
  for (let index = 0; index < partial.length; index++) {
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
  };