tla-ts 0.0.3-dev.33ae522 → 0.0.3-dev.3539317

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.
@@ -1,6 +1,8 @@
1
- import type { Declaration, Definition, Expression, SourceLocation } from "./ast";
2
- import { TlaSyntaxError } from "./errors";
1
+ import type { Declaration, Definition, Expression, SourceLocation, Theorem } from "./ast";
2
+ import { createSanyError, formatRange } from "./errors";
3
3
  import {
4
+ ACTION_LEVEL,
5
+ analyzeAssumeProve,
4
6
  createLevelAnalyzer,
5
7
  getArgumentKey,
6
8
  MAX_LEVEL,
@@ -24,6 +26,7 @@ interface ModuleContext {
24
26
  variables: string[];
25
27
  definitions: Definition[];
26
28
  assumptions: Expression[];
29
+ theorems: Theorem[];
27
30
  getDefinition: (name: string) => Definition | undefined;
28
31
  }
29
32
 
@@ -46,10 +49,7 @@ interface Substituted {
46
49
  const getMaxLevel = (operator: OperatorLevels, index: number) =>
47
50
  operator.maxLevels[index] ?? MAX_LEVEL;
48
51
 
49
- export const checkInstances = (
50
- checks: InstanceCheck[],
51
- getModule: (name: string) => ModuleContext,
52
- ) => {
52
+ export const createInstanceChecker = (getModule: (name: string) => ModuleContext) => {
53
53
  const analyzers = new Map<string, ReturnType<typeof createLevelAnalyzer>>();
54
54
  const getAnalyzer = (name: string) => {
55
55
  const cached = analyzers.get(name);
@@ -101,17 +101,38 @@ export const checkInstances = (
101
101
  definition.formals.every((formal) => formal.name !== operator && formal.name !== param),
102
102
  ),
103
103
  );
104
+ const addAssumedLevels = (data: ReturnType<typeof analyzeAssumeProve>) => {
105
+ addLevels(data, () => true);
106
+ module.constants.forEach((constant) => {
107
+ if (data.params.has(constant.name)) {
108
+ putConstraint(levels.constraints, constant.name, ACTION_LEVEL);
109
+ }
110
+ });
111
+ };
104
112
  module.assumptions.forEach((assumption) =>
105
- addLevels(analyzer.analyze(assumption, new Map()), () => true),
113
+ addAssumedLevels(analyzer.analyze(assumption, new Map())),
114
+ );
115
+ module.theorems.forEach((theorem) =>
116
+ theorem.statement.kind === "AssumeProve"
117
+ ? addAssumedLevels(analyzeAssumeProve(theorem.statement, new Map(), analyzer))
118
+ : addLevels(analyzer.analyze(theorem.statement, new Map()), () => true),
106
119
  );
107
120
  moduleLevels.set(name, levels);
108
121
  return levels;
109
122
  };
110
123
 
111
- const messages = new Set<string>();
112
- checks.forEach((check) => {
113
- const location = `at line ${check.location.line}, column ${check.location.column}`;
114
- const addMessage = (message: string) => messages.add(`${message} ${location}`);
124
+ return (check: InstanceCheck) => {
125
+ const errors = new Map<string, { location: string; message: string }>();
126
+ // SANY reports each error at the whole instance.
127
+ const location = formatRange(
128
+ check.location.range ?? {
129
+ module: check.instancer,
130
+ start: check.location,
131
+ end: check.location,
132
+ },
133
+ );
134
+ const addMessage = (message: string) =>
135
+ errors.set(`${location}\n${message}`, { location, message });
115
136
  const instancee = getModule(check.module);
116
137
  const levels = getModuleLevels(check.module);
117
138
  const analyzer = getAnalyzer(check.instancer);
@@ -141,14 +162,14 @@ export const checkInstances = (
141
162
  ];
142
163
  });
143
164
  const getLevelMessage = (name: string, level: number) =>
144
- `Level error in instantiating module '${check.module}': the level of the expression or operator substituted for '${name}' must be at most ${level}`;
165
+ `Level error in instantiating module '${check.module}':\nThe level of the expression or operator substituted for '${name}' \nmust be at most ${level}.`;
145
166
  substituted.forEach((item) => {
146
167
  if (!levels.isConstant && item.level > item.maximumLevel) {
147
168
  addMessage(getLevelMessage(item.name, item.maximumLevel));
148
169
  }
149
170
  if (!item.isLeibniz) {
150
171
  addMessage(
151
- `Error in instantiating module '${check.module}': a non-Leibniz operator substituted for '${item.name}'`,
172
+ `Error in instantiating module '${check.module}':\n A non-Leibniz operator substituted for '${item.name}'.`,
152
173
  );
153
174
  }
154
175
  });
@@ -162,7 +183,7 @@ export const checkInstances = (
162
183
  const minimum = levels.argConstraints.get(getArgumentKey(item.name, index));
163
184
  if (minimum !== undefined && getMaxLevel(operator, index) < minimum) {
164
185
  addMessage(
165
- `Level error in instantiating module '${check.module}': the level of the argument ${index + 1} of the operator ${operator.name} must be at least ${minimum}`,
186
+ `Level error in instantiating module '${check.module}':\nThe level of the argument ${index + 1} of the operator ${operator.name} \nmust be at least ${minimum}.`,
166
187
  );
167
188
  }
168
189
  });
@@ -175,10 +196,10 @@ export const checkInstances = (
175
196
  const maximum = getMaxLevel(operator, parameter.index);
176
197
  if (argument.level > maximum) {
177
198
  addMessage(
178
- `Level error when instantiating module '${check.module}': the level of the argument ${parameter.index} of the operator ${parameter.operator}' must be at most ${maximum}`,
199
+ `Level error when instantiating module '${check.module}':\nThe level of the argument ${parameter.index} of the operator ${parameter.operator}' \nmust be at most ${maximum}.`,
179
200
  );
180
201
  }
181
202
  });
182
- });
183
- if (messages.size > 0) throw new TlaSyntaxError([...messages].join("\n"));
203
+ if (errors.size > 0) throw createSanyError([...errors.values()]);
204
+ };
184
205
  };
package/src/symmetry.ts CHANGED
@@ -31,6 +31,20 @@ interface Permutation {
31
31
  cacheLimit: number;
32
32
  }
33
33
 
34
+ // The images of one value under every permutation, the identity first, and how each image compares
35
+ // with the image of each permutation the search has held as the smallest.
36
+ interface Orbit {
37
+ images: Value[];
38
+ comparisons: (Int8Array | undefined)[];
39
+ }
40
+
41
+ interface SymmetryGroup {
42
+ permutations: Permutation[];
43
+ orbits: WeakMap<ObjectValue, Orbit>;
44
+ orbitCount: number;
45
+ orbitLimit: number;
46
+ }
47
+
34
48
  const getPermutationKey = (permutation: Images) =>
35
49
  [...permutation]
36
50
  .map(([name, image]) => `${name}>${image.name}`)
@@ -68,7 +82,10 @@ const toImages = (value: Value) => {
68
82
  return permutation;
69
83
  };
70
84
 
71
- export const getSymmetryGroup = (name: string, environment: Environment): Permutation[] => {
85
+ export const getSymmetryGroup = (
86
+ name: string,
87
+ environment: Environment,
88
+ ): SymmetryGroup | undefined => {
72
89
  const definition = environment.definitions.get(name);
73
90
  if (definition === undefined && !environment.constants.has(name)) {
74
91
  throw new TlaConfigError(
@@ -90,7 +107,7 @@ export const getSymmetryGroup = (name: string, environment: Environment): Permut
90
107
  const permutations = toFiniteSet(value).elements.map(toImages);
91
108
  const isDisabled =
92
109
  definition.body.kind === "Apply" && definition.body.args.length >= permutations.length;
93
- if (isDisabled) return [];
110
+ if (isDisabled) return undefined;
94
111
  const group = new Map<string, Images>();
95
112
  permutations.forEach((permutation) => {
96
113
  if (permutation.size > 0) group.set(getPermutationKey(permutation), permutation);
@@ -109,13 +126,19 @@ export const getSymmetryGroup = (name: string, environment: Environment): Permut
109
126
  );
110
127
  frontier.start = end;
111
128
  }
129
+ if (group.size === 0) return undefined;
112
130
  const cacheLimit = Math.max(256, Math.floor(CACHE_LIMIT / group.size));
113
- return [...group.values()].map((images) => ({
114
- images,
115
- cache: new WeakMap<ObjectValue, Value>(),
116
- cacheSize: 0,
117
- cacheLimit,
118
- }));
131
+ return {
132
+ permutations: [...group.values()].map((images) => ({
133
+ images,
134
+ cache: new WeakMap<ObjectValue, Value>(),
135
+ cacheSize: 0,
136
+ cacheLimit,
137
+ })),
138
+ orbits: new WeakMap(),
139
+ orbitCount: 0,
140
+ orbitLimit: cacheLimit,
141
+ };
119
142
  };
120
143
 
121
144
  const permuteElements = (elements: Value[], permutation: Permutation) => {
@@ -218,41 +241,76 @@ const computePermutedValue = (value: ObjectValue, permutation: Permutation) => {
218
241
  return elements ? createSet(elements) : set;
219
242
  };
220
243
 
221
- const permuteRemaining = (state: Value[], permuted: Value[], permutation: Permutation) => {
222
- for (let index = permuted.length; index < state.length; index++) {
223
- permuted.push(permuteValue(state[index], permutation));
244
+ const getOrbit = (value: ObjectValue, group: SymmetryGroup) => {
245
+ const cached = group.orbits.get(value);
246
+ if (cached !== undefined) return cached;
247
+ if (group.orbitCount >= group.orbitLimit) {
248
+ group.orbits = new WeakMap();
249
+ group.orbitCount = 0;
224
250
  }
225
- return permuted;
251
+ const orbit: Orbit = { images: [value], comparisons: [] };
252
+ group.orbits.set(value, orbit);
253
+ group.orbitCount++;
254
+ return orbit;
255
+ };
256
+
257
+ const getImage = (orbit: Orbit, permutation: number, group: SymmetryGroup) =>
258
+ (orbit.images[permutation] ??= permuteValue(
259
+ orbit.images[0],
260
+ group.permutations[permutation - 1],
261
+ ));
262
+
263
+ // Two images of a value compare the same way every time, and comparing them again changes nothing,
264
+ // so an orbit compares each pair once.
265
+ const compareImages = (
266
+ value: ObjectValue,
267
+ permutation: number,
268
+ minimum: number,
269
+ group: SymmetryGroup,
270
+ ) => {
271
+ const orbit = getOrbit(value, group);
272
+ const comparisons = (orbit.comparisons[minimum] ??= new Int8Array(group.permutations.length + 1));
273
+ if (comparisons[permutation] === 0) {
274
+ const comparison = compareValues(
275
+ getImage(orbit, permutation, group),
276
+ getImage(orbit, minimum, group),
277
+ );
278
+ comparisons[permutation] = Math.sign(comparison) + 2;
279
+ }
280
+ return comparisons[permutation] - 2;
226
281
  };
227
282
 
228
- const getSmallerPermutation = (
283
+ const isSmallerImage = (
229
284
  state: Value[],
230
- minimum: Value[],
231
- permutation: Permutation,
232
- order: number[] | undefined,
285
+ permutation: number,
286
+ minimum: number,
287
+ group: SymmetryGroup,
288
+ order: number[],
233
289
  ) => {
234
- const permuted: Value[] = [];
235
- for (let position = 0; position < state.length; position++) {
236
- const index = order ? order[position] : position;
237
- const value = permuteValue(state[index], permutation);
238
- const comparison = compareValues(value, minimum[index]);
239
- if (comparison > 0) return undefined;
240
- if (!order) permuted.push(value);
241
- if (comparison < 0) {
242
- return order
243
- ? state.map((item) => permuteValue(item, permutation))
244
- : permuteRemaining(state, permuted, permutation);
245
- }
290
+ for (const index of order) {
291
+ const value = state[index];
292
+ const comparison =
293
+ typeof value === "object" ? compareImages(value, permutation, minimum, group) : 0;
294
+ if (comparison !== 0) return comparison < 0;
246
295
  }
247
- return undefined;
296
+ return false;
248
297
  };
249
298
 
299
+ // TLC keeps the smallest image of the state in its variable order, replacing it only with a
300
+ // strictly smaller one.
250
301
  export const getRepresentative = (
251
302
  state: Value[],
252
- group: Permutation[],
253
- order?: number[],
254
- ): Value[] =>
255
- group.reduce(
256
- (minimum, permutation) => getSmallerPermutation(state, minimum, permutation, order) ?? minimum,
257
- state,
303
+ group: SymmetryGroup,
304
+ order: number[],
305
+ ): Value[] => {
306
+ const minimum = group.permutations.reduce(
307
+ (smallest, _, index) =>
308
+ isSmallerImage(state, index + 1, smallest, group, order) ? index + 1 : smallest,
309
+ 0,
258
310
  );
311
+ return minimum === 0
312
+ ? state
313
+ : state.map((value) =>
314
+ typeof value === "object" ? getImage(getOrbit(value, group), minimum, group) : value,
315
+ );
316
+ };
package/src/values.ts CHANGED
@@ -1199,6 +1199,41 @@ const advanceCombination = (indices: number[], length: number) => {
1199
1199
  return false;
1200
1200
  };
1201
1201
 
1202
+ // TLC enumerates SUBSET S lazily, by size and then in the order of S, so a quantifier that finds
1203
+ // its witness early never builds the rest. For a power set too large to build, the elements are
1204
+ // computed in that order as a loop reads them.
1205
+ export const getLazySubsets = (value: Value): Value[] | undefined => {
1206
+ if (typeof value !== "object" || value.kind !== "Subset" || isOverriddenSet(value.base)) {
1207
+ return undefined;
1208
+ }
1209
+ const base = toFiniteSet(value.base).elements;
1210
+ if (base.length <= MAXIMUM_ENUMERATED_SUBSET_BASE) return undefined;
1211
+ const cursor = { index: -1, indices: [0] };
1212
+ const getSubset = (index: number) => {
1213
+ if (index <= cursor.index) cursor.index = -1;
1214
+ while (cursor.index < index) {
1215
+ if (cursor.index === -1) cursor.indices = [];
1216
+ else if (!advanceCombination(cursor.indices, base.length)) {
1217
+ cursor.indices = Array.from({ length: cursor.indices.length + 1 }, (_, item) => item);
1218
+ }
1219
+ cursor.index++;
1220
+ }
1221
+ return createSortedSet(cursor.indices.map((item) => base[item]));
1222
+ };
1223
+ const length = 2 ** base.length;
1224
+ const isIndex = (property: string | symbol) =>
1225
+ typeof property === "string" && /^\d+$/.test(property) && Number(property) < length;
1226
+ return new Proxy<Value[]>([], {
1227
+ get: (target, property, receiver) => {
1228
+ if (property === "length") return length;
1229
+ return isIndex(property)
1230
+ ? getSubset(Number(property))
1231
+ : Reflect.get(target, property, receiver);
1232
+ },
1233
+ has: (target, property) => isIndex(property) || Reflect.has(target, property),
1234
+ });
1235
+ };
1236
+
1202
1237
  const getSortedSubsets = (base: Value[]) => {
1203
1238
  const subsets: Value[] = [];
1204
1239
  for (let size = 0; size <= base.length; size++) {
@@ -1291,7 +1326,7 @@ const enumerateSet = (value: Value): Value[] => {
1291
1326
  case "SetOperation": {
1292
1327
  if (
1293
1328
  value.operator === "\\cup" &&
1294
- (isOverriddenSet(value.left) || isOverriddenSet(value.right))
1329
+ (!isTlcEnumerable(value.left) || !isTlcEnumerable(value.right))
1295
1330
  ) {
1296
1331
  throw new TlaEvaluationError(
1297
1332
  `Attempted to enumerate S \\cup T when S:\n${formatValue(value.left)}\nand T:\n${formatValue(value.right)}\nare not both enumerable`,
@@ -1299,14 +1334,14 @@ const enumerateSet = (value: Value): Value[] => {
1299
1334
  }
1300
1335
  if (
1301
1336
  value.operator === "\\cap" &&
1302
- isOverriddenSet(value.left) &&
1303
- isOverriddenSet(value.right)
1337
+ !isTlcEnumerable(value.left) &&
1338
+ !isTlcEnumerable(value.right)
1304
1339
  ) {
1305
1340
  throw new TlaEvaluationError(
1306
1341
  `Attempted to enumerate S \\cap T when neither S:\n${formatValue(value.left)}\nnor T:\n${formatValue(value.right)}\nis enumerable`,
1307
1342
  );
1308
1343
  }
1309
- if (value.operator === "\\" && isOverriddenSet(value.left)) {
1344
+ if (value.operator === "\\" && !isTlcEnumerable(value.left)) {
1310
1345
  throw new TlaEvaluationError(
1311
1346
  `Attempted to enumerate S \\ T when S:\n${formatValue(value.left)}\nis not enumerable.`,
1312
1347
  );
@@ -1393,14 +1428,14 @@ export const getStreamedElements = (value: Value): Value[] => {
1393
1428
  }
1394
1429
  if (value.kind !== "SetOperation") return toFiniteSet(value).elements;
1395
1430
  if (value.operator === "\\cup") {
1396
- return isOverriddenSet(value.left) || isOverriddenSet(value.right)
1431
+ return !isTlcEnumerable(value.left) || !isTlcEnumerable(value.right)
1397
1432
  ? toFiniteSet(value).elements
1398
1433
  : [...getStreamedElements(value.left), ...getStreamedElements(value.right)];
1399
1434
  }
1400
1435
  const isLeftEnumerated = value.operator === "\\" || isEnumerable(value.left);
1401
1436
  const enumerated = isLeftEnumerated ? value.left : value.right;
1402
1437
  const other = isLeftEnumerated ? value.right : value.left;
1403
- if (isOverriddenSet(enumerated)) return toFiniteSet(value).elements;
1438
+ if (!isTlcEnumerable(enumerated)) return toFiniteSet(value).elements;
1404
1439
  return getStreamedElements(enumerated).filter(
1405
1440
  (element) => isElementOf(element, other) === (value.operator === "\\cap"),
1406
1441
  );
@@ -1959,10 +1994,15 @@ const getElementContribution = (element: Value) =>
1959
1994
  const getEntryContribution = (key: Value, value: Value) =>
1960
1995
  finalizeHash((Math.imul(getValueHash(key), 0x27d4eb2d) + getValueHash(value)) | 0);
1961
1996
 
1997
+ const unenumeratedSets = { isHashed: false };
1998
+
1962
1999
  const computeValueHash = (value: ObjectValue) => {
1963
2000
  if (value.kind === "ModelValue") return finalizeHash(combineHash(hashString(value.name), 0x6d));
1964
2001
  if (isSetValue(value)) {
1965
- if (!isEnumerable(value)) return hashString(getValueKey(value));
2002
+ if (!isEnumerable(value)) {
2003
+ unenumeratedSets.isHashed = true;
2004
+ return hashString(getValueKey(value));
2005
+ }
1966
2006
  const elements = toFiniteSet(value).elements;
1967
2007
  let hash = SET_HASH_SEED;
1968
2008
  for (let index = 0; index < elements.length; index++) {
@@ -1994,6 +2034,25 @@ export const getValueHash = (value: Value): number => {
1994
2034
  return hash;
1995
2035
  };
1996
2036
 
2037
+ const fingerprintLikeTlc = (value: Value): void => {
2038
+ if (typeof value !== "object" || value.kind === "ModelValue") return;
2039
+ if (isOverriddenSet(value)) {
2040
+ throw new TlaEvaluationError(
2041
+ `TLC has found a state in which the value of a variable contains ${formatValue(value)}`,
2042
+ );
2043
+ }
2044
+ if (isSetValue(value)) return toFiniteSet(value).elements.forEach(fingerprintLikeTlc);
2045
+ const functionValue = toFiniteFunction(value);
2046
+ functionValue.domain.forEach(fingerprintLikeTlc);
2047
+ functionValue.range.forEach(fingerprintLikeTlc);
2048
+ };
2049
+
2050
+ // TLC enumerates every set in a state to fingerprint it, so it fails on a set it can't enumerate.
2051
+ // A state holds one only if hashing it met one, so states go unchecked until then.
2052
+ export const assertFingerprintable = (state: Value[]) => {
2053
+ if (unenumeratedSets.isHashed) state.forEach(fingerprintLikeTlc);
2054
+ };
2055
+
1997
2056
  const valueFingerprints = new WeakMap<ObjectValue, number>();
1998
2057
 
1999
2058
  const finalizeFingerprint = (hash: number) => {
@@ -2020,7 +2079,10 @@ const getEntryFingerprint = (key: Value, value: Value) =>
2020
2079
  const computeValueFingerprint = (value: ObjectValue) => {
2021
2080
  if (value.kind === "ModelValue") return finalizeFingerprint(fingerprintString(value.name) ^ 0x3c);
2022
2081
  if (isSetValue(value)) {
2023
- if (!isEnumerable(value)) return fingerprintString(getValueKey(value));
2082
+ if (!isEnumerable(value)) {
2083
+ unenumeratedSets.isHashed = true;
2084
+ return fingerprintString(getValueKey(value));
2085
+ }
2024
2086
  const elements = toFiniteSet(value).elements;
2025
2087
  let fingerprint = 0x1b873593;
2026
2088
  for (let index = 0; index < elements.length; index++) {